blob: b62c47c67f3eda91f20d0d81eb03d3a7a1eb7c6e [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"
Guy Benyei11169dd2012-12-18 14:30:41 +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"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000109#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000110#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000111#include "llvm/Support/ErrorHandling.h"
112#include "llvm/Support/FileSystem.h"
113#include "llvm/Support/MemoryBuffer.h"
114#include "llvm/Support/Path.h"
115#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000116#include "llvm/Support/Timer.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000117#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000118#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000119#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000120#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000121#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000122#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000123#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000124#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000125#include <limits>
126#include <map>
127#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000128#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000129#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000130#include <tuple>
131#include <utility>
132#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000133
134using namespace clang;
135using namespace clang::serialization;
136using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000137using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000138
Ben Langmuircb69b572014-03-07 06:40:32 +0000139//===----------------------------------------------------------------------===//
140// ChainedASTReaderListener implementation
141//===----------------------------------------------------------------------===//
142
143bool
144ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
145 return First->ReadFullVersionInformation(FullVersion) ||
146 Second->ReadFullVersionInformation(FullVersion);
147}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000148
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000149void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
150 First->ReadModuleName(ModuleName);
151 Second->ReadModuleName(ModuleName);
152}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000153
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000154void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
155 First->ReadModuleMapFile(ModuleMapPath);
156 Second->ReadModuleMapFile(ModuleMapPath);
157}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000158
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000159bool
160ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
161 bool Complain,
162 bool AllowCompatibleDifferences) {
163 return First->ReadLanguageOptions(LangOpts, Complain,
164 AllowCompatibleDifferences) ||
165 Second->ReadLanguageOptions(LangOpts, Complain,
166 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000167}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000168
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000169bool ChainedASTReaderListener::ReadTargetOptions(
170 const TargetOptions &TargetOpts, bool Complain,
171 bool AllowCompatibleDifferences) {
172 return First->ReadTargetOptions(TargetOpts, Complain,
173 AllowCompatibleDifferences) ||
174 Second->ReadTargetOptions(TargetOpts, Complain,
175 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000176}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000177
Ben Langmuircb69b572014-03-07 06:40:32 +0000178bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000179 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000180 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
181 Second->ReadDiagnosticOptions(DiagOpts, Complain);
182}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000183
Ben Langmuircb69b572014-03-07 06:40:32 +0000184bool
185ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
186 bool Complain) {
187 return First->ReadFileSystemOptions(FSOpts, Complain) ||
188 Second->ReadFileSystemOptions(FSOpts, Complain);
189}
190
191bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000192 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
193 bool Complain) {
194 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
195 Complain) ||
196 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
197 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000198}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000199
Ben Langmuircb69b572014-03-07 06:40:32 +0000200bool ChainedASTReaderListener::ReadPreprocessorOptions(
201 const PreprocessorOptions &PPOpts, bool Complain,
202 std::string &SuggestedPredefines) {
203 return First->ReadPreprocessorOptions(PPOpts, Complain,
204 SuggestedPredefines) ||
205 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
206}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000207
Ben Langmuircb69b572014-03-07 06:40:32 +0000208void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
209 unsigned Value) {
210 First->ReadCounter(M, Value);
211 Second->ReadCounter(M, Value);
212}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000213
Ben Langmuircb69b572014-03-07 06:40:32 +0000214bool ChainedASTReaderListener::needsInputFileVisitation() {
215 return First->needsInputFileVisitation() ||
216 Second->needsInputFileVisitation();
217}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000218
Ben Langmuircb69b572014-03-07 06:40:32 +0000219bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
220 return First->needsSystemInputFileVisitation() ||
221 Second->needsSystemInputFileVisitation();
222}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000223
Richard Smith216a3bd2015-08-13 17:57:10 +0000224void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
225 ModuleKind Kind) {
226 First->visitModuleFile(Filename, Kind);
227 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000228}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000229
Ben Langmuircb69b572014-03-07 06:40:32 +0000230bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000231 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000232 bool isOverridden,
233 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000234 bool Continue = false;
235 if (First->needsInputFileVisitation() &&
236 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000237 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
238 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000239 if (Second->needsInputFileVisitation() &&
240 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000241 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
242 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000243 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000244}
245
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000246void ChainedASTReaderListener::readModuleFileExtension(
247 const ModuleFileExtensionMetadata &Metadata) {
248 First->readModuleFileExtension(Metadata);
249 Second->readModuleFileExtension(Metadata);
250}
251
Guy Benyei11169dd2012-12-18 14:30:41 +0000252//===----------------------------------------------------------------------===//
253// PCH validator implementation
254//===----------------------------------------------------------------------===//
255
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000256ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000257
258/// \brief Compare the given set of language options against an existing set of
259/// language options.
260///
261/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000262/// \param AllowCompatibleDifferences If true, differences between compatible
263/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000264///
265/// \returns true if the languagae options mis-match, false otherwise.
266static bool checkLanguageOptions(const LangOptions &LangOpts,
267 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000268 DiagnosticsEngine *Diags,
269 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000270#define LANGOPT(Name, Bits, Default, Description) \
271 if (ExistingLangOpts.Name != LangOpts.Name) { \
272 if (Diags) \
273 Diags->Report(diag::err_pch_langopt_mismatch) \
274 << Description << LangOpts.Name << ExistingLangOpts.Name; \
275 return true; \
276 }
277
278#define VALUE_LANGOPT(Name, Bits, Default, Description) \
279 if (ExistingLangOpts.Name != LangOpts.Name) { \
280 if (Diags) \
281 Diags->Report(diag::err_pch_langopt_value_mismatch) \
282 << Description; \
283 return true; \
284 }
285
286#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
287 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
288 if (Diags) \
289 Diags->Report(diag::err_pch_langopt_value_mismatch) \
290 << Description; \
291 return true; \
292 }
293
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000294#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
295 if (!AllowCompatibleDifferences) \
296 LANGOPT(Name, Bits, Default, Description)
297
298#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
299 if (!AllowCompatibleDifferences) \
300 ENUM_LANGOPT(Name, Bits, Default, Description)
301
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000302#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
303 if (!AllowCompatibleDifferences) \
304 VALUE_LANGOPT(Name, Bits, Default, Description)
305
Guy Benyei11169dd2012-12-18 14:30:41 +0000306#define BENIGN_LANGOPT(Name, Bits, Default, Description)
307#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000308#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000309#include "clang/Basic/LangOptions.def"
310
Ben Langmuircd98cb72015-06-23 18:20:18 +0000311 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
312 if (Diags)
313 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
314 return true;
315 }
316
Guy Benyei11169dd2012-12-18 14:30:41 +0000317 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
318 if (Diags)
319 Diags->Report(diag::err_pch_langopt_value_mismatch)
320 << "target Objective-C runtime";
321 return true;
322 }
323
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000324 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
325 LangOpts.CommentOpts.BlockCommandNames) {
326 if (Diags)
327 Diags->Report(diag::err_pch_langopt_value_mismatch)
328 << "block command names";
329 return true;
330 }
331
Vedant Kumar85a83c22017-06-01 20:01:01 +0000332 // Sanitizer feature mismatches are treated as compatible differences. If
333 // compatible differences aren't allowed, we still only want to check for
334 // mismatches of non-modular sanitizers (the only ones which can affect AST
335 // generation).
336 if (!AllowCompatibleDifferences) {
337 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
338 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
339 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
340 ExistingSanitizers.clear(ModularSanitizers);
341 ImportedSanitizers.clear(ModularSanitizers);
342 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
343 const std::string Flag = "-fsanitize=";
344 if (Diags) {
345#define SANITIZER(NAME, ID) \
346 { \
347 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
348 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
349 if (InExistingModule != InImportedModule) \
350 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
351 << InExistingModule << (Flag + NAME); \
352 }
353#include "clang/Basic/Sanitizers.def"
354 }
355 return true;
356 }
357 }
358
Guy Benyei11169dd2012-12-18 14:30:41 +0000359 return false;
360}
361
362/// \brief Compare the given set of target options against an existing set of
363/// target options.
364///
365/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
366///
367/// \returns true if the target options mis-match, false otherwise.
368static bool checkTargetOptions(const TargetOptions &TargetOpts,
369 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000370 DiagnosticsEngine *Diags,
371 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000372#define CHECK_TARGET_OPT(Field, Name) \
373 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
374 if (Diags) \
375 Diags->Report(diag::err_pch_targetopt_mismatch) \
376 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
377 return true; \
378 }
379
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000380 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000381 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000382 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000383
384 // We can tolerate different CPUs in many cases, notably when one CPU
385 // supports a strict superset of another. When allowing compatible
386 // differences skip this check.
387 if (!AllowCompatibleDifferences)
388 CHECK_TARGET_OPT(CPU, "target CPU");
389
Guy Benyei11169dd2012-12-18 14:30:41 +0000390#undef CHECK_TARGET_OPT
391
392 // Compare feature sets.
393 SmallVector<StringRef, 4> ExistingFeatures(
394 ExistingTargetOpts.FeaturesAsWritten.begin(),
395 ExistingTargetOpts.FeaturesAsWritten.end());
396 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
397 TargetOpts.FeaturesAsWritten.end());
398 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
399 std::sort(ReadFeatures.begin(), ReadFeatures.end());
400
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000401 // We compute the set difference in both directions explicitly so that we can
402 // diagnose the differences differently.
403 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
404 std::set_difference(
405 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
406 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
407 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
408 ExistingFeatures.begin(), ExistingFeatures.end(),
409 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000410
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000411 // If we are allowing compatible differences and the read feature set is
412 // a strict subset of the existing feature set, there is nothing to diagnose.
413 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
414 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000415
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000416 if (Diags) {
417 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000418 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000419 << /* is-existing-feature */ false << Feature;
420 for (StringRef Feature : UnmatchedExistingFeatures)
421 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
422 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000423 }
424
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000425 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000426}
427
428bool
429PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000430 bool Complain,
431 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000432 const LangOptions &ExistingLangOpts = PP.getLangOpts();
433 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000434 Complain ? &Reader.Diags : nullptr,
435 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000436}
437
438bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000439 bool Complain,
440 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
442 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000443 Complain ? &Reader.Diags : nullptr,
444 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000445}
446
447namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000448
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000449using MacroDefinitionsMap =
450 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
451using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000452
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000453} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000454
Ben Langmuirb92de022014-04-29 16:25:26 +0000455static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
456 DiagnosticsEngine &Diags,
457 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000458 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000459
460 // Check current mappings for new -Werror mappings, and the stored mappings
461 // for cases that were explicitly mapped to *not* be errors that are now
462 // errors because of options like -Werror.
463 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
464
465 for (DiagnosticsEngine *MappingSource : MappingSources) {
466 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
467 diag::kind DiagID = DiagIDMappingPair.first;
468 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
469 if (CurLevel < DiagnosticsEngine::Error)
470 continue; // not significant
471 Level StoredLevel =
472 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
473 if (StoredLevel < DiagnosticsEngine::Error) {
474 if (Complain)
475 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
476 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
477 return true;
478 }
479 }
480 }
481
482 return false;
483}
484
Alp Tokerac4e8e52014-06-22 21:58:33 +0000485static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
486 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
487 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
488 return true;
489 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000490}
491
492static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
493 DiagnosticsEngine &Diags,
494 bool IsSystem, bool Complain) {
495 // Top-level options
496 if (IsSystem) {
497 if (Diags.getSuppressSystemWarnings())
498 return false;
499 // If -Wsystem-headers was not enabled before, be conservative
500 if (StoredDiags.getSuppressSystemWarnings()) {
501 if (Complain)
502 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
503 return true;
504 }
505 }
506
507 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
508 if (Complain)
509 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
510 return true;
511 }
512
513 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
514 !StoredDiags.getEnableAllWarnings()) {
515 if (Complain)
516 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
517 return true;
518 }
519
520 if (isExtHandlingFromDiagsError(Diags) &&
521 !isExtHandlingFromDiagsError(StoredDiags)) {
522 if (Complain)
523 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
524 return true;
525 }
526
527 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
528}
529
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000530/// Return the top import module if it is implicit, nullptr otherwise.
531static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
532 Preprocessor &PP) {
533 // If the original import came from a file explicitly generated by the user,
534 // don't check the diagnostic mappings.
535 // FIXME: currently this is approximated by checking whether this is not a
536 // module import of an implicitly-loaded module file.
537 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
538 // the transitive closure of its imports, since unrelated modules cannot be
539 // imported until after this module finishes validation.
540 ModuleFile *TopImport = &*ModuleMgr.rbegin();
541 while (!TopImport->ImportedBy.empty())
542 TopImport = TopImport->ImportedBy[0];
543 if (TopImport->Kind != MK_ImplicitModule)
544 return nullptr;
545
546 StringRef ModuleName = TopImport->ModuleName;
547 assert(!ModuleName.empty() && "diagnostic options read before module name");
548
549 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
550 assert(M && "missing module");
551 return M;
552}
553
Ben Langmuirb92de022014-04-29 16:25:26 +0000554bool PCHValidator::ReadDiagnosticOptions(
555 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
556 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
557 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
558 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000559 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000560 // This should never fail, because we would have processed these options
561 // before writing them to an ASTFile.
562 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
563
564 ModuleManager &ModuleMgr = Reader.getModuleManager();
565 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
566
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000567 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
568 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000569 return false;
570
Ben Langmuirb92de022014-04-29 16:25:26 +0000571 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
572 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000573 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
574 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000575}
576
Guy Benyei11169dd2012-12-18 14:30:41 +0000577/// \brief Collect the macro definitions provided by the given preprocessor
578/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000579static void
580collectMacroDefinitions(const PreprocessorOptions &PPOpts,
581 MacroDefinitionsMap &Macros,
582 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000583 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
584 StringRef Macro = PPOpts.Macros[I].first;
585 bool IsUndef = PPOpts.Macros[I].second;
586
587 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
588 StringRef MacroName = MacroPair.first;
589 StringRef MacroBody = MacroPair.second;
590
591 // For an #undef'd macro, we only care about the name.
592 if (IsUndef) {
593 if (MacroNames && !Macros.count(MacroName))
594 MacroNames->push_back(MacroName);
595
596 Macros[MacroName] = std::make_pair("", true);
597 continue;
598 }
599
600 // For a #define'd macro, figure out the actual definition.
601 if (MacroName.size() == Macro.size())
602 MacroBody = "1";
603 else {
604 // Note: GCC drops anything following an end-of-line character.
605 StringRef::size_type End = MacroBody.find_first_of("\n\r");
606 MacroBody = MacroBody.substr(0, End);
607 }
608
609 if (MacroNames && !Macros.count(MacroName))
610 MacroNames->push_back(MacroName);
611 Macros[MacroName] = std::make_pair(MacroBody, false);
612 }
613}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000614
Guy Benyei11169dd2012-12-18 14:30:41 +0000615/// \brief Check the preprocessor options deserialized from the control block
616/// against the preprocessor options in an existing preprocessor.
617///
618/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000619/// \param Validate If true, validate preprocessor options. If false, allow
620/// macros defined by \p ExistingPPOpts to override those defined by
621/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000622static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
623 const PreprocessorOptions &ExistingPPOpts,
624 DiagnosticsEngine *Diags,
625 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000626 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000627 const LangOptions &LangOpts,
628 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000629 // Check macro definitions.
630 MacroDefinitionsMap ASTFileMacros;
631 collectMacroDefinitions(PPOpts, ASTFileMacros);
632 MacroDefinitionsMap ExistingMacros;
633 SmallVector<StringRef, 4> ExistingMacroNames;
634 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
635
636 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
637 // Dig out the macro definition in the existing preprocessor options.
638 StringRef MacroName = ExistingMacroNames[I];
639 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
640
641 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000642 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
643 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000644 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 // FIXME: Check whether this identifier was referenced anywhere in the
646 // AST file. If so, we should reject the AST file. Unfortunately, this
647 // information isn't in the control block. What shall we do about it?
648
649 if (Existing.second) {
650 SuggestedPredefines += "#undef ";
651 SuggestedPredefines += MacroName.str();
652 SuggestedPredefines += '\n';
653 } else {
654 SuggestedPredefines += "#define ";
655 SuggestedPredefines += MacroName.str();
656 SuggestedPredefines += ' ';
657 SuggestedPredefines += Existing.first.str();
658 SuggestedPredefines += '\n';
659 }
660 continue;
661 }
662
663 // If the macro was defined in one but undef'd in the other, we have a
664 // conflict.
665 if (Existing.second != Known->second.second) {
666 if (Diags) {
667 Diags->Report(diag::err_pch_macro_def_undef)
668 << MacroName << Known->second.second;
669 }
670 return true;
671 }
672
673 // If the macro was #undef'd in both, or if the macro bodies are identical,
674 // it's fine.
675 if (Existing.second || Existing.first == Known->second.first)
676 continue;
677
678 // The macro bodies differ; complain.
679 if (Diags) {
680 Diags->Report(diag::err_pch_macro_def_conflict)
681 << MacroName << Known->second.first << Existing.first;
682 }
683 return true;
684 }
685
686 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000687 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000688 if (Diags) {
689 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
690 }
691 return true;
692 }
693
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000694 // Detailed record is important since it is used for the module cache hash.
695 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000696 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000697 if (Diags) {
698 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
699 }
700 return true;
701 }
702
Guy Benyei11169dd2012-12-18 14:30:41 +0000703 // Compute the #include and #include_macros lines we need.
704 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
705 StringRef File = ExistingPPOpts.Includes[I];
706 if (File == ExistingPPOpts.ImplicitPCHInclude)
707 continue;
708
709 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
710 != PPOpts.Includes.end())
711 continue;
712
713 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000714 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000715 SuggestedPredefines += "\"\n";
716 }
717
718 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
719 StringRef File = ExistingPPOpts.MacroIncludes[I];
720 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
721 File)
722 != PPOpts.MacroIncludes.end())
723 continue;
724
725 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000726 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 SuggestedPredefines += "\"\n##\n";
728 }
729
730 return false;
731}
732
733bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
734 bool Complain,
735 std::string &SuggestedPredefines) {
736 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
737
738 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000739 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000740 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000741 SuggestedPredefines,
742 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000743}
744
Yaxun Liu43712e02016-09-07 18:40:20 +0000745bool SimpleASTReaderListener::ReadPreprocessorOptions(
746 const PreprocessorOptions &PPOpts,
747 bool Complain,
748 std::string &SuggestedPredefines) {
749 return checkPreprocessorOptions(PPOpts,
750 PP.getPreprocessorOpts(),
751 nullptr,
752 PP.getFileManager(),
753 SuggestedPredefines,
754 PP.getLangOpts(),
755 false);
756}
757
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000758/// Check the header search options deserialized from the control block
759/// against the header search options in an existing preprocessor.
760///
761/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
762static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
763 StringRef SpecificModuleCachePath,
764 StringRef ExistingModuleCachePath,
765 DiagnosticsEngine *Diags,
766 const LangOptions &LangOpts) {
767 if (LangOpts.Modules) {
768 if (SpecificModuleCachePath != ExistingModuleCachePath) {
769 if (Diags)
770 Diags->Report(diag::err_pch_modulecache_mismatch)
771 << SpecificModuleCachePath << ExistingModuleCachePath;
772 return true;
773 }
774 }
775
776 return false;
777}
778
779bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
780 StringRef SpecificModuleCachePath,
781 bool Complain) {
782 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
783 PP.getHeaderSearchInfo().getModuleCachePath(),
784 Complain ? &Reader.Diags : nullptr,
785 PP.getLangOpts());
786}
787
Guy Benyei11169dd2012-12-18 14:30:41 +0000788void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
789 PP.setCounterValue(Value);
790}
791
792//===----------------------------------------------------------------------===//
793// AST reader implementation
794//===----------------------------------------------------------------------===//
795
Nico Weber824285e2014-05-08 04:26:47 +0000796void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
797 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000798 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000799 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000800}
801
Guy Benyei11169dd2012-12-18 14:30:41 +0000802unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
803 return serialization::ComputeHash(Sel);
804}
805
Guy Benyei11169dd2012-12-18 14:30:41 +0000806std::pair<unsigned, unsigned>
807ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000808 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000809
Justin Bogner57ba0b22014-03-28 22:03:24 +0000810 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
811 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000812 return std::make_pair(KeyLen, DataLen);
813}
814
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000815ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000816ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000817 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000818
Guy Benyei11169dd2012-12-18 14:30:41 +0000819 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
821 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
822 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000823 if (N == 0)
824 return SelTable.getNullarySelector(FirstII);
825 else if (N == 1)
826 return SelTable.getUnarySelector(FirstII);
827
828 SmallVector<IdentifierInfo *, 16> Args;
829 Args.push_back(FirstII);
830 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000831 Args.push_back(Reader.getLocalIdentifier(
832 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000833
834 return SelTable.getSelector(N, Args.data());
835}
836
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000837ASTSelectorLookupTrait::data_type
838ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000839 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000840 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000841
842 data_type Result;
843
Justin Bogner57ba0b22014-03-28 22:03:24 +0000844 Result.ID = Reader.getGlobalSelectorID(
845 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000846 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
847 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
848 Result.InstanceBits = FullInstanceBits & 0x3;
849 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
850 Result.FactoryBits = FullFactoryBits & 0x3;
851 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
852 unsigned NumInstanceMethods = FullInstanceBits >> 3;
853 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000854
855 // Load instance methods
856 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000857 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
858 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000859 Result.Instance.push_back(Method);
860 }
861
862 // Load factory methods
863 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000864 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
865 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 Result.Factory.push_back(Method);
867 }
868
869 return Result;
870}
871
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000872unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
873 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000874}
875
876std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000877ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000878 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000879
Justin Bogner57ba0b22014-03-28 22:03:24 +0000880 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
881 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000882 return std::make_pair(KeyLen, DataLen);
883}
884
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000885ASTIdentifierLookupTraitBase::internal_key_type
886ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000887 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000888 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000889}
890
Douglas Gregordcf25082013-02-11 18:16:18 +0000891/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000892static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
893 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000894 return II.hadMacroDefinition() ||
895 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000896 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000897 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000898 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Richard Smitha534a312015-07-21 23:54:07 +0000899 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000900}
901
Richard Smith76c2f2c2015-07-17 20:09:43 +0000902static bool readBit(unsigned &Bits) {
903 bool Value = Bits & 0x1;
904 Bits >>= 1;
905 return Value;
906}
907
Richard Smith79bf9202015-08-24 03:33:22 +0000908IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
909 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000910
Richard Smith79bf9202015-08-24 03:33:22 +0000911 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
912 return Reader.getGlobalIdentifierID(F, RawID >> 1);
913}
914
Richard Smitheb4b58f62016-02-05 01:40:54 +0000915static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
916 if (!II.isFromAST()) {
917 II.setIsFromAST();
918 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
919 if (isInterestingIdentifier(Reader, II, IsModule))
920 II.setChangedSinceDeserialization();
921 }
922}
923
Guy Benyei11169dd2012-12-18 14:30:41 +0000924IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
925 const unsigned char* d,
926 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000927 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000928
Justin Bogner57ba0b22014-03-28 22:03:24 +0000929 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000930 bool IsInteresting = RawID & 0x01;
931
932 // Wipe out the "is interesting" bit.
933 RawID = RawID >> 1;
934
Richard Smith76c2f2c2015-07-17 20:09:43 +0000935 // Build the IdentifierInfo and link the identifier ID with it.
936 IdentifierInfo *II = KnownII;
937 if (!II) {
938 II = &Reader.getIdentifierTable().getOwn(k);
939 KnownII = II;
940 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000941 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000942 Reader.markIdentifierUpToDate(II);
943
Guy Benyei11169dd2012-12-18 14:30:41 +0000944 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
945 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000946 // For uninteresting identifiers, there's nothing else to do. Just notify
947 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000948 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000949 return II;
950 }
951
Justin Bogner57ba0b22014-03-28 22:03:24 +0000952 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
953 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000954 bool CPlusPlusOperatorKeyword = readBit(Bits);
955 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000956 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000957 bool Poisoned = readBit(Bits);
958 bool ExtensionToken = readBit(Bits);
959 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000960
961 assert(Bits == 0 && "Extra bits in the identifier?");
962 DataLen -= 8;
963
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 // Set or check the various bits in the IdentifierInfo structure.
965 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000966 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000967 II->revertTokenIDToIdentifier();
968 if (!F.isModule())
969 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
970 else if (HasRevertedBuiltin && II->getBuiltinID()) {
971 II->revertBuiltin();
972 assert((II->hasRevertedBuiltin() ||
973 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
974 "Incorrect ObjC keyword or builtin ID");
975 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 assert(II->isExtensionToken() == ExtensionToken &&
977 "Incorrect extension token flag");
978 (void)ExtensionToken;
979 if (Poisoned)
980 II->setIsPoisoned(true);
981 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
982 "Incorrect C++ operator keyword flag");
983 (void)CPlusPlusOperatorKeyword;
984
985 // If this identifier is a macro, deserialize the macro
986 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000987 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000988 uint32_t MacroDirectivesOffset =
989 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000990 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000991
Richard Smithd7329392015-04-21 21:46:32 +0000992 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 }
994
995 Reader.SetIdentifierInfo(ID, II);
996
997 // Read all of the declarations visible at global scope with this
998 // name.
999 if (DataLen > 0) {
1000 SmallVector<uint32_t, 4> DeclIDs;
1001 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001002 DeclIDs.push_back(Reader.getGlobalDeclID(
1003 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001004 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1005 }
1006
1007 return II;
1008}
1009
Richard Smitha06c7e62015-08-26 23:55:49 +00001010DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1011 : Kind(Name.getNameKind()) {
1012 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001013 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001014 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 break;
1016 case DeclarationName::ObjCZeroArgSelector:
1017 case DeclarationName::ObjCOneArgSelector:
1018 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001019 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001020 break;
1021 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001022 Data = Name.getCXXOverloadedOperator();
1023 break;
1024 case DeclarationName::CXXLiteralOperatorName:
1025 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1026 break;
Richard Smith35845152017-02-07 01:37:30 +00001027 case DeclarationName::CXXDeductionGuideName:
1028 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1029 ->getDeclName().getAsIdentifierInfo();
1030 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 case DeclarationName::CXXConstructorName:
1032 case DeclarationName::CXXDestructorName:
1033 case DeclarationName::CXXConversionFunctionName:
1034 case DeclarationName::CXXUsingDirective:
1035 Data = 0;
1036 break;
1037 }
1038}
1039
1040unsigned DeclarationNameKey::getHash() const {
1041 llvm::FoldingSetNodeID ID;
1042 ID.AddInteger(Kind);
1043
1044 switch (Kind) {
1045 case DeclarationName::Identifier:
1046 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001047 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001048 ID.AddString(((IdentifierInfo*)Data)->getName());
1049 break;
1050 case DeclarationName::ObjCZeroArgSelector:
1051 case DeclarationName::ObjCOneArgSelector:
1052 case DeclarationName::ObjCMultiArgSelector:
1053 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1054 break;
1055 case DeclarationName::CXXOperatorName:
1056 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001057 break;
1058 case DeclarationName::CXXConstructorName:
1059 case DeclarationName::CXXDestructorName:
1060 case DeclarationName::CXXConversionFunctionName:
1061 case DeclarationName::CXXUsingDirective:
1062 break;
1063 }
1064
1065 return ID.ComputeHash();
1066}
1067
Richard Smithd88a7f12015-09-01 20:35:42 +00001068ModuleFile *
1069ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1070 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001071
Richard Smithd88a7f12015-09-01 20:35:42 +00001072 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1073 return Reader.getLocalModuleFile(F, ModuleFileID);
1074}
1075
Guy Benyei11169dd2012-12-18 14:30:41 +00001076std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001077ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001078 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001079
Justin Bogner57ba0b22014-03-28 22:03:24 +00001080 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1081 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001082 return std::make_pair(KeyLen, DataLen);
1083}
1084
Richard Smitha06c7e62015-08-26 23:55:49 +00001085ASTDeclContextNameLookupTrait::internal_key_type
1086ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001087 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001088
Richard Smitha06c7e62015-08-26 23:55:49 +00001089 auto Kind = (DeclarationName::NameKind)*d++;
1090 uint64_t Data;
1091 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001092 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001093 case DeclarationName::CXXLiteralOperatorName:
1094 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001095 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001096 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 break;
1098 case DeclarationName::ObjCZeroArgSelector:
1099 case DeclarationName::ObjCOneArgSelector:
1100 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001101 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001102 (uint64_t)Reader.getLocalSelector(
1103 F, endian::readNext<uint32_t, little, unaligned>(
1104 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 break;
1106 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001107 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 case DeclarationName::CXXConstructorName:
1110 case DeclarationName::CXXDestructorName:
1111 case DeclarationName::CXXConversionFunctionName:
1112 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001113 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 break;
1115 }
1116
Richard Smitha06c7e62015-08-26 23:55:49 +00001117 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001118}
1119
Richard Smithd88a7f12015-09-01 20:35:42 +00001120void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1121 const unsigned char *d,
1122 unsigned DataLen,
1123 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001124 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001125
Richard Smithd88a7f12015-09-01 20:35:42 +00001126 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1127 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1128 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1129 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001130}
1131
Richard Smith0f4e2c42015-08-06 04:23:48 +00001132bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1133 BitstreamCursor &Cursor,
1134 uint64_t Offset,
1135 DeclContext *DC) {
1136 assert(Offset != 0);
1137
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001139 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001140
Richard Smith0f4e2c42015-08-06 04:23:48 +00001141 RecordData Record;
1142 StringRef Blob;
1143 unsigned Code = Cursor.ReadCode();
1144 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1145 if (RecCode != DECL_CONTEXT_LEXICAL) {
1146 Error("Expected lexical block");
1147 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001148 }
1149
Richard Smith82f8fcd2015-08-06 22:07:25 +00001150 assert(!isa<TranslationUnitDecl>(DC) &&
1151 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001152 // If we are handling a C++ class template instantiation, we can see multiple
1153 // lexical updates for the same record. It's important that we select only one
1154 // of them, so that field numbering works properly. Just pick the first one we
1155 // see.
1156 auto &Lex = LexicalDecls[DC];
1157 if (!Lex.first) {
1158 Lex = std::make_pair(
1159 &M, llvm::makeArrayRef(
1160 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1161 Blob.data()),
1162 Blob.size() / 4));
1163 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001164 DC->setHasExternalLexicalStorage(true);
1165 return false;
1166}
Guy Benyei11169dd2012-12-18 14:30:41 +00001167
Richard Smith0f4e2c42015-08-06 04:23:48 +00001168bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1169 BitstreamCursor &Cursor,
1170 uint64_t Offset,
1171 DeclID ID) {
1172 assert(Offset != 0);
1173
1174 SavedStreamPosition SavedPosition(Cursor);
1175 Cursor.JumpToBit(Offset);
1176
1177 RecordData Record;
1178 StringRef Blob;
1179 unsigned Code = Cursor.ReadCode();
1180 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1181 if (RecCode != DECL_CONTEXT_VISIBLE) {
1182 Error("Expected visible lookup table block");
1183 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001184 }
1185
Richard Smith0f4e2c42015-08-06 04:23:48 +00001186 // We can't safely determine the primary context yet, so delay attaching the
1187 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001188 auto *Data = (const unsigned char*)Blob.data();
1189 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 return false;
1191}
1192
Richard Smith37a93df2017-02-18 00:32:02 +00001193void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001195 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001196 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001197 Diag(diag::note_module_cache_path)
1198 << PP.getHeaderSearchInfo().getModuleCachePath();
1199 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001200}
1201
1202void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001203 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001204 if (Diags.isDiagnosticInFlight())
1205 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1206 else
1207 Diag(DiagID) << Arg1 << Arg2;
1208}
1209
1210//===----------------------------------------------------------------------===//
1211// Source Manager Deserialization
1212//===----------------------------------------------------------------------===//
1213
1214/// \brief Read the line table in the source manager block.
1215/// \returns true if there was an error.
1216bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001217 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 unsigned Idx = 0;
1219 LineTableInfo &LineTable = SourceMgr.getLineTable();
1220
1221 // Parse the file names
1222 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001223 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001224 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001225 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001226 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001227 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1228 }
Richard Smith63078492015-09-01 07:41:55 +00001229 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001230
1231 // Parse the line entries
1232 std::vector<LineEntry> Entries;
1233 while (Idx < Record.size()) {
1234 int FID = Record[Idx++];
1235 assert(FID >= 0 && "Serialized line entries for non-local file.");
1236 // Remap FileID from 1-based old view.
1237 FID += F.SLocEntryBaseID - 1;
1238
1239 // Extract the line entries
1240 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001241 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001242 Entries.clear();
1243 Entries.reserve(NumEntries);
1244 for (unsigned I = 0; I != NumEntries; ++I) {
1245 unsigned FileOffset = Record[Idx++];
1246 unsigned LineNo = Record[Idx++];
1247 int FilenameID = FileIDs[Record[Idx++]];
1248 SrcMgr::CharacteristicKind FileKind
1249 = (SrcMgr::CharacteristicKind)Record[Idx++];
1250 unsigned IncludeOffset = Record[Idx++];
1251 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1252 FileKind, IncludeOffset));
1253 }
1254 LineTable.AddEntry(FileID::get(FID), Entries);
1255 }
1256
1257 return false;
1258}
1259
1260/// \brief Read a source manager block
1261bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1262 using namespace SrcMgr;
1263
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001264 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001265
1266 // Set the source-location entry cursor to the current position in
1267 // the stream. This cursor will be used to read the contents of the
1268 // source manager block initially, and then lazily read
1269 // source-location entries as needed.
1270 SLocEntryCursor = F.Stream;
1271
1272 // The stream itself is going to skip over the source manager block.
1273 if (F.Stream.SkipBlock()) {
1274 Error("malformed block record in AST file");
1275 return true;
1276 }
1277
1278 // Enter the source manager block.
1279 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1280 Error("malformed source manager block record in AST file");
1281 return true;
1282 }
1283
1284 RecordData Record;
1285 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001286 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001287
Chris Lattnere7b154b2013-01-19 21:39:22 +00001288 switch (E.Kind) {
1289 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1290 case llvm::BitstreamEntry::Error:
1291 Error("malformed block record in AST file");
1292 return true;
1293 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001295 case llvm::BitstreamEntry::Record:
1296 // The interesting case.
1297 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001298 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001299
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001302 StringRef Blob;
1303 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001304 default: // Default behavior: ignore.
1305 break;
1306
1307 case SM_SLOC_FILE_ENTRY:
1308 case SM_SLOC_BUFFER_ENTRY:
1309 case SM_SLOC_EXPANSION_ENTRY:
1310 // Once we hit one of the source location entries, we're done.
1311 return false;
1312 }
1313 }
1314}
1315
1316/// \brief If a header file is not found at the path that we expect it to be
1317/// and the PCH file was moved from its original location, try to resolve the
1318/// file by assuming that header+PCH were moved together and the header is in
1319/// the same place relative to the PCH.
1320static std::string
1321resolveFileRelativeToOriginalDir(const std::string &Filename,
1322 const std::string &OriginalDir,
1323 const std::string &CurrDir) {
1324 assert(OriginalDir != CurrDir &&
1325 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001326
Guy Benyei11169dd2012-12-18 14:30:41 +00001327 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001328
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 SmallString<128> filePath(Filename);
1330 fs::make_absolute(filePath);
1331 assert(path::is_absolute(OriginalDir));
1332 SmallString<128> currPCHPath(CurrDir);
1333
1334 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1335 fileDirE = path::end(path::parent_path(filePath));
1336 path::const_iterator origDirI = path::begin(OriginalDir),
1337 origDirE = path::end(OriginalDir);
1338 // Skip the common path components from filePath and OriginalDir.
1339 while (fileDirI != fileDirE && origDirI != origDirE &&
1340 *fileDirI == *origDirI) {
1341 ++fileDirI;
1342 ++origDirI;
1343 }
1344 for (; origDirI != origDirE; ++origDirI)
1345 path::append(currPCHPath, "..");
1346 path::append(currPCHPath, fileDirI, fileDirE);
1347 path::append(currPCHPath, path::filename(Filename));
1348 return currPCHPath.str();
1349}
1350
1351bool ASTReader::ReadSLocEntry(int ID) {
1352 if (ID == 0)
1353 return false;
1354
1355 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1356 Error("source location entry ID out-of-range for AST file");
1357 return true;
1358 }
1359
Richard Smithaada85c2016-02-06 02:06:43 +00001360 // Local helper to read the (possibly-compressed) buffer data following the
1361 // entry record.
1362 auto ReadBuffer = [this](
1363 BitstreamCursor &SLocEntryCursor,
1364 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1365 RecordData Record;
1366 StringRef Blob;
1367 unsigned Code = SLocEntryCursor.ReadCode();
1368 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1369
1370 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001371 if (!llvm::zlib::isAvailable()) {
1372 Error("zlib is not available");
1373 return nullptr;
1374 }
Richard Smithaada85c2016-02-06 02:06:43 +00001375 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001376 if (llvm::Error E =
1377 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1378 Error("could not decompress embedded file contents: " +
1379 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001380 return nullptr;
1381 }
1382 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1383 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1384 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1385 } else {
1386 Error("AST record has invalid code");
1387 return nullptr;
1388 }
1389 };
1390
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1392 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001393 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 unsigned BaseOffset = F->SLocEntryBaseOffset;
1395
1396 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001397 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1398 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 Error("incorrectly-formatted source location entry in AST file");
1400 return true;
1401 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001402
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001404 StringRef Blob;
1405 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 default:
1407 Error("incorrectly-formatted source location entry in AST file");
1408 return true;
1409
1410 case SM_SLOC_FILE_ENTRY: {
1411 // We will detect whether a file changed and return 'Failure' for it, but
1412 // we will also try to fail gracefully by setting up the SLocEntry.
1413 unsigned InputID = Record[4];
1414 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001415 const FileEntry *File = IF.getFile();
1416 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001417
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001418 // Note that we only check if a File was returned. If it was out-of-date
1419 // we have complained but we will continue creating a FileID to recover
1420 // gracefully.
1421 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 return true;
1423
1424 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1425 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1426 // This is the module's main file.
1427 IncludeLoc = getImportLocation(F);
1428 }
1429 SrcMgr::CharacteristicKind
1430 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1431 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1432 ID, BaseOffset + Record[0]);
1433 SrcMgr::FileInfo &FileInfo =
1434 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1435 FileInfo.NumCreatedFIDs = Record[5];
1436 if (Record[3])
1437 FileInfo.setHasLineDirectives();
1438
1439 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1440 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001441 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1443 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1444 NumFileDecls));
1445 }
Richard Smithaada85c2016-02-06 02:06:43 +00001446
Guy Benyei11169dd2012-12-18 14:30:41 +00001447 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001448 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001449 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001450 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1451 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001452 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1453 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001455 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001456 }
1457
1458 break;
1459 }
1460
1461 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001462 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001463 unsigned Offset = Record[0];
1464 SrcMgr::CharacteristicKind
1465 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1466 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001467 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 IncludeLoc = getImportLocation(F);
1469 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001470
Richard Smithaada85c2016-02-06 02:06:43 +00001471 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1472 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001474 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001475 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001476 break;
1477 }
1478
1479 case SM_SLOC_EXPANSION_ENTRY: {
1480 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1481 SourceMgr.createExpansionLoc(SpellingLoc,
1482 ReadSourceLocation(*F, Record[2]),
1483 ReadSourceLocation(*F, Record[3]),
1484 Record[4],
1485 ID,
1486 BaseOffset + Record[0]);
1487 break;
1488 }
1489 }
1490
1491 return false;
1492}
1493
1494std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1495 if (ID == 0)
1496 return std::make_pair(SourceLocation(), "");
1497
1498 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1499 Error("source location entry ID out-of-range for AST file");
1500 return std::make_pair(SourceLocation(), "");
1501 }
1502
1503 // Find which module file this entry lands in.
1504 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001505 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001506 return std::make_pair(SourceLocation(), "");
1507
1508 // FIXME: Can we map this down to a particular submodule? That would be
1509 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001510 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001511}
1512
1513/// \brief Find the location where the module F is imported.
1514SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1515 if (F->ImportLoc.isValid())
1516 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001517
Guy Benyei11169dd2012-12-18 14:30:41 +00001518 // Otherwise we have a PCH. It's considered to be "imported" at the first
1519 // location of its includer.
1520 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001521 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001522 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001523 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001525 return F->ImportedBy[0]->FirstLoc;
1526}
1527
1528/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1529/// specified cursor. Read the abbreviations that are at the top of the block
1530/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001531bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001532 if (Cursor.EnterSubBlock(BlockID))
1533 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001534
1535 while (true) {
1536 uint64_t Offset = Cursor.GetCurrentBitNo();
1537 unsigned Code = Cursor.ReadCode();
1538
1539 // We expect all abbrevs to be at the start of the block.
1540 if (Code != llvm::bitc::DEFINE_ABBREV) {
1541 Cursor.JumpToBit(Offset);
1542 return false;
1543 }
1544 Cursor.ReadAbbrevRecord();
1545 }
1546}
1547
Richard Smithe40f2ba2013-08-07 21:41:30 +00001548Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001549 unsigned &Idx) {
1550 Token Tok;
1551 Tok.startToken();
1552 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1553 Tok.setLength(Record[Idx++]);
1554 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1555 Tok.setIdentifierInfo(II);
1556 Tok.setKind((tok::TokenKind)Record[Idx++]);
1557 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1558 return Tok;
1559}
1560
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001561MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001562 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001563
1564 // Keep track of where we are in the stream, then jump back there
1565 // after reading this macro.
1566 SavedStreamPosition SavedPosition(Stream);
1567
1568 Stream.JumpToBit(Offset);
1569 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001570 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001571 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001572
Guy Benyei11169dd2012-12-18 14:30:41 +00001573 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001574 // Advance to the next record, but if we get to the end of the block, don't
1575 // pop it (removing all the abbreviations from the cursor) since we want to
1576 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001577 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001578 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001579
Chris Lattnerefa77172013-01-20 00:00:22 +00001580 switch (Entry.Kind) {
1581 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1582 case llvm::BitstreamEntry::Error:
1583 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001584 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001585 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001586 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001587 case llvm::BitstreamEntry::Record:
1588 // The interesting case.
1589 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001590 }
1591
1592 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 Record.clear();
1594 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001595 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001596 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001597 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001598 case PP_MACRO_DIRECTIVE_HISTORY:
1599 return Macro;
1600
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 case PP_MACRO_OBJECT_LIKE:
1602 case PP_MACRO_FUNCTION_LIKE: {
1603 // If we already have a macro, that means that we've hit the end
1604 // of the definition of the macro we were looking for. We're
1605 // done.
1606 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001607 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001608
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001609 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001610 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001611 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001612 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001614 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001615
Guy Benyei11169dd2012-12-18 14:30:41 +00001616 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1617 // Decode function-like macro info.
1618 bool isC99VarArgs = Record[NextIndex++];
1619 bool isGNUVarArgs = Record[NextIndex++];
1620 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001621 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001622 unsigned NumArgs = Record[NextIndex++];
1623 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001624 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001625
1626 // Install function-like macro info.
1627 MI->setIsFunctionLike();
1628 if (isC99VarArgs) MI->setIsC99Varargs();
1629 if (isGNUVarArgs) MI->setIsGNUVarargs();
1630 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001631 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 }
1633
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 // Remember that we saw this macro last so that we add the tokens that
1635 // form its body to it.
1636 Macro = MI;
1637
1638 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1639 Record[NextIndex]) {
1640 // We have a macro definition. Register the association
1641 PreprocessedEntityID
1642 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1643 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001644 PreprocessingRecord::PPEntityID PPID =
1645 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1646 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1647 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001648 if (PPDef)
1649 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 }
1651
1652 ++NumMacrosRead;
1653 break;
1654 }
1655
1656 case PP_TOKEN: {
1657 // If we see a TOKEN before a PP_MACRO_*, then the file is
1658 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001659 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001660
John McCallf413f5e2013-05-03 00:10:13 +00001661 unsigned Idx = 0;
1662 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001663 Macro->AddTokenToBody(Tok);
1664 break;
1665 }
1666 }
1667 }
1668}
1669
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001670PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001671ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1672 unsigned LocalID) const {
1673 if (!M.ModuleOffsetMap.empty())
1674 ReadModuleOffsetMap(M);
1675
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001676 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001677 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001678 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001680
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 return LocalID + I->second;
1682}
1683
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001684unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1685 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001686}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001687
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001688HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001689HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001690 internal_key_type ikey = {FE->getSize(),
1691 M.HasTimestamps ? FE->getModificationTime() : 0,
1692 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001693 return ikey;
1694}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001695
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001696bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001697 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001698 return false;
1699
Mehdi Amini004b9c72016-10-10 22:52:47 +00001700 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001701 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001702
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001704 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001705 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1706 if (!Key.Imported)
1707 return FileMgr.getFile(Key.Filename);
1708
1709 std::string Resolved = Key.Filename;
1710 Reader.ResolveImportedPath(M, Resolved);
1711 return FileMgr.getFile(Resolved);
1712 };
1713
1714 const FileEntry *FEA = GetFile(a);
1715 const FileEntry *FEB = GetFile(b);
1716 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001717}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001718
Guy Benyei11169dd2012-12-18 14:30:41 +00001719std::pair<unsigned, unsigned>
1720HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001721 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001722
Justin Bogner57ba0b22014-03-28 22:03:24 +00001723 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001724 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001725 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001726}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001727
1728HeaderFileInfoTrait::internal_key_type
1729HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001730 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001731
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001732 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001733 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1734 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001735 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001736 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001737 return ikey;
1738}
1739
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001740HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001741HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001742 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001743 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001744
1745 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001746 HeaderFileInfo HFI;
1747 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001748 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001749 HFI.isImport |= (Flags >> 5) & 0x01;
1750 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1751 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001752 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001753 // FIXME: Find a better way to handle this. Maybe just store a
1754 // "has been included" flag?
1755 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1756 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001757 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1758 M, endian::readNext<uint32_t, little, unaligned>(d));
1759 if (unsigned FrameworkOffset =
1760 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001761 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001762 // since 0 is used as an indicator for "no framework name".
1763 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1764 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1765 }
Richard Smith386bb072015-08-18 23:42:23 +00001766
1767 assert((End - d) % 4 == 0 &&
1768 "Wrong data length in HeaderFileInfo deserialization");
1769 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001770 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001771 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1772 LocalSMID >>= 2;
1773
1774 // This header is part of a module. Associate it with the module to enable
1775 // implicit module import.
1776 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1777 Module *Mod = Reader.getSubmodule(GlobalSMID);
1778 FileManager &FileMgr = Reader.getFileManager();
1779 ModuleMap &ModMap =
1780 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1781
1782 std::string Filename = key.Filename;
1783 if (key.Imported)
1784 Reader.ResolveImportedPath(M, Filename);
1785 // FIXME: This is not always the right filename-as-written, but we're not
1786 // going to use this information to rebuild the module, so it doesn't make
1787 // a lot of difference.
1788 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001789 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1790 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001791 }
1792
Guy Benyei11169dd2012-12-18 14:30:41 +00001793 // This HeaderFileInfo was externally loaded.
1794 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001795 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 return HFI;
1797}
1798
Richard Smithd7329392015-04-21 21:46:32 +00001799void ASTReader::addPendingMacro(IdentifierInfo *II,
1800 ModuleFile *M,
1801 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001802 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1803 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001804}
1805
1806void ASTReader::ReadDefinedMacros() {
1807 // Note that we are loading defined macros.
1808 Deserializing Macros(this);
1809
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001810 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1811 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001812
1813 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001814 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001815 continue;
1816
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001817 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001818 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001819
1820 RecordData Record;
1821 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001822 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001823
Chris Lattnere7b154b2013-01-19 21:39:22 +00001824 switch (E.Kind) {
1825 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1826 case llvm::BitstreamEntry::Error:
1827 Error("malformed block record in AST file");
1828 return;
1829 case llvm::BitstreamEntry::EndBlock:
1830 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001831
Chris Lattnere7b154b2013-01-19 21:39:22 +00001832 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001833 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001834 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001835 default: // Default behavior: ignore.
1836 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001837
Chris Lattnere7b154b2013-01-19 21:39:22 +00001838 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001839 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001840 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001841 if (II->isOutOfDate())
1842 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001843 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001844 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001845
Chris Lattnere7b154b2013-01-19 21:39:22 +00001846 case PP_TOKEN:
1847 // Ignore tokens.
1848 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001850 break;
1851 }
1852 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001853 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001854 }
1855}
1856
1857namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001858
Guy Benyei11169dd2012-12-18 14:30:41 +00001859 /// \brief Visitor class used to look up identifirs in an AST file.
1860 class IdentifierLookupVisitor {
1861 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001862 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001863 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001864 unsigned &NumIdentifierLookups;
1865 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001866 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001867
Guy Benyei11169dd2012-12-18 14:30:41 +00001868 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001869 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1870 unsigned &NumIdentifierLookups,
1871 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001872 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1873 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001874 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001875 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001876
1877 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001878 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001879 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001881
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 ASTIdentifierLookupTable *IdTable
1883 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1884 if (!IdTable)
1885 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001886
1887 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001888 Found);
1889 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001890 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001891 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 if (Pos == IdTable->end())
1893 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001894
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 // Dereferencing the iterator has the effect of building the
1896 // IdentifierInfo node and populating it with the various
1897 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001898 ++NumIdentifierLookupHits;
1899 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001900 return true;
1901 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001902
Guy Benyei11169dd2012-12-18 14:30:41 +00001903 // \brief Retrieve the identifier info found within the module
1904 // files.
1905 IdentifierInfo *getIdentifierInfo() const { return Found; }
1906 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001907
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001908} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001909
1910void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1911 // Note that we are loading an identifier.
1912 Deserializing AnIdentifier(this);
1913
1914 unsigned PriorGeneration = 0;
1915 if (getContext().getLangOpts().Modules)
1916 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001917
1918 // If there is a global index, look there first to determine which modules
1919 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001920 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001921 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001922 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001923 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1924 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001925 }
1926 }
1927
Douglas Gregor7211ac12013-01-25 23:32:03 +00001928 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001929 NumIdentifierLookups,
1930 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001931 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 markIdentifierUpToDate(&II);
1933}
1934
1935void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1936 if (!II)
1937 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001938
Guy Benyei11169dd2012-12-18 14:30:41 +00001939 II->setOutOfDate(false);
1940
1941 // Update the generation for this identifier.
1942 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001943 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001944}
1945
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001946void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1947 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001948 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001949
1950 BitstreamCursor &Cursor = M.MacroCursor;
1951 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001952 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001953
Richard Smith713369b2015-04-23 20:40:50 +00001954 struct ModuleMacroRecord {
1955 SubmoduleID SubModID;
1956 MacroInfo *MI;
1957 SmallVector<SubmoduleID, 8> Overrides;
1958 };
1959 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001960
Richard Smithd7329392015-04-21 21:46:32 +00001961 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1962 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1963 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001964 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001965 while (true) {
1966 llvm::BitstreamEntry Entry =
1967 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1968 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1969 Error("malformed block record in AST file");
1970 return;
1971 }
1972
1973 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001974 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001975 case PP_MACRO_DIRECTIVE_HISTORY:
1976 break;
1977
1978 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001979 ModuleMacros.push_back(ModuleMacroRecord());
1980 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001981 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1982 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001983 for (int I = 2, N = Record.size(); I != N; ++I)
1984 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001985 continue;
1986 }
1987
1988 default:
1989 Error("malformed block record in AST file");
1990 return;
1991 }
1992
1993 // We found the macro directive history; that's the last record
1994 // for this macro.
1995 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001996 }
1997
Richard Smithd7329392015-04-21 21:46:32 +00001998 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001999 {
2000 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002001 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002002 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002003 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00002004 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002005 Module *Mod = getSubmodule(ModID);
2006 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002007 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002008 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002009 }
2010
2011 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002012 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002013 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002014 }
2015 }
2016
2017 // Don't read the directive history for a module; we don't have anywhere
2018 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002019 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002020 return;
2021
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002022 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002023 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002024 unsigned Idx = 0, N = Record.size();
2025 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002026 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002027 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002028 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2029 switch (K) {
2030 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002031 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002032 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002033 break;
2034 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002035 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002036 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002037 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002038 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002039 bool isPublic = Record[Idx++];
2040 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2041 break;
2042 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002043
2044 if (!Latest)
2045 Latest = MD;
2046 if (Earliest)
2047 Earliest->setPrevious(MD);
2048 Earliest = MD;
2049 }
2050
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002051 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002052 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002053}
2054
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002055ASTReader::InputFileInfo
2056ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002057 // Go find this input file.
2058 BitstreamCursor &Cursor = F.InputFilesCursor;
2059 SavedStreamPosition SavedPosition(Cursor);
2060 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2061
2062 unsigned Code = Cursor.ReadCode();
2063 RecordData Record;
2064 StringRef Blob;
2065
2066 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2067 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2068 "invalid record type for input file");
2069 (void)Result;
2070
2071 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002072 InputFileInfo R;
2073 R.StoredSize = static_cast<off_t>(Record[1]);
2074 R.StoredTime = static_cast<time_t>(Record[2]);
2075 R.Overridden = static_cast<bool>(Record[3]);
2076 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002077 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002078 R.Filename = Blob;
2079 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002080 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002081}
2082
Manman Renc8c94152016-10-21 23:35:03 +00002083static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002084InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002085 // If this ID is bogus, just return an empty input file.
2086 if (ID == 0 || ID > F.InputFilesLoaded.size())
2087 return InputFile();
2088
2089 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002090 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002091 return F.InputFilesLoaded[ID-1];
2092
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002093 if (F.InputFilesLoaded[ID-1].isNotFound())
2094 return InputFile();
2095
Guy Benyei11169dd2012-12-18 14:30:41 +00002096 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002097 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 SavedStreamPosition SavedPosition(Cursor);
2099 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002100
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002101 InputFileInfo FI = readInputFileInfo(F, ID);
2102 off_t StoredSize = FI.StoredSize;
2103 time_t StoredTime = FI.StoredTime;
2104 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002105 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002106 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002107
Richard Smitha8cfffa2015-11-26 02:04:16 +00002108 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002109 // If we didn't find the file, resolve it relative to the
2110 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002111 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2112 F.OriginalDir != F.BaseDirectory) {
2113 std::string Resolved = resolveFileRelativeToOriginalDir(
2114 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002115 if (!Resolved.empty())
2116 File = FileMgr.getFile(Resolved);
2117 }
2118
2119 // For an overridden file, create a virtual file with the stored
2120 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002121 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002123
Craig Toppera13603a2014-05-22 05:54:18 +00002124 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002125 if (Complain) {
2126 std::string ErrorStr = "could not find file '";
2127 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002128 ErrorStr += "' referenced by AST file '";
2129 ErrorStr += F.FileName;
2130 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002131 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002132 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002133 // Record that we didn't find the file.
2134 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2135 return InputFile();
2136 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002137
Ben Langmuir198c1682014-03-07 07:27:49 +00002138 // Check if there was a request to override the contents of the file
2139 // that was part of the precompiled header. Overridding such a file
2140 // can lead to problems when lexing using the source locations from the
2141 // PCH.
2142 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002143 // FIXME: Reject if the overrides are different.
2144 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002145 if (Complain)
2146 Error(diag::err_fe_pch_file_overridden, Filename);
2147 // After emitting the diagnostic, recover by disabling the override so
2148 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002149 //
2150 // FIXME: This recovery is just as broken as the original state; there may
2151 // be another precompiled module that's using the overridden contents, or
2152 // we might be half way through parsing it. Instead, we should treat the
2153 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002154 SM.disableFileContentsOverride(File);
2155 // The FileEntry is a virtual file entry with the size of the contents
2156 // that would override the original contents. Set it to the original's
2157 // size/time.
2158 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2159 StoredSize, StoredTime);
2160 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002161
Ben Langmuir198c1682014-03-07 07:27:49 +00002162 bool IsOutOfDate = false;
2163
2164 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002165 if (!Overridden && //
2166 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002167 (StoredTime && StoredTime != File->getModificationTime() &&
2168 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002169 )) {
2170 if (Complain) {
2171 // Build a list of the PCH imports that got us here (in reverse).
2172 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002173 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002174 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002175
Ben Langmuir198c1682014-03-07 07:27:49 +00002176 // The top-level PCH is stale.
2177 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002178 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2179 if (DiagnosticKind == 0)
2180 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2181 else if (DiagnosticKind == 1)
2182 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2183 else
2184 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002185
Ben Langmuir198c1682014-03-07 07:27:49 +00002186 // Print the import stack.
2187 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2188 Diag(diag::note_pch_required_by)
2189 << Filename << ImportStack[0]->FileName;
2190 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002191 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002192 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002193 }
2194
Ben Langmuir198c1682014-03-07 07:27:49 +00002195 if (!Diags.isDiagnosticInFlight())
2196 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002197 }
2198
Ben Langmuir198c1682014-03-07 07:27:49 +00002199 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002200 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002201 // FIXME: If the file is overridden and we've already opened it,
2202 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002203
Richard Smitha8cfffa2015-11-26 02:04:16 +00002204 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002205
2206 // Note that we've loaded this input file.
2207 F.InputFilesLoaded[ID-1] = IF;
2208 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002209}
2210
Richard Smith7ed1bc92014-12-05 22:42:13 +00002211/// \brief If we are loading a relocatable PCH or module file, and the filename
2212/// is not an absolute path, add the system or module root to the beginning of
2213/// the file name.
2214void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2215 // Resolve relative to the base directory, if we have one.
2216 if (!M.BaseDirectory.empty())
2217 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002218}
2219
Richard Smith7ed1bc92014-12-05 22:42:13 +00002220void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2222 return;
2223
Richard Smith7ed1bc92014-12-05 22:42:13 +00002224 SmallString<128> Buffer;
2225 llvm::sys::path::append(Buffer, Prefix, Filename);
2226 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002227}
2228
Richard Smith0f99d6a2015-08-09 08:48:41 +00002229static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2230 switch (ARR) {
2231 case ASTReader::Failure: return true;
2232 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2233 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2234 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2235 case ASTReader::ConfigurationMismatch:
2236 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2237 case ASTReader::HadErrors: return true;
2238 case ASTReader::Success: return false;
2239 }
2240
2241 llvm_unreachable("unknown ASTReadResult");
2242}
2243
Richard Smith0516b182015-09-08 19:40:14 +00002244ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2245 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2246 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002247 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002248 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2249 return Failure;
2250
2251 // Read all of the records in the options block.
2252 RecordData Record;
2253 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002254 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002255 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002256
Richard Smith0516b182015-09-08 19:40:14 +00002257 switch (Entry.Kind) {
2258 case llvm::BitstreamEntry::Error:
2259 case llvm::BitstreamEntry::SubBlock:
2260 return Failure;
2261
2262 case llvm::BitstreamEntry::EndBlock:
2263 return Result;
2264
2265 case llvm::BitstreamEntry::Record:
2266 // The interesting case.
2267 break;
2268 }
2269
2270 // Read and process a record.
2271 Record.clear();
2272 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2273 case LANGUAGE_OPTIONS: {
2274 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2275 if (ParseLanguageOptions(Record, Complain, Listener,
2276 AllowCompatibleConfigurationMismatch))
2277 Result = ConfigurationMismatch;
2278 break;
2279 }
2280
2281 case TARGET_OPTIONS: {
2282 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2283 if (ParseTargetOptions(Record, Complain, Listener,
2284 AllowCompatibleConfigurationMismatch))
2285 Result = ConfigurationMismatch;
2286 break;
2287 }
2288
Richard Smith0516b182015-09-08 19:40:14 +00002289 case FILE_SYSTEM_OPTIONS: {
2290 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2291 if (!AllowCompatibleConfigurationMismatch &&
2292 ParseFileSystemOptions(Record, Complain, Listener))
2293 Result = ConfigurationMismatch;
2294 break;
2295 }
2296
2297 case HEADER_SEARCH_OPTIONS: {
2298 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2299 if (!AllowCompatibleConfigurationMismatch &&
2300 ParseHeaderSearchOptions(Record, Complain, Listener))
2301 Result = ConfigurationMismatch;
2302 break;
2303 }
2304
2305 case PREPROCESSOR_OPTIONS:
2306 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2307 if (!AllowCompatibleConfigurationMismatch &&
2308 ParsePreprocessorOptions(Record, Complain, Listener,
2309 SuggestedPredefines))
2310 Result = ConfigurationMismatch;
2311 break;
2312 }
2313 }
2314}
2315
Guy Benyei11169dd2012-12-18 14:30:41 +00002316ASTReader::ASTReadResult
2317ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002318 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002319 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002320 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002321 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002322 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002323
2324 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2325 Error("malformed block record in AST file");
2326 return Failure;
2327 }
2328
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002329 // Lambda to read the unhashed control block the first time it's called.
2330 //
2331 // For PCM files, the unhashed control block cannot be read until after the
2332 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2333 // need to look ahead before reading the IMPORTS record. For consistency,
2334 // this block is always read somehow (see BitstreamEntry::EndBlock).
2335 bool HasReadUnhashedControlBlock = false;
2336 auto readUnhashedControlBlockOnce = [&]() {
2337 if (!HasReadUnhashedControlBlock) {
2338 HasReadUnhashedControlBlock = true;
2339 if (ASTReadResult Result =
2340 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2341 return Result;
2342 }
2343 return Success;
2344 };
2345
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 // Read all of the records and blocks in the control block.
2347 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002348 unsigned NumInputs = 0;
2349 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002350 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002351 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002352
Chris Lattnere7b154b2013-01-19 21:39:22 +00002353 switch (Entry.Kind) {
2354 case llvm::BitstreamEntry::Error:
2355 Error("malformed block record in AST file");
2356 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002357 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002358 // Validate the module before returning. This call catches an AST with
2359 // no module name and no imports.
2360 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2361 return Result;
2362
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002363 // Validate input files.
2364 const HeaderSearchOptions &HSOpts =
2365 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002366
Richard Smitha1825302014-10-23 22:18:29 +00002367 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002368 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2369 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002370 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2371 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002373
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002374 // If we are reading a module, we will create a verification timestamp,
2375 // so we verify all input files. Otherwise, verify only user input
2376 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002377
2378 unsigned N = NumUserInputs;
2379 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002380 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002381 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002382 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002383 N = NumInputs;
2384
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002385 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002386 InputFile IF = getInputFile(F, I+1, Complain);
2387 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002389 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002391
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002392 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002393 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002394
Ben Langmuircb69b572014-03-07 06:40:32 +00002395 if (Listener && Listener->needsInputFileVisitation()) {
2396 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2397 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002398 for (unsigned I = 0; I < N; ++I) {
2399 bool IsSystem = I >= NumUserInputs;
2400 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002401 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002402 F.Kind == MK_ExplicitModule ||
2403 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002404 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002405 }
2406
Richard Smith8a308ec2015-11-05 00:54:55 +00002407 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002408 }
2409
Chris Lattnere7b154b2013-01-19 21:39:22 +00002410 case llvm::BitstreamEntry::SubBlock:
2411 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 case INPUT_FILES_BLOCK_ID:
2413 F.InputFilesCursor = Stream;
2414 if (Stream.SkipBlock() || // Skip with the main cursor
2415 // Read the abbreviations
2416 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2417 Error("malformed block record in AST file");
2418 return Failure;
2419 }
2420 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002421
2422 case OPTIONS_BLOCK_ID:
2423 // If we're reading the first module for this group, check its options
2424 // are compatible with ours. For modules it imports, no further checking
2425 // is required, because we checked them when we built it.
2426 if (Listener && !ImportedBy) {
2427 // Should we allow the configuration of the module file to differ from
2428 // the configuration of the current translation unit in a compatible
2429 // way?
2430 //
2431 // FIXME: Allow this for files explicitly specified with -include-pch.
2432 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002433 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002434
Richard Smith8a308ec2015-11-05 00:54:55 +00002435 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2436 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002437 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002438 if (Result == Failure) {
2439 Error("malformed block record in AST file");
2440 return Result;
2441 }
2442
Richard Smith8a308ec2015-11-05 00:54:55 +00002443 if (DisableValidation ||
2444 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2445 Result = Success;
2446
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002447 // If we can't load the module, exit early since we likely
2448 // will rebuild the module anyway. The stream may be in the
2449 // middle of a block.
2450 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002451 return Result;
2452 } else if (Stream.SkipBlock()) {
2453 Error("malformed block record in AST file");
2454 return Failure;
2455 }
2456 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002457
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002459 if (Stream.SkipBlock()) {
2460 Error("malformed block record in AST file");
2461 return Failure;
2462 }
2463 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002464 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002465
Chris Lattnere7b154b2013-01-19 21:39:22 +00002466 case llvm::BitstreamEntry::Record:
2467 // The interesting case.
2468 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 }
2470
2471 // Read and process a record.
2472 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002473 StringRef Blob;
2474 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 case METADATA: {
2476 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2477 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002478 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2479 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 return VersionMismatch;
2481 }
2482
Richard Smithe75ee0f2015-08-17 07:13:32 +00002483 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002484 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2485 Diag(diag::err_pch_with_compiler_errors);
2486 return HadErrors;
2487 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002488 if (hasErrors) {
2489 Diags.ErrorOccurred = true;
2490 Diags.UncompilableErrorOccurred = true;
2491 Diags.UnrecoverableErrorOccurred = true;
2492 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002493
2494 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002495 // Relative paths in a relocatable PCH are relative to our sysroot.
2496 if (F.RelocatablePCH)
2497 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002498
Richard Smithe75ee0f2015-08-17 07:13:32 +00002499 F.HasTimestamps = Record[5];
2500
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002502 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2504 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002505 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002506 return VersionMismatch;
2507 }
2508 break;
2509 }
2510
2511 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002512 // Validate the AST before processing any imports (otherwise, untangling
2513 // them can be error-prone and expensive). A module will have a name and
2514 // will already have been validated, but this catches the PCH case.
2515 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2516 return Result;
2517
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002518 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 unsigned Idx = 0, N = Record.size();
2520 while (Idx < N) {
2521 // Read information about the AST file.
2522 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2523 // The import location will be the local one for now; we will adjust
2524 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002525 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002527 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002528 off_t StoredSize = (off_t)Record[Idx++];
2529 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002530 ASTFileSignature StoredSignature = {
2531 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2532 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2533 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002534
2535 std::string ImportedName = ReadString(Record, Idx);
2536 std::string ImportedFile;
2537
2538 // For prebuilt and explicit modules first consult the file map for
2539 // an override. Note that here we don't search prebuilt module
2540 // directories, only the explicit name to file mappings. Also, we will
2541 // still verify the size/signature making sure it is essentially the
2542 // same file but perhaps in a different location.
2543 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2544 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2545 ImportedName, /*FileMapOnly*/ true);
2546
2547 if (ImportedFile.empty())
2548 ImportedFile = ReadPath(F, Record, Idx);
2549 else
2550 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002551
Richard Smith0f99d6a2015-08-09 08:48:41 +00002552 // If our client can't cope with us being out of date, we can't cope with
2553 // our dependency being missing.
2554 unsigned Capabilities = ClientLoadCapabilities;
2555 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2556 Capabilities &= ~ARR_Missing;
2557
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002559 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2560 Loaded, StoredSize, StoredModTime,
2561 StoredSignature, Capabilities);
2562
2563 // If we diagnosed a problem, produce a backtrace.
2564 if (isDiagnosedResult(Result, Capabilities))
2565 Diag(diag::note_module_file_imported_by)
2566 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2567
2568 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002569 case Failure: return Failure;
2570 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002571 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 case OutOfDate: return OutOfDate;
2573 case VersionMismatch: return VersionMismatch;
2574 case ConfigurationMismatch: return ConfigurationMismatch;
2575 case HadErrors: return HadErrors;
2576 case Success: break;
2577 }
2578 }
2579 break;
2580 }
2581
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 case ORIGINAL_FILE:
2583 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002584 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002585 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002586 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 break;
2588
2589 case ORIGINAL_FILE_ID:
2590 F.OriginalSourceFileID = FileID::get(Record[0]);
2591 break;
2592
2593 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002594 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 break;
2596
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002597 case MODULE_NAME:
2598 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002599 if (Listener)
2600 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002601
2602 // Validate the AST as soon as we have a name so we can exit early on
2603 // failure.
2604 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2605 return Result;
2606
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002607 break;
2608
Richard Smith223d3f22014-12-06 03:21:08 +00002609 case MODULE_DIRECTORY: {
2610 assert(!F.ModuleName.empty() &&
2611 "MODULE_DIRECTORY found before MODULE_NAME");
2612 // If we've already loaded a module map file covering this module, we may
2613 // have a better path for it (relative to the current build).
2614 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2615 if (M && M->Directory) {
2616 // If we're implicitly loading a module, the base directory can't
2617 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002618 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002619 const DirectoryEntry *BuildDir =
2620 PP.getFileManager().getDirectory(Blob);
2621 if (!BuildDir || BuildDir != M->Directory) {
2622 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2623 Diag(diag::err_imported_module_relocated)
2624 << F.ModuleName << Blob << M->Directory->getName();
2625 return OutOfDate;
2626 }
2627 }
2628 F.BaseDirectory = M->Directory->getName();
2629 } else {
2630 F.BaseDirectory = Blob;
2631 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002632 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002633 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002634
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002635 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002636 if (ASTReadResult Result =
2637 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2638 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002639 break;
2640
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002641 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002642 NumInputs = Record[0];
2643 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002644 F.InputFileOffsets =
2645 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002646 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002647 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 break;
2649 }
2650 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002651}
2652
Ben Langmuir2c9af442014-04-10 17:57:43 +00002653ASTReader::ASTReadResult
2654ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002655 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002656
2657 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2658 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002659 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 }
2661
2662 // Read all of the records and blocks for the AST file.
2663 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002664 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002665 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002666
Chris Lattnere7b154b2013-01-19 21:39:22 +00002667 switch (Entry.Kind) {
2668 case llvm::BitstreamEntry::Error:
2669 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002670 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002671 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002672 // Outside of C++, we do not store a lookup map for the translation unit.
2673 // Instead, mark it as needing a lookup map to be built if this module
2674 // contains any declarations lexically within it (which it always does!).
2675 // This usually has no cost, since we very rarely need the lookup map for
2676 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002677 if (ASTContext *Ctx = ContextObj) {
2678 DeclContext *DC = Ctx->getTranslationUnitDecl();
2679 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2680 DC->setMustBuildLookupTable();
2681 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002682
Ben Langmuir2c9af442014-04-10 17:57:43 +00002683 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002684 case llvm::BitstreamEntry::SubBlock:
2685 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002686 case DECLTYPES_BLOCK_ID:
2687 // We lazily load the decls block, but we want to set up the
2688 // DeclsCursor cursor to point into it. Clone our current bitcode
2689 // cursor to it, enter the block and read the abbrevs in that block.
2690 // With the main cursor, we just skip over it.
2691 F.DeclsCursor = Stream;
2692 if (Stream.SkipBlock() || // Skip with the main cursor.
2693 // Read the abbrevs.
2694 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2695 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002696 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 }
2698 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002699
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 case PREPROCESSOR_BLOCK_ID:
2701 F.MacroCursor = Stream;
2702 if (!PP.getExternalSource())
2703 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002704
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 if (Stream.SkipBlock() ||
2706 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2707 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002708 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 }
2710 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2711 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002712
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 case PREPROCESSOR_DETAIL_BLOCK_ID:
2714 F.PreprocessorDetailCursor = Stream;
2715 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002716 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002718 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002719 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002720 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002722 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002723
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 if (!PP.getPreprocessingRecord())
2725 PP.createPreprocessingRecord();
2726 if (!PP.getPreprocessingRecord()->getExternalSource())
2727 PP.getPreprocessingRecord()->SetExternalSource(*this);
2728 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002729
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 case SOURCE_MANAGER_BLOCK_ID:
2731 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002732 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002734
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002736 if (ASTReadResult Result =
2737 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002738 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002740
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002742 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 if (Stream.SkipBlock() ||
2744 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2745 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002746 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 }
2748 CommentsCursors.push_back(std::make_pair(C, &F));
2749 break;
2750 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002751
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002753 if (Stream.SkipBlock()) {
2754 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002755 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002756 }
2757 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 }
2759 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002760
Chris Lattnere7b154b2013-01-19 21:39:22 +00002761 case llvm::BitstreamEntry::Record:
2762 // The interesting case.
2763 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 }
2765
2766 // Read and process a record.
2767 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002768 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002769 auto RecordType =
2770 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2771
2772 // If we're not loading an AST context, we don't care about most records.
2773 if (!ContextObj) {
2774 switch (RecordType) {
2775 case IDENTIFIER_TABLE:
2776 case IDENTIFIER_OFFSET:
2777 case INTERESTING_IDENTIFIERS:
2778 case STATISTICS:
2779 case PP_CONDITIONAL_STACK:
2780 case PP_COUNTER_VALUE:
2781 case SOURCE_LOCATION_OFFSETS:
2782 case MODULE_OFFSET_MAP:
2783 case SOURCE_MANAGER_LINE_TABLE:
2784 case SOURCE_LOCATION_PRELOADS:
2785 case PPD_ENTITIES_OFFSETS:
2786 case HEADER_SEARCH_TABLE:
2787 case IMPORTED_MODULES:
2788 case MACRO_OFFSET:
2789 break;
2790 default:
2791 continue;
2792 }
2793 }
2794
2795 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002796 default: // Default behavior: ignore.
2797 break;
2798
2799 case TYPE_OFFSET: {
2800 if (F.LocalNumTypes != 0) {
2801 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002802 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002804 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 F.LocalNumTypes = Record[0];
2806 unsigned LocalBaseTypeIndex = Record[1];
2807 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002808
Guy Benyei11169dd2012-12-18 14:30:41 +00002809 if (F.LocalNumTypes > 0) {
2810 // Introduce the global -> local mapping for types within this module.
2811 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002812
Guy Benyei11169dd2012-12-18 14:30:41 +00002813 // Introduce the local -> global mapping for types within this module.
2814 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002815 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002816 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002817
2818 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002819 }
2820 break;
2821 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002822
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 case DECL_OFFSET: {
2824 if (F.LocalNumDecls != 0) {
2825 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002826 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002827 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002828 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 F.LocalNumDecls = Record[0];
2830 unsigned LocalBaseDeclID = Record[1];
2831 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002832
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002834 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 // module.
2836 GlobalDeclMap.insert(
2837 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002838
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 // Introduce the local -> global mapping for declarations within this
2840 // module.
2841 F.DeclRemap.insertOrReplace(
2842 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002843
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 // Introduce the global -> local mapping for declarations within this
2845 // module.
2846 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002847
Ben Langmuir52ca6782014-10-20 16:27:32 +00002848 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2849 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 break;
2851 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002852
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002854 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002855 LexicalContents Contents(
2856 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2857 Blob.data()),
2858 static_cast<unsigned int>(Blob.size() / 4));
2859 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 TU->setHasExternalLexicalStorage(true);
2861 break;
2862 }
2863
2864 case UPDATE_VISIBLE: {
2865 unsigned Idx = 0;
2866 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002867 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002868 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002869 // If we've already loaded the decl, perform the updates when we finish
2870 // loading this block.
2871 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002872 PendingUpdateRecords.push_back(
2873 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002874 break;
2875 }
2876
2877 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002878 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002880 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2881 (const unsigned char *)F.IdentifierTableData + Record[0],
2882 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2883 (const unsigned char *)F.IdentifierTableData,
2884 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002885
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2887 }
2888 break;
2889
2890 case IDENTIFIER_OFFSET: {
2891 if (F.LocalNumIdentifiers != 0) {
2892 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002893 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002894 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002895 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 F.LocalNumIdentifiers = Record[0];
2897 unsigned LocalBaseIdentifierID = Record[1];
2898 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002899
Guy Benyei11169dd2012-12-18 14:30:41 +00002900 if (F.LocalNumIdentifiers > 0) {
2901 // Introduce the global -> local mapping for identifiers within this
2902 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002903 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002905
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 // Introduce the local -> global mapping for identifiers within this
2907 // module.
2908 F.IdentifierRemap.insertOrReplace(
2909 std::make_pair(LocalBaseIdentifierID,
2910 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002911
Ben Langmuir52ca6782014-10-20 16:27:32 +00002912 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2913 + F.LocalNumIdentifiers);
2914 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 break;
2916 }
2917
Richard Smith33e0f7e2015-07-22 02:08:40 +00002918 case INTERESTING_IDENTIFIERS:
2919 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2920 break;
2921
Ben Langmuir332aafe2014-01-31 01:06:56 +00002922 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002923 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2924 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002926 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 break;
2928
David Blaikie9ffe5a32017-01-30 05:00:26 +00002929 case MODULAR_CODEGEN_DECLS:
2930 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2931 // them (ie: if we're not codegenerating this module).
2932 if (F.Kind == MK_MainFile)
2933 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2934 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2935 break;
2936
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002938 if (SpecialTypes.empty()) {
2939 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2940 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2941 break;
2942 }
2943
2944 if (SpecialTypes.size() != Record.size()) {
2945 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002946 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002947 }
2948
2949 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2950 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2951 if (!SpecialTypes[I])
2952 SpecialTypes[I] = ID;
2953 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2954 // merge step?
2955 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 break;
2957
2958 case STATISTICS:
2959 TotalNumStatements += Record[0];
2960 TotalNumMacros += Record[1];
2961 TotalLexicalDeclContexts += Record[2];
2962 TotalVisibleDeclContexts += Record[3];
2963 break;
2964
2965 case UNUSED_FILESCOPED_DECLS:
2966 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2967 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2968 break;
2969
2970 case DELEGATING_CTORS:
2971 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2972 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2973 break;
2974
2975 case WEAK_UNDECLARED_IDENTIFIERS:
2976 if (Record.size() % 4 != 0) {
2977 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002978 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002980
2981 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 // files. This isn't the way to do it :)
2983 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002984
Guy Benyei11169dd2012-12-18 14:30:41 +00002985 // Translate the weak, undeclared identifiers into global IDs.
2986 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2987 WeakUndeclaredIdentifiers.push_back(
2988 getGlobalIdentifierID(F, Record[I++]));
2989 WeakUndeclaredIdentifiers.push_back(
2990 getGlobalIdentifierID(F, Record[I++]));
2991 WeakUndeclaredIdentifiers.push_back(
2992 ReadSourceLocation(F, Record, I).getRawEncoding());
2993 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2994 }
2995 break;
2996
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002998 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002999 F.LocalNumSelectors = Record[0];
3000 unsigned LocalBaseSelectorID = Record[1];
3001 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003002
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003004 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 // module.
3006 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003007
3008 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 // module.
3010 F.SelectorRemap.insertOrReplace(
3011 std::make_pair(LocalBaseSelectorID,
3012 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003013
3014 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003015 }
3016 break;
3017 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003018
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003020 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 if (Record[0])
3022 F.SelectorLookupTable
3023 = ASTSelectorLookupTable::Create(
3024 F.SelectorLookupTableData + Record[0],
3025 F.SelectorLookupTableData,
3026 ASTSelectorLookupTrait(*this, F));
3027 TotalNumMethodPoolEntries += Record[1];
3028 break;
3029
3030 case REFERENCED_SELECTOR_POOL:
3031 if (!Record.empty()) {
3032 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003033 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 Record[Idx++]));
3035 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3036 getRawEncoding());
3037 }
3038 }
3039 break;
3040
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003041 case PP_CONDITIONAL_STACK:
3042 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003043 unsigned Idx = 0, End = Record.size() - 1;
3044 bool ReachedEOFWhileSkipping = Record[Idx++];
3045 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3046 if (ReachedEOFWhileSkipping) {
3047 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3048 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3049 bool FoundNonSkipPortion = Record[Idx++];
3050 bool FoundElse = Record[Idx++];
3051 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3052 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3053 FoundElse, ElseLoc);
3054 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003055 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003056 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003057 auto Loc = ReadSourceLocation(F, Record, Idx);
3058 bool WasSkipping = Record[Idx++];
3059 bool FoundNonSkip = Record[Idx++];
3060 bool FoundElse = Record[Idx++];
3061 ConditionalStack.push_back(
3062 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3063 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003064 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003065 }
3066 break;
3067
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 case PP_COUNTER_VALUE:
3069 if (!Record.empty() && Listener)
3070 Listener->ReadCounter(F, Record[0]);
3071 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003072
Guy Benyei11169dd2012-12-18 14:30:41 +00003073 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003074 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 F.NumFileSortedDecls = Record[0];
3076 break;
3077
3078 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003079 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003080 F.LocalNumSLocEntries = Record[0];
3081 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003082 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003083 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003085 if (!F.SLocEntryBaseID) {
3086 Error("ran out of source locations");
3087 break;
3088 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 // Make our entry in the range map. BaseID is negative and growing, so
3090 // we invert it. Because we invert it, though, we need the other end of
3091 // the range.
3092 unsigned RangeStart =
3093 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3094 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3095 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3096
3097 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3098 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3099 GlobalSLocOffsetMap.insert(
3100 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3101 - SLocSpaceSize,&F));
3102
3103 // Initialize the remapping table.
3104 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003105 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003107 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003109
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 TotalNumSLocEntries += F.LocalNumSLocEntries;
3111 break;
3112 }
3113
Richard Smith37a93df2017-02-18 00:32:02 +00003114 case MODULE_OFFSET_MAP:
3115 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003117
3118 case SOURCE_MANAGER_LINE_TABLE:
3119 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003120 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 break;
3122
3123 case SOURCE_LOCATION_PRELOADS: {
3124 // Need to transform from the local view (1-based IDs) to the global view,
3125 // which is based off F.SLocEntryBaseID.
3126 if (!F.PreloadSLocEntries.empty()) {
3127 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003128 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003130
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 F.PreloadSLocEntries.swap(Record);
3132 break;
3133 }
3134
3135 case EXT_VECTOR_DECLS:
3136 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3137 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3138 break;
3139
3140 case VTABLE_USES:
3141 if (Record.size() % 3 != 0) {
3142 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003143 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003145
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 // Later tables overwrite earlier ones.
3147 // FIXME: Modules will have some trouble with this. This is clearly not
3148 // the right way to do this.
3149 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3152 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3153 VTableUses.push_back(
3154 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3155 VTableUses.push_back(Record[Idx++]);
3156 }
3157 break;
3158
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 case PENDING_IMPLICIT_INSTANTIATIONS:
3160 if (PendingInstantiations.size() % 2 != 0) {
3161 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003162 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 }
3164
3165 if (Record.size() % 2 != 0) {
3166 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003167 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 }
3169
3170 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3171 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3172 PendingInstantiations.push_back(
3173 ReadSourceLocation(F, Record, I).getRawEncoding());
3174 }
3175 break;
3176
3177 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003178 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003179 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003180 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003181 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3183 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3184 break;
3185
3186 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003187 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3188 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3189 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003190
3191 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003192
Guy Benyei11169dd2012-12-18 14:30:41 +00003193 unsigned StartingID;
3194 if (!PP.getPreprocessingRecord())
3195 PP.createPreprocessingRecord();
3196 if (!PP.getPreprocessingRecord()->getExternalSource())
3197 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003198 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003199 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003200 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 F.BasePreprocessedEntityID = StartingID;
3202
3203 if (F.NumPreprocessedEntities > 0) {
3204 // Introduce the global -> local mapping for preprocessed entities in
3205 // this module.
3206 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003207
Guy Benyei11169dd2012-12-18 14:30:41 +00003208 // Introduce the local -> global mapping for preprocessed entities in
3209 // this module.
3210 F.PreprocessedEntityRemap.insertOrReplace(
3211 std::make_pair(LocalBasePreprocessedEntityID,
3212 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3213 }
3214
3215 break;
3216 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003217
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003218 case PPD_SKIPPED_RANGES: {
3219 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3220 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3221 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3222
3223 if (!PP.getPreprocessingRecord())
3224 PP.createPreprocessingRecord();
3225 if (!PP.getPreprocessingRecord()->getExternalSource())
3226 PP.getPreprocessingRecord()->SetExternalSource(*this);
3227 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3228 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3229
3230 if (F.NumPreprocessedSkippedRanges > 0)
3231 GlobalSkippedRangeMap.insert(
3232 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3233 break;
3234 }
3235
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003236 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003237 if (Record.size() % 2 != 0) {
3238 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003239 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003241 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3242 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3243 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3244
3245 // If we've already loaded the decl, perform the updates when we finish
3246 // loading this block.
3247 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003248 PendingUpdateRecords.push_back(
3249 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003250 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003251 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003252
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003253 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 if (F.LocalNumObjCCategoriesInMap != 0) {
3255 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003256 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003258
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003260 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003261 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003262
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 case OBJC_CATEGORIES:
3264 F.ObjCCategories.swap(Record);
3265 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003266
Guy Benyei11169dd2012-12-18 14:30:41 +00003267 case CUDA_SPECIAL_DECL_REFS:
3268 // Later tables overwrite earlier ones.
3269 // FIXME: Modules will have trouble with this.
3270 CUDASpecialDeclRefs.clear();
3271 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3272 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3273 break;
3274
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003275 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003276 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 if (Record[0]) {
3279 F.HeaderFileInfoTable
3280 = HeaderFileInfoLookupTable::Create(
3281 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3282 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003283 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003285 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003286
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 PP.getHeaderSearchInfo().SetExternalSource(this);
3288 if (!PP.getHeaderSearchInfo().getExternalLookup())
3289 PP.getHeaderSearchInfo().SetExternalLookup(this);
3290 }
3291 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 case FP_PRAGMA_OPTIONS:
3294 // Later tables overwrite earlier ones.
3295 FPPragmaOptions.swap(Record);
3296 break;
3297
3298 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003299 for (unsigned I = 0, E = Record.size(); I != E; ) {
3300 auto Name = ReadString(Record, I);
3301 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003302 Opt.Supported = Record[I++] != 0;
3303 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003304 Opt.Avail = Record[I++];
3305 Opt.Core = Record[I++];
3306 }
3307 break;
3308
3309 case OPENCL_EXTENSION_TYPES:
3310 for (unsigned I = 0, E = Record.size(); I != E;) {
3311 auto TypeID = static_cast<::TypeID>(Record[I++]);
3312 auto *Type = GetType(TypeID).getTypePtr();
3313 auto NumExt = static_cast<unsigned>(Record[I++]);
3314 for (unsigned II = 0; II != NumExt; ++II) {
3315 auto Ext = ReadString(Record, I);
3316 OpenCLTypeExtMap[Type].insert(Ext);
3317 }
3318 }
3319 break;
3320
3321 case OPENCL_EXTENSION_DECLS:
3322 for (unsigned I = 0, E = Record.size(); I != E;) {
3323 auto DeclID = static_cast<::DeclID>(Record[I++]);
3324 auto *Decl = GetDecl(DeclID);
3325 auto NumExt = static_cast<unsigned>(Record[I++]);
3326 for (unsigned II = 0; II != NumExt; ++II) {
3327 auto Ext = ReadString(Record, I);
3328 OpenCLDeclExtMap[Decl].insert(Ext);
3329 }
3330 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003331 break;
3332
3333 case TENTATIVE_DEFINITIONS:
3334 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3335 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3336 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003337
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 case KNOWN_NAMESPACES:
3339 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3340 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3341 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003342
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003343 case UNDEFINED_BUT_USED:
3344 if (UndefinedButUsed.size() % 2 != 0) {
3345 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003346 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003347 }
3348
3349 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003350 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003351 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003352 }
3353 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003354 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3355 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003356 ReadSourceLocation(F, Record, I).getRawEncoding());
3357 }
3358 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003359
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003360 case DELETE_EXPRS_TO_ANALYZE:
3361 for (unsigned I = 0, N = Record.size(); I != N;) {
3362 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3363 const uint64_t Count = Record[I++];
3364 DelayedDeleteExprs.push_back(Count);
3365 for (uint64_t C = 0; C < Count; ++C) {
3366 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3367 bool IsArrayForm = Record[I++] == 1;
3368 DelayedDeleteExprs.push_back(IsArrayForm);
3369 }
3370 }
3371 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003372
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003373 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003374 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 // If we aren't loading a module (which has its own exports), make
3376 // all of the imported modules visible.
3377 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003378 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3379 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3380 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003381 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003382 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003383 if (DeserializationListener)
3384 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 }
3387 }
3388 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003389
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 case MACRO_OFFSET: {
3391 if (F.LocalNumMacros != 0) {
3392 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003393 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003395 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003396 F.LocalNumMacros = Record[0];
3397 unsigned LocalBaseMacroID = Record[1];
3398 F.BaseMacroID = getTotalNumMacros();
3399
3400 if (F.LocalNumMacros > 0) {
3401 // Introduce the global -> local mapping for macros within this module.
3402 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3403
3404 // Introduce the local -> global mapping for macros within this module.
3405 F.MacroRemap.insertOrReplace(
3406 std::make_pair(LocalBaseMacroID,
3407 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003408
3409 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003410 }
3411 break;
3412 }
3413
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003414 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003415 LateParsedTemplates.append(Record.begin(), Record.end());
3416 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003417
3418 case OPTIMIZE_PRAGMA_OPTIONS:
3419 if (Record.size() != 1) {
3420 Error("invalid pragma optimize record");
3421 return Failure;
3422 }
3423 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3424 break;
Nico Weber72889432014-09-06 01:25:55 +00003425
Nico Weber779355f2016-03-02 23:22:00 +00003426 case MSSTRUCT_PRAGMA_OPTIONS:
3427 if (Record.size() != 1) {
3428 Error("invalid pragma ms_struct record");
3429 return Failure;
3430 }
3431 PragmaMSStructState = Record[0];
3432 break;
3433
Nico Weber42932312016-03-03 00:17:35 +00003434 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3435 if (Record.size() != 2) {
3436 Error("invalid pragma ms_struct record");
3437 return Failure;
3438 }
3439 PragmaMSPointersToMembersState = Record[0];
3440 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3441 break;
3442
Nico Weber72889432014-09-06 01:25:55 +00003443 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3444 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3445 UnusedLocalTypedefNameCandidates.push_back(
3446 getGlobalDeclID(F, Record[I]));
3447 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003448
3449 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3450 if (Record.size() != 1) {
3451 Error("invalid cuda pragma options record");
3452 return Failure;
3453 }
3454 ForceCUDAHostDeviceDepth = Record[0];
3455 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003456
3457 case PACK_PRAGMA_OPTIONS: {
3458 if (Record.size() < 3) {
3459 Error("invalid pragma pack record");
3460 return Failure;
3461 }
3462 PragmaPackCurrentValue = Record[0];
3463 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3464 unsigned NumStackEntries = Record[2];
3465 unsigned Idx = 3;
3466 // Reset the stack when importing a new module.
3467 PragmaPackStack.clear();
3468 for (unsigned I = 0; I < NumStackEntries; ++I) {
3469 PragmaPackStackEntry Entry;
3470 Entry.Value = Record[Idx++];
3471 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003472 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003473 PragmaPackStrings.push_back(ReadString(Record, Idx));
3474 Entry.SlotLabel = PragmaPackStrings.back();
3475 PragmaPackStack.push_back(Entry);
3476 }
3477 break;
3478 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003479 }
3480 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003481}
3482
Richard Smith37a93df2017-02-18 00:32:02 +00003483void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3484 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3485
3486 // Additional remapping information.
3487 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3488 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3489 F.ModuleOffsetMap = StringRef();
3490
3491 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3492 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3493 F.SLocRemap.insert(std::make_pair(0U, 0));
3494 F.SLocRemap.insert(std::make_pair(2U, 1));
3495 }
3496
3497 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003498 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003499 RemapBuilder SLocRemap(F.SLocRemap);
3500 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3501 RemapBuilder MacroRemap(F.MacroRemap);
3502 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3503 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3504 RemapBuilder SelectorRemap(F.SelectorRemap);
3505 RemapBuilder DeclRemap(F.DeclRemap);
3506 RemapBuilder TypeRemap(F.TypeRemap);
3507
3508 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003509 // FIXME: Looking up dependency modules by filename is horrible. Let's
3510 // start fixing this with prebuilt and explicit modules and see how it
3511 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003512 using namespace llvm::support;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003513 ModuleKind Kind = static_cast<ModuleKind>(
3514 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003515 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3516 StringRef Name = StringRef((const char*)Data, Len);
3517 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003518 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3519 ? ModuleMgr.lookupByModuleName(Name)
3520 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003521 if (!OM) {
3522 std::string Msg =
3523 "SourceLocation remap refers to unknown module, cannot find ";
3524 Msg.append(Name);
3525 Error(Msg);
3526 return;
3527 }
3528
3529 uint32_t SLocOffset =
3530 endian::readNext<uint32_t, little, unaligned>(Data);
3531 uint32_t IdentifierIDOffset =
3532 endian::readNext<uint32_t, little, unaligned>(Data);
3533 uint32_t MacroIDOffset =
3534 endian::readNext<uint32_t, little, unaligned>(Data);
3535 uint32_t PreprocessedEntityIDOffset =
3536 endian::readNext<uint32_t, little, unaligned>(Data);
3537 uint32_t SubmoduleIDOffset =
3538 endian::readNext<uint32_t, little, unaligned>(Data);
3539 uint32_t SelectorIDOffset =
3540 endian::readNext<uint32_t, little, unaligned>(Data);
3541 uint32_t DeclIDOffset =
3542 endian::readNext<uint32_t, little, unaligned>(Data);
3543 uint32_t TypeIndexOffset =
3544 endian::readNext<uint32_t, little, unaligned>(Data);
3545
3546 uint32_t None = std::numeric_limits<uint32_t>::max();
3547
3548 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3549 RemapBuilder &Remap) {
3550 if (Offset != None)
3551 Remap.insert(std::make_pair(Offset,
3552 static_cast<int>(BaseOffset - Offset)));
3553 };
3554 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3555 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3556 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3557 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3558 PreprocessedEntityRemap);
3559 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3560 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3561 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3562 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3563
3564 // Global -> local mappings.
3565 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3566 }
3567}
3568
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003569ASTReader::ASTReadResult
3570ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3571 const ModuleFile *ImportedBy,
3572 unsigned ClientLoadCapabilities) {
3573 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003574 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003575
3576 // Try to resolve ModuleName in the current header search context and
3577 // verify that it is found in the same module map file as we saved. If the
3578 // top-level AST file is a main file, skip this check because there is no
3579 // usable header search context.
3580 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003581 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003582 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003583 // An implicitly-loaded module file should have its module listed in some
3584 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003585 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003586 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3587 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3588 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003589 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003590 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003591 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003592 // This module was defined by an imported (explicit) module.
3593 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3594 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003595 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003596 // This module was built with a different module map.
3597 Diag(diag::err_imported_module_not_found)
3598 << F.ModuleName << F.FileName << ImportedBy->FileName
3599 << F.ModuleMapPath;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003600 // In case it was imported by a PCH, there's a chance the user is
3601 // just missing to include the search path to the directory containing
3602 // the modulemap.
3603 if (ImportedBy->Kind == MK_PCH)
3604 Diag(diag::note_imported_by_pch_module_not_found)
3605 << llvm::sys::path::parent_path(F.ModuleMapPath);
3606 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003607 }
3608 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003609 }
3610
Richard Smithe842a472014-10-22 02:05:46 +00003611 assert(M->Name == F.ModuleName && "found module with different name");
3612
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003613 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003614 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003615 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3616 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003617 assert(ImportedBy && "top-level import should be verified");
3618 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3619 Diag(diag::err_imported_module_modmap_changed)
3620 << F.ModuleName << ImportedBy->FileName
3621 << ModMap->getName() << F.ModuleMapPath;
3622 return OutOfDate;
3623 }
3624
3625 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3626 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3627 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003628 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003629 const FileEntry *F =
3630 FileMgr.getFile(Filename, false, false);
3631 if (F == nullptr) {
3632 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3633 Error("could not find file '" + Filename +"' referenced by AST file");
3634 return OutOfDate;
3635 }
3636 AdditionalStoredMaps.insert(F);
3637 }
3638
3639 // Check any additional module map files (e.g. module.private.modulemap)
3640 // that are not in the pcm.
3641 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3642 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3643 // Remove files that match
3644 // Note: SmallPtrSet::erase is really remove
3645 if (!AdditionalStoredMaps.erase(ModMap)) {
3646 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3647 Diag(diag::err_module_different_modmap)
3648 << F.ModuleName << /*new*/0 << ModMap->getName();
3649 return OutOfDate;
3650 }
3651 }
3652 }
3653
3654 // Check any additional module map files that are in the pcm, but not
3655 // found in header search. Cases that match are already removed.
3656 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3657 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3658 Diag(diag::err_module_different_modmap)
3659 << F.ModuleName << /*not new*/1 << ModMap->getName();
3660 return OutOfDate;
3661 }
3662 }
3663
3664 if (Listener)
3665 Listener->ReadModuleMapFile(F.ModuleMapPath);
3666 return Success;
3667}
3668
Douglas Gregorc1489562013-02-12 23:36:21 +00003669/// \brief Move the given method to the back of the global list of methods.
3670static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3671 // Find the entry for this selector in the method pool.
3672 Sema::GlobalMethodPool::iterator Known
3673 = S.MethodPool.find(Method->getSelector());
3674 if (Known == S.MethodPool.end())
3675 return;
3676
3677 // Retrieve the appropriate method list.
3678 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3679 : Known->second.second;
3680 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003681 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003682 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003683 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003684 Found = true;
3685 } else {
3686 // Keep searching.
3687 continue;
3688 }
3689 }
3690
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003691 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003692 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003693 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003694 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003695 }
3696}
3697
Richard Smithde711422015-04-23 21:20:19 +00003698void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003699 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003700 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003701 bool wasHidden = D->isHidden();
3702 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003703
Richard Smith49f906a2014-03-01 00:08:04 +00003704 if (wasHidden && SemaObj) {
3705 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3706 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003707 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 }
3709 }
3710}
3711
Richard Smith49f906a2014-03-01 00:08:04 +00003712void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003713 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003714 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003715 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003716 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003717 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003718 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003719 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003720
3721 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003722 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003723 // there is nothing more to do.
3724 continue;
3725 }
Richard Smith49f906a2014-03-01 00:08:04 +00003726
Guy Benyei11169dd2012-12-18 14:30:41 +00003727 if (!Mod->isAvailable()) {
3728 // Modules that aren't available cannot be made visible.
3729 continue;
3730 }
3731
3732 // Update the module's name visibility.
3733 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003734
Guy Benyei11169dd2012-12-18 14:30:41 +00003735 // If we've already deserialized any names from this module,
3736 // mark them as visible.
3737 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3738 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003739 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003740 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003741 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003742 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3743 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003744 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003745
Guy Benyei11169dd2012-12-18 14:30:41 +00003746 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003747 SmallVector<Module *, 16> Exports;
3748 Mod->getExportedModules(Exports);
3749 for (SmallVectorImpl<Module *>::iterator
3750 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3751 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003752 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003753 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 }
3755 }
3756}
3757
Richard Smith6561f922016-09-12 21:06:40 +00003758/// We've merged the definition \p MergedDef into the existing definition
3759/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3760/// visible.
3761void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3762 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003763 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3764 // in modules other than its owning module. We should instead give the
3765 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003766 if (Def->isHidden()) {
3767 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003768 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003769 Def->setVisibleDespiteOwningModule();
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003770 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3771 getContext().mergeDefinitionIntoModule(
3772 Def, MergedDef->getImportedOwningModule(),
3773 /*NotifyListeners*/ false);
3774 PendingMergedDefinitionsToDeduplicate.insert(Def);
3775 } else {
3776 auto SubmoduleID = MergedDef->getOwningModuleID();
3777 assert(SubmoduleID && "hidden definition in no module");
3778 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3779 }
Richard Smith6561f922016-09-12 21:06:40 +00003780 }
3781}
3782
Douglas Gregore060e572013-01-25 01:03:03 +00003783bool ASTReader::loadGlobalIndex() {
3784 if (GlobalIndex)
3785 return false;
3786
3787 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003788 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003789 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003790
Douglas Gregore060e572013-01-25 01:03:03 +00003791 // Try to load the global index.
3792 TriedLoadingGlobalIndex = true;
3793 StringRef ModuleCachePath
3794 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3795 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003796 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003797 if (!Result.first)
3798 return true;
3799
3800 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003801 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003802 return false;
3803}
3804
3805bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003806 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003807 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3808}
3809
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003810static void updateModuleTimestamp(ModuleFile &MF) {
3811 // Overwrite the timestamp file contents so that file's mtime changes.
3812 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003813 std::error_code EC;
3814 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3815 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003816 return;
3817 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003818 OS.close();
3819 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003820}
3821
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003822/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3823/// cursor into the start of the given block ID, returning false on success and
3824/// true on failure.
3825static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003826 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003827 llvm::BitstreamEntry Entry = Cursor.advance();
3828 switch (Entry.Kind) {
3829 case llvm::BitstreamEntry::Error:
3830 case llvm::BitstreamEntry::EndBlock:
3831 return true;
3832
3833 case llvm::BitstreamEntry::Record:
3834 // Ignore top-level records.
3835 Cursor.skipRecord(Entry.ID);
3836 break;
3837
3838 case llvm::BitstreamEntry::SubBlock:
3839 if (Entry.ID == BlockID) {
3840 if (Cursor.EnterSubBlock(BlockID))
3841 return true;
3842 // Found it!
3843 return false;
3844 }
3845
3846 if (Cursor.SkipBlock())
3847 return true;
3848 }
3849 }
3850}
3851
Benjamin Kramer0772c422016-02-13 13:42:54 +00003852ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003853 ModuleKind Type,
3854 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003855 unsigned ClientLoadCapabilities,
3856 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003857 llvm::SaveAndRestore<SourceLocation>
3858 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3859
Richard Smithd1c46742014-04-30 02:24:17 +00003860 // Defer any pending actions until we get to the end of reading the AST file.
3861 Deserializing AnASTFile(this);
3862
Guy Benyei11169dd2012-12-18 14:30:41 +00003863 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003864 unsigned PreviousGeneration = 0;
3865 if (ContextObj)
3866 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003867
3868 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003869 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003870 switch (ASTReadResult ReadResult =
3871 ReadASTCore(FileName, Type, ImportLoc,
3872 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3873 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003874 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003875 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 case OutOfDate:
3877 case VersionMismatch:
3878 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003879 case HadErrors: {
3880 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3881 for (const ImportedModule &IM : Loaded)
3882 LoadedSet.insert(IM.Mod);
3883
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003884 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003885 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003886 ? &PP.getHeaderSearchInfo().getModuleMap()
3887 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003888
3889 // If we find that any modules are unusable, the global index is going
3890 // to be out-of-date. Just remove it.
3891 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003892 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003893 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003894 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003895 case Success:
3896 break;
3897 }
3898
3899 // Here comes stuff that we only do once the entire chain is loaded.
3900
3901 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003902 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3903 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 M != MEnd; ++M) {
3905 ModuleFile &F = *M->Mod;
3906
3907 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003908 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3909 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003910
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003911 // Read the extension blocks.
3912 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3913 if (ASTReadResult Result = ReadExtensionBlock(F))
3914 return Result;
3915 }
3916
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003917 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 // bits of all files we've seen.
3919 F.GlobalBitOffset = TotalModulesSizeInBits;
3920 TotalModulesSizeInBits += F.SizeInBits;
3921 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003922
Guy Benyei11169dd2012-12-18 14:30:41 +00003923 // Preload SLocEntries.
3924 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3925 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3926 // Load it through the SourceManager and don't call ReadSLocEntry()
3927 // directly because the entry may have already been loaded in which case
3928 // calling ReadSLocEntry() directly would trigger an assertion in
3929 // SourceManager.
3930 SourceMgr.getLoadedSLocEntryByID(Index);
3931 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003932
Richard Smithea741482017-05-01 22:10:47 +00003933 // Map the original source file ID into the ID space of the current
3934 // compilation.
3935 if (F.OriginalSourceFileID.isValid()) {
3936 F.OriginalSourceFileID = FileID::get(
3937 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3938 }
3939
Richard Smith33e0f7e2015-07-22 02:08:40 +00003940 // Preload all the pending interesting identifiers by marking them out of
3941 // date.
3942 for (auto Offset : F.PreloadIdentifierOffsets) {
3943 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3944 F.IdentifierTableData + Offset);
3945
3946 ASTIdentifierLookupTrait Trait(*this, F);
3947 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3948 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003949 auto &II = PP.getIdentifierTable().getOwn(Key);
3950 II.setOutOfDate(true);
3951
3952 // Mark this identifier as being from an AST file so that we can track
3953 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003954 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003955
3956 // Associate the ID with the identifier so that the writer can reuse it.
3957 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3958 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003959 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 }
3961
Douglas Gregor603cd862013-03-22 18:50:14 +00003962 // Setup the import locations and notify the module manager that we've
3963 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003964 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3965 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003966 M != MEnd; ++M) {
3967 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003968
3969 ModuleMgr.moduleFileAccepted(&F);
3970
3971 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003972 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003973 // FIXME: We assume that locations from PCH / preamble do not need
3974 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003975 if (!M->ImportedBy)
3976 F.ImportLoc = M->ImportLoc;
3977 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003978 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 }
3980
Richard Smithdbafb6c2017-06-29 23:23:46 +00003981 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003982 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3983 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003984 // Mark all of the identifiers in the identifier table as being out of date,
3985 // so that various accessors know to check the loaded modules when the
3986 // identifier is used.
3987 //
3988 // For C++ modules, we don't need information on many identifiers (just
3989 // those that provide macros or are poisoned), so we mark all of
3990 // the interesting ones via PreloadIdentifierOffsets.
3991 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3992 IdEnd = PP.getIdentifierTable().end();
3993 Id != IdEnd; ++Id)
3994 Id->second->setOutOfDate(true);
3995 }
Manman Rena0f31a02016-04-29 19:04:05 +00003996 // Mark selectors as out of date.
3997 for (auto Sel : SelectorGeneration)
3998 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003999
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00004001 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4002 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004003 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4004 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004005
4006 switch (Unresolved.Kind) {
4007 case UnresolvedModuleRef::Conflict:
4008 if (ResolvedMod) {
4009 Module::Conflict Conflict;
4010 Conflict.Other = ResolvedMod;
4011 Conflict.Message = Unresolved.String.str();
4012 Unresolved.Mod->Conflicts.push_back(Conflict);
4013 }
4014 continue;
4015
4016 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004018 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004020
Douglas Gregorfb912652013-03-20 21:10:35 +00004021 case UnresolvedModuleRef::Export:
4022 if (ResolvedMod || Unresolved.IsWildcard)
4023 Unresolved.Mod->Exports.push_back(
4024 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4025 continue;
4026 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004028 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004029
Graydon Hoaree7196af2016-12-09 21:45:49 +00004030 if (Imported)
4031 Imported->append(ImportedModules.begin(),
4032 ImportedModules.end());
4033
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004034 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4035 // Might be unnecessary as use declarations are only used to build the
4036 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004037
Richard Smithdbafb6c2017-06-29 23:23:46 +00004038 if (ContextObj)
4039 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004040
Richard Smith3d8e97e2013-10-18 06:54:39 +00004041 if (SemaObj)
4042 UpdateSema();
4043
Guy Benyei11169dd2012-12-18 14:30:41 +00004044 if (DeserializationListener)
4045 DeserializationListener->ReaderInitialized(this);
4046
4047 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004048 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 // If this AST file is a precompiled preamble, then set the
4050 // preamble file ID of the source manager to the file source file
4051 // from which the preamble was built.
4052 if (Type == MK_Preamble) {
4053 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4054 } else if (Type == MK_MainFile) {
4055 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4056 }
4057 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004058
Guy Benyei11169dd2012-12-18 14:30:41 +00004059 // For any Objective-C class definitions we have already loaded, make sure
4060 // that we load any additional categories.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004061 if (ContextObj) {
4062 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4063 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4064 ObjCClassesLoaded[I],
4065 PreviousGeneration);
4066 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 }
Douglas Gregore060e572013-01-25 01:03:03 +00004068
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004069 if (PP.getHeaderSearchInfo()
4070 .getHeaderSearchOpts()
4071 .ModulesValidateOncePerBuildSession) {
4072 // Now we are certain that the module and all modules it depends on are
4073 // up to date. Create or update timestamp files for modules that are
4074 // located in the module cache (not for PCH files that could be anywhere
4075 // in the filesystem).
4076 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4077 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00004078 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004079 updateModuleTimestamp(*M.Mod);
4080 }
4081 }
4082 }
4083
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 return Success;
4085}
4086
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004087static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004088
Ben Langmuir70a1b812015-03-24 04:43:52 +00004089/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
4090static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004091 return Stream.canSkipToPos(4) &&
4092 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00004093 Stream.Read(8) == 'P' &&
4094 Stream.Read(8) == 'C' &&
4095 Stream.Read(8) == 'H';
4096}
4097
Richard Smith0f99d6a2015-08-09 08:48:41 +00004098static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4099 switch (Kind) {
4100 case MK_PCH:
4101 return 0; // PCH
4102 case MK_ImplicitModule:
4103 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004104 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004105 return 1; // module
4106 case MK_MainFile:
4107 case MK_Preamble:
4108 return 2; // main source file
4109 }
4110 llvm_unreachable("unknown module kind");
4111}
4112
Guy Benyei11169dd2012-12-18 14:30:41 +00004113ASTReader::ASTReadResult
4114ASTReader::ReadASTCore(StringRef FileName,
4115 ModuleKind Type,
4116 SourceLocation ImportLoc,
4117 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004118 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004119 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004120 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 unsigned ClientLoadCapabilities) {
4122 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004124 ModuleManager::AddModuleResult AddResult
4125 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004126 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004127 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004128 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004129
Douglas Gregor7029ce12013-03-19 00:28:20 +00004130 switch (AddResult) {
4131 case ModuleManager::AlreadyLoaded:
4132 return Success;
4133
4134 case ModuleManager::NewlyLoaded:
4135 // Load module file below.
4136 break;
4137
4138 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004139 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004140 // it.
4141 if (ClientLoadCapabilities & ARR_Missing)
4142 return Missing;
4143
4144 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004145 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004146 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004147 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004148 return Failure;
4149
4150 case ModuleManager::OutOfDate:
4151 // We couldn't load the module file because it is out-of-date. If the
4152 // client can handle out-of-date, return it.
4153 if (ClientLoadCapabilities & ARR_OutOfDate)
4154 return OutOfDate;
4155
4156 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004157 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004158 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004159 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004160 return Failure;
4161 }
4162
Douglas Gregor7029ce12013-03-19 00:28:20 +00004163 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004164
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004166 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004167 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004168 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004169
Guy Benyei11169dd2012-12-18 14:30:41 +00004170 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004171 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004172 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4173 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 return Failure;
4175 }
4176
4177 // This is used for compatibility with older PCH formats.
4178 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004179 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004180 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004181
Chris Lattnerefa77172013-01-20 00:00:22 +00004182 switch (Entry.Kind) {
4183 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004184 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004185 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 Error("invalid record at top-level of AST file");
4187 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004188
Chris Lattnerefa77172013-01-20 00:00:22 +00004189 case llvm::BitstreamEntry::SubBlock:
4190 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004191 }
4192
Chris Lattnerefa77172013-01-20 00:00:22 +00004193 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 case CONTROL_BLOCK_ID:
4195 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004196 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004198 // Check that we didn't try to load a non-module AST file as a module.
4199 //
4200 // FIXME: Should we also perform the converse check? Loading a module as
4201 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004202 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4203 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004204 F.ModuleName.empty()) {
4205 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4206 if (Result != OutOfDate ||
4207 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4208 Diag(diag::err_module_file_not_module) << FileName;
4209 return Result;
4210 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 break;
4212
4213 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004214 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 case OutOfDate: return OutOfDate;
4216 case VersionMismatch: return VersionMismatch;
4217 case ConfigurationMismatch: return ConfigurationMismatch;
4218 case HadErrors: return HadErrors;
4219 }
4220 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004221
Guy Benyei11169dd2012-12-18 14:30:41 +00004222 case AST_BLOCK_ID:
4223 if (!HaveReadControlBlock) {
4224 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004225 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004226 return VersionMismatch;
4227 }
4228
4229 // Record that we've loaded this module.
4230 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4231 return Success;
4232
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004233 case UNHASHED_CONTROL_BLOCK_ID:
4234 // This block is handled using look-ahead during ReadControlBlock. We
4235 // shouldn't get here!
4236 Error("malformed block record in AST file");
4237 return Failure;
4238
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 default:
4240 if (Stream.SkipBlock()) {
4241 Error("malformed block record in AST file");
4242 return Failure;
4243 }
4244 break;
4245 }
4246 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004247
4248 return Success;
4249}
4250
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004251ASTReader::ASTReadResult
4252ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4253 unsigned ClientLoadCapabilities) {
4254 const HeaderSearchOptions &HSOpts =
4255 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4256 bool AllowCompatibleConfigurationMismatch =
4257 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4258
4259 ASTReadResult Result = readUnhashedControlBlockImpl(
4260 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4261 Listener.get(),
4262 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4263
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004264 // If F was directly imported by another module, it's implicitly validated by
4265 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004266 if (DisableValidation || WasImportedBy ||
4267 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4268 return Success;
4269
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004270 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004271 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004272 return Failure;
4273 }
4274
4275 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4276 // If this module has already been finalized in the PCMCache, we're stuck
4277 // with it; we can only load a single version of each module.
4278 //
4279 // This can happen when a module is imported in two contexts: in one, as a
4280 // user module; in another, as a system module (due to an import from
4281 // another module marked with the [system] flag). It usually indicates a
4282 // bug in the module map: this module should also be marked with [system].
4283 //
4284 // If -Wno-system-headers (the default), and the first import is as a
4285 // system module, then validation will fail during the as-user import,
4286 // since -Werror flags won't have been validated. However, it's reasonable
4287 // to treat this consistently as a system module.
4288 //
4289 // If -Wsystem-headers, the PCM on disk was built with
4290 // -Wno-system-headers, and the first import is as a user module, then
4291 // validation will fail during the as-system import since the PCM on disk
4292 // doesn't guarantee that -Werror was respected. However, the -Werror
4293 // flags were checked during the initial as-user import.
4294 if (PCMCache.isBufferFinal(F.FileName)) {
4295 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4296 return Success;
4297 }
4298 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004299
4300 return Result;
4301}
4302
4303ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4304 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4305 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4306 bool ValidateDiagnosticOptions) {
4307 // Initialize a stream.
4308 BitstreamCursor Stream(StreamData);
4309
4310 // Sniff for the signature.
4311 if (!startsWithASTFileMagic(Stream))
4312 return Failure;
4313
4314 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4315 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4316 return Failure;
4317
4318 // Read all of the records in the options block.
4319 RecordData Record;
4320 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004321 while (true) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004322 llvm::BitstreamEntry Entry = Stream.advance();
4323
4324 switch (Entry.Kind) {
4325 case llvm::BitstreamEntry::Error:
4326 case llvm::BitstreamEntry::SubBlock:
4327 return Failure;
4328
4329 case llvm::BitstreamEntry::EndBlock:
4330 return Result;
4331
4332 case llvm::BitstreamEntry::Record:
4333 // The interesting case.
4334 break;
4335 }
4336
4337 // Read and process a record.
4338 Record.clear();
4339 switch (
4340 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004341 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004342 if (F)
4343 std::copy(Record.begin(), Record.end(), F->Signature.data());
4344 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004345 case DIAGNOSTIC_OPTIONS: {
4346 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4347 if (Listener && ValidateDiagnosticOptions &&
4348 !AllowCompatibleConfigurationMismatch &&
4349 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004350 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004351 break;
4352 }
4353 case DIAG_PRAGMA_MAPPINGS:
4354 if (!F)
4355 break;
4356 if (F->PragmaDiagMappings.empty())
4357 F->PragmaDiagMappings.swap(Record);
4358 else
4359 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4360 Record.begin(), Record.end());
4361 break;
4362 }
4363 }
4364}
4365
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004366/// Parse a record and blob containing module file extension metadata.
4367static bool parseModuleFileExtensionMetadata(
4368 const SmallVectorImpl<uint64_t> &Record,
4369 StringRef Blob,
4370 ModuleFileExtensionMetadata &Metadata) {
4371 if (Record.size() < 4) return true;
4372
4373 Metadata.MajorVersion = Record[0];
4374 Metadata.MinorVersion = Record[1];
4375
4376 unsigned BlockNameLen = Record[2];
4377 unsigned UserInfoLen = Record[3];
4378
4379 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4380
4381 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4382 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4383 Blob.data() + BlockNameLen + UserInfoLen);
4384 return false;
4385}
4386
4387ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4388 BitstreamCursor &Stream = F.Stream;
4389
4390 RecordData Record;
4391 while (true) {
4392 llvm::BitstreamEntry Entry = Stream.advance();
4393 switch (Entry.Kind) {
4394 case llvm::BitstreamEntry::SubBlock:
4395 if (Stream.SkipBlock())
4396 return Failure;
4397
4398 continue;
4399
4400 case llvm::BitstreamEntry::EndBlock:
4401 return Success;
4402
4403 case llvm::BitstreamEntry::Error:
4404 return HadErrors;
4405
4406 case llvm::BitstreamEntry::Record:
4407 break;
4408 }
4409
4410 Record.clear();
4411 StringRef Blob;
4412 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4413 switch (RecCode) {
4414 case EXTENSION_METADATA: {
4415 ModuleFileExtensionMetadata Metadata;
4416 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4417 return Failure;
4418
4419 // Find a module file extension with this block name.
4420 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4421 if (Known == ModuleFileExtensions.end()) break;
4422
4423 // Form a reader.
4424 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4425 F, Stream)) {
4426 F.ExtensionReaders.push_back(std::move(Reader));
4427 }
4428
4429 break;
4430 }
4431 }
4432 }
4433
4434 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004435}
4436
Richard Smitha7e2cc62015-05-01 01:53:09 +00004437void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004438 assert(ContextObj && "no context to initialize");
4439 ASTContext &Context = *ContextObj;
4440
Guy Benyei11169dd2012-12-18 14:30:41 +00004441 // If there's a listener, notify them that we "read" the translation unit.
4442 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004443 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 Context.getTranslationUnitDecl());
4445
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 // FIXME: Find a better way to deal with collisions between these
4447 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004448
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 // Load the special types.
4450 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4451 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4452 if (!Context.CFConstantStringTypeDecl)
4453 Context.setCFConstantStringType(GetType(String));
4454 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004455
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4457 QualType FileType = GetType(File);
4458 if (FileType.isNull()) {
4459 Error("FILE type is NULL");
4460 return;
4461 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004462
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 if (!Context.FILEDecl) {
4464 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4465 Context.setFILEDecl(Typedef->getDecl());
4466 else {
4467 const TagType *Tag = FileType->getAs<TagType>();
4468 if (!Tag) {
4469 Error("Invalid FILE type in AST file");
4470 return;
4471 }
4472 Context.setFILEDecl(Tag->getDecl());
4473 }
4474 }
4475 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004476
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4478 QualType Jmp_bufType = GetType(Jmp_buf);
4479 if (Jmp_bufType.isNull()) {
4480 Error("jmp_buf type is NULL");
4481 return;
4482 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004483
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 if (!Context.jmp_bufDecl) {
4485 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4486 Context.setjmp_bufDecl(Typedef->getDecl());
4487 else {
4488 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4489 if (!Tag) {
4490 Error("Invalid jmp_buf type in AST file");
4491 return;
4492 }
4493 Context.setjmp_bufDecl(Tag->getDecl());
4494 }
4495 }
4496 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004497
Guy Benyei11169dd2012-12-18 14:30:41 +00004498 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4499 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4500 if (Sigjmp_bufType.isNull()) {
4501 Error("sigjmp_buf type is NULL");
4502 return;
4503 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004504
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 if (!Context.sigjmp_bufDecl) {
4506 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4507 Context.setsigjmp_bufDecl(Typedef->getDecl());
4508 else {
4509 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4510 assert(Tag && "Invalid sigjmp_buf type in AST file");
4511 Context.setsigjmp_bufDecl(Tag->getDecl());
4512 }
4513 }
4514 }
4515
4516 if (unsigned ObjCIdRedef
4517 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4518 if (Context.ObjCIdRedefinitionType.isNull())
4519 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4520 }
4521
4522 if (unsigned ObjCClassRedef
4523 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4524 if (Context.ObjCClassRedefinitionType.isNull())
4525 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4526 }
4527
4528 if (unsigned ObjCSelRedef
4529 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4530 if (Context.ObjCSelRedefinitionType.isNull())
4531 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4532 }
4533
4534 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4535 QualType Ucontext_tType = GetType(Ucontext_t);
4536 if (Ucontext_tType.isNull()) {
4537 Error("ucontext_t type is NULL");
4538 return;
4539 }
4540
4541 if (!Context.ucontext_tDecl) {
4542 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4543 Context.setucontext_tDecl(Typedef->getDecl());
4544 else {
4545 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4546 assert(Tag && "Invalid ucontext_t type in AST file");
4547 Context.setucontext_tDecl(Tag->getDecl());
4548 }
4549 }
4550 }
4551 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004552
Guy Benyei11169dd2012-12-18 14:30:41 +00004553 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4554
4555 // If there were any CUDA special declarations, deserialize them.
4556 if (!CUDASpecialDeclRefs.empty()) {
4557 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4558 Context.setcudaConfigureCallDecl(
4559 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4560 }
Richard Smith56be7542014-03-21 00:33:59 +00004561
Guy Benyei11169dd2012-12-18 14:30:41 +00004562 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004563 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004564 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004565 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004566 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004567 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004568 if (Import.ImportLoc.isValid())
4569 PP.makeModuleVisible(Imported, Import.ImportLoc);
4570 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004571 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 }
4573 ImportedModules.clear();
4574}
4575
4576void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004577 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004578}
4579
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004580/// \brief Reads and return the signature record from \p PCH's control block, or
4581/// else returns 0.
4582static ASTFileSignature readASTFileSignature(StringRef PCH) {
4583 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004584 if (!startsWithASTFileMagic(Stream))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004585 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004586
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004587 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4588 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4589 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004590
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004591 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004592 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004593 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004594 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004595 if (Entry.Kind != llvm::BitstreamEntry::Record)
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004596 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004597
4598 Record.clear();
4599 StringRef Blob;
4600 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004601 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4602 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004603 }
4604}
4605
Guy Benyei11169dd2012-12-18 14:30:41 +00004606/// \brief Retrieve the name of the original source file name
4607/// directly from the AST file, without actually loading the AST
4608/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004609std::string ASTReader::getOriginalSourceFile(
4610 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004611 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004613 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004615 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4616 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004617 return std::string();
4618 }
4619
4620 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004621 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004622
4623 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004624 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4626 return std::string();
4627 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004628
Chris Lattnere7b154b2013-01-19 21:39:22 +00004629 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004630 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004631 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4632 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004633 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004634
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004635 // Scan for ORIGINAL_FILE inside the control block.
4636 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004637 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004638 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004639 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4640 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004641
Chris Lattnere7b154b2013-01-19 21:39:22 +00004642 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4643 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4644 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004646
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004648 StringRef Blob;
4649 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4650 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004652}
4653
4654namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004655
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 class SimplePCHValidator : public ASTReaderListener {
4657 const LangOptions &ExistingLangOpts;
4658 const TargetOptions &ExistingTargetOpts;
4659 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004660 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004662
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 public:
4664 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4665 const TargetOptions &ExistingTargetOpts,
4666 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004667 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004668 FileManager &FileMgr)
4669 : ExistingLangOpts(ExistingLangOpts),
4670 ExistingTargetOpts(ExistingTargetOpts),
4671 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004672 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004673 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00004674
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004675 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4676 bool AllowCompatibleDifferences) override {
4677 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4678 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004680
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004681 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4682 bool AllowCompatibleDifferences) override {
4683 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4684 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004686
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004687 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4688 StringRef SpecificModuleCachePath,
4689 bool Complain) override {
4690 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4691 ExistingModuleCachePath,
4692 nullptr, ExistingLangOpts);
4693 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004694
Craig Topper3e89dfe2014-03-13 02:13:41 +00004695 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4696 bool Complain,
4697 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004698 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004699 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 }
4701 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004702
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004703} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004704
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004705bool ASTReader::readASTFileControlBlock(
4706 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004707 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004708 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004709 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004711 // FIXME: This allows use of the VFS; we do not allow use of the
4712 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004713 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004714 if (!Buffer) {
4715 return true;
4716 }
4717
4718 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004719 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4720 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004721
4722 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004723 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004725
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004726 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004727 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004728 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004729
4730 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004731 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004732 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004733 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004734
Guy Benyei11169dd2012-12-18 14:30:41 +00004735 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004736 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004737 bool DoneWithControlBlock = false;
4738 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004739 llvm::BitstreamEntry Entry = Stream.advance();
4740
4741 switch (Entry.Kind) {
4742 case llvm::BitstreamEntry::SubBlock: {
4743 switch (Entry.ID) {
4744 case OPTIONS_BLOCK_ID: {
4745 std::string IgnoredSuggestedPredefines;
4746 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4747 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004748 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004749 return true;
4750 break;
4751 }
4752
4753 case INPUT_FILES_BLOCK_ID:
4754 InputFilesCursor = Stream;
4755 if (Stream.SkipBlock() ||
4756 (NeedsInputFiles &&
4757 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4758 return true;
4759 break;
4760
4761 default:
4762 if (Stream.SkipBlock())
4763 return true;
4764 break;
4765 }
4766
4767 continue;
4768 }
4769
4770 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004771 DoneWithControlBlock = true;
4772 break;
Richard Smith0516b182015-09-08 19:40:14 +00004773
4774 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004775 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004776
4777 case llvm::BitstreamEntry::Record:
4778 break;
4779 }
4780
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004781 if (DoneWithControlBlock) break;
4782
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004784 StringRef Blob;
4785 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004786 switch ((ControlRecordTypes)RecCode) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004787 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004788 if (Record[0] != VERSION_MAJOR)
4789 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004790 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004791 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004792 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004793 case MODULE_NAME:
4794 Listener.ReadModuleName(Blob);
4795 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004796 case MODULE_DIRECTORY:
4797 ModuleDir = Blob;
4798 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004799 case MODULE_MAP_FILE: {
4800 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004801 auto Path = ReadString(Record, Idx);
4802 ResolveImportedPath(Path, ModuleDir);
4803 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004804 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004805 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004806 case INPUT_FILE_OFFSETS: {
4807 if (!NeedsInputFiles)
4808 break;
4809
4810 unsigned NumInputFiles = Record[0];
4811 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004812 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004813 for (unsigned I = 0; I != NumInputFiles; ++I) {
4814 // Go find this input file.
4815 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004816
4817 if (isSystemFile && !NeedsSystemInputFiles)
4818 break; // the rest are system input files
4819
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004820 BitstreamCursor &Cursor = InputFilesCursor;
4821 SavedStreamPosition SavedPosition(Cursor);
4822 Cursor.JumpToBit(InputFileOffs[I]);
4823
4824 unsigned Code = Cursor.ReadCode();
4825 RecordData Record;
4826 StringRef Blob;
4827 bool shouldContinue = false;
4828 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4829 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004830 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004831 std::string Filename = Blob;
4832 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004833 shouldContinue = Listener.visitInputFile(
4834 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004835 break;
4836 }
4837 if (!shouldContinue)
4838 break;
4839 }
4840 break;
4841 }
4842
Richard Smithd4b230b2014-10-27 23:01:16 +00004843 case IMPORTS: {
4844 if (!NeedsImports)
4845 break;
4846
4847 unsigned Idx = 0, N = Record.size();
4848 while (Idx < N) {
4849 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004850 Idx += 5; // ImportLoc, Size, ModTime, Signature
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004851 SkipString(Record, Idx); // Module name; FIXME: pass to listener?
Richard Smith7ed1bc92014-12-05 22:42:13 +00004852 std::string Filename = ReadString(Record, Idx);
4853 ResolveImportedPath(Filename, ModuleDir);
4854 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004855 }
4856 break;
4857 }
4858
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004859 default:
4860 // No other validation to perform.
4861 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 }
4863 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004864
4865 // Look for module file extension blocks, if requested.
4866 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004867 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004868 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4869 bool DoneWithExtensionBlock = false;
4870 while (!DoneWithExtensionBlock) {
4871 llvm::BitstreamEntry Entry = Stream.advance();
4872
4873 switch (Entry.Kind) {
4874 case llvm::BitstreamEntry::SubBlock:
4875 if (Stream.SkipBlock())
4876 return true;
4877
4878 continue;
4879
4880 case llvm::BitstreamEntry::EndBlock:
4881 DoneWithExtensionBlock = true;
4882 continue;
4883
4884 case llvm::BitstreamEntry::Error:
4885 return true;
4886
4887 case llvm::BitstreamEntry::Record:
4888 break;
4889 }
4890
4891 Record.clear();
4892 StringRef Blob;
4893 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4894 switch (RecCode) {
4895 case EXTENSION_METADATA: {
4896 ModuleFileExtensionMetadata Metadata;
4897 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4898 return true;
4899
4900 Listener.readModuleFileExtension(Metadata);
4901 break;
4902 }
4903 }
4904 }
4905 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004906 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004907 }
4908
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004909 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4910 if (readUnhashedControlBlockImpl(
4911 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4912 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4913 ValidateDiagnosticOptions) != Success)
4914 return true;
4915
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004916 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004917}
4918
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004919bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4920 const PCHContainerReader &PCHContainerRdr,
4921 const LangOptions &LangOpts,
4922 const TargetOptions &TargetOpts,
4923 const PreprocessorOptions &PPOpts,
4924 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004925 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4926 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004927 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004928 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004929 validator,
4930 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004931}
4932
Ben Langmuir2c9af442014-04-10 17:57:43 +00004933ASTReader::ASTReadResult
4934ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 // Enter the submodule block.
4936 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4937 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004938 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004939 }
4940
4941 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4942 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004943 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004944 RecordData Record;
4945 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004946 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004947
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004948 switch (Entry.Kind) {
4949 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4950 case llvm::BitstreamEntry::Error:
4951 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004952 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004953 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004954 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004955 case llvm::BitstreamEntry::Record:
4956 // The interesting case.
4957 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004959
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004961 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004962 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004963 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4964
4965 if ((Kind == SUBMODULE_METADATA) != First) {
4966 Error("submodule metadata record should be at beginning of block");
4967 return Failure;
4968 }
4969 First = false;
4970
4971 // Submodule information is only valid if we have a current module.
4972 // FIXME: Should we error on these cases?
4973 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4974 Kind != SUBMODULE_DEFINITION)
4975 continue;
4976
4977 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004978 default: // Default behavior: ignore.
4979 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004980
Richard Smith03478d92014-10-23 22:12:14 +00004981 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004982 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004984 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 }
Richard Smith03478d92014-10-23 22:12:14 +00004986
Chris Lattner0e6c9402013-01-20 02:38:54 +00004987 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004988 unsigned Idx = 0;
4989 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4990 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Richard Smithdd8b5332017-09-04 05:37:53 +00004991 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00004992 bool IsFramework = Record[Idx++];
4993 bool IsExplicit = Record[Idx++];
4994 bool IsSystem = Record[Idx++];
4995 bool IsExternC = Record[Idx++];
4996 bool InferSubmodules = Record[Idx++];
4997 bool InferExplicitSubmodules = Record[Idx++];
4998 bool InferExportWildcard = Record[Idx++];
4999 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005000
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005001 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005002 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005004
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 // Retrieve this (sub)module from the module map, creating it if
5006 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005007 CurrentModule =
5008 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5009 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005010
5011 // FIXME: set the definition loc for CurrentModule, or call
5012 // ModMap.setInferredModuleAllowedBy()
5013
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5015 if (GlobalIndex >= SubmodulesLoaded.size() ||
5016 SubmodulesLoaded[GlobalIndex]) {
5017 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005018 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005019 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005020
Douglas Gregor7029ce12013-03-19 00:28:20 +00005021 if (!ParentModule) {
5022 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5023 if (CurFile != F.File) {
5024 if (!Diags.isDiagnosticInFlight()) {
5025 Diag(diag::err_module_file_conflict)
5026 << CurrentModule->getTopLevelModuleName()
5027 << CurFile->getName()
5028 << F.File->getName();
5029 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005030 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005031 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005032 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005033
5034 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005035 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005036 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005037
Richard Smithdd8b5332017-09-04 05:37:53 +00005038 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005039 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 CurrentModule->IsFromModuleFile = true;
5041 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005042 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 CurrentModule->InferSubmodules = InferSubmodules;
5044 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5045 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005046 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 if (DeserializationListener)
5048 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005049
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005051
Richard Smith8a3e39a2016-03-28 21:31:09 +00005052 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005053 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005054 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005055 CurrentModule->UnresolvedConflicts.clear();
5056 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005057
5058 // The module is available unless it's missing a requirement; relevant
5059 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5060 // Missing headers that were present when the module was built do not
5061 // make it unavailable -- if we got this far, this must be an explicitly
5062 // imported module file.
5063 CurrentModule->Requirements.clear();
5064 CurrentModule->MissingHeaders.clear();
5065 CurrentModule->IsMissingRequirement =
5066 ParentModule && ParentModule->IsMissingRequirement;
5067 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 break;
5069 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005070
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005072 std::string Filename = Blob;
5073 ResolveImportedPath(F, Filename);
5074 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005076 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5077 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005078 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5079 Error("mismatched umbrella headers in submodule");
5080 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 }
5082 }
5083 break;
5084 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005085
Richard Smith202210b2014-10-24 20:23:01 +00005086 case SUBMODULE_HEADER:
5087 case SUBMODULE_EXCLUDED_HEADER:
5088 case SUBMODULE_PRIVATE_HEADER:
5089 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005090 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5091 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005092 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005093
Richard Smith202210b2014-10-24 20:23:01 +00005094 case SUBMODULE_TEXTUAL_HEADER:
5095 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5096 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5097 // them here.
5098 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005099
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005100 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005101 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005103
5104 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005105 std::string Dirname = Blob;
5106 ResolveImportedPath(F, Dirname);
5107 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005108 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005109 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5110 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005111 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5112 Error("mismatched umbrella directories in submodule");
5113 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 }
5115 }
5116 break;
5117 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005118
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 F.BaseSubmoduleID = getTotalNumSubmodules();
5121 F.LocalNumSubmodules = Record[0];
5122 unsigned LocalBaseSubmoduleID = Record[1];
5123 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005124 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 // module.
5126 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005127
5128 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 // module.
5130 F.SubmoduleRemap.insertOrReplace(
5131 std::make_pair(LocalBaseSubmoduleID,
5132 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005133
Ben Langmuir52ca6782014-10-20 16:27:32 +00005134 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5135 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005136 break;
5137 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005138
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005139 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005141 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 Unresolved.File = &F;
5143 Unresolved.Mod = CurrentModule;
5144 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005145 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005146 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005147 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005148 }
5149 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005150
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005151 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005152 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005153 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 Unresolved.File = &F;
5155 Unresolved.Mod = CurrentModule;
5156 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005157 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005159 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005161
5162 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 // the parsed, unresolved exports around.
5164 CurrentModule->UnresolvedExports.clear();
5165 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005166
5167 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005168 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5169 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005171
5172 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005173 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005174 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005175 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005176
5177 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005178 CurrentModule->ConfigMacros.push_back(Blob.str());
5179 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005180
5181 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005182 UnresolvedModuleRef Unresolved;
5183 Unresolved.File = &F;
5184 Unresolved.Mod = CurrentModule;
5185 Unresolved.ID = Record[0];
5186 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5187 Unresolved.IsWildcard = false;
5188 Unresolved.String = Blob;
5189 UnresolvedModuleRefs.push_back(Unresolved);
5190 break;
5191 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005192
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005193 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005194 if (!ContextObj)
5195 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005196 SmallVector<uint32_t, 16> Inits;
5197 for (auto &ID : Record)
5198 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005199 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005200 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005201 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005202
5203 case SUBMODULE_EXPORT_AS:
5204 CurrentModule->ExportAsModule = Blob.str();
5205 break;
5206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 }
5208}
5209
5210/// \brief Parse the record that corresponds to a LangOptions data
5211/// structure.
5212///
5213/// This routine parses the language options from the AST file and then gives
5214/// them to the AST listener if one is set.
5215///
5216/// \returns true if the listener deems the file unacceptable, false otherwise.
5217bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5218 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005219 ASTReaderListener &Listener,
5220 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005221 LangOptions LangOpts;
5222 unsigned Idx = 0;
5223#define LANGOPT(Name, Bits, Default, Description) \
5224 LangOpts.Name = Record[Idx++];
5225#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5226 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5227#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005228#define SANITIZER(NAME, ID) \
5229 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005230#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005231
Ben Langmuircd98cb72015-06-23 18:20:18 +00005232 for (unsigned N = Record[Idx++]; N; --N)
5233 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5234
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5236 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5237 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005238
Ben Langmuird4a667a2015-06-23 18:20:23 +00005239 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005240
5241 // Comment options.
5242 for (unsigned N = Record[Idx++]; N; --N) {
5243 LangOpts.CommentOpts.BlockCommandNames.push_back(
5244 ReadString(Record, Idx));
5245 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005246 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005247
Samuel Antaoee8fb302016-01-06 13:42:12 +00005248 // OpenMP offloading options.
5249 for (unsigned N = Record[Idx++]; N; --N) {
5250 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5251 }
5252
5253 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5254
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005255 return Listener.ReadLanguageOptions(LangOpts, Complain,
5256 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005257}
5258
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005259bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5260 ASTReaderListener &Listener,
5261 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 unsigned Idx = 0;
5263 TargetOptions TargetOpts;
5264 TargetOpts.Triple = ReadString(Record, Idx);
5265 TargetOpts.CPU = ReadString(Record, Idx);
5266 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 for (unsigned N = Record[Idx++]; N; --N) {
5268 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5269 }
5270 for (unsigned N = Record[Idx++]; N; --N) {
5271 TargetOpts.Features.push_back(ReadString(Record, Idx));
5272 }
5273
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005274 return Listener.ReadTargetOptions(TargetOpts, Complain,
5275 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005276}
5277
5278bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5279 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005280 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005281 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005282#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005283#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005284 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005285#include "clang/Basic/DiagnosticOptions.def"
5286
Richard Smith3be1cb22014-08-07 00:24:21 +00005287 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005288 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005289 for (unsigned N = Record[Idx++]; N; --N)
5290 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005291
5292 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5293}
5294
5295bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5296 ASTReaderListener &Listener) {
5297 FileSystemOptions FSOpts;
5298 unsigned Idx = 0;
5299 FSOpts.WorkingDir = ReadString(Record, Idx);
5300 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5301}
5302
5303bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5304 bool Complain,
5305 ASTReaderListener &Listener) {
5306 HeaderSearchOptions HSOpts;
5307 unsigned Idx = 0;
5308 HSOpts.Sysroot = ReadString(Record, Idx);
5309
5310 // Include entries.
5311 for (unsigned N = Record[Idx++]; N; --N) {
5312 std::string Path = ReadString(Record, Idx);
5313 frontend::IncludeDirGroup Group
5314 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 bool IsFramework = Record[Idx++];
5316 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005317 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5318 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005319 }
5320
5321 // System header prefixes.
5322 for (unsigned N = Record[Idx++]; N; --N) {
5323 std::string Prefix = ReadString(Record, Idx);
5324 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005325 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 }
5327
5328 HSOpts.ResourceDir = ReadString(Record, Idx);
5329 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005330 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005331 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005332 HSOpts.ImplicitModuleMaps = Record[Idx++];
5333 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005334 HSOpts.UseBuiltinIncludes = Record[Idx++];
5335 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5336 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5337 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005338 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005339
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005340 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5341 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005342}
5343
5344bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5345 bool Complain,
5346 ASTReaderListener &Listener,
5347 std::string &SuggestedPredefines) {
5348 PreprocessorOptions PPOpts;
5349 unsigned Idx = 0;
5350
5351 // Macro definitions/undefs
5352 for (unsigned N = Record[Idx++]; N; --N) {
5353 std::string Macro = ReadString(Record, Idx);
5354 bool IsUndef = Record[Idx++];
5355 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5356 }
5357
5358 // Includes
5359 for (unsigned N = Record[Idx++]; N; --N) {
5360 PPOpts.Includes.push_back(ReadString(Record, Idx));
5361 }
5362
5363 // Macro Includes
5364 for (unsigned N = Record[Idx++]; N; --N) {
5365 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5366 }
5367
5368 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005369 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5371 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5372 PPOpts.ObjCXXARCStandardLibrary =
5373 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5374 SuggestedPredefines.clear();
5375 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5376 SuggestedPredefines);
5377}
5378
5379std::pair<ModuleFile *, unsigned>
5380ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5381 GlobalPreprocessedEntityMapType::iterator
5382 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005383 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005384 "Corrupted global preprocessed entity map");
5385 ModuleFile *M = I->second;
5386 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5387 return std::make_pair(M, LocalIndex);
5388}
5389
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005390llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005391ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5392 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5393 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5394 Mod.NumPreprocessedEntities);
5395
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005396 return llvm::make_range(PreprocessingRecord::iterator(),
5397 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005398}
5399
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005400llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005401ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005402 return llvm::make_range(
5403 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5404 ModuleDeclIterator(this, &Mod,
5405 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005406}
5407
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005408SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5409 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5410 assert(I != GlobalSkippedRangeMap.end() &&
5411 "Corrupted global skipped range map");
5412 ModuleFile *M = I->second;
5413 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5414 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5415 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5416 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5417 TranslateSourceLocation(*M, RawRange.getEnd()));
5418 assert(Range.isValid());
5419 return Range;
5420}
5421
Guy Benyei11169dd2012-12-18 14:30:41 +00005422PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5423 PreprocessedEntityID PPID = Index+1;
5424 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5425 ModuleFile &M = *PPInfo.first;
5426 unsigned LocalIndex = PPInfo.second;
5427 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5428
Guy Benyei11169dd2012-12-18 14:30:41 +00005429 if (!PP.getPreprocessingRecord()) {
5430 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005431 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005433
5434 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005435 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5436
5437 llvm::BitstreamEntry Entry =
5438 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5439 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005440 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005441
Guy Benyei11169dd2012-12-18 14:30:41 +00005442 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005443 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5444 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005445 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005446 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005447 RecordData Record;
5448 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005449 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5450 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 switch (RecType) {
5452 case PPD_MACRO_EXPANSION: {
5453 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005454 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005455 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005456 if (isBuiltin)
5457 Name = getLocalIdentifier(M, Record[1]);
5458 else {
Richard Smith66a81862015-05-04 02:25:31 +00005459 PreprocessedEntityID GlobalID =
5460 getGlobalPreprocessedEntityID(M, Record[1]);
5461 Def = cast<MacroDefinitionRecord>(
5462 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005463 }
5464
5465 MacroExpansion *ME;
5466 if (isBuiltin)
5467 ME = new (PPRec) MacroExpansion(Name, Range);
5468 else
5469 ME = new (PPRec) MacroExpansion(Def, Range);
5470
5471 return ME;
5472 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005473
Guy Benyei11169dd2012-12-18 14:30:41 +00005474 case PPD_MACRO_DEFINITION: {
5475 // Decode the identifier info and then check again; if the macro is
5476 // still defined and associated with the identifier,
5477 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005478 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005479
5480 if (DeserializationListener)
5481 DeserializationListener->MacroDefinitionRead(PPID, MD);
5482
5483 return MD;
5484 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005485
Guy Benyei11169dd2012-12-18 14:30:41 +00005486 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005487 const char *FullFileNameStart = Blob.data() + Record[0];
5488 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005489 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005490 if (!FullFileName.empty())
5491 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005492
Guy Benyei11169dd2012-12-18 14:30:41 +00005493 // FIXME: Stable encoding
5494 InclusionDirective::InclusionKind Kind
5495 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5496 InclusionDirective *ID
5497 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005498 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005499 Record[1], Record[3],
5500 File,
5501 Range);
5502 return ID;
5503 }
5504 }
5505
5506 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5507}
5508
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005509/// \brief Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005510/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005511///
5512/// \param SLocMapI points at a chunk of a module that contains no
5513/// preprocessed entities or the entities it contains are not the ones we are
5514/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005515PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5516 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5517 ++SLocMapI;
5518 for (GlobalSLocOffsetMapType::const_iterator
5519 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5520 ModuleFile &M = *SLocMapI->second;
5521 if (M.NumPreprocessedEntities)
5522 return M.BasePreprocessedEntityID;
5523 }
5524
5525 return getTotalNumPreprocessedEntities();
5526}
5527
5528namespace {
5529
Guy Benyei11169dd2012-12-18 14:30:41 +00005530struct PPEntityComp {
5531 const ASTReader &Reader;
5532 ModuleFile &M;
5533
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005534 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005535
5536 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5537 SourceLocation LHS = getLoc(L);
5538 SourceLocation RHS = getLoc(R);
5539 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5540 }
5541
5542 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5543 SourceLocation LHS = getLoc(L);
5544 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5545 }
5546
5547 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5548 SourceLocation RHS = getLoc(R);
5549 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5550 }
5551
5552 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005553 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 }
5555};
5556
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005557} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005558
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005559PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5560 bool EndsAfter) const {
5561 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005562 return getTotalNumPreprocessedEntities();
5563
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005564 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5565 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005566 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5567 "Corrupted global sloc offset map");
5568
5569 if (SLocMapI->second->NumPreprocessedEntities == 0)
5570 return findNextPreprocessedEntity(SLocMapI);
5571
5572 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005573
5574 using pp_iterator = const PPEntityOffset *;
5575
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5577 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5578
5579 size_t Count = M.NumPreprocessedEntities;
5580 size_t Half;
5581 pp_iterator First = pp_begin;
5582 pp_iterator PPI;
5583
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005584 if (EndsAfter) {
5585 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005586 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005587 } else {
5588 // Do a binary search manually instead of using std::lower_bound because
5589 // The end locations of entities may be unordered (when a macro expansion
5590 // is inside another macro argument), but for this case it is not important
5591 // whether we get the first macro expansion or its containing macro.
5592 while (Count > 0) {
5593 Half = Count / 2;
5594 PPI = First;
5595 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005596 if (SourceMgr.isBeforeInTranslationUnit(
5597 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005598 First = PPI;
5599 ++First;
5600 Count = Count - Half - 1;
5601 } else
5602 Count = Half;
5603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 }
5605
5606 if (PPI == pp_end)
5607 return findNextPreprocessedEntity(SLocMapI);
5608
5609 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5610}
5611
Guy Benyei11169dd2012-12-18 14:30:41 +00005612/// \brief Returns a pair of [Begin, End) indices of preallocated
5613/// preprocessed entities that \arg Range encompasses.
5614std::pair<unsigned, unsigned>
5615 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5616 if (Range.isInvalid())
5617 return std::make_pair(0,0);
5618 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5619
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005620 PreprocessedEntityID BeginID =
5621 findPreprocessedEntity(Range.getBegin(), false);
5622 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005623 return std::make_pair(BeginID, EndID);
5624}
5625
5626/// \brief Optionally returns true or false if the preallocated preprocessed
5627/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005628Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 FileID FID) {
5630 if (FID.isInvalid())
5631 return false;
5632
5633 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5634 ModuleFile &M = *PPInfo.first;
5635 unsigned LocalIndex = PPInfo.second;
5636 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005637
Richard Smithcb34bd32016-03-27 07:28:06 +00005638 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005639 if (Loc.isInvalid())
5640 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005641
Guy Benyei11169dd2012-12-18 14:30:41 +00005642 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5643 return true;
5644 else
5645 return false;
5646}
5647
5648namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005649
Guy Benyei11169dd2012-12-18 14:30:41 +00005650 /// \brief Visitor used to search for information about a header file.
5651 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005652 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00005653 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005654
Guy Benyei11169dd2012-12-18 14:30:41 +00005655 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005656 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005657
5658 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005659 HeaderFileInfoLookupTable *Table
5660 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5661 if (!Table)
5662 return false;
5663
5664 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005665 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 if (Pos == Table->end())
5667 return false;
5668
Richard Smithbdf2d932015-07-30 03:37:16 +00005669 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005670 return true;
5671 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005672
David Blaikie05785d12013-02-20 22:23:23 +00005673 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005674 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005675
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005676} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005677
5678HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005679 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005680 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005681 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005682 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005683
Guy Benyei11169dd2012-12-18 14:30:41 +00005684 return HeaderFileInfo();
5685}
5686
5687void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005688 using DiagState = DiagnosticsEngine::DiagState;
5689 SmallVector<DiagState *, 32> DiagStates;
5690
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005691 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005692 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005693 auto &Record = F.PragmaDiagMappings;
5694 if (Record.empty())
5695 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005696
Richard Smithd230de22017-01-26 01:01:01 +00005697 DiagStates.clear();
5698
5699 auto ReadDiagState =
5700 [&](const DiagState &BasedOn, SourceLocation Loc,
5701 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5702 unsigned BackrefID = Record[Idx++];
5703 if (BackrefID != 0)
5704 return DiagStates[BackrefID - 1];
5705
Guy Benyei11169dd2012-12-18 14:30:41 +00005706 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005707 Diag.DiagStates.push_back(BasedOn);
5708 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005709 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005710 unsigned Size = Record[Idx++];
5711 assert(Idx + Size * 2 <= Record.size() &&
5712 "Invalid data, not enough diag/map pairs");
5713 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005714 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005715 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005716 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005717 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5718 continue;
5719
5720 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5721
5722 // If this mapping was specified as a warning but the severity was
5723 // upgraded due to diagnostic settings, simulate the current diagnostic
5724 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005725 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5726 NewMapping.setSeverity(diag::Severity::Warning);
5727 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005728 }
5729
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005730 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005731 }
Richard Smithd230de22017-01-26 01:01:01 +00005732 return NewState;
5733 };
5734
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005735 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005736 DiagState *FirstState;
5737 if (F.Kind == MK_ImplicitModule) {
5738 // Implicitly-built modules are reused with different diagnostic
5739 // settings. Use the initial diagnostic state from Diag to simulate this
5740 // compilation's diagnostic settings.
5741 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5742 DiagStates.push_back(FirstState);
5743
5744 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005745 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005746 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005747 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005748 assert(Idx < Record.size() &&
5749 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005750 } else if (F.isModule()) {
5751 // For an explicit module, preserve the flags from the module build
5752 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5753 // -Wblah flags.
5754 unsigned Flags = Record[Idx++];
5755 DiagState Initial;
5756 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5757 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5758 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5759 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5760 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5761 Initial.ExtBehavior = (diag::Severity)Flags;
5762 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005763
Richard Smithe37391c2017-05-03 00:28:49 +00005764 // Set up the root buffer of the module to start with the initial
5765 // diagnostic state of the module itself, to cover files that contain no
5766 // explicit transitions (for which we did not serialize anything).
5767 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5768 .StateTransitions.push_back({FirstState, 0});
5769 } else {
5770 // For prefix ASTs, start with whatever the user configured on the
5771 // command line.
5772 Idx++; // Skip flags.
5773 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5774 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005775 }
Richard Smithd230de22017-01-26 01:01:01 +00005776
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005777 // Read the state transitions.
5778 unsigned NumLocations = Record[Idx++];
5779 while (NumLocations--) {
5780 assert(Idx < Record.size() &&
5781 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005782 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5783 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5784 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5785 unsigned Transitions = Record[Idx++];
5786
5787 // Note that we don't need to set up Parent/ParentOffset here, because
5788 // we won't be changing the diagnostic state within imported FileIDs
5789 // (other than perhaps appending to the main source file, which has no
5790 // parent).
5791 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5792 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5793 for (unsigned I = 0; I != Transitions; ++I) {
5794 unsigned Offset = Record[Idx++];
5795 auto *State =
5796 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5797 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005798 }
5799 }
Richard Smithd230de22017-01-26 01:01:01 +00005800
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005801 // Read the final state.
5802 assert(Idx < Record.size() &&
5803 "Invalid data, missing final pragma diagnostic state");
5804 SourceLocation CurStateLoc =
5805 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5806 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5807
5808 if (!F.isModule()) {
5809 Diag.DiagStatesByLoc.CurDiagState = CurState;
5810 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5811
5812 // Preserve the property that the imaginary root file describes the
5813 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00005814 FileID NullFile;
5815 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005816 if (T.empty())
5817 T.push_back({CurState, 0});
5818 else
5819 T[0].State = CurState;
5820 }
5821
Richard Smithd230de22017-01-26 01:01:01 +00005822 // Don't try to read these mappings again.
5823 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005824 }
5825}
5826
5827/// \brief Get the correct cursor and offset for loading a type.
5828ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5829 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5830 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5831 ModuleFile *M = I->second;
5832 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5833}
5834
5835/// \brief Read and return the type with the given index..
5836///
5837/// The index is the type ID, shifted and minus the number of predefs. This
5838/// routine actually reads the record corresponding to the type at the given
5839/// location. It is a helper routine for GetType, which deals with reading type
5840/// IDs.
5841QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005842 assert(ContextObj && "reading type with no AST context");
5843 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005844 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005845 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005846
5847 // Keep track of where we are in the stream, then jump back there
5848 // after reading this type.
5849 SavedStreamPosition SavedPosition(DeclsCursor);
5850
5851 ReadingKindTracker ReadingKind(Read_Type, *this);
5852
5853 // Note that we are loading a type record.
5854 Deserializing AType(this);
5855
5856 unsigned Idx = 0;
5857 DeclsCursor.JumpToBit(Loc.Offset);
5858 RecordData Record;
5859 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005860 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005861 case TYPE_EXT_QUAL: {
5862 if (Record.size() != 2) {
5863 Error("Incorrect encoding of extended qualifier type");
5864 return QualType();
5865 }
5866 QualType Base = readType(*Loc.F, Record, Idx);
5867 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5868 return Context.getQualifiedType(Base, Quals);
5869 }
5870
5871 case TYPE_COMPLEX: {
5872 if (Record.size() != 1) {
5873 Error("Incorrect encoding of complex type");
5874 return QualType();
5875 }
5876 QualType ElemType = readType(*Loc.F, Record, Idx);
5877 return Context.getComplexType(ElemType);
5878 }
5879
5880 case TYPE_POINTER: {
5881 if (Record.size() != 1) {
5882 Error("Incorrect encoding of pointer type");
5883 return QualType();
5884 }
5885 QualType PointeeType = readType(*Loc.F, Record, Idx);
5886 return Context.getPointerType(PointeeType);
5887 }
5888
Reid Kleckner8a365022013-06-24 17:51:48 +00005889 case TYPE_DECAYED: {
5890 if (Record.size() != 1) {
5891 Error("Incorrect encoding of decayed type");
5892 return QualType();
5893 }
5894 QualType OriginalType = readType(*Loc.F, Record, Idx);
5895 QualType DT = Context.getAdjustedParameterType(OriginalType);
5896 if (!isa<DecayedType>(DT))
5897 Error("Decayed type does not decay");
5898 return DT;
5899 }
5900
Reid Kleckner0503a872013-12-05 01:23:43 +00005901 case TYPE_ADJUSTED: {
5902 if (Record.size() != 2) {
5903 Error("Incorrect encoding of adjusted type");
5904 return QualType();
5905 }
5906 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5907 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5908 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5909 }
5910
Guy Benyei11169dd2012-12-18 14:30:41 +00005911 case TYPE_BLOCK_POINTER: {
5912 if (Record.size() != 1) {
5913 Error("Incorrect encoding of block pointer type");
5914 return QualType();
5915 }
5916 QualType PointeeType = readType(*Loc.F, Record, Idx);
5917 return Context.getBlockPointerType(PointeeType);
5918 }
5919
5920 case TYPE_LVALUE_REFERENCE: {
5921 if (Record.size() != 2) {
5922 Error("Incorrect encoding of lvalue reference type");
5923 return QualType();
5924 }
5925 QualType PointeeType = readType(*Loc.F, Record, Idx);
5926 return Context.getLValueReferenceType(PointeeType, Record[1]);
5927 }
5928
5929 case TYPE_RVALUE_REFERENCE: {
5930 if (Record.size() != 1) {
5931 Error("Incorrect encoding of rvalue reference type");
5932 return QualType();
5933 }
5934 QualType PointeeType = readType(*Loc.F, Record, Idx);
5935 return Context.getRValueReferenceType(PointeeType);
5936 }
5937
5938 case TYPE_MEMBER_POINTER: {
5939 if (Record.size() != 2) {
5940 Error("Incorrect encoding of member pointer type");
5941 return QualType();
5942 }
5943 QualType PointeeType = readType(*Loc.F, Record, Idx);
5944 QualType ClassType = readType(*Loc.F, Record, Idx);
5945 if (PointeeType.isNull() || ClassType.isNull())
5946 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005947
Guy Benyei11169dd2012-12-18 14:30:41 +00005948 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5949 }
5950
5951 case TYPE_CONSTANT_ARRAY: {
5952 QualType ElementType = readType(*Loc.F, Record, Idx);
5953 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5954 unsigned IndexTypeQuals = Record[2];
5955 unsigned Idx = 3;
5956 llvm::APInt Size = ReadAPInt(Record, Idx);
5957 return Context.getConstantArrayType(ElementType, Size,
5958 ASM, IndexTypeQuals);
5959 }
5960
5961 case TYPE_INCOMPLETE_ARRAY: {
5962 QualType ElementType = readType(*Loc.F, Record, Idx);
5963 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5964 unsigned IndexTypeQuals = Record[2];
5965 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5966 }
5967
5968 case TYPE_VARIABLE_ARRAY: {
5969 QualType ElementType = readType(*Loc.F, Record, Idx);
5970 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5971 unsigned IndexTypeQuals = Record[2];
5972 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5973 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5974 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5975 ASM, IndexTypeQuals,
5976 SourceRange(LBLoc, RBLoc));
5977 }
5978
5979 case TYPE_VECTOR: {
5980 if (Record.size() != 3) {
5981 Error("incorrect encoding of vector type in AST file");
5982 return QualType();
5983 }
5984
5985 QualType ElementType = readType(*Loc.F, Record, Idx);
5986 unsigned NumElements = Record[1];
5987 unsigned VecKind = Record[2];
5988 return Context.getVectorType(ElementType, NumElements,
5989 (VectorType::VectorKind)VecKind);
5990 }
5991
5992 case TYPE_EXT_VECTOR: {
5993 if (Record.size() != 3) {
5994 Error("incorrect encoding of extended vector type in AST file");
5995 return QualType();
5996 }
5997
5998 QualType ElementType = readType(*Loc.F, Record, Idx);
5999 unsigned NumElements = Record[1];
6000 return Context.getExtVectorType(ElementType, NumElements);
6001 }
6002
6003 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006004 if (Record.size() != 7) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006005 Error("incorrect encoding of no-proto function type");
6006 return QualType();
6007 }
6008 QualType ResultType = readType(*Loc.F, Record, Idx);
6009 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006010 (CallingConv)Record[4], Record[5], Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 return Context.getFunctionNoProtoType(ResultType, Info);
6012 }
6013
6014 case TYPE_FUNCTION_PROTO: {
6015 QualType ResultType = readType(*Loc.F, Record, Idx);
6016
6017 FunctionProtoType::ExtProtoInfo EPI;
6018 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6019 /*hasregparm*/ Record[2],
6020 /*regparm*/ Record[3],
6021 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006022 /*produces*/ Record[5],
6023 /*nocallersavedregs*/ Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006024
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006025 unsigned Idx = 7;
Guy Benyei11169dd2012-12-18 14:30:41 +00006026
6027 EPI.Variadic = Record[Idx++];
6028 EPI.HasTrailingReturn = Record[Idx++];
6029 EPI.TypeQuals = Record[Idx++];
6030 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006031 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006032 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006033
6034 unsigned NumParams = Record[Idx++];
6035 SmallVector<QualType, 16> ParamTypes;
6036 for (unsigned I = 0; I != NumParams; ++I)
6037 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6038
John McCall18afab72016-03-01 00:49:02 +00006039 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6040 if (Idx != Record.size()) {
6041 for (unsigned I = 0; I != NumParams; ++I)
6042 ExtParameterInfos.push_back(
6043 FunctionProtoType::ExtParameterInfo
6044 ::getFromOpaqueValue(Record[Idx++]));
6045 EPI.ExtParameterInfos = ExtParameterInfos.data();
6046 }
6047
6048 assert(Idx == Record.size());
6049
Jordan Rose5c382722013-03-08 21:51:21 +00006050 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006051 }
6052
6053 case TYPE_UNRESOLVED_USING: {
6054 unsigned Idx = 0;
6055 return Context.getTypeDeclType(
6056 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6057 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006058
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 case TYPE_TYPEDEF: {
6060 if (Record.size() != 2) {
6061 Error("incorrect encoding of typedef type");
6062 return QualType();
6063 }
6064 unsigned Idx = 0;
6065 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
6066 QualType Canonical = readType(*Loc.F, Record, Idx);
6067 if (!Canonical.isNull())
6068 Canonical = Context.getCanonicalType(Canonical);
6069 return Context.getTypedefType(Decl, Canonical);
6070 }
6071
6072 case TYPE_TYPEOF_EXPR:
6073 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6074
6075 case TYPE_TYPEOF: {
6076 if (Record.size() != 1) {
6077 Error("incorrect encoding of typeof(type) in AST file");
6078 return QualType();
6079 }
6080 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6081 return Context.getTypeOfType(UnderlyingType);
6082 }
6083
6084 case TYPE_DECLTYPE: {
6085 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6086 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6087 }
6088
6089 case TYPE_UNARY_TRANSFORM: {
6090 QualType BaseType = readType(*Loc.F, Record, Idx);
6091 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6092 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
6093 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6094 }
6095
Richard Smith74aeef52013-04-26 16:15:35 +00006096 case TYPE_AUTO: {
6097 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00006098 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00006099 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00006100 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00006101 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006102
Richard Smith600b5262017-01-26 20:40:47 +00006103 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6104 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6105 QualType Deduced = readType(*Loc.F, Record, Idx);
6106 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6107 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6108 IsDependent);
6109 }
6110
Guy Benyei11169dd2012-12-18 14:30:41 +00006111 case TYPE_RECORD: {
6112 if (Record.size() != 2) {
6113 Error("incorrect encoding of record type");
6114 return QualType();
6115 }
6116 unsigned Idx = 0;
6117 bool IsDependent = Record[Idx++];
6118 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
6119 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6120 QualType T = Context.getRecordType(RD);
6121 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6122 return T;
6123 }
6124
6125 case TYPE_ENUM: {
6126 if (Record.size() != 2) {
6127 Error("incorrect encoding of enum type");
6128 return QualType();
6129 }
6130 unsigned Idx = 0;
6131 bool IsDependent = Record[Idx++];
6132 QualType T
6133 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6134 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6135 return T;
6136 }
6137
6138 case TYPE_ATTRIBUTED: {
6139 if (Record.size() != 3) {
6140 Error("incorrect encoding of attributed type");
6141 return QualType();
6142 }
6143 QualType modifiedType = readType(*Loc.F, Record, Idx);
6144 QualType equivalentType = readType(*Loc.F, Record, Idx);
6145 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
6146 return Context.getAttributedType(kind, modifiedType, equivalentType);
6147 }
6148
6149 case TYPE_PAREN: {
6150 if (Record.size() != 1) {
6151 Error("incorrect encoding of paren type");
6152 return QualType();
6153 }
6154 QualType InnerType = readType(*Loc.F, Record, Idx);
6155 return Context.getParenType(InnerType);
6156 }
6157
6158 case TYPE_PACK_EXPANSION: {
6159 if (Record.size() != 2) {
6160 Error("incorrect encoding of pack expansion type");
6161 return QualType();
6162 }
6163 QualType Pattern = readType(*Loc.F, Record, Idx);
6164 if (Pattern.isNull())
6165 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006166 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 if (Record[1])
6168 NumExpansions = Record[1] - 1;
6169 return Context.getPackExpansionType(Pattern, NumExpansions);
6170 }
6171
6172 case TYPE_ELABORATED: {
6173 unsigned Idx = 0;
6174 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6175 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6176 QualType NamedType = readType(*Loc.F, Record, Idx);
6177 return Context.getElaboratedType(Keyword, NNS, NamedType);
6178 }
6179
6180 case TYPE_OBJC_INTERFACE: {
6181 unsigned Idx = 0;
6182 ObjCInterfaceDecl *ItfD
6183 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6184 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6185 }
6186
Manman Rene6be26c2016-09-13 17:25:08 +00006187 case TYPE_OBJC_TYPE_PARAM: {
6188 unsigned Idx = 0;
6189 ObjCTypeParamDecl *Decl
6190 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6191 unsigned NumProtos = Record[Idx++];
6192 SmallVector<ObjCProtocolDecl*, 4> Protos;
6193 for (unsigned I = 0; I != NumProtos; ++I)
6194 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6195 return Context.getObjCTypeParamType(Decl, Protos);
6196 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006197
Guy Benyei11169dd2012-12-18 14:30:41 +00006198 case TYPE_OBJC_OBJECT: {
6199 unsigned Idx = 0;
6200 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006201 unsigned NumTypeArgs = Record[Idx++];
6202 SmallVector<QualType, 4> TypeArgs;
6203 for (unsigned I = 0; I != NumTypeArgs; ++I)
6204 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006205 unsigned NumProtos = Record[Idx++];
6206 SmallVector<ObjCProtocolDecl*, 4> Protos;
6207 for (unsigned I = 0; I != NumProtos; ++I)
6208 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006209 bool IsKindOf = Record[Idx++];
6210 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 }
6212
6213 case TYPE_OBJC_OBJECT_POINTER: {
6214 unsigned Idx = 0;
6215 QualType Pointee = readType(*Loc.F, Record, Idx);
6216 return Context.getObjCObjectPointerType(Pointee);
6217 }
6218
6219 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6220 unsigned Idx = 0;
6221 QualType Parm = readType(*Loc.F, Record, Idx);
6222 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006223 return Context.getSubstTemplateTypeParmType(
6224 cast<TemplateTypeParmType>(Parm),
6225 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006226 }
6227
6228 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6229 unsigned Idx = 0;
6230 QualType Parm = readType(*Loc.F, Record, Idx);
6231 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6232 return Context.getSubstTemplateTypeParmPackType(
6233 cast<TemplateTypeParmType>(Parm),
6234 ArgPack);
6235 }
6236
6237 case TYPE_INJECTED_CLASS_NAME: {
6238 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6239 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6240 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6241 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006242 const Type *T = nullptr;
6243 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6244 if (const Type *Existing = DI->getTypeForDecl()) {
6245 T = Existing;
6246 break;
6247 }
6248 }
6249 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006250 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006251 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6252 DI->setTypeForDecl(T);
6253 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006254 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 }
6256
6257 case TYPE_TEMPLATE_TYPE_PARM: {
6258 unsigned Idx = 0;
6259 unsigned Depth = Record[Idx++];
6260 unsigned Index = Record[Idx++];
6261 bool Pack = Record[Idx++];
6262 TemplateTypeParmDecl *D
6263 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6264 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6265 }
6266
6267 case TYPE_DEPENDENT_NAME: {
6268 unsigned Idx = 0;
6269 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6270 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006271 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006272 QualType Canon = readType(*Loc.F, Record, Idx);
6273 if (!Canon.isNull())
6274 Canon = Context.getCanonicalType(Canon);
6275 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6276 }
6277
6278 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6279 unsigned Idx = 0;
6280 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6281 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006282 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 unsigned NumArgs = Record[Idx++];
6284 SmallVector<TemplateArgument, 8> Args;
6285 Args.reserve(NumArgs);
6286 while (NumArgs--)
6287 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6288 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006289 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 }
6291
6292 case TYPE_DEPENDENT_SIZED_ARRAY: {
6293 unsigned Idx = 0;
6294
6295 // ArrayType
6296 QualType ElementType = readType(*Loc.F, Record, Idx);
6297 ArrayType::ArraySizeModifier ASM
6298 = (ArrayType::ArraySizeModifier)Record[Idx++];
6299 unsigned IndexTypeQuals = Record[Idx++];
6300
6301 // DependentSizedArrayType
6302 Expr *NumElts = ReadExpr(*Loc.F);
6303 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6304
6305 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6306 IndexTypeQuals, Brackets);
6307 }
6308
6309 case TYPE_TEMPLATE_SPECIALIZATION: {
6310 unsigned Idx = 0;
6311 bool IsDependent = Record[Idx++];
6312 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6313 SmallVector<TemplateArgument, 8> Args;
6314 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6315 QualType Underlying = readType(*Loc.F, Record, Idx);
6316 QualType T;
6317 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006318 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006319 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006320 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006321 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6322 return T;
6323 }
6324
6325 case TYPE_ATOMIC: {
6326 if (Record.size() != 1) {
6327 Error("Incorrect encoding of atomic type");
6328 return QualType();
6329 }
6330 QualType ValueType = readType(*Loc.F, Record, Idx);
6331 return Context.getAtomicType(ValueType);
6332 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006333
Joey Goulye3c85de2016-12-01 11:30:49 +00006334 case TYPE_PIPE: {
6335 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006336 Error("Incorrect encoding of pipe type");
6337 return QualType();
6338 }
6339
6340 // Reading the pipe element type.
6341 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006342 unsigned ReadOnly = Record[1];
6343 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006344 }
6345
Alex Lorenz00aee432017-03-22 10:04:48 +00006346 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6347 unsigned Idx = 0;
6348
6349 // DependentSizedExtVectorType
6350 QualType ElementType = readType(*Loc.F, Record, Idx);
6351 Expr *SizeExpr = ReadExpr(*Loc.F);
6352 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6353
6354 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6355 AttrLoc);
6356 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006357
6358 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6359 unsigned Idx = 0;
6360
6361 // DependentAddressSpaceType
6362 QualType PointeeType = readType(*Loc.F, Record, Idx);
6363 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6364 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6365
6366 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6367 AttrLoc);
6368 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006369 }
6370 llvm_unreachable("Invalid TypeCode!");
6371}
6372
Richard Smith564417a2014-03-20 21:47:22 +00006373void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6374 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006375 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006376 const RecordData &Record, unsigned &Idx) {
6377 ExceptionSpecificationType EST =
6378 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006379 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006380 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006381 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006382 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006383 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006384 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006385 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006386 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006387 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6388 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006389 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006390 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006391 }
6392}
6393
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006394namespace clang {
6395
6396class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006397 ModuleFile *F;
6398 ASTReader *Reader;
6399 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006400 unsigned &Idx;
6401
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006402 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006403 return Reader->ReadSourceLocation(*F, Record, Idx);
6404 }
6405
6406 TypeSourceInfo *GetTypeSourceInfo() {
6407 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6408 }
6409
6410 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6411 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006412 }
6413
Guy Benyei11169dd2012-12-18 14:30:41 +00006414public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006415 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006416 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006417 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006418
6419 // We want compile-time assurance that we've enumerated all of
6420 // these, so unfortunately we have to declare them first, then
6421 // define them out-of-line.
6422#define ABSTRACT_TYPELOC(CLASS, PARENT)
6423#define TYPELOC(CLASS, PARENT) \
6424 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6425#include "clang/AST/TypeLocNodes.def"
6426
6427 void VisitFunctionTypeLoc(FunctionTypeLoc);
6428 void VisitArrayTypeLoc(ArrayTypeLoc);
6429};
6430
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006431} // namespace clang
6432
Guy Benyei11169dd2012-12-18 14:30:41 +00006433void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6434 // nothing to do
6435}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006436
Guy Benyei11169dd2012-12-18 14:30:41 +00006437void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006438 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006440 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6441 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6442 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6443 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006444 }
6445}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006446
Guy Benyei11169dd2012-12-18 14:30:41 +00006447void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006448 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006449}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006450
Guy Benyei11169dd2012-12-18 14:30:41 +00006451void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006452 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006453}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006454
Reid Kleckner8a365022013-06-24 17:51:48 +00006455void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6456 // nothing to do
6457}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006458
Reid Kleckner0503a872013-12-05 01:23:43 +00006459void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6460 // nothing to do
6461}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006462
Guy Benyei11169dd2012-12-18 14:30:41 +00006463void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006464 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006465}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006466
Guy Benyei11169dd2012-12-18 14:30:41 +00006467void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006468 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006469}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006470
Guy Benyei11169dd2012-12-18 14:30:41 +00006471void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006472 TL.setAmpAmpLoc(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::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006476 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006477 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006478}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006479
Guy Benyei11169dd2012-12-18 14:30:41 +00006480void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006481 TL.setLBracketLoc(ReadSourceLocation());
6482 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006483 if (Record[Idx++])
6484 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 else
Craig Toppera13603a2014-05-22 05:54:18 +00006486 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006487}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006488
Guy Benyei11169dd2012-12-18 14:30:41 +00006489void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6490 VisitArrayTypeLoc(TL);
6491}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006492
Guy Benyei11169dd2012-12-18 14:30:41 +00006493void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6494 VisitArrayTypeLoc(TL);
6495}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006496
Guy Benyei11169dd2012-12-18 14:30:41 +00006497void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6498 VisitArrayTypeLoc(TL);
6499}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006500
Guy Benyei11169dd2012-12-18 14:30:41 +00006501void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6502 DependentSizedArrayTypeLoc TL) {
6503 VisitArrayTypeLoc(TL);
6504}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006505
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006506void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6507 DependentAddressSpaceTypeLoc TL) {
6508
6509 TL.setAttrNameLoc(ReadSourceLocation());
6510 SourceRange range;
6511 range.setBegin(ReadSourceLocation());
6512 range.setEnd(ReadSourceLocation());
6513 TL.setAttrOperandParensRange(range);
6514 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6515}
6516
Guy Benyei11169dd2012-12-18 14:30:41 +00006517void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6518 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006519 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006520}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006521
Guy Benyei11169dd2012-12-18 14:30:41 +00006522void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006523 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006524}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006525
Guy Benyei11169dd2012-12-18 14:30:41 +00006526void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc 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::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006531 TL.setLocalRangeBegin(ReadSourceLocation());
6532 TL.setLParenLoc(ReadSourceLocation());
6533 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006534 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6535 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006536 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006537 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006538 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006539 }
6540}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006541
Guy Benyei11169dd2012-12-18 14:30:41 +00006542void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6543 VisitFunctionTypeLoc(TL);
6544}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006545
Guy Benyei11169dd2012-12-18 14:30:41 +00006546void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6547 VisitFunctionTypeLoc(TL);
6548}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006549
Guy Benyei11169dd2012-12-18 14:30:41 +00006550void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006551 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006552}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006553
Guy Benyei11169dd2012-12-18 14:30:41 +00006554void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006555 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006556}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006557
Guy Benyei11169dd2012-12-18 14:30:41 +00006558void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006559 TL.setTypeofLoc(ReadSourceLocation());
6560 TL.setLParenLoc(ReadSourceLocation());
6561 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006562}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006563
Guy Benyei11169dd2012-12-18 14:30:41 +00006564void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006565 TL.setTypeofLoc(ReadSourceLocation());
6566 TL.setLParenLoc(ReadSourceLocation());
6567 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006568 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006569}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006570
Guy Benyei11169dd2012-12-18 14:30:41 +00006571void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006572 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006573}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006574
Guy Benyei11169dd2012-12-18 14:30:41 +00006575void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006576 TL.setKWLoc(ReadSourceLocation());
6577 TL.setLParenLoc(ReadSourceLocation());
6578 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006579 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006580}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006581
Guy Benyei11169dd2012-12-18 14:30:41 +00006582void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006583 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006584}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006585
Richard Smith600b5262017-01-26 20:40:47 +00006586void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6587 DeducedTemplateSpecializationTypeLoc TL) {
6588 TL.setTemplateNameLoc(ReadSourceLocation());
6589}
6590
Guy Benyei11169dd2012-12-18 14:30:41 +00006591void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006592 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006593}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006594
Guy Benyei11169dd2012-12-18 14:30:41 +00006595void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006596 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006597}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006598
Guy Benyei11169dd2012-12-18 14:30:41 +00006599void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006600 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 if (TL.hasAttrOperand()) {
6602 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006603 range.setBegin(ReadSourceLocation());
6604 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 TL.setAttrOperandParensRange(range);
6606 }
6607 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006608 if (Record[Idx++])
6609 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 else
Craig Toppera13603a2014-05-22 05:54:18 +00006611 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006612 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006613 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006614}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006615
Guy Benyei11169dd2012-12-18 14:30:41 +00006616void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006617 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006618}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006619
Guy Benyei11169dd2012-12-18 14:30:41 +00006620void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6621 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006622 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006623}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006624
Guy Benyei11169dd2012-12-18 14:30:41 +00006625void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6626 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006627 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006628}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006629
Guy Benyei11169dd2012-12-18 14:30:41 +00006630void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6631 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006632 TL.setTemplateKeywordLoc(ReadSourceLocation());
6633 TL.setTemplateNameLoc(ReadSourceLocation());
6634 TL.setLAngleLoc(ReadSourceLocation());
6635 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006636 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006637 TL.setArgLocInfo(
6638 i,
6639 Reader->GetTemplateArgumentLocInfo(
6640 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006641}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006644 TL.setLParenLoc(ReadSourceLocation());
6645 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006646}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006647
Guy Benyei11169dd2012-12-18 14:30:41 +00006648void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006649 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006650 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006651}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006652
Guy Benyei11169dd2012-12-18 14:30:41 +00006653void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006654 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006655}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006656
Guy Benyei11169dd2012-12-18 14:30:41 +00006657void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006658 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006659 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006660 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006661}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006662
Guy Benyei11169dd2012-12-18 14:30:41 +00006663void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6664 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006665 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006666 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006667 TL.setTemplateKeywordLoc(ReadSourceLocation());
6668 TL.setTemplateNameLoc(ReadSourceLocation());
6669 TL.setLAngleLoc(ReadSourceLocation());
6670 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006671 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006672 TL.setArgLocInfo(
6673 I,
6674 Reader->GetTemplateArgumentLocInfo(
6675 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006676}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006677
Guy Benyei11169dd2012-12-18 14:30:41 +00006678void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006679 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006680}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006681
Guy Benyei11169dd2012-12-18 14:30:41 +00006682void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006683 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006684}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006685
Manman Rene6be26c2016-09-13 17:25:08 +00006686void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6687 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006688 TL.setProtocolLAngleLoc(ReadSourceLocation());
6689 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006690 }
6691 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006692 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006693}
6694
Guy Benyei11169dd2012-12-18 14:30:41 +00006695void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006696 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006697 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6698 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006699 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006700 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006701 TL.setProtocolLAngleLoc(ReadSourceLocation());
6702 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006703 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006704 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006705}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006706
Guy Benyei11169dd2012-12-18 14:30:41 +00006707void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006708 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006709}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006710
Guy Benyei11169dd2012-12-18 14:30:41 +00006711void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006712 TL.setKWLoc(ReadSourceLocation());
6713 TL.setLParenLoc(ReadSourceLocation());
6714 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006715}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006716
Xiuli Pan9c14e282016-01-09 12:53:17 +00006717void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006718 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006719}
Guy Benyei11169dd2012-12-18 14:30:41 +00006720
David L. Jonesbe1557a2016-12-21 00:17:49 +00006721TypeSourceInfo *
6722ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6723 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006724 QualType InfoTy = readType(F, Record, Idx);
6725 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006726 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006727
6728 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006729 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006730 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6731 TLR.Visit(TL);
6732 return TInfo;
6733}
6734
6735QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006736 assert(ContextObj && "reading type with no AST context");
6737 ASTContext &Context = *ContextObj;
6738
Guy Benyei11169dd2012-12-18 14:30:41 +00006739 unsigned FastQuals = ID & Qualifiers::FastMask;
6740 unsigned Index = ID >> Qualifiers::FastWidth;
6741
6742 if (Index < NUM_PREDEF_TYPE_IDS) {
6743 QualType T;
6744 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006745 case PREDEF_TYPE_NULL_ID:
6746 return QualType();
6747 case PREDEF_TYPE_VOID_ID:
6748 T = Context.VoidTy;
6749 break;
6750 case PREDEF_TYPE_BOOL_ID:
6751 T = Context.BoolTy;
6752 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006753 case PREDEF_TYPE_CHAR_U_ID:
6754 case PREDEF_TYPE_CHAR_S_ID:
6755 // FIXME: Check that the signedness of CharTy is correct!
6756 T = Context.CharTy;
6757 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006758 case PREDEF_TYPE_UCHAR_ID:
6759 T = Context.UnsignedCharTy;
6760 break;
6761 case PREDEF_TYPE_USHORT_ID:
6762 T = Context.UnsignedShortTy;
6763 break;
6764 case PREDEF_TYPE_UINT_ID:
6765 T = Context.UnsignedIntTy;
6766 break;
6767 case PREDEF_TYPE_ULONG_ID:
6768 T = Context.UnsignedLongTy;
6769 break;
6770 case PREDEF_TYPE_ULONGLONG_ID:
6771 T = Context.UnsignedLongLongTy;
6772 break;
6773 case PREDEF_TYPE_UINT128_ID:
6774 T = Context.UnsignedInt128Ty;
6775 break;
6776 case PREDEF_TYPE_SCHAR_ID:
6777 T = Context.SignedCharTy;
6778 break;
6779 case PREDEF_TYPE_WCHAR_ID:
6780 T = Context.WCharTy;
6781 break;
6782 case PREDEF_TYPE_SHORT_ID:
6783 T = Context.ShortTy;
6784 break;
6785 case PREDEF_TYPE_INT_ID:
6786 T = Context.IntTy;
6787 break;
6788 case PREDEF_TYPE_LONG_ID:
6789 T = Context.LongTy;
6790 break;
6791 case PREDEF_TYPE_LONGLONG_ID:
6792 T = Context.LongLongTy;
6793 break;
6794 case PREDEF_TYPE_INT128_ID:
6795 T = Context.Int128Ty;
6796 break;
6797 case PREDEF_TYPE_HALF_ID:
6798 T = Context.HalfTy;
6799 break;
6800 case PREDEF_TYPE_FLOAT_ID:
6801 T = Context.FloatTy;
6802 break;
6803 case PREDEF_TYPE_DOUBLE_ID:
6804 T = Context.DoubleTy;
6805 break;
6806 case PREDEF_TYPE_LONGDOUBLE_ID:
6807 T = Context.LongDoubleTy;
6808 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006809 case PREDEF_TYPE_FLOAT16_ID:
6810 T = Context.Float16Ty;
6811 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006812 case PREDEF_TYPE_FLOAT128_ID:
6813 T = Context.Float128Ty;
6814 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006815 case PREDEF_TYPE_OVERLOAD_ID:
6816 T = Context.OverloadTy;
6817 break;
6818 case PREDEF_TYPE_BOUND_MEMBER:
6819 T = Context.BoundMemberTy;
6820 break;
6821 case PREDEF_TYPE_PSEUDO_OBJECT:
6822 T = Context.PseudoObjectTy;
6823 break;
6824 case PREDEF_TYPE_DEPENDENT_ID:
6825 T = Context.DependentTy;
6826 break;
6827 case PREDEF_TYPE_UNKNOWN_ANY:
6828 T = Context.UnknownAnyTy;
6829 break;
6830 case PREDEF_TYPE_NULLPTR_ID:
6831 T = Context.NullPtrTy;
6832 break;
6833 case PREDEF_TYPE_CHAR16_ID:
6834 T = Context.Char16Ty;
6835 break;
6836 case PREDEF_TYPE_CHAR32_ID:
6837 T = Context.Char32Ty;
6838 break;
6839 case PREDEF_TYPE_OBJC_ID:
6840 T = Context.ObjCBuiltinIdTy;
6841 break;
6842 case PREDEF_TYPE_OBJC_CLASS:
6843 T = Context.ObjCBuiltinClassTy;
6844 break;
6845 case PREDEF_TYPE_OBJC_SEL:
6846 T = Context.ObjCBuiltinSelTy;
6847 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006848#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6849 case PREDEF_TYPE_##Id##_ID: \
6850 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006851 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006852#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006853 case PREDEF_TYPE_SAMPLER_ID:
6854 T = Context.OCLSamplerTy;
6855 break;
6856 case PREDEF_TYPE_EVENT_ID:
6857 T = Context.OCLEventTy;
6858 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006859 case PREDEF_TYPE_CLK_EVENT_ID:
6860 T = Context.OCLClkEventTy;
6861 break;
6862 case PREDEF_TYPE_QUEUE_ID:
6863 T = Context.OCLQueueTy;
6864 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006865 case PREDEF_TYPE_RESERVE_ID_ID:
6866 T = Context.OCLReserveIDTy;
6867 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006868 case PREDEF_TYPE_AUTO_DEDUCT:
6869 T = Context.getAutoDeductType();
6870 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006871 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6872 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006873 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6875 T = Context.ARCUnbridgedCastTy;
6876 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006877 case PREDEF_TYPE_BUILTIN_FN:
6878 T = Context.BuiltinFnTy;
6879 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006880 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6881 T = Context.OMPArraySectionTy;
6882 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006883 }
6884
6885 assert(!T.isNull() && "Unknown predefined type");
6886 return T.withFastQualifiers(FastQuals);
6887 }
6888
6889 Index -= NUM_PREDEF_TYPE_IDS;
6890 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6891 if (TypesLoaded[Index].isNull()) {
6892 TypesLoaded[Index] = readTypeRecord(Index);
6893 if (TypesLoaded[Index].isNull())
6894 return QualType();
6895
6896 TypesLoaded[Index]->setFromAST();
6897 if (DeserializationListener)
6898 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6899 TypesLoaded[Index]);
6900 }
6901
6902 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6903}
6904
6905QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6906 return GetType(getGlobalTypeID(F, LocalID));
6907}
6908
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006909serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006910ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6911 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6912 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006913
Guy Benyei11169dd2012-12-18 14:30:41 +00006914 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6915 return LocalID;
6916
Richard Smith37a93df2017-02-18 00:32:02 +00006917 if (!F.ModuleOffsetMap.empty())
6918 ReadModuleOffsetMap(F);
6919
Guy Benyei11169dd2012-12-18 14:30:41 +00006920 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6921 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6922 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006923
Guy Benyei11169dd2012-12-18 14:30:41 +00006924 unsigned GlobalIndex = LocalIndex + I->second;
6925 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6926}
6927
6928TemplateArgumentLocInfo
6929ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6930 TemplateArgument::ArgKind Kind,
6931 const RecordData &Record,
6932 unsigned &Index) {
6933 switch (Kind) {
6934 case TemplateArgument::Expression:
6935 return ReadExpr(F);
6936 case TemplateArgument::Type:
6937 return GetTypeSourceInfo(F, Record, Index);
6938 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006939 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 Index);
6941 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6942 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6943 SourceLocation());
6944 }
6945 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006946 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 Index);
6948 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6949 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006950 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006951 EllipsisLoc);
6952 }
6953 case TemplateArgument::Null:
6954 case TemplateArgument::Integral:
6955 case TemplateArgument::Declaration:
6956 case TemplateArgument::NullPtr:
6957 case TemplateArgument::Pack:
6958 // FIXME: Is this right?
6959 return TemplateArgumentLocInfo();
6960 }
6961 llvm_unreachable("unexpected template argument loc");
6962}
6963
6964TemplateArgumentLoc
6965ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6966 const RecordData &Record, unsigned &Index) {
6967 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6968
6969 if (Arg.getKind() == TemplateArgument::Expression) {
6970 if (Record[Index++]) // bool InfoHasSameExpr.
6971 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6972 }
6973 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6974 Record, Index));
6975}
6976
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006977const ASTTemplateArgumentListInfo*
6978ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6979 const RecordData &Record,
6980 unsigned &Index) {
6981 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6982 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6983 unsigned NumArgsAsWritten = Record[Index++];
6984 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6985 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6986 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6987 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6988}
6989
Guy Benyei11169dd2012-12-18 14:30:41 +00006990Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6991 return GetDecl(ID);
6992}
6993
Richard Smith053f6c62014-05-16 23:01:30 +00006994void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006995 if (NumCurrentElementsDeserializing) {
6996 // We arrange to not care about the complete redeclaration chain while we're
6997 // deserializing. Just remember that the AST has marked this one as complete
6998 // but that it's not actually complete yet, so we know we still need to
6999 // complete it later.
7000 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7001 return;
7002 }
7003
Richard Smith053f6c62014-05-16 23:01:30 +00007004 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7005
Richard Smith053f6c62014-05-16 23:01:30 +00007006 // If this is a named declaration, complete it by looking it up
7007 // within its context.
7008 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007009 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007010 // all mergeable entities within it.
7011 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7012 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7013 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007014 if (!getContext().getLangOpts().CPlusPlus &&
7015 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007016 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007017 // the identifier instead. (For C++ modules, we don't store decls
7018 // in the serialized identifier table, so we do the lookup in the TU.)
7019 auto *II = Name.getAsIdentifierInfo();
7020 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007021 if (II->isOutOfDate())
7022 updateOutOfDateIdentifier(*II);
7023 } else
7024 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007025 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007026 // Find all declarations of this kind from the relevant context.
7027 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7028 auto *DC = cast<DeclContext>(DCDecl);
7029 SmallVector<Decl*, 8> Decls;
7030 FindExternalLexicalDecls(
7031 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7032 }
Richard Smith053f6c62014-05-16 23:01:30 +00007033 }
7034 }
Richard Smith50895422015-01-31 03:04:55 +00007035
7036 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7037 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7038 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7039 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7040 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7041 if (auto *Template = FD->getPrimaryTemplate())
7042 Template->LoadLazySpecializations();
7043 }
Richard Smith053f6c62014-05-16 23:01:30 +00007044}
7045
Richard Smithc2bb8182015-03-24 06:36:48 +00007046CXXCtorInitializer **
7047ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7048 RecordLocation Loc = getLocalBitOffset(Offset);
7049 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7050 SavedStreamPosition SavedPosition(Cursor);
7051 Cursor.JumpToBit(Loc.Offset);
7052 ReadingKindTracker ReadingKind(Read_Decl, *this);
7053
7054 RecordData Record;
7055 unsigned Code = Cursor.ReadCode();
7056 unsigned RecCode = Cursor.readRecord(Code, Record);
7057 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
7058 Error("malformed AST file: missing C++ ctor initializers");
7059 return nullptr;
7060 }
7061
7062 unsigned Idx = 0;
7063 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7064}
7065
Guy Benyei11169dd2012-12-18 14:30:41 +00007066CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007067 assert(ContextObj && "reading base specifiers with no AST context");
7068 ASTContext &Context = *ContextObj;
7069
Guy Benyei11169dd2012-12-18 14:30:41 +00007070 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007071 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007072 SavedStreamPosition SavedPosition(Cursor);
7073 Cursor.JumpToBit(Loc.Offset);
7074 ReadingKindTracker ReadingKind(Read_Decl, *this);
7075 RecordData Record;
7076 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007077 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00007078 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007079 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007080 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007081 }
7082
7083 unsigned Idx = 0;
7084 unsigned NumBases = Record[Idx++];
7085 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7086 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7087 for (unsigned I = 0; I != NumBases; ++I)
7088 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7089 return Bases;
7090}
7091
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007092serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007093ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7094 if (LocalID < NUM_PREDEF_DECL_IDS)
7095 return LocalID;
7096
Richard Smith37a93df2017-02-18 00:32:02 +00007097 if (!F.ModuleOffsetMap.empty())
7098 ReadModuleOffsetMap(F);
7099
Guy Benyei11169dd2012-12-18 14:30:41 +00007100 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7101 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7102 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007103
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 return LocalID + I->second;
7105}
7106
7107bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7108 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007109 // Predefined decls aren't from any module.
7110 if (ID < NUM_PREDEF_DECL_IDS)
7111 return false;
7112
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007113 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007114 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007115}
7116
Douglas Gregor9f782892013-01-21 15:25:38 +00007117ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007118 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007119 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007120 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7121 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7122 return I->second;
7123}
7124
7125SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7126 if (ID < NUM_PREDEF_DECL_IDS)
7127 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007128
Guy Benyei11169dd2012-12-18 14:30:41 +00007129 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7130
7131 if (Index > DeclsLoaded.size()) {
7132 Error("declaration ID out-of-range for AST file");
7133 return SourceLocation();
7134 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007135
Guy Benyei11169dd2012-12-18 14:30:41 +00007136 if (Decl *D = DeclsLoaded[Index])
7137 return D->getLocation();
7138
Richard Smithcb34bd32016-03-27 07:28:06 +00007139 SourceLocation Loc;
7140 DeclCursorForID(ID, Loc);
7141 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007142}
7143
Richard Smithfe620d22015-03-05 23:24:12 +00007144static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7145 switch (ID) {
7146 case PREDEF_DECL_NULL_ID:
7147 return nullptr;
7148
7149 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7150 return Context.getTranslationUnitDecl();
7151
7152 case PREDEF_DECL_OBJC_ID_ID:
7153 return Context.getObjCIdDecl();
7154
7155 case PREDEF_DECL_OBJC_SEL_ID:
7156 return Context.getObjCSelDecl();
7157
7158 case PREDEF_DECL_OBJC_CLASS_ID:
7159 return Context.getObjCClassDecl();
7160
7161 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7162 return Context.getObjCProtocolDecl();
7163
7164 case PREDEF_DECL_INT_128_ID:
7165 return Context.getInt128Decl();
7166
7167 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7168 return Context.getUInt128Decl();
7169
7170 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7171 return Context.getObjCInstanceTypeDecl();
7172
7173 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7174 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007175
Richard Smith9b88a4c2015-07-27 05:40:23 +00007176 case PREDEF_DECL_VA_LIST_TAG:
7177 return Context.getVaListTagDecl();
7178
Charles Davisc7d5c942015-09-17 20:55:33 +00007179 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7180 return Context.getBuiltinMSVaListDecl();
7181
Richard Smithf19e1272015-03-07 00:04:49 +00007182 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7183 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007184
7185 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7186 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007187
7188 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7189 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007190
7191 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7192 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007193
7194 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7195 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007196 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007197 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007198}
7199
Richard Smithcd45dbc2014-04-19 03:48:30 +00007200Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007201 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007202 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007203 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007204 if (D) {
7205 // Track that we have merged the declaration with ID \p ID into the
7206 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007207 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007208 if (Merged.empty())
7209 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007210 }
Richard Smithfe620d22015-03-05 23:24:12 +00007211 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007212 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007213
Guy Benyei11169dd2012-12-18 14:30:41 +00007214 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7215
7216 if (Index >= DeclsLoaded.size()) {
7217 assert(0 && "declaration ID out-of-range for AST file");
7218 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007219 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007220 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007221
7222 return DeclsLoaded[Index];
7223}
7224
7225Decl *ASTReader::GetDecl(DeclID ID) {
7226 if (ID < NUM_PREDEF_DECL_IDS)
7227 return GetExistingDecl(ID);
7228
7229 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7230
7231 if (Index >= DeclsLoaded.size()) {
7232 assert(0 && "declaration ID out-of-range for AST file");
7233 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007234 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007235 }
7236
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 if (!DeclsLoaded[Index]) {
7238 ReadDeclRecord(ID);
7239 if (DeserializationListener)
7240 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7241 }
7242
7243 return DeclsLoaded[Index];
7244}
7245
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007246DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 DeclID GlobalID) {
7248 if (GlobalID < NUM_PREDEF_DECL_IDS)
7249 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007250
Guy Benyei11169dd2012-12-18 14:30:41 +00007251 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7252 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7253 ModuleFile *Owner = I->second;
7254
7255 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7256 = M.GlobalToLocalDeclIDs.find(Owner);
7257 if (Pos == M.GlobalToLocalDeclIDs.end())
7258 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007259
Guy Benyei11169dd2012-12-18 14:30:41 +00007260 return GlobalID - Owner->BaseDeclID + Pos->second;
7261}
7262
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007263serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007264 const RecordData &Record,
7265 unsigned &Idx) {
7266 if (Idx >= Record.size()) {
7267 Error("Corrupted AST file");
7268 return 0;
7269 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007270
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 return getGlobalDeclID(F, Record[Idx++]);
7272}
7273
7274/// \brief Resolve the offset of a statement into a statement.
7275///
7276/// This operation will read a new statement from the external
7277/// source each time it is called, and is meant to be used via a
7278/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7279Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7280 // Switch case IDs are per Decl.
7281 ClearSwitchCaseIDs();
7282
7283 // Offset here is a global offset across the entire chain.
7284 RecordLocation Loc = getLocalBitOffset(Offset);
7285 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007286 assert(NumCurrentElementsDeserializing == 0 &&
7287 "should not be called while already deserializing");
7288 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007289 return ReadStmtFromStream(*Loc.F);
7290}
7291
Richard Smith3cb15722015-08-05 22:41:45 +00007292void ASTReader::FindExternalLexicalDecls(
7293 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7294 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007295 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7296
Richard Smith9ccdd932015-08-06 22:14:12 +00007297 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007298 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7299 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7300 auto K = (Decl::Kind)+LexicalDecls[I];
7301 if (!IsKindWeWant(K))
7302 continue;
7303
7304 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7305
7306 // Don't add predefined declarations to the lexical context more
7307 // than once.
7308 if (ID < NUM_PREDEF_DECL_IDS) {
7309 if (PredefsVisited[ID])
7310 continue;
7311
7312 PredefsVisited[ID] = true;
7313 }
7314
7315 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007316 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007317 if (!DC->isDeclInLexicalTraversal(D))
7318 Decls.push_back(D);
7319 }
7320 }
7321 };
7322
7323 if (isa<TranslationUnitDecl>(DC)) {
7324 for (auto Lexical : TULexicalDecls)
7325 Visit(Lexical.first, Lexical.second);
7326 } else {
7327 auto I = LexicalDecls.find(DC);
7328 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007329 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007330 }
7331
Guy Benyei11169dd2012-12-18 14:30:41 +00007332 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007333}
7334
7335namespace {
7336
7337class DeclIDComp {
7338 ASTReader &Reader;
7339 ModuleFile &Mod;
7340
7341public:
7342 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7343
7344 bool operator()(LocalDeclID L, LocalDeclID R) const {
7345 SourceLocation LHS = getLocation(L);
7346 SourceLocation RHS = getLocation(R);
7347 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7348 }
7349
7350 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7351 SourceLocation RHS = getLocation(R);
7352 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7353 }
7354
7355 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7356 SourceLocation LHS = getLocation(L);
7357 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7358 }
7359
7360 SourceLocation getLocation(LocalDeclID ID) const {
7361 return Reader.getSourceManager().getFileLoc(
7362 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7363 }
7364};
7365
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007366} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007367
7368void ASTReader::FindFileRegionDecls(FileID File,
7369 unsigned Offset, unsigned Length,
7370 SmallVectorImpl<Decl *> &Decls) {
7371 SourceManager &SM = getSourceManager();
7372
7373 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7374 if (I == FileDeclIDs.end())
7375 return;
7376
7377 FileDeclsInfo &DInfo = I->second;
7378 if (DInfo.Decls.empty())
7379 return;
7380
7381 SourceLocation
7382 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7383 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7384
7385 DeclIDComp DIDComp(*this, *DInfo.Mod);
7386 ArrayRef<serialization::LocalDeclID>::iterator
7387 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7388 BeginLoc, DIDComp);
7389 if (BeginIt != DInfo.Decls.begin())
7390 --BeginIt;
7391
7392 // If we are pointing at a top-level decl inside an objc container, we need
7393 // to backtrack until we find it otherwise we will fail to report that the
7394 // region overlaps with an objc container.
7395 while (BeginIt != DInfo.Decls.begin() &&
7396 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7397 ->isTopLevelDeclInObjCContainer())
7398 --BeginIt;
7399
7400 ArrayRef<serialization::LocalDeclID>::iterator
7401 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7402 EndLoc, DIDComp);
7403 if (EndIt != DInfo.Decls.end())
7404 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007405
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 for (ArrayRef<serialization::LocalDeclID>::iterator
7407 DIt = BeginIt; DIt != EndIt; ++DIt)
7408 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7409}
7410
Richard Smith9ce12e32013-02-07 03:30:24 +00007411bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007412ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7413 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007414 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 "DeclContext has no visible decls in storage");
7416 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007417 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007418
Richard Smithd88a7f12015-09-01 20:35:42 +00007419 auto It = Lookups.find(DC);
7420 if (It == Lookups.end())
7421 return false;
7422
Richard Smith8c913ec2014-08-14 02:21:01 +00007423 Deserializing LookupResults(this);
7424
Richard Smithd88a7f12015-09-01 20:35:42 +00007425 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007426 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00007427 for (DeclID ID : It->second.Table.find(Name)) {
7428 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7429 if (ND->getDeclName() == Name)
7430 Decls.push_back(ND);
7431 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007432
Guy Benyei11169dd2012-12-18 14:30:41 +00007433 ++NumVisibleDeclContextsRead;
7434 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007435 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007436}
7437
Guy Benyei11169dd2012-12-18 14:30:41 +00007438void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7439 if (!DC->hasExternalVisibleStorage())
7440 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007441
7442 auto It = Lookups.find(DC);
7443 assert(It != Lookups.end() &&
7444 "have external visible storage but no lookup tables");
7445
Craig Topper79be4cd2013-07-05 04:33:53 +00007446 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007447
Richard Smithd88a7f12015-09-01 20:35:42 +00007448 for (DeclID ID : It->second.Table.findAll()) {
7449 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7450 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007451 }
7452
Guy Benyei11169dd2012-12-18 14:30:41 +00007453 ++NumVisibleDeclContextsRead;
7454
Craig Topper79be4cd2013-07-05 04:33:53 +00007455 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007456 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7457 }
7458 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7459}
7460
Richard Smithd88a7f12015-09-01 20:35:42 +00007461const serialization::reader::DeclContextLookupTable *
7462ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7463 auto I = Lookups.find(Primary);
7464 return I == Lookups.end() ? nullptr : &I->second;
7465}
7466
Guy Benyei11169dd2012-12-18 14:30:41 +00007467/// \brief Under non-PCH compilation the consumer receives the objc methods
7468/// before receiving the implementation, and codegen depends on this.
7469/// We simulate this by deserializing and passing to consumer the methods of the
7470/// implementation before passing the deserialized implementation decl.
7471static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7472 ASTConsumer *Consumer) {
7473 assert(ImplD && Consumer);
7474
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007475 for (auto *I : ImplD->methods())
7476 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007477
7478 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7479}
7480
Guy Benyei11169dd2012-12-18 14:30:41 +00007481void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7482 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7483 PassObjCImplDeclToConsumer(ImplD, Consumer);
7484 else
7485 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7486}
7487
7488void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7489 this->Consumer = Consumer;
7490
Richard Smith9e2341d2015-03-23 03:25:59 +00007491 if (Consumer)
7492 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007493
7494 if (DeserializationListener)
7495 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007496}
7497
7498void ASTReader::PrintStats() {
7499 std::fprintf(stderr, "*** AST File Statistics:\n");
7500
7501 unsigned NumTypesLoaded
7502 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7503 QualType());
7504 unsigned NumDeclsLoaded
7505 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007506 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007507 unsigned NumIdentifiersLoaded
7508 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7509 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007510 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007511 unsigned NumMacrosLoaded
7512 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7513 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007514 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007515 unsigned NumSelectorsLoaded
7516 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7517 SelectorsLoaded.end(),
7518 Selector());
7519
7520 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7521 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7522 NumSLocEntriesRead, TotalNumSLocEntries,
7523 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7524 if (!TypesLoaded.empty())
7525 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7526 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7527 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7528 if (!DeclsLoaded.empty())
7529 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7530 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7531 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7532 if (!IdentifiersLoaded.empty())
7533 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7534 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7535 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7536 if (!MacrosLoaded.empty())
7537 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7538 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7539 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7540 if (!SelectorsLoaded.empty())
7541 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7542 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7543 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7544 if (TotalNumStatements)
7545 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7546 NumStatementsRead, TotalNumStatements,
7547 ((float)NumStatementsRead/TotalNumStatements * 100));
7548 if (TotalNumMacros)
7549 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7550 NumMacrosRead, TotalNumMacros,
7551 ((float)NumMacrosRead/TotalNumMacros * 100));
7552 if (TotalLexicalDeclContexts)
7553 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7554 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7555 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7556 * 100));
7557 if (TotalVisibleDeclContexts)
7558 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7559 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7560 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7561 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007562 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007563 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7564 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7565 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7566 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007567 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007568 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7569 NumMethodPoolHits, NumMethodPoolLookups,
7570 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007571 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007572 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7573 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7574 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7575 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007576 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007577 std::fprintf(stderr,
7578 " %u / %u identifier table lookups succeeded (%f%%)\n",
7579 NumIdentifierLookupHits, NumIdentifierLookups,
7580 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007581
Douglas Gregore060e572013-01-25 01:03:03 +00007582 if (GlobalIndex) {
7583 std::fprintf(stderr, "\n");
7584 GlobalIndex->printStats();
7585 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007586
Guy Benyei11169dd2012-12-18 14:30:41 +00007587 std::fprintf(stderr, "\n");
7588 dump();
7589 std::fprintf(stderr, "\n");
7590}
7591
7592template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007593LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007594dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007595 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007596 InitialCapacity> &Map) {
7597 if (Map.begin() == Map.end())
7598 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007599
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007600 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7601
Guy Benyei11169dd2012-12-18 14:30:41 +00007602 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007603 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007604 I != IEnd; ++I) {
7605 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7606 << "\n";
7607 }
7608}
7609
Yaron Kerencdae9412016-01-29 19:38:18 +00007610LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007611 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7612 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7613 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7614 dumpModuleIDMap("Global type map", GlobalTypeMap);
7615 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7616 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7617 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7618 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7619 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007620 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007621 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007622
Guy Benyei11169dd2012-12-18 14:30:41 +00007623 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007624 for (ModuleFile &M : ModuleMgr)
7625 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007626}
7627
7628/// Return the amount of memory used by memory buffers, breaking down
7629/// by heap-backed versus mmap'ed memory.
7630void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007631 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007632 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007633 size_t bytes = buf->getBufferSize();
7634 switch (buf->getBufferKind()) {
7635 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7636 sizes.malloc_bytes += bytes;
7637 break;
7638 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7639 sizes.mmap_bytes += bytes;
7640 break;
7641 }
7642 }
7643 }
7644}
7645
7646void ASTReader::InitializeSema(Sema &S) {
7647 SemaObj = &S;
7648 S.addExternalSource(this);
7649
7650 // Makes sure any declarations that were deserialized "too early"
7651 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007652 for (uint64_t ID : PreloadedDeclIDs) {
7653 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7654 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007656 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007657
Richard Smith3d8e97e2013-10-18 06:54:39 +00007658 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007659 if (!FPPragmaOptions.empty()) {
7660 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007661 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007662 }
7663
Yaxun Liu5b746652016-12-18 05:18:55 +00007664 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7665 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7666 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007667
7668 UpdateSema();
7669}
7670
7671void ASTReader::UpdateSema() {
7672 assert(SemaObj && "no Sema to update");
7673
7674 // Load the offsets of the declarations that Sema references.
7675 // They will be lazily deserialized when needed.
7676 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007677 assert(SemaDeclRefs.size() % 3 == 0);
7678 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007679 if (!SemaObj->StdNamespace)
7680 SemaObj->StdNamespace = SemaDeclRefs[I];
7681 if (!SemaObj->StdBadAlloc)
7682 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007683 if (!SemaObj->StdAlignValT)
7684 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007685 }
7686 SemaDeclRefs.clear();
7687 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007688
Nico Weber779355f2016-03-02 23:22:00 +00007689 // Update the state of pragmas. Use the same API as if we had encountered the
7690 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007691 if(OptimizeOffPragmaLocation.isValid())
7692 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007693 if (PragmaMSStructState != -1)
7694 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007695 if (PointersToMembersPragmaLocation.isValid()) {
7696 SemaObj->ActOnPragmaMSPointersToMembers(
7697 (LangOptions::PragmaMSPointersToMembersKind)
7698 PragmaMSPointersToMembersState,
7699 PointersToMembersPragmaLocation);
7700 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007701 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007702
7703 if (PragmaPackCurrentValue) {
7704 // The bottom of the stack might have a default value. It must be adjusted
7705 // to the current value to ensure that the packing state is preserved after
7706 // popping entries that were included/imported from a PCH/module.
7707 bool DropFirst = false;
7708 if (!PragmaPackStack.empty() &&
7709 PragmaPackStack.front().Location.isInvalid()) {
7710 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7711 "Expected a default alignment value");
7712 SemaObj->PackStack.Stack.emplace_back(
7713 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007714 SemaObj->PackStack.CurrentPragmaLocation,
7715 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007716 DropFirst = true;
7717 }
7718 for (const auto &Entry :
7719 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7720 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007721 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007722 if (PragmaPackCurrentLocation.isInvalid()) {
7723 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7724 "Expected a default alignment value");
7725 // Keep the current values.
7726 } else {
7727 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7728 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7729 }
7730 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007731}
7732
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007733IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 // Note that we are loading an identifier.
7735 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007736
Douglas Gregor7211ac12013-01-25 23:32:03 +00007737 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007738 NumIdentifierLookups,
7739 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007740
7741 // We don't need to do identifier table lookups in C++ modules (we preload
7742 // all interesting declarations, and don't need to use the scope for name
7743 // lookups). Perform the lookup in PCH files, though, since we don't build
7744 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007745 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007746 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007747 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007748 break;
7749 } else {
7750 // If there is a global index, look there first to determine which modules
7751 // provably do not have any results for this identifier.
7752 GlobalModuleIndex::HitSet Hits;
7753 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7754 if (!loadGlobalIndex()) {
7755 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7756 HitsPtr = &Hits;
7757 }
7758 }
7759
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007760 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007761 }
7762
Guy Benyei11169dd2012-12-18 14:30:41 +00007763 IdentifierInfo *II = Visitor.getIdentifierInfo();
7764 markIdentifierUpToDate(II);
7765 return II;
7766}
7767
7768namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007769
Guy Benyei11169dd2012-12-18 14:30:41 +00007770 /// \brief An identifier-lookup iterator that enumerates all of the
7771 /// identifiers stored within a set of AST files.
7772 class ASTIdentifierIterator : public IdentifierIterator {
7773 /// \brief The AST reader whose identifiers are being enumerated.
7774 const ASTReader &Reader;
7775
7776 /// \brief The current index into the chain of AST files stored in
7777 /// the AST reader.
7778 unsigned Index;
7779
7780 /// \brief The current position within the identifier lookup table
7781 /// of the current AST file.
7782 ASTIdentifierLookupTable::key_iterator Current;
7783
7784 /// \brief The end position within the identifier lookup table of
7785 /// the current AST file.
7786 ASTIdentifierLookupTable::key_iterator End;
7787
Ben Langmuir537c5b52016-05-04 00:53:13 +00007788 /// \brief Whether to skip any modules in the ASTReader.
7789 bool SkipModules;
7790
Guy Benyei11169dd2012-12-18 14:30:41 +00007791 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007792 explicit ASTIdentifierIterator(const ASTReader &Reader,
7793 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007794
Craig Topper3e89dfe2014-03-13 02:13:41 +00007795 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007796 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007797
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007798} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007799
Ben Langmuir537c5b52016-05-04 00:53:13 +00007800ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7801 bool SkipModules)
7802 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007803}
7804
7805StringRef ASTIdentifierIterator::Next() {
7806 while (Current == End) {
7807 // If we have exhausted all of our AST files, we're done.
7808 if (Index == 0)
7809 return StringRef();
7810
7811 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007812 ModuleFile &F = Reader.ModuleMgr[Index];
7813 if (SkipModules && F.isModule())
7814 continue;
7815
7816 ASTIdentifierLookupTable *IdTable =
7817 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007818 Current = IdTable->key_begin();
7819 End = IdTable->key_end();
7820 }
7821
7822 // We have any identifiers remaining in the current AST file; return
7823 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007824 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007825 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007826 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007827}
7828
Ben Langmuir537c5b52016-05-04 00:53:13 +00007829namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007830
Ben Langmuir537c5b52016-05-04 00:53:13 +00007831/// A utility for appending two IdentifierIterators.
7832class ChainedIdentifierIterator : public IdentifierIterator {
7833 std::unique_ptr<IdentifierIterator> Current;
7834 std::unique_ptr<IdentifierIterator> Queued;
7835
7836public:
7837 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7838 std::unique_ptr<IdentifierIterator> Second)
7839 : Current(std::move(First)), Queued(std::move(Second)) {}
7840
7841 StringRef Next() override {
7842 if (!Current)
7843 return StringRef();
7844
7845 StringRef result = Current->Next();
7846 if (!result.empty())
7847 return result;
7848
7849 // Try the queued iterator, which may itself be empty.
7850 Current.reset();
7851 std::swap(Current, Queued);
7852 return Next();
7853 }
7854};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007855
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007856} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007857
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007858IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007859 if (!loadGlobalIndex()) {
7860 std::unique_ptr<IdentifierIterator> ReaderIter(
7861 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7862 std::unique_ptr<IdentifierIterator> ModulesIter(
7863 GlobalIndex->createIdentifierIterator());
7864 return new ChainedIdentifierIterator(std::move(ReaderIter),
7865 std::move(ModulesIter));
7866 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007867
Guy Benyei11169dd2012-12-18 14:30:41 +00007868 return new ASTIdentifierIterator(*this);
7869}
7870
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007871namespace clang {
7872namespace serialization {
7873
Guy Benyei11169dd2012-12-18 14:30:41 +00007874 class ReadMethodPoolVisitor {
7875 ASTReader &Reader;
7876 Selector Sel;
7877 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007878 unsigned InstanceBits = 0;
7879 unsigned FactoryBits = 0;
7880 bool InstanceHasMoreThanOneDecl = false;
7881 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007882 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7883 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007884
7885 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007886 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007888 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007889
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007890 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 if (!M.SelectorLookupTable)
7892 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007893
Guy Benyei11169dd2012-12-18 14:30:41 +00007894 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007895 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007896 return true;
7897
Richard Smithbdf2d932015-07-30 03:37:16 +00007898 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007899 ASTSelectorLookupTable *PoolTable
7900 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007901 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 if (Pos == PoolTable->end())
7903 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007904
Richard Smithbdf2d932015-07-30 03:37:16 +00007905 ++Reader.NumMethodPoolTableHits;
7906 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007907 // FIXME: Not quite happy with the statistics here. We probably should
7908 // disable this tracking when called via LoadSelector.
7909 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007910 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007911 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007912 if (Reader.DeserializationListener)
7913 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007914
Richard Smithbdf2d932015-07-30 03:37:16 +00007915 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7916 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7917 InstanceBits = Data.InstanceBits;
7918 FactoryBits = Data.FactoryBits;
7919 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7920 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007921 return true;
7922 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007923
Guy Benyei11169dd2012-12-18 14:30:41 +00007924 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007925 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7926 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007927 }
7928
7929 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007930 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007931 return FactoryMethods;
7932 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007933
7934 unsigned getInstanceBits() const { return InstanceBits; }
7935 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007936
Nico Weberff4b35e2014-12-27 22:14:15 +00007937 bool instanceHasMoreThanOneDecl() const {
7938 return InstanceHasMoreThanOneDecl;
7939 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007940
Nico Weberff4b35e2014-12-27 22:14:15 +00007941 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007943
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007944} // namespace serialization
7945} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007946
7947/// \brief Add the given set of methods to the method list.
7948static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7949 ObjCMethodList &List) {
7950 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7951 S.addMethodToGlobalList(&List, Methods[I]);
7952 }
7953}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007954
Guy Benyei11169dd2012-12-18 14:30:41 +00007955void ASTReader::ReadMethodPool(Selector Sel) {
7956 // Get the selector generation and update it to the current generation.
7957 unsigned &Generation = SelectorGeneration[Sel];
7958 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007959 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007960 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007961
Guy Benyei11169dd2012-12-18 14:30:41 +00007962 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007963 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007964 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007965 ModuleMgr.visit(Visitor);
7966
Guy Benyei11169dd2012-12-18 14:30:41 +00007967 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007968 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007970
7971 ++NumMethodPoolHits;
7972
Guy Benyei11169dd2012-12-18 14:30:41 +00007973 if (!getSema())
7974 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007975
Guy Benyei11169dd2012-12-18 14:30:41 +00007976 Sema &S = *getSema();
7977 Sema::GlobalMethodPool::iterator Pos
7978 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007979
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007980 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007981 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007982 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007983 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007984
7985 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7986 // when building a module we keep every method individually and may need to
7987 // update hasMoreThanOneDecl as we add the methods.
7988 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7989 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007990}
7991
Manman Rena0f31a02016-04-29 19:04:05 +00007992void ASTReader::updateOutOfDateSelector(Selector Sel) {
7993 if (SelectorOutOfDate[Sel])
7994 ReadMethodPool(Sel);
7995}
7996
Guy Benyei11169dd2012-12-18 14:30:41 +00007997void ASTReader::ReadKnownNamespaces(
7998 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7999 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008000
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008002 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00008003 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8004 Namespaces.push_back(Namespace);
8005 }
8006}
8007
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008008void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008009 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008010 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8011 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008012 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008013 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008014 Undefined.insert(std::make_pair(D, Loc));
8015 }
8016}
Nick Lewycky8334af82013-01-26 00:35:08 +00008017
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008018void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8019 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8020 Exprs) {
8021 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8022 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
8023 uint64_t Count = DelayedDeleteExprs[Idx++];
8024 for (uint64_t C = 0; C < Count; ++C) {
8025 SourceLocation DeleteLoc =
8026 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8027 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8028 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8029 }
8030 }
8031}
8032
Guy Benyei11169dd2012-12-18 14:30:41 +00008033void ASTReader::ReadTentativeDefinitions(
8034 SmallVectorImpl<VarDecl *> &TentativeDefs) {
8035 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8036 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8037 if (Var)
8038 TentativeDefs.push_back(Var);
8039 }
8040 TentativeDefinitions.clear();
8041}
8042
8043void ASTReader::ReadUnusedFileScopedDecls(
8044 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8045 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8046 DeclaratorDecl *D
8047 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8048 if (D)
8049 Decls.push_back(D);
8050 }
8051 UnusedFileScopedDecls.clear();
8052}
8053
8054void ASTReader::ReadDelegatingConstructors(
8055 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8056 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8057 CXXConstructorDecl *D
8058 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8059 if (D)
8060 Decls.push_back(D);
8061 }
8062 DelegatingCtorDecls.clear();
8063}
8064
8065void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8066 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8067 TypedefNameDecl *D
8068 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8069 if (D)
8070 Decls.push_back(D);
8071 }
8072 ExtVectorDecls.clear();
8073}
8074
Nico Weber72889432014-09-06 01:25:55 +00008075void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8076 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8077 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8078 ++I) {
8079 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8080 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8081 if (D)
8082 Decls.insert(D);
8083 }
8084 UnusedLocalTypedefNameCandidates.clear();
8085}
8086
Guy Benyei11169dd2012-12-18 14:30:41 +00008087void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008088 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008089 if (ReferencedSelectorsData.empty())
8090 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008091
Guy Benyei11169dd2012-12-18 14:30:41 +00008092 // If there are @selector references added them to its pool. This is for
8093 // implementation of -Wselector.
8094 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8095 unsigned I = 0;
8096 while (I < DataSize) {
8097 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8098 SourceLocation SelLoc
8099 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8100 Sels.push_back(std::make_pair(Sel, SelLoc));
8101 }
8102 ReferencedSelectorsData.clear();
8103}
8104
8105void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008106 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008107 if (WeakUndeclaredIdentifiers.empty())
8108 return;
8109
8110 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008111 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008113 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008114 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8115 SourceLocation Loc
8116 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8117 bool Used = WeakUndeclaredIdentifiers[I++];
8118 WeakInfo WI(AliasId, Loc);
8119 WI.setUsed(Used);
8120 WeakIDs.push_back(std::make_pair(WeakId, WI));
8121 }
8122 WeakUndeclaredIdentifiers.clear();
8123}
8124
8125void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8126 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8127 ExternalVTableUse VT;
8128 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8129 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8130 VT.DefinitionRequired = VTableUses[Idx++];
8131 VTables.push_back(VT);
8132 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008133
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 VTableUses.clear();
8135}
8136
8137void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008138 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008139 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8140 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8141 SourceLocation Loc
8142 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8143
8144 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008145 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 PendingInstantiations.clear();
8147}
8148
Richard Smithe40f2ba2013-08-07 21:41:30 +00008149void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008150 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8151 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008152 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8153 /* In loop */) {
8154 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
8155
Justin Lebar28f09c52016-10-10 16:26:08 +00008156 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008157 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8158
8159 ModuleFile *F = getOwningModuleFile(LT->D);
8160 assert(F && "No module");
8161
8162 unsigned TokN = LateParsedTemplates[Idx++];
8163 LT->Toks.reserve(TokN);
8164 for (unsigned T = 0; T < TokN; ++T)
8165 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8166
Justin Lebar28f09c52016-10-10 16:26:08 +00008167 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008168 }
8169
8170 LateParsedTemplates.clear();
8171}
8172
Guy Benyei11169dd2012-12-18 14:30:41 +00008173void ASTReader::LoadSelector(Selector Sel) {
8174 // It would be complicated to avoid reading the methods anyway. So don't.
8175 ReadMethodPool(Sel);
8176}
8177
8178void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8179 assert(ID && "Non-zero identifier ID required");
8180 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8181 IdentifiersLoaded[ID - 1] = II;
8182 if (DeserializationListener)
8183 DeserializationListener->IdentifierRead(ID, II);
8184}
8185
8186/// \brief Set the globally-visible declarations associated with the given
8187/// identifier.
8188///
8189/// If the AST reader is currently in a state where the given declaration IDs
8190/// cannot safely be resolved, they are queued until it is safe to resolve
8191/// them.
8192///
8193/// \param II an IdentifierInfo that refers to one or more globally-visible
8194/// declarations.
8195///
8196/// \param DeclIDs the set of declaration IDs with the name @p II that are
8197/// visible at global scope.
8198///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008199/// \param Decls if non-null, this vector will be populated with the set of
8200/// deserialized declarations. These declarations will not be pushed into
8201/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008202void
8203ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8204 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008205 SmallVectorImpl<Decl *> *Decls) {
8206 if (NumCurrentElementsDeserializing && !Decls) {
8207 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008208 return;
8209 }
8210
8211 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008212 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008213 // Queue this declaration so that it will be added to the
8214 // translation unit scope and identifier's declaration chain
8215 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00008216 PreloadedDeclIDs.push_back(DeclIDs[I]);
8217 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008218 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008219
8220 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8221
8222 // If we're simply supposed to record the declarations, do so now.
8223 if (Decls) {
8224 Decls->push_back(D);
8225 continue;
8226 }
8227
8228 // Introduce this declaration into the translation-unit scope
8229 // and add it to the declaration chain for this identifier, so
8230 // that (unqualified) name lookup will find it.
8231 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008232 }
8233}
8234
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008235IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008237 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008238
8239 if (IdentifiersLoaded.empty()) {
8240 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008241 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 }
8243
8244 ID -= 1;
8245 if (!IdentifiersLoaded[ID]) {
8246 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8247 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8248 ModuleFile *M = I->second;
8249 unsigned Index = ID - M->BaseIdentifierID;
8250 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8251
8252 // All of the strings in the AST file are preceded by a 16-bit length.
8253 // Extract that 16-bit length to avoid having to execute strlen().
8254 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8255 // unsigned integers. This is important to avoid integer overflow when
8256 // we cast them to 'unsigned'.
8257 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8258 unsigned StrLen = (((unsigned) StrLenPtr[0])
8259 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008260 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8261 IdentifiersLoaded[ID] = &II;
8262 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008263 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008264 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008265 }
8266
8267 return IdentifiersLoaded[ID];
8268}
8269
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008270IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8271 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008272}
8273
8274IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8275 if (LocalID < NUM_PREDEF_IDENT_IDS)
8276 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008277
Richard Smith37a93df2017-02-18 00:32:02 +00008278 if (!M.ModuleOffsetMap.empty())
8279 ReadModuleOffsetMap(M);
8280
Guy Benyei11169dd2012-12-18 14:30:41 +00008281 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8282 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008283 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008284 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008285
Guy Benyei11169dd2012-12-18 14:30:41 +00008286 return LocalID + I->second;
8287}
8288
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008289MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008290 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008291 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008292
8293 if (MacrosLoaded.empty()) {
8294 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008295 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008296 }
8297
8298 ID -= NUM_PREDEF_MACRO_IDS;
8299 if (!MacrosLoaded[ID]) {
8300 GlobalMacroMapType::iterator I
8301 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8302 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8303 ModuleFile *M = I->second;
8304 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008305 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008306
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008307 if (DeserializationListener)
8308 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8309 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008310 }
8311
8312 return MacrosLoaded[ID];
8313}
8314
8315MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8316 if (LocalID < NUM_PREDEF_MACRO_IDS)
8317 return LocalID;
8318
Richard Smith37a93df2017-02-18 00:32:02 +00008319 if (!M.ModuleOffsetMap.empty())
8320 ReadModuleOffsetMap(M);
8321
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8323 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8324 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8325
8326 return LocalID + I->second;
8327}
8328
8329serialization::SubmoduleID
8330ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8331 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8332 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008333
Richard Smith37a93df2017-02-18 00:32:02 +00008334 if (!M.ModuleOffsetMap.empty())
8335 ReadModuleOffsetMap(M);
8336
Guy Benyei11169dd2012-12-18 14:30:41 +00008337 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8338 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008339 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008340 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008341
Guy Benyei11169dd2012-12-18 14:30:41 +00008342 return LocalID + I->second;
8343}
8344
8345Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8346 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8347 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008348 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008349 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008350
Guy Benyei11169dd2012-12-18 14:30:41 +00008351 if (GlobalID > SubmodulesLoaded.size()) {
8352 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008353 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008354 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008355
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8357}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008358
8359Module *ASTReader::getModule(unsigned ID) {
8360 return getSubmodule(ID);
8361}
8362
Richard Smithd88a7f12015-09-01 20:35:42 +00008363ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8364 if (ID & 1) {
8365 // It's a module, look it up by submodule ID.
8366 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8367 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8368 } else {
8369 // It's a prefix (preamble, PCH, ...). Look it up by index.
8370 unsigned IndexFromEnd = ID >> 1;
8371 assert(IndexFromEnd && "got reference to unknown module file");
8372 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8373 }
8374}
8375
8376unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8377 if (!F)
8378 return 1;
8379
8380 // For a file representing a module, use the submodule ID of the top-level
8381 // module as the file ID. For any other kind of file, the number of such
8382 // files loaded beforehand will be the same on reload.
8383 // FIXME: Is this true even if we have an explicit module file and a PCH?
8384 if (F->isModule())
8385 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8386
8387 auto PCHModules = getModuleManager().pch_modules();
8388 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8389 assert(I != PCHModules.end() && "emitting reference to unknown file");
8390 return (I - PCHModules.end()) << 1;
8391}
8392
Adrian Prantl15bcf702015-06-30 17:39:43 +00008393llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8394ASTReader::getSourceDescriptor(unsigned ID) {
8395 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008396 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008397
8398 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008399 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008400 const auto &PCHChain = ModuleMgr.pch_modules();
8401 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008402 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008403 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008404 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8405 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8406 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008407 }
8408 return None;
8409}
8410
David Blaikie1ac9c982017-04-11 21:13:37 +00008411ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008412 auto I = DefinitionSource.find(FD);
8413 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008414 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008415 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008416}
8417
Guy Benyei11169dd2012-12-18 14:30:41 +00008418Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8419 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8420}
8421
8422Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8423 if (ID == 0)
8424 return Selector();
8425
8426 if (ID > SelectorsLoaded.size()) {
8427 Error("selector ID out of range in AST file");
8428 return Selector();
8429 }
8430
Craig Toppera13603a2014-05-22 05:54:18 +00008431 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008432 // Load this selector from the selector table.
8433 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8434 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8435 ModuleFile &M = *I->second;
8436 ASTSelectorLookupTrait Trait(*this, M);
8437 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8438 SelectorsLoaded[ID - 1] =
8439 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8440 if (DeserializationListener)
8441 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8442 }
8443
8444 return SelectorsLoaded[ID - 1];
8445}
8446
8447Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8448 return DecodeSelector(ID);
8449}
8450
8451uint32_t ASTReader::GetNumExternalSelectors() {
8452 // ID 0 (the null selector) is considered an external selector.
8453 return getTotalNumSelectors() + 1;
8454}
8455
8456serialization::SelectorID
8457ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8458 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8459 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008460
Richard Smith37a93df2017-02-18 00:32:02 +00008461 if (!M.ModuleOffsetMap.empty())
8462 ReadModuleOffsetMap(M);
8463
Guy Benyei11169dd2012-12-18 14:30:41 +00008464 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8465 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008466 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008467 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008468
Guy Benyei11169dd2012-12-18 14:30:41 +00008469 return LocalID + I->second;
8470}
8471
8472DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008473ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008474 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008475 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8477 switch (Kind) {
8478 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008479 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008480
8481 case DeclarationName::ObjCZeroArgSelector:
8482 case DeclarationName::ObjCOneArgSelector:
8483 case DeclarationName::ObjCMultiArgSelector:
8484 return DeclarationName(ReadSelector(F, Record, Idx));
8485
8486 case DeclarationName::CXXConstructorName:
8487 return Context.DeclarationNames.getCXXConstructorName(
8488 Context.getCanonicalType(readType(F, Record, Idx)));
8489
8490 case DeclarationName::CXXDestructorName:
8491 return Context.DeclarationNames.getCXXDestructorName(
8492 Context.getCanonicalType(readType(F, Record, Idx)));
8493
Richard Smith35845152017-02-07 01:37:30 +00008494 case DeclarationName::CXXDeductionGuideName:
8495 return Context.DeclarationNames.getCXXDeductionGuideName(
8496 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8497
Guy Benyei11169dd2012-12-18 14:30:41 +00008498 case DeclarationName::CXXConversionFunctionName:
8499 return Context.DeclarationNames.getCXXConversionFunctionName(
8500 Context.getCanonicalType(readType(F, Record, Idx)));
8501
8502 case DeclarationName::CXXOperatorName:
8503 return Context.DeclarationNames.getCXXOperatorName(
8504 (OverloadedOperatorKind)Record[Idx++]);
8505
8506 case DeclarationName::CXXLiteralOperatorName:
8507 return Context.DeclarationNames.getCXXLiteralOperatorName(
8508 GetIdentifierInfo(F, Record, Idx));
8509
8510 case DeclarationName::CXXUsingDirective:
8511 return DeclarationName::getUsingDirectiveName();
8512 }
8513
8514 llvm_unreachable("Invalid NameKind!");
8515}
8516
8517void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8518 DeclarationNameLoc &DNLoc,
8519 DeclarationName Name,
8520 const RecordData &Record, unsigned &Idx) {
8521 switch (Name.getNameKind()) {
8522 case DeclarationName::CXXConstructorName:
8523 case DeclarationName::CXXDestructorName:
8524 case DeclarationName::CXXConversionFunctionName:
8525 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8526 break;
8527
8528 case DeclarationName::CXXOperatorName:
8529 DNLoc.CXXOperatorName.BeginOpNameLoc
8530 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8531 DNLoc.CXXOperatorName.EndOpNameLoc
8532 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8533 break;
8534
8535 case DeclarationName::CXXLiteralOperatorName:
8536 DNLoc.CXXLiteralOperatorName.OpNameLoc
8537 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8538 break;
8539
8540 case DeclarationName::Identifier:
8541 case DeclarationName::ObjCZeroArgSelector:
8542 case DeclarationName::ObjCOneArgSelector:
8543 case DeclarationName::ObjCMultiArgSelector:
8544 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008545 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008546 break;
8547 }
8548}
8549
8550void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8551 DeclarationNameInfo &NameInfo,
8552 const RecordData &Record, unsigned &Idx) {
8553 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8554 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8555 DeclarationNameLoc DNLoc;
8556 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8557 NameInfo.setInfo(DNLoc);
8558}
8559
8560void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8561 const RecordData &Record, unsigned &Idx) {
8562 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8563 unsigned NumTPLists = Record[Idx++];
8564 Info.NumTemplParamLists = NumTPLists;
8565 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008566 Info.TemplParamLists =
8567 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008568 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008569 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8570 }
8571}
8572
8573TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008574ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008575 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008576 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008577 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8578 switch (Kind) {
8579 case TemplateName::Template:
8580 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8581
8582 case TemplateName::OverloadedTemplate: {
8583 unsigned size = Record[Idx++];
8584 UnresolvedSet<8> Decls;
8585 while (size--)
8586 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8587
8588 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8589 }
8590
8591 case TemplateName::QualifiedTemplate: {
8592 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8593 bool hasTemplKeyword = Record[Idx++];
8594 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8595 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8596 }
8597
8598 case TemplateName::DependentTemplate: {
8599 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8600 if (Record[Idx++]) // isIdentifier
8601 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008602 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008603 Idx));
8604 return Context.getDependentTemplateName(NNS,
8605 (OverloadedOperatorKind)Record[Idx++]);
8606 }
8607
8608 case TemplateName::SubstTemplateTemplateParm: {
8609 TemplateTemplateParmDecl *param
8610 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8611 if (!param) return TemplateName();
8612 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8613 return Context.getSubstTemplateTemplateParm(param, replacement);
8614 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008615
Guy Benyei11169dd2012-12-18 14:30:41 +00008616 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008617 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008618 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8619 if (!Param)
8620 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008621
Guy Benyei11169dd2012-12-18 14:30:41 +00008622 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8623 if (ArgPack.getKind() != TemplateArgument::Pack)
8624 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008625
Guy Benyei11169dd2012-12-18 14:30:41 +00008626 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8627 }
8628 }
8629
8630 llvm_unreachable("Unhandled template name kind!");
8631}
8632
Richard Smith2bb3c342015-08-09 01:05:31 +00008633TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8634 const RecordData &Record,
8635 unsigned &Idx,
8636 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008637 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008638 if (Canonicalize) {
8639 // The caller wants a canonical template argument. Sometimes the AST only
8640 // wants template arguments in canonical form (particularly as the template
8641 // argument lists of template specializations) so ensure we preserve that
8642 // canonical form across serialization.
8643 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8644 return Context.getCanonicalTemplateArgument(Arg);
8645 }
8646
Guy Benyei11169dd2012-12-18 14:30:41 +00008647 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8648 switch (Kind) {
8649 case TemplateArgument::Null:
8650 return TemplateArgument();
8651 case TemplateArgument::Type:
8652 return TemplateArgument(readType(F, Record, Idx));
8653 case TemplateArgument::Declaration: {
8654 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008655 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008656 }
8657 case TemplateArgument::NullPtr:
8658 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8659 case TemplateArgument::Integral: {
8660 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8661 QualType T = readType(F, Record, Idx);
8662 return TemplateArgument(Context, Value, T);
8663 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008664 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008665 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8666 case TemplateArgument::TemplateExpansion: {
8667 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008668 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008669 if (unsigned NumExpansions = Record[Idx++])
8670 NumTemplateExpansions = NumExpansions - 1;
8671 return TemplateArgument(Name, NumTemplateExpansions);
8672 }
8673 case TemplateArgument::Expression:
8674 return TemplateArgument(ReadExpr(F));
8675 case TemplateArgument::Pack: {
8676 unsigned NumArgs = Record[Idx++];
8677 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8678 for (unsigned I = 0; I != NumArgs; ++I)
8679 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008680 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008681 }
8682 }
8683
8684 llvm_unreachable("Unhandled template argument kind!");
8685}
8686
8687TemplateParameterList *
8688ASTReader::ReadTemplateParameterList(ModuleFile &F,
8689 const RecordData &Record, unsigned &Idx) {
8690 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8691 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8692 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8693
8694 unsigned NumParams = Record[Idx++];
8695 SmallVector<NamedDecl *, 16> Params;
8696 Params.reserve(NumParams);
8697 while (NumParams--)
8698 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8699
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008700 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008701 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8702 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008703 return TemplateParams;
8704}
8705
8706void
8707ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008708ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008709 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008710 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008711 unsigned NumTemplateArgs = Record[Idx++];
8712 TemplArgs.reserve(NumTemplateArgs);
8713 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008714 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008715}
8716
8717/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008718void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008719 const RecordData &Record, unsigned &Idx) {
8720 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008721 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008722 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008723 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008724 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008725 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008726 }
8727}
8728
8729CXXBaseSpecifier
8730ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8731 const RecordData &Record, unsigned &Idx) {
8732 bool isVirtual = static_cast<bool>(Record[Idx++]);
8733 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8734 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8735 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8736 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8737 SourceRange Range = ReadSourceRange(F, Record, Idx);
8738 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008739 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008740 EllipsisLoc);
8741 Result.setInheritConstructors(inheritConstructors);
8742 return Result;
8743}
8744
Richard Smithc2bb8182015-03-24 06:36:48 +00008745CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008746ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8747 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008748 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008749 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008750 assert(NumInitializers && "wrote ctor initializers but have no inits");
8751 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8752 for (unsigned i = 0; i != NumInitializers; ++i) {
8753 TypeSourceInfo *TInfo = nullptr;
8754 bool IsBaseVirtual = false;
8755 FieldDecl *Member = nullptr;
8756 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008757
Richard Smithc2bb8182015-03-24 06:36:48 +00008758 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8759 switch (Type) {
8760 case CTOR_INITIALIZER_BASE:
8761 TInfo = GetTypeSourceInfo(F, Record, Idx);
8762 IsBaseVirtual = Record[Idx++];
8763 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008764
Richard Smithc2bb8182015-03-24 06:36:48 +00008765 case CTOR_INITIALIZER_DELEGATING:
8766 TInfo = GetTypeSourceInfo(F, Record, Idx);
8767 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008768
Richard Smithc2bb8182015-03-24 06:36:48 +00008769 case CTOR_INITIALIZER_MEMBER:
8770 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8771 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008772
Richard Smithc2bb8182015-03-24 06:36:48 +00008773 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8774 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8775 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008776 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008777
8778 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8779 Expr *Init = ReadExpr(F);
8780 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8781 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008782
8783 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008784 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008785 BOMInit = new (Context)
8786 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8787 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008788 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008789 BOMInit = new (Context)
8790 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008791 else if (Member)
8792 BOMInit = new (Context)
8793 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8794 Init, RParenLoc);
8795 else
8796 BOMInit = new (Context)
8797 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8798 LParenLoc, Init, RParenLoc);
8799
Richard Smith418ed822016-12-14 19:45:03 +00008800 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008801 unsigned SourceOrder = Record[Idx++];
8802 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008803 }
8804
Richard Smithc2bb8182015-03-24 06:36:48 +00008805 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008806 }
8807
Richard Smithc2bb8182015-03-24 06:36:48 +00008808 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008809}
8810
8811NestedNameSpecifier *
8812ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8813 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008814 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008815 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008816 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008817 for (unsigned I = 0; I != N; ++I) {
8818 NestedNameSpecifier::SpecifierKind Kind
8819 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8820 switch (Kind) {
8821 case NestedNameSpecifier::Identifier: {
8822 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8823 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8824 break;
8825 }
8826
8827 case NestedNameSpecifier::Namespace: {
8828 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8829 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8830 break;
8831 }
8832
8833 case NestedNameSpecifier::NamespaceAlias: {
8834 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8835 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8836 break;
8837 }
8838
8839 case NestedNameSpecifier::TypeSpec:
8840 case NestedNameSpecifier::TypeSpecWithTemplate: {
8841 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8842 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008843 return nullptr;
8844
Guy Benyei11169dd2012-12-18 14:30:41 +00008845 bool Template = Record[Idx++];
8846 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8847 break;
8848 }
8849
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008850 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00008851 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8852 // No associated value, and there can't be a prefix.
8853 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00008854
8855 case NestedNameSpecifier::Super: {
8856 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8857 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8858 break;
8859 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008860 }
8861 Prev = NNS;
8862 }
8863 return NNS;
8864}
8865
8866NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008867ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008868 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008869 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008870 unsigned N = Record[Idx++];
8871 NestedNameSpecifierLocBuilder Builder;
8872 for (unsigned I = 0; I != N; ++I) {
8873 NestedNameSpecifier::SpecifierKind Kind
8874 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8875 switch (Kind) {
8876 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008877 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008878 SourceRange Range = ReadSourceRange(F, Record, Idx);
8879 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8880 break;
8881 }
8882
8883 case NestedNameSpecifier::Namespace: {
8884 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8885 SourceRange Range = ReadSourceRange(F, Record, Idx);
8886 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8887 break;
8888 }
8889
8890 case NestedNameSpecifier::NamespaceAlias: {
8891 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8892 SourceRange Range = ReadSourceRange(F, Record, Idx);
8893 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8894 break;
8895 }
8896
8897 case NestedNameSpecifier::TypeSpec:
8898 case NestedNameSpecifier::TypeSpecWithTemplate: {
8899 bool Template = Record[Idx++];
8900 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8901 if (!T)
8902 return NestedNameSpecifierLoc();
8903 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8904
8905 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008906 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008907 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8908 T->getTypeLoc(), ColonColonLoc);
8909 break;
8910 }
8911
8912 case NestedNameSpecifier::Global: {
8913 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8914 Builder.MakeGlobal(Context, ColonColonLoc);
8915 break;
8916 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008917
8918 case NestedNameSpecifier::Super: {
8919 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8920 SourceRange Range = ReadSourceRange(F, Record, Idx);
8921 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8922 break;
8923 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008924 }
8925 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008926
Guy Benyei11169dd2012-12-18 14:30:41 +00008927 return Builder.getWithLocInContext(Context);
8928}
8929
8930SourceRange
8931ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8932 unsigned &Idx) {
8933 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8934 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8935 return SourceRange(beg, end);
8936}
8937
8938/// \brief Read an integral value
8939llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8940 unsigned BitWidth = Record[Idx++];
8941 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8942 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8943 Idx += NumWords;
8944 return Result;
8945}
8946
8947/// \brief Read a signed integral value
8948llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8949 bool isUnsigned = Record[Idx++];
8950 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8951}
8952
8953/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008954llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8955 const llvm::fltSemantics &Sem,
8956 unsigned &Idx) {
8957 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008958}
8959
8960// \brief Read a string
8961std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8962 unsigned Len = Record[Idx++];
8963 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8964 Idx += Len;
8965 return Result;
8966}
8967
Richard Smith7ed1bc92014-12-05 22:42:13 +00008968std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8969 unsigned &Idx) {
8970 std::string Filename = ReadString(Record, Idx);
8971 ResolveImportedPath(F, Filename);
8972 return Filename;
8973}
8974
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008975VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008976 unsigned &Idx) {
8977 unsigned Major = Record[Idx++];
8978 unsigned Minor = Record[Idx++];
8979 unsigned Subminor = Record[Idx++];
8980 if (Minor == 0)
8981 return VersionTuple(Major);
8982 if (Subminor == 0)
8983 return VersionTuple(Major, Minor - 1);
8984 return VersionTuple(Major, Minor - 1, Subminor - 1);
8985}
8986
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008987CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008988 const RecordData &Record,
8989 unsigned &Idx) {
8990 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00008991 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00008992}
8993
Richard Smith37a93df2017-02-18 00:32:02 +00008994DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008995 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008996}
8997
Richard Smith37a93df2017-02-18 00:32:02 +00008998DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008999 return Diags.Report(Loc, DiagID);
9000}
9001
9002/// \brief Retrieve the identifier table associated with the
9003/// preprocessor.
9004IdentifierTable &ASTReader::getIdentifierTable() {
9005 return PP.getIdentifierTable();
9006}
9007
9008/// \brief Record that the given ID maps to the given switch-case
9009/// statement.
9010void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009011 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009012 "Already have a SwitchCase with this ID");
9013 (*CurrSwitchCaseStmts)[ID] = SC;
9014}
9015
9016/// \brief Retrieve the switch-case statement with the given ID.
9017SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009018 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009019 return (*CurrSwitchCaseStmts)[ID];
9020}
9021
9022void ASTReader::ClearSwitchCaseIDs() {
9023 CurrSwitchCaseStmts->clear();
9024}
9025
9026void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009027 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009028 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009029 for (SmallVectorImpl<std::pair<BitstreamCursor,
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009030 serialization::ModuleFile *>>::iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00009031 I = CommentsCursors.begin(),
9032 E = CommentsCursors.end();
9033 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009034 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009035 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00009036 serialization::ModuleFile &F = *I->second;
9037 SavedStreamPosition SavedPosition(Cursor);
9038
9039 RecordData Record;
9040 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009041 llvm::BitstreamEntry Entry =
9042 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009043
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009044 switch (Entry.Kind) {
9045 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9046 case llvm::BitstreamEntry::Error:
9047 Error("malformed block record in AST file");
9048 return;
9049 case llvm::BitstreamEntry::EndBlock:
9050 goto NextCursor;
9051 case llvm::BitstreamEntry::Record:
9052 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009053 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009054 }
9055
9056 // Read a record.
9057 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00009058 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009059 case COMMENTS_RAW_COMMENT: {
9060 unsigned Idx = 0;
9061 SourceRange SR = ReadSourceRange(F, Record, Idx);
9062 RawComment::CommentKind Kind =
9063 (RawComment::CommentKind) Record[Idx++];
9064 bool IsTrailingComment = Record[Idx++];
9065 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009066 Comments.push_back(new (Context) RawComment(
9067 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
9068 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00009069 break;
9070 }
9071 }
9072 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009073 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009074 // De-serialized SourceLocations get negative FileIDs for other modules,
9075 // potentially invalidating the original order. Sort it again.
9076 std::sort(Comments.begin(), Comments.end(),
9077 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009078 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009079 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009080}
9081
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009082void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9083 bool IncludeSystem, bool Complain,
9084 llvm::function_ref<void(const serialization::InputFile &IF,
9085 bool isSystem)> Visitor) {
9086 unsigned NumUserInputs = MF.NumUserInputFiles;
9087 unsigned NumInputs = MF.InputFilesLoaded.size();
9088 assert(NumUserInputs <= NumInputs);
9089 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9090 for (unsigned I = 0; I < N; ++I) {
9091 bool IsSystem = I >= NumUserInputs;
9092 InputFile IF = getInputFile(MF, I+1, Complain);
9093 Visitor(IF, IsSystem);
9094 }
9095}
9096
Richard Smithf3f84612017-06-29 02:19:42 +00009097void ASTReader::visitTopLevelModuleMaps(
9098 serialization::ModuleFile &MF,
9099 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9100 unsigned NumInputs = MF.InputFilesLoaded.size();
9101 for (unsigned I = 0; I < NumInputs; ++I) {
9102 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9103 if (IFI.TopLevelModuleMap)
9104 // FIXME: This unnecessarily re-reads the InputFileInfo.
9105 if (auto *FE = getInputFile(MF, I + 1).getFile())
9106 Visitor(FE);
9107 }
9108}
9109
Richard Smithcd45dbc2014-04-19 03:48:30 +00009110std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9111 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009112 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009113 return M->getFullModuleName();
9114
9115 // Otherwise, use the name of the top-level module the decl is within.
9116 if (ModuleFile *M = getOwningModuleFile(D))
9117 return M->ModuleName;
9118
9119 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009120 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009121}
9122
Guy Benyei11169dd2012-12-18 14:30:41 +00009123void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00009124 while (!PendingIdentifierInfos.empty() ||
9125 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009126 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009127 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009128 // If any identifiers with corresponding top-level declarations have
9129 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009130 using TopLevelDeclsMap =
9131 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009132 TopLevelDeclsMap TopLevelDecls;
9133
Guy Benyei11169dd2012-12-18 14:30:41 +00009134 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009135 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009136 SmallVector<uint32_t, 4> DeclIDs =
9137 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009138 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009139
9140 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009141 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009142
Richard Smith851072e2014-05-19 20:59:20 +00009143 // For each decl chain that we wanted to complete while deserializing, mark
9144 // it as "still needs to be completed".
9145 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9146 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9147 }
9148 PendingIncompleteDeclChains.clear();
9149
Guy Benyei11169dd2012-12-18 14:30:41 +00009150 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00009151 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00009152 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009153 PendingDeclChains.clear();
9154
Douglas Gregor6168bd22013-02-18 15:53:43 +00009155 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00009156 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9157 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009158 IdentifierInfo *II = TLD->first;
9159 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009160 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009161 }
9162 }
9163
Guy Benyei11169dd2012-12-18 14:30:41 +00009164 // Load any pending macro definitions.
9165 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009166 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9167 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9168 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9169 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009170 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009171 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009172 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009173 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009174 resolvePendingMacro(II, Info);
9175 }
9176 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009177 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009178 ++IDIdx) {
9179 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);
Guy Benyei11169dd2012-12-18 14:30:41 +00009182 }
9183 }
9184 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009185
9186 // Wire up the DeclContexts for Decls that we delayed setting until
9187 // recursive loading is completed.
9188 while (!PendingDeclContextInfos.empty()) {
9189 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9190 PendingDeclContextInfos.pop_front();
9191 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9192 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9193 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9194 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009195
Richard Smithd1c46742014-04-30 02:24:17 +00009196 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009197 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009198 auto Update = PendingUpdateRecords.pop_back_val();
9199 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009200 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009201 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009202 }
Richard Smith8a639892015-01-24 01:07:20 +00009203
9204 // At this point, all update records for loaded decls are in place, so any
9205 // fake class definitions should have become real.
9206 assert(PendingFakeDefinitionData.empty() &&
9207 "faked up a class definition but never saw the real one");
9208
Guy Benyei11169dd2012-12-18 14:30:41 +00009209 // If we deserialized any C++ or Objective-C class definitions, any
9210 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009211 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009212 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00009213 for (Decl *D : PendingDefinitions) {
9214 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00009215 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009216 // Make sure that the TagType points at the definition.
9217 const_cast<TagType*>(TagT)->decl = TD;
9218 }
Richard Smith8ce51082015-03-11 01:44:51 +00009219
Craig Topperc6914d02014-08-25 04:15:02 +00009220 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009221 for (auto *R = getMostRecentExistingDecl(RD); R;
9222 R = R->getPreviousDecl()) {
9223 assert((R == D) ==
9224 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009225 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009226 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009227 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009228 }
9229
9230 continue;
9231 }
Richard Smith8ce51082015-03-11 01:44:51 +00009232
Craig Topperc6914d02014-08-25 04:15:02 +00009233 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009234 // Make sure that the ObjCInterfaceType points at the definition.
9235 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9236 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009237
9238 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9239 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9240
Guy Benyei11169dd2012-12-18 14:30:41 +00009241 continue;
9242 }
Richard Smith8ce51082015-03-11 01:44:51 +00009243
Craig Topperc6914d02014-08-25 04:15:02 +00009244 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009245 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9246 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9247
Guy Benyei11169dd2012-12-18 14:30:41 +00009248 continue;
9249 }
Richard Smith8ce51082015-03-11 01:44:51 +00009250
Craig Topperc6914d02014-08-25 04:15:02 +00009251 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009252 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9253 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009254 }
9255 PendingDefinitions.clear();
9256
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009257 // Load the bodies of any functions or methods we've encountered. We do
9258 // this now (delayed) so that we can be sure that the declaration chains
9259 // have been fully wired up (hasBody relies on this).
9260 // FIXME: We shouldn't require complete redeclaration chains here.
9261 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9262 PBEnd = PendingBodies.end();
9263 PB != PBEnd; ++PB) {
9264 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9265 // FIXME: Check for =delete/=default?
9266 // FIXME: Complain about ODR violations here?
9267 const FunctionDecl *Defn = nullptr;
9268 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9269 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009270 } else {
9271 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9272 mergeDefinitionVisibility(NonConstDefn, FD);
9273
9274 if (!FD->isLateTemplateParsed() &&
9275 !NonConstDefn->isLateTemplateParsed() &&
9276 FD->getODRHash() != NonConstDefn->getODRHash()) {
9277 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9278 }
9279 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009280 continue;
9281 }
9282
9283 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9284 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9285 MD->setLazyBody(PB->second);
9286 }
9287 PendingBodies.clear();
9288
Richard Smith42413142015-05-15 20:05:43 +00009289 // Do some cleanup.
9290 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9291 getContext().deduplicateMergedDefinitonsFor(ND);
9292 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009293}
9294
9295void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009296 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9297 PendingFunctionOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009298 return;
9299
Richard Smitha0ce9c42014-07-29 23:23:27 +00009300 // Trigger the import of the full definition of each class that had any
9301 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009302 // These updates may in turn find and diagnose some ODR failures, so take
9303 // ownership of the set first.
9304 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9305 PendingOdrMergeFailures.clear();
9306 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009307 Merge.first->buildLookup();
9308 Merge.first->decls_begin();
9309 Merge.first->bases_begin();
9310 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009311 for (auto &RecordPair : Merge.second) {
9312 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009313 RD->decls_begin();
9314 RD->bases_begin();
9315 RD->vbases_begin();
9316 }
9317 }
9318
Richard Trieue6caa262017-12-23 00:41:01 +00009319 // Trigger the import of functions.
9320 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9321 PendingFunctionOdrMergeFailures.clear();
9322 for (auto &Merge : FunctionOdrMergeFailures) {
9323 Merge.first->buildLookup();
9324 Merge.first->decls_begin();
9325 Merge.first->getBody();
9326 for (auto &FD : Merge.second) {
9327 FD->buildLookup();
9328 FD->decls_begin();
9329 FD->getBody();
9330 }
9331 }
9332
Richard Smitha0ce9c42014-07-29 23:23:27 +00009333 // For each declaration from a merged context, check that the canonical
9334 // definition of that context also contains a declaration of the same
9335 // entity.
9336 //
9337 // Caution: this loop does things that might invalidate iterators into
9338 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9339 while (!PendingOdrMergeChecks.empty()) {
9340 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9341
9342 // FIXME: Skip over implicit declarations for now. This matters for things
9343 // like implicitly-declared special member functions. This isn't entirely
9344 // correct; we can end up with multiple unmerged declarations of the same
9345 // implicit entity.
9346 if (D->isImplicit())
9347 continue;
9348
9349 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009350
9351 bool Found = false;
9352 const Decl *DCanon = D->getCanonicalDecl();
9353
Richard Smith01bdb7a2014-08-28 05:44:07 +00009354 for (auto RI : D->redecls()) {
9355 if (RI->getLexicalDeclContext() == CanonDef) {
9356 Found = true;
9357 break;
9358 }
9359 }
9360 if (Found)
9361 continue;
9362
Richard Smith0f4e2c42015-08-06 04:23:48 +00009363 // Quick check failed, time to do the slow thing. Note, we can't just
9364 // look up the name of D in CanonDef here, because the member that is
9365 // in CanonDef might not be found by name lookup (it might have been
9366 // replaced by a more recent declaration in the lookup table), and we
9367 // can't necessarily find it in the redeclaration chain because it might
9368 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009369 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009370 for (auto *CanonMember : CanonDef->decls()) {
9371 if (CanonMember->getCanonicalDecl() == DCanon) {
9372 // This can happen if the declaration is merely mergeable and not
9373 // actually redeclarable (we looked for redeclarations earlier).
9374 //
9375 // FIXME: We should be able to detect this more efficiently, without
9376 // pulling in all of the members of CanonDef.
9377 Found = true;
9378 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009379 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009380 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9381 if (ND->getDeclName() == D->getDeclName())
9382 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009383 }
9384
9385 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009386 // The AST doesn't like TagDecls becoming invalid after they've been
9387 // completed. We only really need to mark FieldDecls as invalid here.
9388 if (!isa<TagDecl>(D))
9389 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009390
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009391 // Ensure we don't accidentally recursively enter deserialization while
9392 // we're producing our diagnostic.
9393 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009394
9395 std::string CanonDefModule =
9396 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9397 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9398 << D << getOwningModuleNameForDiagnostic(D)
9399 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9400
9401 if (Candidates.empty())
9402 Diag(cast<Decl>(CanonDef)->getLocation(),
9403 diag::note_module_odr_violation_no_possible_decls) << D;
9404 else {
9405 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9406 Diag(Candidates[I]->getLocation(),
9407 diag::note_module_odr_violation_possible_decl)
9408 << Candidates[I];
9409 }
9410
9411 DiagnosedOdrMergeFailures.insert(CanonDef);
9412 }
9413 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009414
Richard Trieue6caa262017-12-23 00:41:01 +00009415 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009416 return;
9417
9418 // Ensure we don't accidentally recursively enter deserialization while
9419 // we're producing our diagnostics.
9420 Deserializing RecursionGuard(this);
9421
Richard Trieue6caa262017-12-23 00:41:01 +00009422 // Common code for hashing helpers.
9423 ODRHash Hash;
9424 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9425 Hash.clear();
9426 Hash.AddQualType(Ty);
9427 return Hash.CalculateHash();
9428 };
9429
9430 auto ComputeODRHash = [&Hash](const Stmt *S) {
9431 assert(S);
9432 Hash.clear();
9433 Hash.AddStmt(S);
9434 return Hash.CalculateHash();
9435 };
9436
9437 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9438 assert(D);
9439 Hash.clear();
9440 Hash.AddSubDecl(D);
9441 return Hash.CalculateHash();
9442 };
9443
Richard Smithcd45dbc2014-04-19 03:48:30 +00009444 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009445 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009446 // If we've already pointed out a specific problem with this class, don't
9447 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009448 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009449 continue;
9450
9451 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009452 CXXRecordDecl *FirstRecord = Merge.first;
9453 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009454 for (auto &RecordPair : Merge.second) {
9455 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009456 // Multiple different declarations got merged together; tell the user
9457 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009458 if (FirstRecord == SecondRecord)
9459 continue;
9460
9461 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009462
9463 auto *FirstDD = FirstRecord->DefinitionData;
9464 auto *SecondDD = RecordPair.second;
9465
9466 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9467
9468 // Diagnostics from DefinitionData are emitted here.
9469 if (FirstDD != SecondDD) {
9470 enum ODRDefinitionDataDifference {
9471 NumBases,
9472 NumVBases,
9473 BaseType,
9474 BaseVirtual,
9475 BaseAccess,
9476 };
9477 auto ODRDiagError = [FirstRecord, &FirstModule,
9478 this](SourceLocation Loc, SourceRange Range,
9479 ODRDefinitionDataDifference DiffType) {
9480 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9481 << FirstRecord << FirstModule.empty() << FirstModule << Range
9482 << DiffType;
9483 };
9484 auto ODRDiagNote = [&SecondModule,
9485 this](SourceLocation Loc, SourceRange Range,
9486 ODRDefinitionDataDifference DiffType) {
9487 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9488 << SecondModule << Range << DiffType;
9489 };
9490
Richard Trieue13eabe2017-09-30 02:19:17 +00009491 unsigned FirstNumBases = FirstDD->NumBases;
9492 unsigned FirstNumVBases = FirstDD->NumVBases;
9493 unsigned SecondNumBases = SecondDD->NumBases;
9494 unsigned SecondNumVBases = SecondDD->NumVBases;
9495
9496 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9497 unsigned NumBases = DD->NumBases;
9498 if (NumBases == 0) return SourceRange();
9499 auto bases = DD->bases();
9500 return SourceRange(bases[0].getLocStart(),
9501 bases[NumBases - 1].getLocEnd());
9502 };
9503
9504 if (FirstNumBases != SecondNumBases) {
9505 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9506 NumBases)
9507 << FirstNumBases;
9508 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9509 NumBases)
9510 << SecondNumBases;
9511 Diagnosed = true;
9512 break;
9513 }
9514
9515 if (FirstNumVBases != SecondNumVBases) {
9516 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9517 NumVBases)
9518 << FirstNumVBases;
9519 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9520 NumVBases)
9521 << SecondNumVBases;
9522 Diagnosed = true;
9523 break;
9524 }
9525
9526 auto FirstBases = FirstDD->bases();
9527 auto SecondBases = SecondDD->bases();
9528 unsigned i = 0;
9529 for (i = 0; i < FirstNumBases; ++i) {
9530 auto FirstBase = FirstBases[i];
9531 auto SecondBase = SecondBases[i];
9532 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9533 ComputeQualTypeODRHash(SecondBase.getType())) {
9534 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9535 BaseType)
9536 << (i + 1) << FirstBase.getType();
9537 ODRDiagNote(SecondRecord->getLocation(),
9538 SecondBase.getSourceRange(), BaseType)
9539 << (i + 1) << SecondBase.getType();
9540 break;
9541 }
9542
9543 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9544 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9545 BaseVirtual)
9546 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9547 ODRDiagNote(SecondRecord->getLocation(),
9548 SecondBase.getSourceRange(), BaseVirtual)
9549 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9550 break;
9551 }
9552
9553 if (FirstBase.getAccessSpecifierAsWritten() !=
9554 SecondBase.getAccessSpecifierAsWritten()) {
9555 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9556 BaseAccess)
9557 << (i + 1) << FirstBase.getType()
9558 << (int)FirstBase.getAccessSpecifierAsWritten();
9559 ODRDiagNote(SecondRecord->getLocation(),
9560 SecondBase.getSourceRange(), BaseAccess)
9561 << (i + 1) << SecondBase.getType()
9562 << (int)SecondBase.getAccessSpecifierAsWritten();
9563 break;
9564 }
9565 }
9566
9567 if (i != FirstNumBases) {
9568 Diagnosed = true;
9569 break;
9570 }
9571 }
9572
Richard Trieue7f7ed22017-02-22 01:11:25 +00009573 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009574
9575 const ClassTemplateDecl *FirstTemplate =
9576 FirstRecord->getDescribedClassTemplate();
9577 const ClassTemplateDecl *SecondTemplate =
9578 SecondRecord->getDescribedClassTemplate();
9579
9580 assert(!FirstTemplate == !SecondTemplate &&
9581 "Both pointers should be null or non-null");
9582
9583 enum ODRTemplateDifference {
9584 ParamEmptyName,
9585 ParamName,
9586 ParamSingleDefaultArgument,
9587 ParamDifferentDefaultArgument,
9588 };
9589
9590 if (FirstTemplate && SecondTemplate) {
9591 DeclHashes FirstTemplateHashes;
9592 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +00009593
9594 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +00009595 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9596 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +00009597 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +00009598 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +00009599 }
9600 };
9601
9602 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9603 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9604
9605 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9606 "Number of template parameters should be equal.");
9607
9608 auto FirstIt = FirstTemplateHashes.begin();
9609 auto FirstEnd = FirstTemplateHashes.end();
9610 auto SecondIt = SecondTemplateHashes.begin();
9611 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9612 if (FirstIt->second == SecondIt->second)
9613 continue;
9614
9615 auto ODRDiagError = [FirstRecord, &FirstModule,
9616 this](SourceLocation Loc, SourceRange Range,
9617 ODRTemplateDifference DiffType) {
9618 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9619 << FirstRecord << FirstModule.empty() << FirstModule << Range
9620 << DiffType;
9621 };
9622 auto ODRDiagNote = [&SecondModule,
9623 this](SourceLocation Loc, SourceRange Range,
9624 ODRTemplateDifference DiffType) {
9625 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9626 << SecondModule << Range << DiffType;
9627 };
9628
9629 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9630 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
9631
9632 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9633 "Parameter Decl's should be the same kind.");
9634
9635 DeclarationName FirstName = FirstDecl->getDeclName();
9636 DeclarationName SecondName = SecondDecl->getDeclName();
9637
9638 if (FirstName != SecondName) {
9639 const bool FirstNameEmpty =
9640 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9641 const bool SecondNameEmpty =
9642 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9643 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9644 "Both template parameters cannot be unnamed.");
9645 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9646 FirstNameEmpty ? ParamEmptyName : ParamName)
9647 << FirstName;
9648 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9649 SecondNameEmpty ? ParamEmptyName : ParamName)
9650 << SecondName;
9651 break;
9652 }
9653
9654 switch (FirstDecl->getKind()) {
9655 default:
9656 llvm_unreachable("Invalid template parameter type.");
9657 case Decl::TemplateTypeParm: {
9658 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9659 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9660 const bool HasFirstDefaultArgument =
9661 FirstParam->hasDefaultArgument() &&
9662 !FirstParam->defaultArgumentWasInherited();
9663 const bool HasSecondDefaultArgument =
9664 SecondParam->hasDefaultArgument() &&
9665 !SecondParam->defaultArgumentWasInherited();
9666
9667 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9668 ODRDiagError(FirstDecl->getLocation(),
9669 FirstDecl->getSourceRange(),
9670 ParamSingleDefaultArgument)
9671 << HasFirstDefaultArgument;
9672 ODRDiagNote(SecondDecl->getLocation(),
9673 SecondDecl->getSourceRange(),
9674 ParamSingleDefaultArgument)
9675 << HasSecondDefaultArgument;
9676 break;
9677 }
9678
9679 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9680 "Expecting default arguments.");
9681
9682 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9683 ParamDifferentDefaultArgument);
9684 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9685 ParamDifferentDefaultArgument);
9686
9687 break;
9688 }
9689 case Decl::NonTypeTemplateParm: {
9690 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9691 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9692 const bool HasFirstDefaultArgument =
9693 FirstParam->hasDefaultArgument() &&
9694 !FirstParam->defaultArgumentWasInherited();
9695 const bool HasSecondDefaultArgument =
9696 SecondParam->hasDefaultArgument() &&
9697 !SecondParam->defaultArgumentWasInherited();
9698
9699 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9700 ODRDiagError(FirstDecl->getLocation(),
9701 FirstDecl->getSourceRange(),
9702 ParamSingleDefaultArgument)
9703 << HasFirstDefaultArgument;
9704 ODRDiagNote(SecondDecl->getLocation(),
9705 SecondDecl->getSourceRange(),
9706 ParamSingleDefaultArgument)
9707 << HasSecondDefaultArgument;
9708 break;
9709 }
9710
9711 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9712 "Expecting default arguments.");
9713
9714 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9715 ParamDifferentDefaultArgument);
9716 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9717 ParamDifferentDefaultArgument);
9718
9719 break;
9720 }
9721 case Decl::TemplateTemplateParm: {
9722 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9723 const auto *SecondParam =
9724 cast<TemplateTemplateParmDecl>(SecondDecl);
9725 const bool HasFirstDefaultArgument =
9726 FirstParam->hasDefaultArgument() &&
9727 !FirstParam->defaultArgumentWasInherited();
9728 const bool HasSecondDefaultArgument =
9729 SecondParam->hasDefaultArgument() &&
9730 !SecondParam->defaultArgumentWasInherited();
9731
9732 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9733 ODRDiagError(FirstDecl->getLocation(),
9734 FirstDecl->getSourceRange(),
9735 ParamSingleDefaultArgument)
9736 << HasFirstDefaultArgument;
9737 ODRDiagNote(SecondDecl->getLocation(),
9738 SecondDecl->getSourceRange(),
9739 ParamSingleDefaultArgument)
9740 << HasSecondDefaultArgument;
9741 break;
9742 }
9743
9744 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9745 "Expecting default arguments.");
9746
9747 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9748 ParamDifferentDefaultArgument);
9749 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9750 ParamDifferentDefaultArgument);
9751
9752 break;
9753 }
9754 }
9755
9756 break;
9757 }
9758
9759 if (FirstIt != FirstEnd) {
9760 Diagnosed = true;
9761 break;
9762 }
9763 }
9764
Richard Trieue7f7ed22017-02-22 01:11:25 +00009765 DeclHashes FirstHashes;
9766 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009767
Richard Trieue6caa262017-12-23 00:41:01 +00009768 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9769 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009770 for (auto *D : Record->decls()) {
9771 // Due to decl merging, the first CXXRecordDecl is the parent of
9772 // Decls in both records.
9773 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9774 continue;
Richard Trieue6caa262017-12-23 00:41:01 +00009775 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +00009776 }
9777 };
9778 PopulateHashes(FirstHashes, FirstRecord);
9779 PopulateHashes(SecondHashes, SecondRecord);
9780
9781 // Used with err_module_odr_violation_mismatch_decl and
9782 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009783 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009784 enum {
9785 EndOfClass,
9786 PublicSpecifer,
9787 PrivateSpecifer,
9788 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009789 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009790 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009791 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009792 TypeAlias,
9793 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009794 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009795 Friend,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009796 Other
9797 } FirstDiffType = Other,
9798 SecondDiffType = Other;
9799
9800 auto DifferenceSelector = [](Decl *D) {
9801 assert(D && "valid Decl required");
9802 switch (D->getKind()) {
9803 default:
9804 return Other;
9805 case Decl::AccessSpec:
9806 switch (D->getAccess()) {
9807 case AS_public:
9808 return PublicSpecifer;
9809 case AS_private:
9810 return PrivateSpecifer;
9811 case AS_protected:
9812 return ProtectedSpecifer;
9813 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009814 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009815 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009816 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009817 case Decl::StaticAssert:
9818 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009819 case Decl::Field:
9820 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009821 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +00009822 case Decl::CXXConstructor:
9823 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +00009824 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +00009825 case Decl::TypeAlias:
9826 return TypeAlias;
9827 case Decl::Typedef:
9828 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +00009829 case Decl::Var:
9830 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +00009831 case Decl::Friend:
9832 return Friend;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009833 }
9834 };
9835
9836 Decl *FirstDecl = nullptr;
9837 Decl *SecondDecl = nullptr;
9838 auto FirstIt = FirstHashes.begin();
9839 auto SecondIt = SecondHashes.begin();
9840
9841 // If there is a diagnoseable difference, FirstDiffType and
9842 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9843 // filled in if not EndOfClass.
9844 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009845 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9846 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009847 ++FirstIt;
9848 ++SecondIt;
9849 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009850 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009851
Richard Trieue7f7ed22017-02-22 01:11:25 +00009852 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9853 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9854
9855 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9856 SecondDiffType =
9857 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9858
9859 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009860 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009861
9862 if (FirstDiffType == Other || SecondDiffType == Other) {
9863 // Reaching this point means an unexpected Decl was encountered
9864 // or no difference was detected. This causes a generic error
9865 // message to be emitted.
9866 Diag(FirstRecord->getLocation(),
9867 diag::err_module_odr_violation_different_definitions)
9868 << FirstRecord << FirstModule.empty() << FirstModule;
9869
Richard Trieuca48d362017-06-21 01:43:13 +00009870 if (FirstDecl) {
9871 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9872 << FirstRecord << FirstDecl->getSourceRange();
9873 }
9874
Richard Trieue7f7ed22017-02-22 01:11:25 +00009875 Diag(SecondRecord->getLocation(),
9876 diag::note_module_odr_violation_different_definitions)
9877 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +00009878
9879 if (SecondDecl) {
9880 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9881 << SecondDecl->getSourceRange();
9882 }
9883
Richard Trieue7f7ed22017-02-22 01:11:25 +00009884 Diagnosed = true;
9885 break;
9886 }
9887
9888 if (FirstDiffType != SecondDiffType) {
9889 SourceLocation FirstLoc;
9890 SourceRange FirstRange;
9891 if (FirstDiffType == EndOfClass) {
9892 FirstLoc = FirstRecord->getBraceRange().getEnd();
9893 } else {
9894 FirstLoc = FirstIt->first->getLocation();
9895 FirstRange = FirstIt->first->getSourceRange();
9896 }
9897 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9898 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9899 << FirstDiffType;
9900
9901 SourceLocation SecondLoc;
9902 SourceRange SecondRange;
9903 if (SecondDiffType == EndOfClass) {
9904 SecondLoc = SecondRecord->getBraceRange().getEnd();
9905 } else {
9906 SecondLoc = SecondDecl->getLocation();
9907 SecondRange = SecondDecl->getSourceRange();
9908 }
9909 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9910 << SecondModule << SecondRange << SecondDiffType;
9911 Diagnosed = true;
9912 break;
9913 }
9914
Richard Trieu639d7b62017-02-22 22:22:42 +00009915 assert(FirstDiffType == SecondDiffType);
9916
9917 // Used with err_module_odr_violation_mismatch_decl_diff and
9918 // note_module_odr_violation_mismatch_decl_diff
9919 enum ODRDeclDifference{
9920 StaticAssertCondition,
9921 StaticAssertMessage,
9922 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009923 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009924 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009925 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009926 FieldDifferentWidthBitField,
9927 FieldSingleMutable,
9928 FieldSingleInitializer,
9929 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009930 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009931 MethodDeleted,
9932 MethodVirtual,
9933 MethodStatic,
9934 MethodVolatile,
9935 MethodConst,
9936 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009937 MethodNumberParameters,
9938 MethodParameterType,
9939 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009940 MethodParameterSingleDefaultArgument,
9941 MethodParameterDifferentDefaultArgument,
Richard Trieu11d566a2017-06-12 21:58:22 +00009942 TypedefName,
9943 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009944 VarName,
9945 VarType,
9946 VarSingleInitializer,
9947 VarDifferentInitializer,
9948 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009949 FriendTypeFunction,
9950 FriendType,
9951 FriendFunction,
Richard Trieu639d7b62017-02-22 22:22:42 +00009952 };
9953
9954 // These lambdas have the common portions of the ODR diagnostics. This
9955 // has the same return as Diag(), so addition parameters can be passed
9956 // in with operator<<
9957 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9958 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9959 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9960 << FirstRecord << FirstModule.empty() << FirstModule << Range
9961 << DiffType;
9962 };
9963 auto ODRDiagNote = [&SecondModule, this](
9964 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9965 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9966 << SecondModule << Range << DiffType;
9967 };
9968
Richard Trieu639d7b62017-02-22 22:22:42 +00009969 switch (FirstDiffType) {
9970 case Other:
9971 case EndOfClass:
9972 case PublicSpecifer:
9973 case PrivateSpecifer:
9974 case ProtectedSpecifer:
9975 llvm_unreachable("Invalid diff type");
9976
9977 case StaticAssert: {
9978 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9979 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9980
9981 Expr *FirstExpr = FirstSA->getAssertExpr();
9982 Expr *SecondExpr = SecondSA->getAssertExpr();
9983 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9984 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9985 if (FirstODRHash != SecondODRHash) {
9986 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9987 StaticAssertCondition);
9988 ODRDiagNote(SecondExpr->getLocStart(),
9989 SecondExpr->getSourceRange(), StaticAssertCondition);
9990 Diagnosed = true;
9991 break;
9992 }
9993
9994 StringLiteral *FirstStr = FirstSA->getMessage();
9995 StringLiteral *SecondStr = SecondSA->getMessage();
9996 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9997 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9998 SourceLocation FirstLoc, SecondLoc;
9999 SourceRange FirstRange, SecondRange;
10000 if (FirstStr) {
10001 FirstLoc = FirstStr->getLocStart();
10002 FirstRange = FirstStr->getSourceRange();
10003 } else {
10004 FirstLoc = FirstSA->getLocStart();
10005 FirstRange = FirstSA->getSourceRange();
10006 }
10007 if (SecondStr) {
10008 SecondLoc = SecondStr->getLocStart();
10009 SecondRange = SecondStr->getSourceRange();
10010 } else {
10011 SecondLoc = SecondSA->getLocStart();
10012 SecondRange = SecondSA->getSourceRange();
10013 }
10014 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10015 << (FirstStr == nullptr);
10016 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10017 << (SecondStr == nullptr);
10018 Diagnosed = true;
10019 break;
10020 }
10021
10022 if (FirstStr && SecondStr &&
10023 FirstStr->getString() != SecondStr->getString()) {
10024 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
10025 StaticAssertMessage);
10026 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
10027 StaticAssertMessage);
10028 Diagnosed = true;
10029 break;
10030 }
10031 break;
10032 }
Richard Trieud0786092017-02-23 00:23:01 +000010033 case Field: {
10034 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10035 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
10036 IdentifierInfo *FirstII = FirstField->getIdentifier();
10037 IdentifierInfo *SecondII = SecondField->getIdentifier();
10038 if (FirstII->getName() != SecondII->getName()) {
10039 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10040 FieldName)
10041 << FirstII;
10042 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10043 FieldName)
10044 << SecondII;
10045
10046 Diagnosed = true;
10047 break;
10048 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010049
Richard Smithdbafb6c2017-06-29 23:23:46 +000010050 assert(getContext().hasSameType(FirstField->getType(),
10051 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010052
10053 QualType FirstType = FirstField->getType();
10054 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010055 if (ComputeQualTypeODRHash(FirstType) !=
10056 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010057 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10058 FieldTypeName)
10059 << FirstII << FirstType;
10060 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10061 FieldTypeName)
10062 << SecondII << SecondType;
10063
10064 Diagnosed = true;
10065 break;
10066 }
10067
Richard Trieu93772fc2017-02-24 20:59:28 +000010068 const bool IsFirstBitField = FirstField->isBitField();
10069 const bool IsSecondBitField = SecondField->isBitField();
10070 if (IsFirstBitField != IsSecondBitField) {
10071 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10072 FieldSingleBitField)
10073 << FirstII << IsFirstBitField;
10074 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10075 FieldSingleBitField)
10076 << SecondII << IsSecondBitField;
10077 Diagnosed = true;
10078 break;
10079 }
10080
10081 if (IsFirstBitField && IsSecondBitField) {
10082 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10083 FieldDifferentWidthBitField)
10084 << FirstII << FirstField->getBitWidth()->getSourceRange();
10085 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10086 FieldDifferentWidthBitField)
10087 << SecondII << SecondField->getBitWidth()->getSourceRange();
10088 Diagnosed = true;
10089 break;
10090 }
10091
Richard Trieu8d543e22017-02-24 23:35:37 +000010092 const bool IsFirstMutable = FirstField->isMutable();
10093 const bool IsSecondMutable = SecondField->isMutable();
10094 if (IsFirstMutable != IsSecondMutable) {
10095 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10096 FieldSingleMutable)
10097 << FirstII << IsFirstMutable;
10098 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10099 FieldSingleMutable)
10100 << SecondII << IsSecondMutable;
10101 Diagnosed = true;
10102 break;
10103 }
10104
10105 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10106 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10107 if ((!FirstInitializer && SecondInitializer) ||
10108 (FirstInitializer && !SecondInitializer)) {
10109 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10110 FieldSingleInitializer)
10111 << FirstII << (FirstInitializer != nullptr);
10112 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10113 FieldSingleInitializer)
10114 << SecondII << (SecondInitializer != nullptr);
10115 Diagnosed = true;
10116 break;
10117 }
10118
10119 if (FirstInitializer && SecondInitializer) {
10120 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10121 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10122 if (FirstInitHash != SecondInitHash) {
10123 ODRDiagError(FirstField->getLocation(),
10124 FirstField->getSourceRange(),
10125 FieldDifferentInitializers)
10126 << FirstII << FirstInitializer->getSourceRange();
10127 ODRDiagNote(SecondField->getLocation(),
10128 SecondField->getSourceRange(),
10129 FieldDifferentInitializers)
10130 << SecondII << SecondInitializer->getSourceRange();
10131 Diagnosed = true;
10132 break;
10133 }
10134 }
10135
Richard Trieud0786092017-02-23 00:23:01 +000010136 break;
10137 }
Richard Trieu48143742017-02-28 21:24:38 +000010138 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010139 enum {
10140 DiagMethod,
10141 DiagConstructor,
10142 DiagDestructor,
10143 } FirstMethodType,
10144 SecondMethodType;
10145 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10146 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10147 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10148 return DiagMethod;
10149 };
Richard Trieu48143742017-02-28 21:24:38 +000010150 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10151 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010152 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10153 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010154 auto FirstName = FirstMethod->getDeclName();
10155 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010156 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010157 ODRDiagError(FirstMethod->getLocation(),
10158 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010159 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010160 ODRDiagNote(SecondMethod->getLocation(),
10161 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010162 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010163
10164 Diagnosed = true;
10165 break;
10166 }
10167
Richard Trieu583e2c12017-03-04 00:08:58 +000010168 const bool FirstDeleted = FirstMethod->isDeleted();
10169 const bool SecondDeleted = SecondMethod->isDeleted();
10170 if (FirstDeleted != SecondDeleted) {
10171 ODRDiagError(FirstMethod->getLocation(),
10172 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010173 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010174
10175 ODRDiagNote(SecondMethod->getLocation(),
10176 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010177 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010178 Diagnosed = true;
10179 break;
10180 }
10181
10182 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10183 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10184 const bool FirstPure = FirstMethod->isPure();
10185 const bool SecondPure = SecondMethod->isPure();
10186 if ((FirstVirtual || SecondVirtual) &&
10187 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10188 ODRDiagError(FirstMethod->getLocation(),
10189 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010190 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010191 ODRDiagNote(SecondMethod->getLocation(),
10192 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010193 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010194 Diagnosed = true;
10195 break;
10196 }
10197
10198 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10199 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10200 // class needs to be checked instead.
10201 const auto FirstStorage = FirstMethod->getStorageClass();
10202 const auto SecondStorage = SecondMethod->getStorageClass();
10203 const bool FirstStatic = FirstStorage == SC_Static;
10204 const bool SecondStatic = SecondStorage == SC_Static;
10205 if (FirstStatic != SecondStatic) {
10206 ODRDiagError(FirstMethod->getLocation(),
10207 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010208 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010209 ODRDiagNote(SecondMethod->getLocation(),
10210 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010211 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010212 Diagnosed = true;
10213 break;
10214 }
10215
10216 const bool FirstVolatile = FirstMethod->isVolatile();
10217 const bool SecondVolatile = SecondMethod->isVolatile();
10218 if (FirstVolatile != SecondVolatile) {
10219 ODRDiagError(FirstMethod->getLocation(),
10220 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010221 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010222 ODRDiagNote(SecondMethod->getLocation(),
10223 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010224 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010225 Diagnosed = true;
10226 break;
10227 }
10228
10229 const bool FirstConst = FirstMethod->isConst();
10230 const bool SecondConst = SecondMethod->isConst();
10231 if (FirstConst != SecondConst) {
10232 ODRDiagError(FirstMethod->getLocation(),
10233 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010234 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010235 ODRDiagNote(SecondMethod->getLocation(),
10236 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010237 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010238 Diagnosed = true;
10239 break;
10240 }
10241
10242 const bool FirstInline = FirstMethod->isInlineSpecified();
10243 const bool SecondInline = SecondMethod->isInlineSpecified();
10244 if (FirstInline != SecondInline) {
10245 ODRDiagError(FirstMethod->getLocation(),
10246 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010247 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010248 ODRDiagNote(SecondMethod->getLocation(),
10249 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010250 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010251 Diagnosed = true;
10252 break;
10253 }
10254
Richard Trieu02552272017-05-02 23:58:52 +000010255 const unsigned FirstNumParameters = FirstMethod->param_size();
10256 const unsigned SecondNumParameters = SecondMethod->param_size();
10257 if (FirstNumParameters != SecondNumParameters) {
10258 ODRDiagError(FirstMethod->getLocation(),
10259 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010260 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010261 ODRDiagNote(SecondMethod->getLocation(),
10262 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010263 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010264 Diagnosed = true;
10265 break;
10266 }
10267
10268 // Need this status boolean to know when break out of the switch.
10269 bool ParameterMismatch = false;
10270 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10271 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10272 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10273
10274 QualType FirstParamType = FirstParam->getType();
10275 QualType SecondParamType = SecondParam->getType();
10276 if (FirstParamType != SecondParamType &&
10277 ComputeQualTypeODRHash(FirstParamType) !=
10278 ComputeQualTypeODRHash(SecondParamType)) {
10279 if (const DecayedType *ParamDecayedType =
10280 FirstParamType->getAs<DecayedType>()) {
10281 ODRDiagError(FirstMethod->getLocation(),
10282 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010283 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10284 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010285 } else {
10286 ODRDiagError(FirstMethod->getLocation(),
10287 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010288 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10289 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010290 }
10291
10292 if (const DecayedType *ParamDecayedType =
10293 SecondParamType->getAs<DecayedType>()) {
10294 ODRDiagNote(SecondMethod->getLocation(),
10295 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010296 << SecondMethodType << SecondName << (I + 1)
10297 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010298 << ParamDecayedType->getOriginalType();
10299 } else {
10300 ODRDiagNote(SecondMethod->getLocation(),
10301 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010302 << SecondMethodType << SecondName << (I + 1)
10303 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010304 }
10305 ParameterMismatch = true;
10306 break;
10307 }
10308
10309 DeclarationName FirstParamName = FirstParam->getDeclName();
10310 DeclarationName SecondParamName = SecondParam->getDeclName();
10311 if (FirstParamName != SecondParamName) {
10312 ODRDiagError(FirstMethod->getLocation(),
10313 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010314 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010315 ODRDiagNote(SecondMethod->getLocation(),
10316 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010317 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010318 ParameterMismatch = true;
10319 break;
10320 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010321
10322 const Expr *FirstInit = FirstParam->getInit();
10323 const Expr *SecondInit = SecondParam->getInit();
10324 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10325 ODRDiagError(FirstMethod->getLocation(),
10326 FirstMethod->getSourceRange(),
10327 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010328 << FirstMethodType << FirstName << (I + 1)
10329 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010330 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10331 ODRDiagNote(SecondMethod->getLocation(),
10332 SecondMethod->getSourceRange(),
10333 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010334 << SecondMethodType << SecondName << (I + 1)
10335 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010336 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10337 ParameterMismatch = true;
10338 break;
10339 }
10340
10341 if (FirstInit && SecondInit &&
10342 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10343 ODRDiagError(FirstMethod->getLocation(),
10344 FirstMethod->getSourceRange(),
10345 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010346 << FirstMethodType << FirstName << (I + 1)
10347 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010348 ODRDiagNote(SecondMethod->getLocation(),
10349 SecondMethod->getSourceRange(),
10350 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010351 << SecondMethodType << SecondName << (I + 1)
10352 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010353 ParameterMismatch = true;
10354 break;
10355
10356 }
Richard Trieu02552272017-05-02 23:58:52 +000010357 }
10358
10359 if (ParameterMismatch) {
10360 Diagnosed = true;
10361 break;
10362 }
10363
Richard Trieu48143742017-02-28 21:24:38 +000010364 break;
10365 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010366 case TypeAlias:
10367 case TypeDef: {
10368 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10369 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
10370 auto FirstName = FirstTD->getDeclName();
10371 auto SecondName = SecondTD->getDeclName();
10372 if (FirstName != SecondName) {
10373 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10374 TypedefName)
10375 << (FirstDiffType == TypeAlias) << FirstName;
10376 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10377 TypedefName)
10378 << (FirstDiffType == TypeAlias) << SecondName;
10379 Diagnosed = true;
10380 break;
10381 }
10382
10383 QualType FirstType = FirstTD->getUnderlyingType();
10384 QualType SecondType = SecondTD->getUnderlyingType();
10385 if (ComputeQualTypeODRHash(FirstType) !=
10386 ComputeQualTypeODRHash(SecondType)) {
10387 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10388 TypedefType)
10389 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10390 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10391 TypedefType)
10392 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10393 Diagnosed = true;
10394 break;
10395 }
10396 break;
10397 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010398 case Var: {
10399 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10400 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
10401 auto FirstName = FirstVD->getDeclName();
10402 auto SecondName = SecondVD->getDeclName();
10403 if (FirstName != SecondName) {
10404 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10405 VarName)
10406 << FirstName;
10407 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10408 VarName)
10409 << SecondName;
10410 Diagnosed = true;
10411 break;
10412 }
10413
10414 QualType FirstType = FirstVD->getType();
10415 QualType SecondType = SecondVD->getType();
10416 if (ComputeQualTypeODRHash(FirstType) !=
10417 ComputeQualTypeODRHash(SecondType)) {
10418 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10419 VarType)
10420 << FirstName << FirstType;
10421 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10422 VarType)
10423 << SecondName << SecondType;
10424 Diagnosed = true;
10425 break;
10426 }
10427
10428 const Expr *FirstInit = FirstVD->getInit();
10429 const Expr *SecondInit = SecondVD->getInit();
10430 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10431 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10432 VarSingleInitializer)
10433 << FirstName << (FirstInit == nullptr)
10434 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10435 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10436 VarSingleInitializer)
10437 << SecondName << (SecondInit == nullptr)
10438 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10439 Diagnosed = true;
10440 break;
10441 }
10442
10443 if (FirstInit && SecondInit &&
10444 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10445 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10446 VarDifferentInitializer)
10447 << FirstName << FirstInit->getSourceRange();
10448 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10449 VarDifferentInitializer)
10450 << SecondName << SecondInit->getSourceRange();
10451 Diagnosed = true;
10452 break;
10453 }
10454
10455 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10456 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10457 if (FirstIsConstexpr != SecondIsConstexpr) {
10458 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10459 VarConstexpr)
10460 << FirstName << FirstIsConstexpr;
10461 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10462 VarConstexpr)
10463 << SecondName << SecondIsConstexpr;
10464 Diagnosed = true;
10465 break;
10466 }
10467 break;
10468 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010469 case Friend: {
10470 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10471 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10472
10473 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10474 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10475
10476 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10477 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10478
10479 if (FirstND && SecondND) {
10480 ODRDiagError(FirstFriend->getFriendLoc(),
10481 FirstFriend->getSourceRange(), FriendFunction)
10482 << FirstND;
10483 ODRDiagNote(SecondFriend->getFriendLoc(),
10484 SecondFriend->getSourceRange(), FriendFunction)
10485 << SecondND;
10486
10487 Diagnosed = true;
10488 break;
10489 }
10490
10491 if (FirstTSI && SecondTSI) {
10492 QualType FirstFriendType = FirstTSI->getType();
10493 QualType SecondFriendType = SecondTSI->getType();
10494 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10495 ComputeQualTypeODRHash(SecondFriendType));
10496 ODRDiagError(FirstFriend->getFriendLoc(),
10497 FirstFriend->getSourceRange(), FriendType)
10498 << FirstFriendType;
10499 ODRDiagNote(SecondFriend->getFriendLoc(),
10500 SecondFriend->getSourceRange(), FriendType)
10501 << SecondFriendType;
10502 Diagnosed = true;
10503 break;
10504 }
10505
10506 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10507 FriendTypeFunction)
10508 << (FirstTSI == nullptr);
10509 ODRDiagNote(SecondFriend->getFriendLoc(),
10510 SecondFriend->getSourceRange(), FriendTypeFunction)
10511 << (SecondTSI == nullptr);
10512
10513 Diagnosed = true;
10514 break;
10515 }
Richard Trieu639d7b62017-02-22 22:22:42 +000010516 }
10517
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000010518 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000010519 continue;
10520
Richard Trieu708859a2017-06-08 00:56:21 +000010521 Diag(FirstDecl->getLocation(),
10522 diag::err_module_odr_violation_mismatch_decl_unknown)
10523 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10524 << FirstDecl->getSourceRange();
10525 Diag(SecondDecl->getLocation(),
10526 diag::note_module_odr_violation_mismatch_decl_unknown)
10527 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000010528 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010529 }
10530
10531 if (!Diagnosed) {
10532 // All definitions are updates to the same declaration. This happens if a
10533 // module instantiates the declaration of a class template specialization
10534 // and two or more other modules instantiate its definition.
10535 //
10536 // FIXME: Indicate which modules had instantiations of this definition.
10537 // FIXME: How can this even happen?
10538 Diag(Merge.first->getLocation(),
10539 diag::err_module_odr_violation_different_instantiations)
10540 << Merge.first;
10541 }
10542 }
Richard Trieue6caa262017-12-23 00:41:01 +000010543
10544 // Issue ODR failures diagnostics for functions.
10545 for (auto &Merge : FunctionOdrMergeFailures) {
10546 enum ODRFunctionDifference {
10547 ReturnType,
10548 ParameterName,
10549 ParameterType,
10550 ParameterSingleDefaultArgument,
10551 ParameterDifferentDefaultArgument,
10552 FunctionBody,
10553 };
10554
10555 FunctionDecl *FirstFunction = Merge.first;
10556 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
10557
10558 bool Diagnosed = false;
10559 for (auto &SecondFunction : Merge.second) {
10560
10561 if (FirstFunction == SecondFunction)
10562 continue;
10563
10564 std::string SecondModule =
10565 getOwningModuleNameForDiagnostic(SecondFunction);
10566
10567 auto ODRDiagError = [FirstFunction, &FirstModule,
10568 this](SourceLocation Loc, SourceRange Range,
10569 ODRFunctionDifference DiffType) {
10570 return Diag(Loc, diag::err_module_odr_violation_function)
10571 << FirstFunction << FirstModule.empty() << FirstModule << Range
10572 << DiffType;
10573 };
10574 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
10575 SourceRange Range,
10576 ODRFunctionDifference DiffType) {
10577 return Diag(Loc, diag::note_module_odr_violation_function)
10578 << SecondModule << Range << DiffType;
10579 };
10580
10581 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
10582 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
10583 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
10584 FirstFunction->getReturnTypeSourceRange(), ReturnType)
10585 << FirstFunction->getReturnType();
10586 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
10587 SecondFunction->getReturnTypeSourceRange(), ReturnType)
10588 << SecondFunction->getReturnType();
10589 Diagnosed = true;
10590 break;
10591 }
10592
10593 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
10594 "Merged functions with different number of parameters");
10595
10596 auto ParamSize = FirstFunction->param_size();
10597 bool ParameterMismatch = false;
10598 for (unsigned I = 0; I < ParamSize; ++I) {
10599 auto *FirstParam = FirstFunction->getParamDecl(I);
10600 auto *SecondParam = SecondFunction->getParamDecl(I);
10601
10602 assert(getContext().hasSameType(FirstParam->getType(),
10603 SecondParam->getType()) &&
10604 "Merged function has different parameter types.");
10605
10606 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
10607 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
10608 ParameterName)
10609 << I + 1 << FirstParam->getDeclName();
10610 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
10611 ParameterName)
10612 << I + 1 << SecondParam->getDeclName();
10613 ParameterMismatch = true;
10614 break;
10615 };
10616
10617 QualType FirstParamType = FirstParam->getType();
10618 QualType SecondParamType = SecondParam->getType();
10619 if (FirstParamType != SecondParamType &&
10620 ComputeQualTypeODRHash(FirstParamType) !=
10621 ComputeQualTypeODRHash(SecondParamType)) {
10622 if (const DecayedType *ParamDecayedType =
10623 FirstParamType->getAs<DecayedType>()) {
10624 ODRDiagError(FirstParam->getLocation(),
10625 FirstParam->getSourceRange(), ParameterType)
10626 << (I + 1) << FirstParamType << true
10627 << ParamDecayedType->getOriginalType();
10628 } else {
10629 ODRDiagError(FirstParam->getLocation(),
10630 FirstParam->getSourceRange(), ParameterType)
10631 << (I + 1) << FirstParamType << false;
10632 }
10633
10634 if (const DecayedType *ParamDecayedType =
10635 SecondParamType->getAs<DecayedType>()) {
10636 ODRDiagNote(SecondParam->getLocation(),
10637 SecondParam->getSourceRange(), ParameterType)
10638 << (I + 1) << SecondParamType << true
10639 << ParamDecayedType->getOriginalType();
10640 } else {
10641 ODRDiagNote(SecondParam->getLocation(),
10642 SecondParam->getSourceRange(), ParameterType)
10643 << (I + 1) << SecondParamType << false;
10644 }
10645 ParameterMismatch = true;
10646 break;
10647 }
10648
10649 const Expr *FirstInit = FirstParam->getInit();
10650 const Expr *SecondInit = SecondParam->getInit();
10651 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10652 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
10653 ParameterSingleDefaultArgument)
10654 << (I + 1) << (FirstInit == nullptr)
10655 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10656 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
10657 ParameterSingleDefaultArgument)
10658 << (I + 1) << (SecondInit == nullptr)
10659 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10660 ParameterMismatch = true;
10661 break;
10662 }
10663
10664 if (FirstInit && SecondInit &&
10665 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10666 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
10667 ParameterDifferentDefaultArgument)
10668 << (I + 1) << FirstInit->getSourceRange();
10669 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
10670 ParameterDifferentDefaultArgument)
10671 << (I + 1) << SecondInit->getSourceRange();
10672 ParameterMismatch = true;
10673 break;
10674 }
10675
10676 assert(ComputeSubDeclODRHash(FirstParam) ==
10677 ComputeSubDeclODRHash(SecondParam) &&
10678 "Undiagnosed parameter difference.");
10679 }
10680
10681 if (ParameterMismatch) {
10682 Diagnosed = true;
10683 break;
10684 }
10685
10686 // If no error has been generated before now, assume the problem is in
10687 // the body and generate a message.
10688 ODRDiagError(FirstFunction->getLocation(),
10689 FirstFunction->getSourceRange(), FunctionBody);
10690 ODRDiagNote(SecondFunction->getLocation(),
10691 SecondFunction->getSourceRange(), FunctionBody);
10692 Diagnosed = true;
10693 break;
10694 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000010695 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000010696 assert(Diagnosed && "Unable to emit ODR diagnostic.");
10697 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010698}
10699
Richard Smithce18a182015-07-14 00:26:00 +000010700void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010701 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000010702 ReadTimer->startTimer();
10703}
10704
Guy Benyei11169dd2012-12-18 14:30:41 +000010705void ASTReader::FinishedDeserializing() {
10706 assert(NumCurrentElementsDeserializing &&
10707 "FinishedDeserializing not paired with StartedDeserializing");
10708 if (NumCurrentElementsDeserializing == 1) {
10709 // We decrease NumCurrentElementsDeserializing only after pending actions
10710 // are finished, to avoid recursively re-calling finishPendingActions().
10711 finishPendingActions();
10712 }
10713 --NumCurrentElementsDeserializing;
10714
Richard Smitha0ce9c42014-07-29 23:23:27 +000010715 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010716 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +000010717 while (!PendingExceptionSpecUpdates.empty()) {
10718 auto Updates = std::move(PendingExceptionSpecUpdates);
10719 PendingExceptionSpecUpdates.clear();
10720 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000010721 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000010722 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000010723 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000010724 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000010725 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000010726 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000010727 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000010728 }
Richard Smith9e2341d2015-03-23 03:25:59 +000010729 }
10730
Richard Smithce18a182015-07-14 00:26:00 +000010731 if (ReadTimer)
10732 ReadTimer->stopTimer();
10733
Richard Smith0f4e2c42015-08-06 04:23:48 +000010734 diagnoseOdrViolations();
10735
Richard Smith04d05b52014-03-23 00:27:18 +000010736 // We are not in recursive loading, so it's safe to pass the "interesting"
10737 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010738 if (Consumer)
10739 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000010740 }
10741}
10742
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010743void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010744 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10745 // Remove any fake results before adding any real ones.
10746 auto It = PendingFakeLookupResults.find(II);
10747 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000010748 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000010749 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000010750 // FIXME: this works around module+PCH performance issue.
10751 // Rather than erase the result from the map, which is O(n), just clear
10752 // the vector of NamedDecls.
10753 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000010754 }
10755 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010756
10757 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10758 SemaObj->TUScope->AddDecl(D);
10759 } else if (SemaObj->TUScope) {
10760 // Adding the decl to IdResolver may have failed because it was already in
10761 // (even though it was not added in scope). If it is already in, make sure
10762 // it gets in the scope as well.
10763 if (std::find(SemaObj->IdResolver.begin(Name),
10764 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
10765 SemaObj->TUScope->AddDecl(D);
10766 }
10767}
10768
Richard Smithdbafb6c2017-06-29 23:23:46 +000010769ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000010770 const PCHContainerReader &PCHContainerRdr,
10771 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10772 StringRef isysroot, bool DisableValidation,
10773 bool AllowASTWithCompilerErrors,
10774 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10775 bool UseGlobalIndex,
10776 std::unique_ptr<llvm::Timer> ReadTimer)
10777 : Listener(DisableValidation
10778 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
10779 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000010780 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010781 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Richard Smithdbafb6c2017-06-29 23:23:46 +000010782 ContextObj(Context),
Boris Kolpackovd30446f2017-08-31 06:26:43 +000010783 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
10784 PP.getHeaderSearchInfo()),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000010785 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
10786 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000010787 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000010788 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10789 AllowConfigurationMismatch(AllowConfigurationMismatch),
10790 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010791 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000010792 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000010793
10794 for (const auto &Ext : Extensions) {
10795 auto BlockName = Ext->getExtensionMetadata().BlockName;
10796 auto Known = ModuleFileExtensions.find(BlockName);
10797 if (Known != ModuleFileExtensions.end()) {
10798 Diags.Report(diag::warn_duplicate_module_file_extension)
10799 << BlockName;
10800 continue;
10801 }
10802
10803 ModuleFileExtensions.insert({BlockName, Ext});
10804 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010805}
10806
10807ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000010808 if (OwnsDeserializationListener)
10809 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000010810}
Richard Smith10379092016-05-06 23:14:07 +000010811
10812IdentifierResolver &ASTReader::getIdResolver() {
10813 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10814}
David L. Jonesbe1557a2016-12-21 00:17:49 +000010815
10816unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
10817 unsigned AbbrevID) {
10818 Idx = 0;
10819 Record.clear();
10820 return Cursor.readRecord(AbbrevID, Record);
10821}