blob: 944eeee6b4ca64384464996cfd629c094a19437c [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;
Richard Smith63078492015-09-01 07:41:55 +00001223 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001225 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1227 }
Richard Smith63078492015-09-01 07:41:55 +00001228 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001229
1230 // Parse the line entries
1231 std::vector<LineEntry> Entries;
1232 while (Idx < Record.size()) {
1233 int FID = Record[Idx++];
1234 assert(FID >= 0 && "Serialized line entries for non-local file.");
1235 // Remap FileID from 1-based old view.
1236 FID += F.SLocEntryBaseID - 1;
1237
1238 // Extract the line entries
1239 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001240 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001241 Entries.clear();
1242 Entries.reserve(NumEntries);
1243 for (unsigned I = 0; I != NumEntries; ++I) {
1244 unsigned FileOffset = Record[Idx++];
1245 unsigned LineNo = Record[Idx++];
1246 int FilenameID = FileIDs[Record[Idx++]];
1247 SrcMgr::CharacteristicKind FileKind
1248 = (SrcMgr::CharacteristicKind)Record[Idx++];
1249 unsigned IncludeOffset = Record[Idx++];
1250 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1251 FileKind, IncludeOffset));
1252 }
1253 LineTable.AddEntry(FileID::get(FID), Entries);
1254 }
1255
1256 return false;
1257}
1258
1259/// \brief Read a source manager block
1260bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1261 using namespace SrcMgr;
1262
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001263 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001264
1265 // Set the source-location entry cursor to the current position in
1266 // the stream. This cursor will be used to read the contents of the
1267 // source manager block initially, and then lazily read
1268 // source-location entries as needed.
1269 SLocEntryCursor = F.Stream;
1270
1271 // The stream itself is going to skip over the source manager block.
1272 if (F.Stream.SkipBlock()) {
1273 Error("malformed block record in AST file");
1274 return true;
1275 }
1276
1277 // Enter the source manager block.
1278 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1279 Error("malformed source manager block record in AST file");
1280 return true;
1281 }
1282
1283 RecordData Record;
1284 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001285 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001286
Chris Lattnere7b154b2013-01-19 21:39:22 +00001287 switch (E.Kind) {
1288 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1289 case llvm::BitstreamEntry::Error:
1290 Error("malformed block record in AST file");
1291 return true;
1292 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001293 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001294 case llvm::BitstreamEntry::Record:
1295 // The interesting case.
1296 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001298
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001301 StringRef Blob;
1302 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 default: // Default behavior: ignore.
1304 break;
1305
1306 case SM_SLOC_FILE_ENTRY:
1307 case SM_SLOC_BUFFER_ENTRY:
1308 case SM_SLOC_EXPANSION_ENTRY:
1309 // Once we hit one of the source location entries, we're done.
1310 return false;
1311 }
1312 }
1313}
1314
1315/// \brief If a header file is not found at the path that we expect it to be
1316/// and the PCH file was moved from its original location, try to resolve the
1317/// file by assuming that header+PCH were moved together and the header is in
1318/// the same place relative to the PCH.
1319static std::string
1320resolveFileRelativeToOriginalDir(const std::string &Filename,
1321 const std::string &OriginalDir,
1322 const std::string &CurrDir) {
1323 assert(OriginalDir != CurrDir &&
1324 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001325
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001327
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 SmallString<128> filePath(Filename);
1329 fs::make_absolute(filePath);
1330 assert(path::is_absolute(OriginalDir));
1331 SmallString<128> currPCHPath(CurrDir);
1332
1333 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1334 fileDirE = path::end(path::parent_path(filePath));
1335 path::const_iterator origDirI = path::begin(OriginalDir),
1336 origDirE = path::end(OriginalDir);
1337 // Skip the common path components from filePath and OriginalDir.
1338 while (fileDirI != fileDirE && origDirI != origDirE &&
1339 *fileDirI == *origDirI) {
1340 ++fileDirI;
1341 ++origDirI;
1342 }
1343 for (; origDirI != origDirE; ++origDirI)
1344 path::append(currPCHPath, "..");
1345 path::append(currPCHPath, fileDirI, fileDirE);
1346 path::append(currPCHPath, path::filename(Filename));
1347 return currPCHPath.str();
1348}
1349
1350bool ASTReader::ReadSLocEntry(int ID) {
1351 if (ID == 0)
1352 return false;
1353
1354 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1355 Error("source location entry ID out-of-range for AST file");
1356 return true;
1357 }
1358
Richard Smithaada85c2016-02-06 02:06:43 +00001359 // Local helper to read the (possibly-compressed) buffer data following the
1360 // entry record.
1361 auto ReadBuffer = [this](
1362 BitstreamCursor &SLocEntryCursor,
1363 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1364 RecordData Record;
1365 StringRef Blob;
1366 unsigned Code = SLocEntryCursor.ReadCode();
1367 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1368
1369 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001370 if (!llvm::zlib::isAvailable()) {
1371 Error("zlib is not available");
1372 return nullptr;
1373 }
Richard Smithaada85c2016-02-06 02:06:43 +00001374 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001375 if (llvm::Error E =
1376 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1377 Error("could not decompress embedded file contents: " +
1378 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001379 return nullptr;
1380 }
1381 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1382 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1383 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1384 } else {
1385 Error("AST record has invalid code");
1386 return nullptr;
1387 }
1388 };
1389
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1391 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001392 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 unsigned BaseOffset = F->SLocEntryBaseOffset;
1394
1395 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001396 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1397 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001398 Error("incorrectly-formatted source location entry in AST file");
1399 return true;
1400 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001401
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001403 StringRef Blob;
1404 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 default:
1406 Error("incorrectly-formatted source location entry in AST file");
1407 return true;
1408
1409 case SM_SLOC_FILE_ENTRY: {
1410 // We will detect whether a file changed and return 'Failure' for it, but
1411 // we will also try to fail gracefully by setting up the SLocEntry.
1412 unsigned InputID = Record[4];
1413 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001414 const FileEntry *File = IF.getFile();
1415 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001416
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001417 // Note that we only check if a File was returned. If it was out-of-date
1418 // we have complained but we will continue creating a FileID to recover
1419 // gracefully.
1420 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 return true;
1422
1423 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1424 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1425 // This is the module's main file.
1426 IncludeLoc = getImportLocation(F);
1427 }
1428 SrcMgr::CharacteristicKind
1429 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1430 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1431 ID, BaseOffset + Record[0]);
1432 SrcMgr::FileInfo &FileInfo =
1433 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1434 FileInfo.NumCreatedFIDs = Record[5];
1435 if (Record[3])
1436 FileInfo.setHasLineDirectives();
1437
1438 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1439 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001440 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001441 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1442 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1443 NumFileDecls));
1444 }
Richard Smithaada85c2016-02-06 02:06:43 +00001445
Guy Benyei11169dd2012-12-18 14:30:41 +00001446 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001447 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001449 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1450 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001451 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1452 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001453 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001454 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 }
1456
1457 break;
1458 }
1459
1460 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001461 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001462 unsigned Offset = Record[0];
1463 SrcMgr::CharacteristicKind
1464 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1465 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001466 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 IncludeLoc = getImportLocation(F);
1468 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001469
Richard Smithaada85c2016-02-06 02:06:43 +00001470 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1471 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001472 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001473 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001474 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 break;
1476 }
1477
1478 case SM_SLOC_EXPANSION_ENTRY: {
1479 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1480 SourceMgr.createExpansionLoc(SpellingLoc,
1481 ReadSourceLocation(*F, Record[2]),
1482 ReadSourceLocation(*F, Record[3]),
1483 Record[4],
1484 ID,
1485 BaseOffset + Record[0]);
1486 break;
1487 }
1488 }
1489
1490 return false;
1491}
1492
1493std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1494 if (ID == 0)
1495 return std::make_pair(SourceLocation(), "");
1496
1497 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1498 Error("source location entry ID out-of-range for AST file");
1499 return std::make_pair(SourceLocation(), "");
1500 }
1501
1502 // Find which module file this entry lands in.
1503 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001504 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 return std::make_pair(SourceLocation(), "");
1506
1507 // FIXME: Can we map this down to a particular submodule? That would be
1508 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001509 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001510}
1511
1512/// \brief Find the location where the module F is imported.
1513SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1514 if (F->ImportLoc.isValid())
1515 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001516
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 // Otherwise we have a PCH. It's considered to be "imported" at the first
1518 // location of its includer.
1519 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001520 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001521 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001522 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 return F->ImportedBy[0]->FirstLoc;
1525}
1526
1527/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1528/// specified cursor. Read the abbreviations that are at the top of the block
1529/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001530bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001531 if (Cursor.EnterSubBlock(BlockID))
1532 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001533
1534 while (true) {
1535 uint64_t Offset = Cursor.GetCurrentBitNo();
1536 unsigned Code = Cursor.ReadCode();
1537
1538 // We expect all abbrevs to be at the start of the block.
1539 if (Code != llvm::bitc::DEFINE_ABBREV) {
1540 Cursor.JumpToBit(Offset);
1541 return false;
1542 }
1543 Cursor.ReadAbbrevRecord();
1544 }
1545}
1546
Richard Smithe40f2ba2013-08-07 21:41:30 +00001547Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001548 unsigned &Idx) {
1549 Token Tok;
1550 Tok.startToken();
1551 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1552 Tok.setLength(Record[Idx++]);
1553 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1554 Tok.setIdentifierInfo(II);
1555 Tok.setKind((tok::TokenKind)Record[Idx++]);
1556 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1557 return Tok;
1558}
1559
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001560MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001561 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001562
1563 // Keep track of where we are in the stream, then jump back there
1564 // after reading this macro.
1565 SavedStreamPosition SavedPosition(Stream);
1566
1567 Stream.JumpToBit(Offset);
1568 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001569 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001570 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001571
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001573 // Advance to the next record, but if we get to the end of the block, don't
1574 // pop it (removing all the abbreviations from the cursor) since we want to
1575 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001576 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001577 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001578
Chris Lattnerefa77172013-01-20 00:00:22 +00001579 switch (Entry.Kind) {
1580 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1581 case llvm::BitstreamEntry::Error:
1582 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001583 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001584 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001585 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001586 case llvm::BitstreamEntry::Record:
1587 // The interesting case.
1588 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001589 }
1590
1591 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001592 Record.clear();
1593 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001594 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001596 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001597 case PP_MACRO_DIRECTIVE_HISTORY:
1598 return Macro;
1599
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 case PP_MACRO_OBJECT_LIKE:
1601 case PP_MACRO_FUNCTION_LIKE: {
1602 // If we already have a macro, that means that we've hit the end
1603 // of the definition of the macro we were looking for. We're
1604 // done.
1605 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001606 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001607
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001608 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001610 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001611 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001613 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001614
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1616 // Decode function-like macro info.
1617 bool isC99VarArgs = Record[NextIndex++];
1618 bool isGNUVarArgs = Record[NextIndex++];
1619 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001620 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 unsigned NumArgs = Record[NextIndex++];
1622 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001623 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001624
1625 // Install function-like macro info.
1626 MI->setIsFunctionLike();
1627 if (isC99VarArgs) MI->setIsC99Varargs();
1628 if (isGNUVarArgs) MI->setIsGNUVarargs();
1629 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001630 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 }
1632
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 // Remember that we saw this macro last so that we add the tokens that
1634 // form its body to it.
1635 Macro = MI;
1636
1637 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1638 Record[NextIndex]) {
1639 // We have a macro definition. Register the association
1640 PreprocessedEntityID
1641 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1642 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001643 PreprocessingRecord::PPEntityID PPID =
1644 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1645 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1646 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001647 if (PPDef)
1648 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 }
1650
1651 ++NumMacrosRead;
1652 break;
1653 }
1654
1655 case PP_TOKEN: {
1656 // If we see a TOKEN before a PP_MACRO_*, then the file is
1657 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001658 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001659
John McCallf413f5e2013-05-03 00:10:13 +00001660 unsigned Idx = 0;
1661 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 Macro->AddTokenToBody(Tok);
1663 break;
1664 }
1665 }
1666 }
1667}
1668
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001669PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001670ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1671 unsigned LocalID) const {
1672 if (!M.ModuleOffsetMap.empty())
1673 ReadModuleOffsetMap(M);
1674
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001675 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001677 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001678 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001679
Guy Benyei11169dd2012-12-18 14:30:41 +00001680 return LocalID + I->second;
1681}
1682
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001683unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1684 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001685}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001686
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001687HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001688HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001689 internal_key_type ikey = {FE->getSize(),
1690 M.HasTimestamps ? FE->getModificationTime() : 0,
1691 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001692 return ikey;
1693}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001694
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001695bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001696 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001697 return false;
1698
Mehdi Amini004b9c72016-10-10 22:52:47 +00001699 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001700 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001701
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001703 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001704 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1705 if (!Key.Imported)
1706 return FileMgr.getFile(Key.Filename);
1707
1708 std::string Resolved = Key.Filename;
1709 Reader.ResolveImportedPath(M, Resolved);
1710 return FileMgr.getFile(Resolved);
1711 };
1712
1713 const FileEntry *FEA = GetFile(a);
1714 const FileEntry *FEB = GetFile(b);
1715 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001716}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001717
Guy Benyei11169dd2012-12-18 14:30:41 +00001718std::pair<unsigned, unsigned>
1719HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001720 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001721
Justin Bogner57ba0b22014-03-28 22:03:24 +00001722 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001724 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001725}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001726
1727HeaderFileInfoTrait::internal_key_type
1728HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001729 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001730
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001731 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001732 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1733 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001734 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001735 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001736 return ikey;
1737}
1738
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001739HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001740HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001741 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001742 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001743
1744 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001745 HeaderFileInfo HFI;
1746 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001747 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001748 HFI.isImport |= (Flags >> 5) & 0x01;
1749 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1750 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001751 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001752 // FIXME: Find a better way to handle this. Maybe just store a
1753 // "has been included" flag?
1754 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1755 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001756 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1757 M, endian::readNext<uint32_t, little, unaligned>(d));
1758 if (unsigned FrameworkOffset =
1759 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001760 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001761 // since 0 is used as an indicator for "no framework name".
1762 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1763 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1764 }
Richard Smith386bb072015-08-18 23:42:23 +00001765
1766 assert((End - d) % 4 == 0 &&
1767 "Wrong data length in HeaderFileInfo deserialization");
1768 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001769 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001770 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1771 LocalSMID >>= 2;
1772
1773 // This header is part of a module. Associate it with the module to enable
1774 // implicit module import.
1775 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1776 Module *Mod = Reader.getSubmodule(GlobalSMID);
1777 FileManager &FileMgr = Reader.getFileManager();
1778 ModuleMap &ModMap =
1779 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1780
1781 std::string Filename = key.Filename;
1782 if (key.Imported)
1783 Reader.ResolveImportedPath(M, Filename);
1784 // FIXME: This is not always the right filename-as-written, but we're not
1785 // going to use this information to rebuild the module, so it doesn't make
1786 // a lot of difference.
1787 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001788 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1789 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001790 }
1791
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 // This HeaderFileInfo was externally loaded.
1793 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001794 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 return HFI;
1796}
1797
Richard Smithd7329392015-04-21 21:46:32 +00001798void ASTReader::addPendingMacro(IdentifierInfo *II,
1799 ModuleFile *M,
1800 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001801 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1802 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001803}
1804
1805void ASTReader::ReadDefinedMacros() {
1806 // Note that we are loading defined macros.
1807 Deserializing Macros(this);
1808
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001809 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1810 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001811
1812 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001813 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001814 continue;
1815
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001816 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001817 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001818
1819 RecordData Record;
1820 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001821 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001822
Chris Lattnere7b154b2013-01-19 21:39:22 +00001823 switch (E.Kind) {
1824 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1825 case llvm::BitstreamEntry::Error:
1826 Error("malformed block record in AST file");
1827 return;
1828 case llvm::BitstreamEntry::EndBlock:
1829 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001830
Chris Lattnere7b154b2013-01-19 21:39:22 +00001831 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001832 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001833 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001834 default: // Default behavior: ignore.
1835 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001836
Chris Lattnere7b154b2013-01-19 21:39:22 +00001837 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001838 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001839 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001840 if (II->isOutOfDate())
1841 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001842 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001843 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001844
Chris Lattnere7b154b2013-01-19 21:39:22 +00001845 case PP_TOKEN:
1846 // Ignore tokens.
1847 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 break;
1850 }
1851 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001852 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001853 }
1854}
1855
1856namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001857
Guy Benyei11169dd2012-12-18 14:30:41 +00001858 /// \brief Visitor class used to look up identifirs in an AST file.
1859 class IdentifierLookupVisitor {
1860 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001861 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001863 unsigned &NumIdentifierLookups;
1864 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001865 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001866
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001868 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1869 unsigned &NumIdentifierLookups,
1870 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001871 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1872 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001873 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001874 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001875
1876 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001878 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001880
Guy Benyei11169dd2012-12-18 14:30:41 +00001881 ASTIdentifierLookupTable *IdTable
1882 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1883 if (!IdTable)
1884 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001885
1886 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001887 Found);
1888 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001889 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001890 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 if (Pos == IdTable->end())
1892 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001893
Guy Benyei11169dd2012-12-18 14:30:41 +00001894 // Dereferencing the iterator has the effect of building the
1895 // IdentifierInfo node and populating it with the various
1896 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001897 ++NumIdentifierLookupHits;
1898 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001899 return true;
1900 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001901
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 // \brief Retrieve the identifier info found within the module
1903 // files.
1904 IdentifierInfo *getIdentifierInfo() const { return Found; }
1905 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001906
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001907} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001908
1909void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1910 // Note that we are loading an identifier.
1911 Deserializing AnIdentifier(this);
1912
1913 unsigned PriorGeneration = 0;
1914 if (getContext().getLangOpts().Modules)
1915 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001916
1917 // If there is a global index, look there first to determine which modules
1918 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001919 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001920 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001921 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001922 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1923 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001924 }
1925 }
1926
Douglas Gregor7211ac12013-01-25 23:32:03 +00001927 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001928 NumIdentifierLookups,
1929 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001930 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 markIdentifierUpToDate(&II);
1932}
1933
1934void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1935 if (!II)
1936 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001937
Guy Benyei11169dd2012-12-18 14:30:41 +00001938 II->setOutOfDate(false);
1939
1940 // Update the generation for this identifier.
1941 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001942 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001943}
1944
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001945void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1946 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001947 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001948
1949 BitstreamCursor &Cursor = M.MacroCursor;
1950 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001951 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001952
Richard Smith713369b2015-04-23 20:40:50 +00001953 struct ModuleMacroRecord {
1954 SubmoduleID SubModID;
1955 MacroInfo *MI;
1956 SmallVector<SubmoduleID, 8> Overrides;
1957 };
1958 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001959
Richard Smithd7329392015-04-21 21:46:32 +00001960 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1961 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1962 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001963 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001964 while (true) {
1965 llvm::BitstreamEntry Entry =
1966 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1967 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1968 Error("malformed block record in AST file");
1969 return;
1970 }
1971
1972 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001973 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001974 case PP_MACRO_DIRECTIVE_HISTORY:
1975 break;
1976
1977 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001978 ModuleMacros.push_back(ModuleMacroRecord());
1979 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001980 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1981 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001982 for (int I = 2, N = Record.size(); I != N; ++I)
1983 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001984 continue;
1985 }
1986
1987 default:
1988 Error("malformed block record in AST file");
1989 return;
1990 }
1991
1992 // We found the macro directive history; that's the last record
1993 // for this macro.
1994 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001995 }
1996
Richard Smithd7329392015-04-21 21:46:32 +00001997 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001998 {
1999 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002000 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002001 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002002 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00002003 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002004 Module *Mod = getSubmodule(ModID);
2005 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002006 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002007 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002008 }
2009
2010 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002011 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002012 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002013 }
2014 }
2015
2016 // Don't read the directive history for a module; we don't have anywhere
2017 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002018 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002019 return;
2020
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002021 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002022 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002023 unsigned Idx = 0, N = Record.size();
2024 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002025 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002026 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002027 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2028 switch (K) {
2029 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002030 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002031 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002032 break;
2033 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002034 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002035 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002036 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002037 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002038 bool isPublic = Record[Idx++];
2039 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2040 break;
2041 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002042
2043 if (!Latest)
2044 Latest = MD;
2045 if (Earliest)
2046 Earliest->setPrevious(MD);
2047 Earliest = MD;
2048 }
2049
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002050 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002051 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002052}
2053
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002054ASTReader::InputFileInfo
2055ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002056 // Go find this input file.
2057 BitstreamCursor &Cursor = F.InputFilesCursor;
2058 SavedStreamPosition SavedPosition(Cursor);
2059 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2060
2061 unsigned Code = Cursor.ReadCode();
2062 RecordData Record;
2063 StringRef Blob;
2064
2065 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2066 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2067 "invalid record type for input file");
2068 (void)Result;
2069
2070 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002071 InputFileInfo R;
2072 R.StoredSize = static_cast<off_t>(Record[1]);
2073 R.StoredTime = static_cast<time_t>(Record[2]);
2074 R.Overridden = static_cast<bool>(Record[3]);
2075 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002076 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002077 R.Filename = Blob;
2078 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002079 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002080}
2081
Manman Renc8c94152016-10-21 23:35:03 +00002082static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002083InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002084 // If this ID is bogus, just return an empty input file.
2085 if (ID == 0 || ID > F.InputFilesLoaded.size())
2086 return InputFile();
2087
2088 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002089 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 return F.InputFilesLoaded[ID-1];
2091
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002092 if (F.InputFilesLoaded[ID-1].isNotFound())
2093 return InputFile();
2094
Guy Benyei11169dd2012-12-18 14:30:41 +00002095 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002096 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002097 SavedStreamPosition SavedPosition(Cursor);
2098 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002099
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002100 InputFileInfo FI = readInputFileInfo(F, ID);
2101 off_t StoredSize = FI.StoredSize;
2102 time_t StoredTime = FI.StoredTime;
2103 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002104 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002105 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002106
Richard Smitha8cfffa2015-11-26 02:04:16 +00002107 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002108 // If we didn't find the file, resolve it relative to the
2109 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002110 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2111 F.OriginalDir != F.BaseDirectory) {
2112 std::string Resolved = resolveFileRelativeToOriginalDir(
2113 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002114 if (!Resolved.empty())
2115 File = FileMgr.getFile(Resolved);
2116 }
2117
2118 // For an overridden file, create a virtual file with the stored
2119 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002120 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002121 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002122
Craig Toppera13603a2014-05-22 05:54:18 +00002123 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002124 if (Complain) {
2125 std::string ErrorStr = "could not find file '";
2126 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002127 ErrorStr += "' referenced by AST file '";
2128 ErrorStr += F.FileName;
2129 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002130 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002131 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002132 // Record that we didn't find the file.
2133 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2134 return InputFile();
2135 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002136
Ben Langmuir198c1682014-03-07 07:27:49 +00002137 // Check if there was a request to override the contents of the file
2138 // that was part of the precompiled header. Overridding such a file
2139 // can lead to problems when lexing using the source locations from the
2140 // PCH.
2141 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002142 // FIXME: Reject if the overrides are different.
2143 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002144 if (Complain)
2145 Error(diag::err_fe_pch_file_overridden, Filename);
2146 // After emitting the diagnostic, recover by disabling the override so
2147 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002148 //
2149 // FIXME: This recovery is just as broken as the original state; there may
2150 // be another precompiled module that's using the overridden contents, or
2151 // we might be half way through parsing it. Instead, we should treat the
2152 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002153 SM.disableFileContentsOverride(File);
2154 // The FileEntry is a virtual file entry with the size of the contents
2155 // that would override the original contents. Set it to the original's
2156 // size/time.
2157 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2158 StoredSize, StoredTime);
2159 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002160
Ben Langmuir198c1682014-03-07 07:27:49 +00002161 bool IsOutOfDate = false;
2162
2163 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002164 if (!Overridden && //
2165 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002166 (StoredTime && StoredTime != File->getModificationTime() &&
2167 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002168 )) {
2169 if (Complain) {
2170 // Build a list of the PCH imports that got us here (in reverse).
2171 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002172 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002173 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002174
Ben Langmuir198c1682014-03-07 07:27:49 +00002175 // The top-level PCH is stale.
2176 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002177 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2178 if (DiagnosticKind == 0)
2179 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2180 else if (DiagnosticKind == 1)
2181 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2182 else
2183 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002184
Ben Langmuir198c1682014-03-07 07:27:49 +00002185 // Print the import stack.
2186 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2187 Diag(diag::note_pch_required_by)
2188 << Filename << ImportStack[0]->FileName;
2189 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002190 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002191 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002192 }
2193
Ben Langmuir198c1682014-03-07 07:27:49 +00002194 if (!Diags.isDiagnosticInFlight())
2195 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002196 }
2197
Ben Langmuir198c1682014-03-07 07:27:49 +00002198 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002200 // FIXME: If the file is overridden and we've already opened it,
2201 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002202
Richard Smitha8cfffa2015-11-26 02:04:16 +00002203 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002204
2205 // Note that we've loaded this input file.
2206 F.InputFilesLoaded[ID-1] = IF;
2207 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002208}
2209
Richard Smith7ed1bc92014-12-05 22:42:13 +00002210/// \brief If we are loading a relocatable PCH or module file, and the filename
2211/// is not an absolute path, add the system or module root to the beginning of
2212/// the file name.
2213void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2214 // Resolve relative to the base directory, if we have one.
2215 if (!M.BaseDirectory.empty())
2216 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002217}
2218
Richard Smith7ed1bc92014-12-05 22:42:13 +00002219void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2221 return;
2222
Richard Smith7ed1bc92014-12-05 22:42:13 +00002223 SmallString<128> Buffer;
2224 llvm::sys::path::append(Buffer, Prefix, Filename);
2225 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002226}
2227
Richard Smith0f99d6a2015-08-09 08:48:41 +00002228static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2229 switch (ARR) {
2230 case ASTReader::Failure: return true;
2231 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2232 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2233 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2234 case ASTReader::ConfigurationMismatch:
2235 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2236 case ASTReader::HadErrors: return true;
2237 case ASTReader::Success: return false;
2238 }
2239
2240 llvm_unreachable("unknown ASTReadResult");
2241}
2242
Richard Smith0516b182015-09-08 19:40:14 +00002243ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2244 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2245 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002246 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002247 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2248 return Failure;
2249
2250 // Read all of the records in the options block.
2251 RecordData Record;
2252 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002253 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002254 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002255
Richard Smith0516b182015-09-08 19:40:14 +00002256 switch (Entry.Kind) {
2257 case llvm::BitstreamEntry::Error:
2258 case llvm::BitstreamEntry::SubBlock:
2259 return Failure;
2260
2261 case llvm::BitstreamEntry::EndBlock:
2262 return Result;
2263
2264 case llvm::BitstreamEntry::Record:
2265 // The interesting case.
2266 break;
2267 }
2268
2269 // Read and process a record.
2270 Record.clear();
2271 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2272 case LANGUAGE_OPTIONS: {
2273 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2274 if (ParseLanguageOptions(Record, Complain, Listener,
2275 AllowCompatibleConfigurationMismatch))
2276 Result = ConfigurationMismatch;
2277 break;
2278 }
2279
2280 case TARGET_OPTIONS: {
2281 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2282 if (ParseTargetOptions(Record, Complain, Listener,
2283 AllowCompatibleConfigurationMismatch))
2284 Result = ConfigurationMismatch;
2285 break;
2286 }
2287
Richard Smith0516b182015-09-08 19:40:14 +00002288 case FILE_SYSTEM_OPTIONS: {
2289 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2290 if (!AllowCompatibleConfigurationMismatch &&
2291 ParseFileSystemOptions(Record, Complain, Listener))
2292 Result = ConfigurationMismatch;
2293 break;
2294 }
2295
2296 case HEADER_SEARCH_OPTIONS: {
2297 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2298 if (!AllowCompatibleConfigurationMismatch &&
2299 ParseHeaderSearchOptions(Record, Complain, Listener))
2300 Result = ConfigurationMismatch;
2301 break;
2302 }
2303
2304 case PREPROCESSOR_OPTIONS:
2305 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2306 if (!AllowCompatibleConfigurationMismatch &&
2307 ParsePreprocessorOptions(Record, Complain, Listener,
2308 SuggestedPredefines))
2309 Result = ConfigurationMismatch;
2310 break;
2311 }
2312 }
2313}
2314
Guy Benyei11169dd2012-12-18 14:30:41 +00002315ASTReader::ASTReadResult
2316ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002317 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002318 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002319 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002320 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002321 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002322
2323 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2324 Error("malformed block record in AST file");
2325 return Failure;
2326 }
2327
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002328 // Lambda to read the unhashed control block the first time it's called.
2329 //
2330 // For PCM files, the unhashed control block cannot be read until after the
2331 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2332 // need to look ahead before reading the IMPORTS record. For consistency,
2333 // this block is always read somehow (see BitstreamEntry::EndBlock).
2334 bool HasReadUnhashedControlBlock = false;
2335 auto readUnhashedControlBlockOnce = [&]() {
2336 if (!HasReadUnhashedControlBlock) {
2337 HasReadUnhashedControlBlock = true;
2338 if (ASTReadResult Result =
2339 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2340 return Result;
2341 }
2342 return Success;
2343 };
2344
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 // Read all of the records and blocks in the control block.
2346 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002347 unsigned NumInputs = 0;
2348 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002349 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002350 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002351
Chris Lattnere7b154b2013-01-19 21:39:22 +00002352 switch (Entry.Kind) {
2353 case llvm::BitstreamEntry::Error:
2354 Error("malformed block record in AST file");
2355 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002356 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002357 // Validate the module before returning. This call catches an AST with
2358 // no module name and no imports.
2359 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2360 return Result;
2361
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002362 // Validate input files.
2363 const HeaderSearchOptions &HSOpts =
2364 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002365
Richard Smitha1825302014-10-23 22:18:29 +00002366 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002367 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2368 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002369 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2370 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002372
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002373 // If we are reading a module, we will create a verification timestamp,
2374 // so we verify all input files. Otherwise, verify only user input
2375 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002376
2377 unsigned N = NumUserInputs;
2378 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002379 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002380 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002381 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002382 N = NumInputs;
2383
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002384 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002385 InputFile IF = getInputFile(F, I+1, Complain);
2386 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002388 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002390
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002391 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002392 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002393
Ben Langmuircb69b572014-03-07 06:40:32 +00002394 if (Listener && Listener->needsInputFileVisitation()) {
2395 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2396 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002397 for (unsigned I = 0; I < N; ++I) {
2398 bool IsSystem = I >= NumUserInputs;
2399 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002400 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002401 F.Kind == MK_ExplicitModule ||
2402 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002403 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002404 }
2405
Richard Smith8a308ec2015-11-05 00:54:55 +00002406 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002407 }
2408
Chris Lattnere7b154b2013-01-19 21:39:22 +00002409 case llvm::BitstreamEntry::SubBlock:
2410 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 case INPUT_FILES_BLOCK_ID:
2412 F.InputFilesCursor = Stream;
2413 if (Stream.SkipBlock() || // Skip with the main cursor
2414 // Read the abbreviations
2415 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2416 Error("malformed block record in AST file");
2417 return Failure;
2418 }
2419 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002420
2421 case OPTIONS_BLOCK_ID:
2422 // If we're reading the first module for this group, check its options
2423 // are compatible with ours. For modules it imports, no further checking
2424 // is required, because we checked them when we built it.
2425 if (Listener && !ImportedBy) {
2426 // Should we allow the configuration of the module file to differ from
2427 // the configuration of the current translation unit in a compatible
2428 // way?
2429 //
2430 // FIXME: Allow this for files explicitly specified with -include-pch.
2431 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002432 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002433
Richard Smith8a308ec2015-11-05 00:54:55 +00002434 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2435 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002436 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002437 if (Result == Failure) {
2438 Error("malformed block record in AST file");
2439 return Result;
2440 }
2441
Richard Smith8a308ec2015-11-05 00:54:55 +00002442 if (DisableValidation ||
2443 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2444 Result = Success;
2445
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002446 // If we can't load the module, exit early since we likely
2447 // will rebuild the module anyway. The stream may be in the
2448 // middle of a block.
2449 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002450 return Result;
2451 } else if (Stream.SkipBlock()) {
2452 Error("malformed block record in AST file");
2453 return Failure;
2454 }
2455 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002456
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002458 if (Stream.SkipBlock()) {
2459 Error("malformed block record in AST file");
2460 return Failure;
2461 }
2462 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002464
Chris Lattnere7b154b2013-01-19 21:39:22 +00002465 case llvm::BitstreamEntry::Record:
2466 // The interesting case.
2467 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 }
2469
2470 // Read and process a record.
2471 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002472 StringRef Blob;
2473 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002474 case METADATA: {
2475 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2476 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002477 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2478 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 return VersionMismatch;
2480 }
2481
Richard Smithe75ee0f2015-08-17 07:13:32 +00002482 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2484 Diag(diag::err_pch_with_compiler_errors);
2485 return HadErrors;
2486 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002487 if (hasErrors) {
2488 Diags.ErrorOccurred = true;
2489 Diags.UncompilableErrorOccurred = true;
2490 Diags.UnrecoverableErrorOccurred = true;
2491 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002492
2493 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002494 // Relative paths in a relocatable PCH are relative to our sysroot.
2495 if (F.RelocatablePCH)
2496 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002497
Richard Smithe75ee0f2015-08-17 07:13:32 +00002498 F.HasTimestamps = Record[5];
2499
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002501 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2503 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002504 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 return VersionMismatch;
2506 }
2507 break;
2508 }
2509
2510 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002511 // Validate the AST before processing any imports (otherwise, untangling
2512 // them can be error-prone and expensive). A module will have a name and
2513 // will already have been validated, but this catches the PCH case.
2514 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2515 return Result;
2516
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002517 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 unsigned Idx = 0, N = Record.size();
2519 while (Idx < N) {
2520 // Read information about the AST file.
2521 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2522 // The import location will be the local one for now; we will adjust
2523 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002524 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002526 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002527 off_t StoredSize = (off_t)Record[Idx++];
2528 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002529 ASTFileSignature StoredSignature = {
2530 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2531 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2532 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002533
2534 std::string ImportedName = ReadString(Record, Idx);
2535 std::string ImportedFile;
2536
2537 // For prebuilt and explicit modules first consult the file map for
2538 // an override. Note that here we don't search prebuilt module
2539 // directories, only the explicit name to file mappings. Also, we will
2540 // still verify the size/signature making sure it is essentially the
2541 // same file but perhaps in a different location.
2542 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2543 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2544 ImportedName, /*FileMapOnly*/ true);
2545
2546 if (ImportedFile.empty())
2547 ImportedFile = ReadPath(F, Record, Idx);
2548 else
2549 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002550
Richard Smith0f99d6a2015-08-09 08:48:41 +00002551 // If our client can't cope with us being out of date, we can't cope with
2552 // our dependency being missing.
2553 unsigned Capabilities = ClientLoadCapabilities;
2554 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2555 Capabilities &= ~ARR_Missing;
2556
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002558 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2559 Loaded, StoredSize, StoredModTime,
2560 StoredSignature, Capabilities);
2561
2562 // If we diagnosed a problem, produce a backtrace.
2563 if (isDiagnosedResult(Result, Capabilities))
2564 Diag(diag::note_module_file_imported_by)
2565 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2566
2567 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 case Failure: return Failure;
2569 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002570 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 case OutOfDate: return OutOfDate;
2572 case VersionMismatch: return VersionMismatch;
2573 case ConfigurationMismatch: return ConfigurationMismatch;
2574 case HadErrors: return HadErrors;
2575 case Success: break;
2576 }
2577 }
2578 break;
2579 }
2580
Guy Benyei11169dd2012-12-18 14:30:41 +00002581 case ORIGINAL_FILE:
2582 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002583 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002585 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002586 break;
2587
2588 case ORIGINAL_FILE_ID:
2589 F.OriginalSourceFileID = FileID::get(Record[0]);
2590 break;
2591
2592 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002593 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002594 break;
2595
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002596 case MODULE_NAME:
2597 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002598 if (Listener)
2599 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002600
2601 // Validate the AST as soon as we have a name so we can exit early on
2602 // failure.
2603 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2604 return Result;
2605
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002606 break;
2607
Richard Smith223d3f22014-12-06 03:21:08 +00002608 case MODULE_DIRECTORY: {
2609 assert(!F.ModuleName.empty() &&
2610 "MODULE_DIRECTORY found before MODULE_NAME");
2611 // If we've already loaded a module map file covering this module, we may
2612 // have a better path for it (relative to the current build).
2613 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2614 if (M && M->Directory) {
2615 // If we're implicitly loading a module, the base directory can't
2616 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002617 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002618 const DirectoryEntry *BuildDir =
2619 PP.getFileManager().getDirectory(Blob);
2620 if (!BuildDir || BuildDir != M->Directory) {
2621 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2622 Diag(diag::err_imported_module_relocated)
2623 << F.ModuleName << Blob << M->Directory->getName();
2624 return OutOfDate;
2625 }
2626 }
2627 F.BaseDirectory = M->Directory->getName();
2628 } else {
2629 F.BaseDirectory = Blob;
2630 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002631 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002632 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002633
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002634 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002635 if (ASTReadResult Result =
2636 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2637 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002638 break;
2639
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002640 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002641 NumInputs = Record[0];
2642 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002643 F.InputFileOffsets =
2644 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002645 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002646 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 break;
2648 }
2649 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002650}
2651
Ben Langmuir2c9af442014-04-10 17:57:43 +00002652ASTReader::ASTReadResult
2653ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002654 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002655
2656 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2657 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002658 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 }
2660
2661 // Read all of the records and blocks for the AST file.
2662 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002663 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002664 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002665
Chris Lattnere7b154b2013-01-19 21:39:22 +00002666 switch (Entry.Kind) {
2667 case llvm::BitstreamEntry::Error:
2668 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002669 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002670 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002671 // Outside of C++, we do not store a lookup map for the translation unit.
2672 // Instead, mark it as needing a lookup map to be built if this module
2673 // contains any declarations lexically within it (which it always does!).
2674 // This usually has no cost, since we very rarely need the lookup map for
2675 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002676 if (ASTContext *Ctx = ContextObj) {
2677 DeclContext *DC = Ctx->getTranslationUnitDecl();
2678 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2679 DC->setMustBuildLookupTable();
2680 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002681
Ben Langmuir2c9af442014-04-10 17:57:43 +00002682 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002683 case llvm::BitstreamEntry::SubBlock:
2684 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 case DECLTYPES_BLOCK_ID:
2686 // We lazily load the decls block, but we want to set up the
2687 // DeclsCursor cursor to point into it. Clone our current bitcode
2688 // cursor to it, enter the block and read the abbrevs in that block.
2689 // With the main cursor, we just skip over it.
2690 F.DeclsCursor = Stream;
2691 if (Stream.SkipBlock() || // Skip with the main cursor.
2692 // Read the abbrevs.
2693 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2694 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002695 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 }
2697 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002698
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 case PREPROCESSOR_BLOCK_ID:
2700 F.MacroCursor = Stream;
2701 if (!PP.getExternalSource())
2702 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002703
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 if (Stream.SkipBlock() ||
2705 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2706 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002707 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 }
2709 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2710 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002711
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 case PREPROCESSOR_DETAIL_BLOCK_ID:
2713 F.PreprocessorDetailCursor = Stream;
2714 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002715 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002717 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002718 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002719 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002721 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002722
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 if (!PP.getPreprocessingRecord())
2724 PP.createPreprocessingRecord();
2725 if (!PP.getPreprocessingRecord()->getExternalSource())
2726 PP.getPreprocessingRecord()->SetExternalSource(*this);
2727 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002728
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 case SOURCE_MANAGER_BLOCK_ID:
2730 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002731 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002733
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002735 if (ASTReadResult Result =
2736 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002737 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002739
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002741 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 if (Stream.SkipBlock() ||
2743 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2744 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002745 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 }
2747 CommentsCursors.push_back(std::make_pair(C, &F));
2748 break;
2749 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002750
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002752 if (Stream.SkipBlock()) {
2753 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002754 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002755 }
2756 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 }
2758 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002759
Chris Lattnere7b154b2013-01-19 21:39:22 +00002760 case llvm::BitstreamEntry::Record:
2761 // The interesting case.
2762 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 }
2764
2765 // Read and process a record.
2766 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002767 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002768 auto RecordType =
2769 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2770
2771 // If we're not loading an AST context, we don't care about most records.
2772 if (!ContextObj) {
2773 switch (RecordType) {
2774 case IDENTIFIER_TABLE:
2775 case IDENTIFIER_OFFSET:
2776 case INTERESTING_IDENTIFIERS:
2777 case STATISTICS:
2778 case PP_CONDITIONAL_STACK:
2779 case PP_COUNTER_VALUE:
2780 case SOURCE_LOCATION_OFFSETS:
2781 case MODULE_OFFSET_MAP:
2782 case SOURCE_MANAGER_LINE_TABLE:
2783 case SOURCE_LOCATION_PRELOADS:
2784 case PPD_ENTITIES_OFFSETS:
2785 case HEADER_SEARCH_TABLE:
2786 case IMPORTED_MODULES:
2787 case MACRO_OFFSET:
2788 break;
2789 default:
2790 continue;
2791 }
2792 }
2793
2794 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002795 default: // Default behavior: ignore.
2796 break;
2797
2798 case TYPE_OFFSET: {
2799 if (F.LocalNumTypes != 0) {
2800 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002801 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002802 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002803 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 F.LocalNumTypes = Record[0];
2805 unsigned LocalBaseTypeIndex = Record[1];
2806 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002807
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 if (F.LocalNumTypes > 0) {
2809 // Introduce the global -> local mapping for types within this module.
2810 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002811
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 // Introduce the local -> global mapping for types within this module.
2813 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002814 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002815 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002816
2817 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 }
2819 break;
2820 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002821
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 case DECL_OFFSET: {
2823 if (F.LocalNumDecls != 0) {
2824 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002825 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002826 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002827 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 F.LocalNumDecls = Record[0];
2829 unsigned LocalBaseDeclID = Record[1];
2830 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002831
Guy Benyei11169dd2012-12-18 14:30:41 +00002832 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002833 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 // module.
2835 GlobalDeclMap.insert(
2836 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002837
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 // Introduce the local -> global mapping for declarations within this
2839 // module.
2840 F.DeclRemap.insertOrReplace(
2841 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002842
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 // Introduce the global -> local mapping for declarations within this
2844 // module.
2845 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002846
Ben Langmuir52ca6782014-10-20 16:27:32 +00002847 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2848 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 break;
2850 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002851
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002853 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002854 LexicalContents Contents(
2855 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2856 Blob.data()),
2857 static_cast<unsigned int>(Blob.size() / 4));
2858 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 TU->setHasExternalLexicalStorage(true);
2860 break;
2861 }
2862
2863 case UPDATE_VISIBLE: {
2864 unsigned Idx = 0;
2865 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002866 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002867 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002868 // If we've already loaded the decl, perform the updates when we finish
2869 // loading this block.
2870 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002871 PendingUpdateRecords.push_back(
2872 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 break;
2874 }
2875
2876 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002877 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002879 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2880 (const unsigned char *)F.IdentifierTableData + Record[0],
2881 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2882 (const unsigned char *)F.IdentifierTableData,
2883 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002884
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2886 }
2887 break;
2888
2889 case IDENTIFIER_OFFSET: {
2890 if (F.LocalNumIdentifiers != 0) {
2891 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002892 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002893 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002894 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 F.LocalNumIdentifiers = Record[0];
2896 unsigned LocalBaseIdentifierID = Record[1];
2897 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002898
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 if (F.LocalNumIdentifiers > 0) {
2900 // Introduce the global -> local mapping for identifiers within this
2901 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002902 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002904
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 // Introduce the local -> global mapping for identifiers within this
2906 // module.
2907 F.IdentifierRemap.insertOrReplace(
2908 std::make_pair(LocalBaseIdentifierID,
2909 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002910
Ben Langmuir52ca6782014-10-20 16:27:32 +00002911 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2912 + F.LocalNumIdentifiers);
2913 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 break;
2915 }
2916
Richard Smith33e0f7e2015-07-22 02:08:40 +00002917 case INTERESTING_IDENTIFIERS:
2918 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2919 break;
2920
Ben Langmuir332aafe2014-01-31 01:06:56 +00002921 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002922 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2923 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002925 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 break;
2927
David Blaikie9ffe5a32017-01-30 05:00:26 +00002928 case MODULAR_CODEGEN_DECLS:
2929 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2930 // them (ie: if we're not codegenerating this module).
2931 if (F.Kind == MK_MainFile)
2932 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2933 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2934 break;
2935
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002937 if (SpecialTypes.empty()) {
2938 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2939 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2940 break;
2941 }
2942
2943 if (SpecialTypes.size() != Record.size()) {
2944 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002945 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002946 }
2947
2948 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2949 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2950 if (!SpecialTypes[I])
2951 SpecialTypes[I] = ID;
2952 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2953 // merge step?
2954 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 break;
2956
2957 case STATISTICS:
2958 TotalNumStatements += Record[0];
2959 TotalNumMacros += Record[1];
2960 TotalLexicalDeclContexts += Record[2];
2961 TotalVisibleDeclContexts += Record[3];
2962 break;
2963
2964 case UNUSED_FILESCOPED_DECLS:
2965 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2966 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2967 break;
2968
2969 case DELEGATING_CTORS:
2970 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2971 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2972 break;
2973
2974 case WEAK_UNDECLARED_IDENTIFIERS:
2975 if (Record.size() % 4 != 0) {
2976 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002977 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002979
2980 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 // files. This isn't the way to do it :)
2982 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002983
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 // Translate the weak, undeclared identifiers into global IDs.
2985 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2986 WeakUndeclaredIdentifiers.push_back(
2987 getGlobalIdentifierID(F, Record[I++]));
2988 WeakUndeclaredIdentifiers.push_back(
2989 getGlobalIdentifierID(F, Record[I++]));
2990 WeakUndeclaredIdentifiers.push_back(
2991 ReadSourceLocation(F, Record, I).getRawEncoding());
2992 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2993 }
2994 break;
2995
Guy Benyei11169dd2012-12-18 14:30:41 +00002996 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002997 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 F.LocalNumSelectors = Record[0];
2999 unsigned LocalBaseSelectorID = Record[1];
3000 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003001
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003003 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 // module.
3005 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003006
3007 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003008 // module.
3009 F.SelectorRemap.insertOrReplace(
3010 std::make_pair(LocalBaseSelectorID,
3011 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003012
3013 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003014 }
3015 break;
3016 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003017
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003019 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003020 if (Record[0])
3021 F.SelectorLookupTable
3022 = ASTSelectorLookupTable::Create(
3023 F.SelectorLookupTableData + Record[0],
3024 F.SelectorLookupTableData,
3025 ASTSelectorLookupTrait(*this, F));
3026 TotalNumMethodPoolEntries += Record[1];
3027 break;
3028
3029 case REFERENCED_SELECTOR_POOL:
3030 if (!Record.empty()) {
3031 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003032 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 Record[Idx++]));
3034 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3035 getRawEncoding());
3036 }
3037 }
3038 break;
3039
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003040 case PP_CONDITIONAL_STACK:
3041 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003042 unsigned Idx = 0, End = Record.size() - 1;
3043 bool ReachedEOFWhileSkipping = Record[Idx++];
3044 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3045 if (ReachedEOFWhileSkipping) {
3046 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3047 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3048 bool FoundNonSkipPortion = Record[Idx++];
3049 bool FoundElse = Record[Idx++];
3050 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3051 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3052 FoundElse, ElseLoc);
3053 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003054 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003055 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003056 auto Loc = ReadSourceLocation(F, Record, Idx);
3057 bool WasSkipping = Record[Idx++];
3058 bool FoundNonSkip = Record[Idx++];
3059 bool FoundElse = Record[Idx++];
3060 ConditionalStack.push_back(
3061 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3062 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003063 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003064 }
3065 break;
3066
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 case PP_COUNTER_VALUE:
3068 if (!Record.empty() && Listener)
3069 Listener->ReadCounter(F, Record[0]);
3070 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003071
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003073 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 F.NumFileSortedDecls = Record[0];
3075 break;
3076
3077 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003078 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 F.LocalNumSLocEntries = Record[0];
3080 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003081 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003082 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003083 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003084 if (!F.SLocEntryBaseID) {
3085 Error("ran out of source locations");
3086 break;
3087 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 // Make our entry in the range map. BaseID is negative and growing, so
3089 // we invert it. Because we invert it, though, we need the other end of
3090 // the range.
3091 unsigned RangeStart =
3092 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3093 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3094 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3095
3096 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3097 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3098 GlobalSLocOffsetMap.insert(
3099 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3100 - SLocSpaceSize,&F));
3101
3102 // Initialize the remapping table.
3103 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003104 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003106 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003108
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 TotalNumSLocEntries += F.LocalNumSLocEntries;
3110 break;
3111 }
3112
Richard Smith37a93df2017-02-18 00:32:02 +00003113 case MODULE_OFFSET_MAP:
3114 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003115 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003116
3117 case SOURCE_MANAGER_LINE_TABLE:
3118 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003119 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 break;
3121
3122 case SOURCE_LOCATION_PRELOADS: {
3123 // Need to transform from the local view (1-based IDs) to the global view,
3124 // which is based off F.SLocEntryBaseID.
3125 if (!F.PreloadSLocEntries.empty()) {
3126 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003127 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003129
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 F.PreloadSLocEntries.swap(Record);
3131 break;
3132 }
3133
3134 case EXT_VECTOR_DECLS:
3135 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3136 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3137 break;
3138
3139 case VTABLE_USES:
3140 if (Record.size() % 3 != 0) {
3141 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003142 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003144
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 // Later tables overwrite earlier ones.
3146 // FIXME: Modules will have some trouble with this. This is clearly not
3147 // the right way to do this.
3148 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003149
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3151 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3152 VTableUses.push_back(
3153 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3154 VTableUses.push_back(Record[Idx++]);
3155 }
3156 break;
3157
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 case PENDING_IMPLICIT_INSTANTIATIONS:
3159 if (PendingInstantiations.size() % 2 != 0) {
3160 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003161 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 }
3163
3164 if (Record.size() % 2 != 0) {
3165 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003166 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 }
3168
3169 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3170 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3171 PendingInstantiations.push_back(
3172 ReadSourceLocation(F, Record, I).getRawEncoding());
3173 }
3174 break;
3175
3176 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003177 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003178 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003179 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003180 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3182 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3183 break;
3184
3185 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003186 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3187 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3188 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003189
3190 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003191
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 unsigned StartingID;
3193 if (!PP.getPreprocessingRecord())
3194 PP.createPreprocessingRecord();
3195 if (!PP.getPreprocessingRecord()->getExternalSource())
3196 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003197 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003199 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003200 F.BasePreprocessedEntityID = StartingID;
3201
3202 if (F.NumPreprocessedEntities > 0) {
3203 // Introduce the global -> local mapping for preprocessed entities in
3204 // this module.
3205 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003206
Guy Benyei11169dd2012-12-18 14:30:41 +00003207 // Introduce the local -> global mapping for preprocessed entities in
3208 // this module.
3209 F.PreprocessedEntityRemap.insertOrReplace(
3210 std::make_pair(LocalBasePreprocessedEntityID,
3211 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3212 }
3213
3214 break;
3215 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003216
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003217 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 if (Record.size() % 2 != 0) {
3219 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003220 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003222 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3223 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3224 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3225
3226 // If we've already loaded the decl, perform the updates when we finish
3227 // loading this block.
3228 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003229 PendingUpdateRecords.push_back(
3230 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003231 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003232 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003233
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003234 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003235 if (F.LocalNumObjCCategoriesInMap != 0) {
3236 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003237 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003238 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003239
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003241 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003243
Guy Benyei11169dd2012-12-18 14:30:41 +00003244 case OBJC_CATEGORIES:
3245 F.ObjCCategories.swap(Record);
3246 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003247
Guy Benyei11169dd2012-12-18 14:30:41 +00003248 case CUDA_SPECIAL_DECL_REFS:
3249 // Later tables overwrite earlier ones.
3250 // FIXME: Modules will have trouble with this.
3251 CUDASpecialDeclRefs.clear();
3252 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3253 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3254 break;
3255
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003256 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003257 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 if (Record[0]) {
3260 F.HeaderFileInfoTable
3261 = HeaderFileInfoLookupTable::Create(
3262 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3263 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003264 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003266 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003267
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 PP.getHeaderSearchInfo().SetExternalSource(this);
3269 if (!PP.getHeaderSearchInfo().getExternalLookup())
3270 PP.getHeaderSearchInfo().SetExternalLookup(this);
3271 }
3272 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003273
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 case FP_PRAGMA_OPTIONS:
3275 // Later tables overwrite earlier ones.
3276 FPPragmaOptions.swap(Record);
3277 break;
3278
3279 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003280 for (unsigned I = 0, E = Record.size(); I != E; ) {
3281 auto Name = ReadString(Record, I);
3282 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003283 Opt.Supported = Record[I++] != 0;
3284 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003285 Opt.Avail = Record[I++];
3286 Opt.Core = Record[I++];
3287 }
3288 break;
3289
3290 case OPENCL_EXTENSION_TYPES:
3291 for (unsigned I = 0, E = Record.size(); I != E;) {
3292 auto TypeID = static_cast<::TypeID>(Record[I++]);
3293 auto *Type = GetType(TypeID).getTypePtr();
3294 auto NumExt = static_cast<unsigned>(Record[I++]);
3295 for (unsigned II = 0; II != NumExt; ++II) {
3296 auto Ext = ReadString(Record, I);
3297 OpenCLTypeExtMap[Type].insert(Ext);
3298 }
3299 }
3300 break;
3301
3302 case OPENCL_EXTENSION_DECLS:
3303 for (unsigned I = 0, E = Record.size(); I != E;) {
3304 auto DeclID = static_cast<::DeclID>(Record[I++]);
3305 auto *Decl = GetDecl(DeclID);
3306 auto NumExt = static_cast<unsigned>(Record[I++]);
3307 for (unsigned II = 0; II != NumExt; ++II) {
3308 auto Ext = ReadString(Record, I);
3309 OpenCLDeclExtMap[Decl].insert(Ext);
3310 }
3311 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 break;
3313
3314 case TENTATIVE_DEFINITIONS:
3315 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3316 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3317 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003318
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 case KNOWN_NAMESPACES:
3320 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3321 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3322 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003323
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003324 case UNDEFINED_BUT_USED:
3325 if (UndefinedButUsed.size() % 2 != 0) {
3326 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003327 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003328 }
3329
3330 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003331 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003332 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003333 }
3334 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003335 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3336 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003337 ReadSourceLocation(F, Record, I).getRawEncoding());
3338 }
3339 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003340
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003341 case DELETE_EXPRS_TO_ANALYZE:
3342 for (unsigned I = 0, N = Record.size(); I != N;) {
3343 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3344 const uint64_t Count = Record[I++];
3345 DelayedDeleteExprs.push_back(Count);
3346 for (uint64_t C = 0; C < Count; ++C) {
3347 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3348 bool IsArrayForm = Record[I++] == 1;
3349 DelayedDeleteExprs.push_back(IsArrayForm);
3350 }
3351 }
3352 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003353
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003354 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003355 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003356 // If we aren't loading a module (which has its own exports), make
3357 // all of the imported modules visible.
3358 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003359 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3360 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3361 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003362 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003363 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003364 if (DeserializationListener)
3365 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3366 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003367 }
3368 }
3369 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003370
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 case MACRO_OFFSET: {
3372 if (F.LocalNumMacros != 0) {
3373 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003374 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003376 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 F.LocalNumMacros = Record[0];
3378 unsigned LocalBaseMacroID = Record[1];
3379 F.BaseMacroID = getTotalNumMacros();
3380
3381 if (F.LocalNumMacros > 0) {
3382 // Introduce the global -> local mapping for macros within this module.
3383 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3384
3385 // Introduce the local -> global mapping for macros within this module.
3386 F.MacroRemap.insertOrReplace(
3387 std::make_pair(LocalBaseMacroID,
3388 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003389
3390 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003391 }
3392 break;
3393 }
3394
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003395 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003396 LateParsedTemplates.append(Record.begin(), Record.end());
3397 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003398
3399 case OPTIMIZE_PRAGMA_OPTIONS:
3400 if (Record.size() != 1) {
3401 Error("invalid pragma optimize record");
3402 return Failure;
3403 }
3404 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3405 break;
Nico Weber72889432014-09-06 01:25:55 +00003406
Nico Weber779355f2016-03-02 23:22:00 +00003407 case MSSTRUCT_PRAGMA_OPTIONS:
3408 if (Record.size() != 1) {
3409 Error("invalid pragma ms_struct record");
3410 return Failure;
3411 }
3412 PragmaMSStructState = Record[0];
3413 break;
3414
Nico Weber42932312016-03-03 00:17:35 +00003415 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3416 if (Record.size() != 2) {
3417 Error("invalid pragma ms_struct record");
3418 return Failure;
3419 }
3420 PragmaMSPointersToMembersState = Record[0];
3421 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3422 break;
3423
Nico Weber72889432014-09-06 01:25:55 +00003424 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3425 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3426 UnusedLocalTypedefNameCandidates.push_back(
3427 getGlobalDeclID(F, Record[I]));
3428 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003429
3430 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3431 if (Record.size() != 1) {
3432 Error("invalid cuda pragma options record");
3433 return Failure;
3434 }
3435 ForceCUDAHostDeviceDepth = Record[0];
3436 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003437
3438 case PACK_PRAGMA_OPTIONS: {
3439 if (Record.size() < 3) {
3440 Error("invalid pragma pack record");
3441 return Failure;
3442 }
3443 PragmaPackCurrentValue = Record[0];
3444 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3445 unsigned NumStackEntries = Record[2];
3446 unsigned Idx = 3;
3447 // Reset the stack when importing a new module.
3448 PragmaPackStack.clear();
3449 for (unsigned I = 0; I < NumStackEntries; ++I) {
3450 PragmaPackStackEntry Entry;
3451 Entry.Value = Record[Idx++];
3452 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003453 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003454 PragmaPackStrings.push_back(ReadString(Record, Idx));
3455 Entry.SlotLabel = PragmaPackStrings.back();
3456 PragmaPackStack.push_back(Entry);
3457 }
3458 break;
3459 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 }
3461 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003462}
3463
Richard Smith37a93df2017-02-18 00:32:02 +00003464void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3465 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3466
3467 // Additional remapping information.
3468 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3469 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3470 F.ModuleOffsetMap = StringRef();
3471
3472 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3473 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3474 F.SLocRemap.insert(std::make_pair(0U, 0));
3475 F.SLocRemap.insert(std::make_pair(2U, 1));
3476 }
3477
3478 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003479 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003480 RemapBuilder SLocRemap(F.SLocRemap);
3481 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3482 RemapBuilder MacroRemap(F.MacroRemap);
3483 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3484 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3485 RemapBuilder SelectorRemap(F.SelectorRemap);
3486 RemapBuilder DeclRemap(F.DeclRemap);
3487 RemapBuilder TypeRemap(F.TypeRemap);
3488
3489 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003490 // FIXME: Looking up dependency modules by filename is horrible. Let's
3491 // start fixing this with prebuilt and explicit modules and see how it
3492 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003493 using namespace llvm::support;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003494 ModuleKind Kind = static_cast<ModuleKind>(
3495 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003496 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3497 StringRef Name = StringRef((const char*)Data, Len);
3498 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003499 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3500 ? ModuleMgr.lookupByModuleName(Name)
3501 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003502 if (!OM) {
3503 std::string Msg =
3504 "SourceLocation remap refers to unknown module, cannot find ";
3505 Msg.append(Name);
3506 Error(Msg);
3507 return;
3508 }
3509
3510 uint32_t SLocOffset =
3511 endian::readNext<uint32_t, little, unaligned>(Data);
3512 uint32_t IdentifierIDOffset =
3513 endian::readNext<uint32_t, little, unaligned>(Data);
3514 uint32_t MacroIDOffset =
3515 endian::readNext<uint32_t, little, unaligned>(Data);
3516 uint32_t PreprocessedEntityIDOffset =
3517 endian::readNext<uint32_t, little, unaligned>(Data);
3518 uint32_t SubmoduleIDOffset =
3519 endian::readNext<uint32_t, little, unaligned>(Data);
3520 uint32_t SelectorIDOffset =
3521 endian::readNext<uint32_t, little, unaligned>(Data);
3522 uint32_t DeclIDOffset =
3523 endian::readNext<uint32_t, little, unaligned>(Data);
3524 uint32_t TypeIndexOffset =
3525 endian::readNext<uint32_t, little, unaligned>(Data);
3526
3527 uint32_t None = std::numeric_limits<uint32_t>::max();
3528
3529 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3530 RemapBuilder &Remap) {
3531 if (Offset != None)
3532 Remap.insert(std::make_pair(Offset,
3533 static_cast<int>(BaseOffset - Offset)));
3534 };
3535 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3536 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3537 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3538 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3539 PreprocessedEntityRemap);
3540 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3541 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3542 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3543 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3544
3545 // Global -> local mappings.
3546 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3547 }
3548}
3549
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003550ASTReader::ASTReadResult
3551ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3552 const ModuleFile *ImportedBy,
3553 unsigned ClientLoadCapabilities) {
3554 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003555 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003556
3557 // Try to resolve ModuleName in the current header search context and
3558 // verify that it is found in the same module map file as we saved. If the
3559 // top-level AST file is a main file, skip this check because there is no
3560 // usable header search context.
3561 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003562 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003563 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003564 // An implicitly-loaded module file should have its module listed in some
3565 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003566 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003567 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3568 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3569 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003570 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003571 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3572 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3573 // This module was defined by an imported (explicit) module.
3574 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3575 << ASTFE->getName();
3576 else
3577 // This module was built with a different module map.
3578 Diag(diag::err_imported_module_not_found)
3579 << F.ModuleName << F.FileName << ImportedBy->FileName
3580 << F.ModuleMapPath;
3581 }
3582 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003583 }
3584
Richard Smithe842a472014-10-22 02:05:46 +00003585 assert(M->Name == F.ModuleName && "found module with different name");
3586
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003587 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003588 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003589 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3590 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003591 assert(ImportedBy && "top-level import should be verified");
3592 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3593 Diag(diag::err_imported_module_modmap_changed)
3594 << F.ModuleName << ImportedBy->FileName
3595 << ModMap->getName() << F.ModuleMapPath;
3596 return OutOfDate;
3597 }
3598
3599 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3600 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3601 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003602 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003603 const FileEntry *F =
3604 FileMgr.getFile(Filename, false, false);
3605 if (F == nullptr) {
3606 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3607 Error("could not find file '" + Filename +"' referenced by AST file");
3608 return OutOfDate;
3609 }
3610 AdditionalStoredMaps.insert(F);
3611 }
3612
3613 // Check any additional module map files (e.g. module.private.modulemap)
3614 // that are not in the pcm.
3615 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3616 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3617 // Remove files that match
3618 // Note: SmallPtrSet::erase is really remove
3619 if (!AdditionalStoredMaps.erase(ModMap)) {
3620 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3621 Diag(diag::err_module_different_modmap)
3622 << F.ModuleName << /*new*/0 << ModMap->getName();
3623 return OutOfDate;
3624 }
3625 }
3626 }
3627
3628 // Check any additional module map files that are in the pcm, but not
3629 // found in header search. Cases that match are already removed.
3630 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3631 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3632 Diag(diag::err_module_different_modmap)
3633 << F.ModuleName << /*not new*/1 << ModMap->getName();
3634 return OutOfDate;
3635 }
3636 }
3637
3638 if (Listener)
3639 Listener->ReadModuleMapFile(F.ModuleMapPath);
3640 return Success;
3641}
3642
Douglas Gregorc1489562013-02-12 23:36:21 +00003643/// \brief Move the given method to the back of the global list of methods.
3644static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3645 // Find the entry for this selector in the method pool.
3646 Sema::GlobalMethodPool::iterator Known
3647 = S.MethodPool.find(Method->getSelector());
3648 if (Known == S.MethodPool.end())
3649 return;
3650
3651 // Retrieve the appropriate method list.
3652 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3653 : Known->second.second;
3654 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003655 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003656 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003657 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003658 Found = true;
3659 } else {
3660 // Keep searching.
3661 continue;
3662 }
3663 }
3664
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003665 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003666 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003667 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003668 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003669 }
3670}
3671
Richard Smithde711422015-04-23 21:20:19 +00003672void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003673 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003674 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003675 bool wasHidden = D->isHidden();
3676 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003677
Richard Smith49f906a2014-03-01 00:08:04 +00003678 if (wasHidden && SemaObj) {
3679 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3680 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003681 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003682 }
3683 }
3684}
3685
Richard Smith49f906a2014-03-01 00:08:04 +00003686void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003687 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003688 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003690 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003691 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003692 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003693 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003694
3695 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003696 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 // there is nothing more to do.
3698 continue;
3699 }
Richard Smith49f906a2014-03-01 00:08:04 +00003700
Guy Benyei11169dd2012-12-18 14:30:41 +00003701 if (!Mod->isAvailable()) {
3702 // Modules that aren't available cannot be made visible.
3703 continue;
3704 }
3705
3706 // Update the module's name visibility.
3707 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003708
Guy Benyei11169dd2012-12-18 14:30:41 +00003709 // If we've already deserialized any names from this module,
3710 // mark them as visible.
3711 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3712 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003713 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003714 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003715 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003716 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3717 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003718 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003719
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003721 SmallVector<Module *, 16> Exports;
3722 Mod->getExportedModules(Exports);
3723 for (SmallVectorImpl<Module *>::iterator
3724 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3725 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003726 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003727 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003728 }
3729 }
3730}
3731
Richard Smith6561f922016-09-12 21:06:40 +00003732/// We've merged the definition \p MergedDef into the existing definition
3733/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3734/// visible.
3735void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3736 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003737 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3738 // in modules other than its owning module. We should instead give the
3739 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003740 if (Def->isHidden()) {
3741 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003742 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003743 Def->setVisibleDespiteOwningModule();
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003744 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3745 getContext().mergeDefinitionIntoModule(
3746 Def, MergedDef->getImportedOwningModule(),
3747 /*NotifyListeners*/ false);
3748 PendingMergedDefinitionsToDeduplicate.insert(Def);
3749 } else {
3750 auto SubmoduleID = MergedDef->getOwningModuleID();
3751 assert(SubmoduleID && "hidden definition in no module");
3752 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3753 }
Richard Smith6561f922016-09-12 21:06:40 +00003754 }
3755}
3756
Douglas Gregore060e572013-01-25 01:03:03 +00003757bool ASTReader::loadGlobalIndex() {
3758 if (GlobalIndex)
3759 return false;
3760
3761 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003762 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003763 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003764
Douglas Gregore060e572013-01-25 01:03:03 +00003765 // Try to load the global index.
3766 TriedLoadingGlobalIndex = true;
3767 StringRef ModuleCachePath
3768 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3769 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003770 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003771 if (!Result.first)
3772 return true;
3773
3774 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003775 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003776 return false;
3777}
3778
3779bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003780 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003781 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3782}
3783
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003784static void updateModuleTimestamp(ModuleFile &MF) {
3785 // Overwrite the timestamp file contents so that file's mtime changes.
3786 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003787 std::error_code EC;
3788 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3789 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003790 return;
3791 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003792 OS.close();
3793 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003794}
3795
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003796/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3797/// cursor into the start of the given block ID, returning false on success and
3798/// true on failure.
3799static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003800 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003801 llvm::BitstreamEntry Entry = Cursor.advance();
3802 switch (Entry.Kind) {
3803 case llvm::BitstreamEntry::Error:
3804 case llvm::BitstreamEntry::EndBlock:
3805 return true;
3806
3807 case llvm::BitstreamEntry::Record:
3808 // Ignore top-level records.
3809 Cursor.skipRecord(Entry.ID);
3810 break;
3811
3812 case llvm::BitstreamEntry::SubBlock:
3813 if (Entry.ID == BlockID) {
3814 if (Cursor.EnterSubBlock(BlockID))
3815 return true;
3816 // Found it!
3817 return false;
3818 }
3819
3820 if (Cursor.SkipBlock())
3821 return true;
3822 }
3823 }
3824}
3825
Benjamin Kramer0772c422016-02-13 13:42:54 +00003826ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003827 ModuleKind Type,
3828 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003829 unsigned ClientLoadCapabilities,
3830 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003831 llvm::SaveAndRestore<SourceLocation>
3832 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3833
Richard Smithd1c46742014-04-30 02:24:17 +00003834 // Defer any pending actions until we get to the end of reading the AST file.
3835 Deserializing AnASTFile(this);
3836
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003838 unsigned PreviousGeneration = 0;
3839 if (ContextObj)
3840 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003841
3842 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003843 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003844 switch (ASTReadResult ReadResult =
3845 ReadASTCore(FileName, Type, ImportLoc,
3846 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3847 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003848 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003849 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003850 case OutOfDate:
3851 case VersionMismatch:
3852 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003853 case HadErrors: {
3854 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3855 for (const ImportedModule &IM : Loaded)
3856 LoadedSet.insert(IM.Mod);
3857
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003858 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003859 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003860 ? &PP.getHeaderSearchInfo().getModuleMap()
3861 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003862
3863 // If we find that any modules are unusable, the global index is going
3864 // to be out-of-date. Just remove it.
3865 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003866 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003867 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003868 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 case Success:
3870 break;
3871 }
3872
3873 // Here comes stuff that we only do once the entire chain is loaded.
3874
3875 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003876 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3877 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 M != MEnd; ++M) {
3879 ModuleFile &F = *M->Mod;
3880
3881 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003882 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3883 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003884
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003885 // Read the extension blocks.
3886 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3887 if (ASTReadResult Result = ReadExtensionBlock(F))
3888 return Result;
3889 }
3890
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003891 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 // bits of all files we've seen.
3893 F.GlobalBitOffset = TotalModulesSizeInBits;
3894 TotalModulesSizeInBits += F.SizeInBits;
3895 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003896
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 // Preload SLocEntries.
3898 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3899 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3900 // Load it through the SourceManager and don't call ReadSLocEntry()
3901 // directly because the entry may have already been loaded in which case
3902 // calling ReadSLocEntry() directly would trigger an assertion in
3903 // SourceManager.
3904 SourceMgr.getLoadedSLocEntryByID(Index);
3905 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003906
Richard Smithea741482017-05-01 22:10:47 +00003907 // Map the original source file ID into the ID space of the current
3908 // compilation.
3909 if (F.OriginalSourceFileID.isValid()) {
3910 F.OriginalSourceFileID = FileID::get(
3911 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3912 }
3913
Richard Smith33e0f7e2015-07-22 02:08:40 +00003914 // Preload all the pending interesting identifiers by marking them out of
3915 // date.
3916 for (auto Offset : F.PreloadIdentifierOffsets) {
3917 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3918 F.IdentifierTableData + Offset);
3919
3920 ASTIdentifierLookupTrait Trait(*this, F);
3921 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3922 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003923 auto &II = PP.getIdentifierTable().getOwn(Key);
3924 II.setOutOfDate(true);
3925
3926 // Mark this identifier as being from an AST file so that we can track
3927 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003928 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003929
3930 // Associate the ID with the identifier so that the writer can reuse it.
3931 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3932 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003933 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003934 }
3935
Douglas Gregor603cd862013-03-22 18:50:14 +00003936 // Setup the import locations and notify the module manager that we've
3937 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003938 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3939 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 M != MEnd; ++M) {
3941 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003942
3943 ModuleMgr.moduleFileAccepted(&F);
3944
3945 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003946 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003947 // FIXME: We assume that locations from PCH / preamble do not need
3948 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003949 if (!M->ImportedBy)
3950 F.ImportLoc = M->ImportLoc;
3951 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003952 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003953 }
3954
Richard Smithdbafb6c2017-06-29 23:23:46 +00003955 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003956 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3957 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003958 // Mark all of the identifiers in the identifier table as being out of date,
3959 // so that various accessors know to check the loaded modules when the
3960 // identifier is used.
3961 //
3962 // For C++ modules, we don't need information on many identifiers (just
3963 // those that provide macros or are poisoned), so we mark all of
3964 // the interesting ones via PreloadIdentifierOffsets.
3965 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3966 IdEnd = PP.getIdentifierTable().end();
3967 Id != IdEnd; ++Id)
3968 Id->second->setOutOfDate(true);
3969 }
Manman Rena0f31a02016-04-29 19:04:05 +00003970 // Mark selectors as out of date.
3971 for (auto Sel : SelectorGeneration)
3972 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003973
Guy Benyei11169dd2012-12-18 14:30:41 +00003974 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003975 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3976 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3978 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003979
3980 switch (Unresolved.Kind) {
3981 case UnresolvedModuleRef::Conflict:
3982 if (ResolvedMod) {
3983 Module::Conflict Conflict;
3984 Conflict.Other = ResolvedMod;
3985 Conflict.Message = Unresolved.String.str();
3986 Unresolved.Mod->Conflicts.push_back(Conflict);
3987 }
3988 continue;
3989
3990 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003992 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003993 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003994
Douglas Gregorfb912652013-03-20 21:10:35 +00003995 case UnresolvedModuleRef::Export:
3996 if (ResolvedMod || Unresolved.IsWildcard)
3997 Unresolved.Mod->Exports.push_back(
3998 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3999 continue;
4000 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004002 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004003
Graydon Hoaree7196af2016-12-09 21:45:49 +00004004 if (Imported)
4005 Imported->append(ImportedModules.begin(),
4006 ImportedModules.end());
4007
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004008 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4009 // Might be unnecessary as use declarations are only used to build the
4010 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004011
Richard Smithdbafb6c2017-06-29 23:23:46 +00004012 if (ContextObj)
4013 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004014
Richard Smith3d8e97e2013-10-18 06:54:39 +00004015 if (SemaObj)
4016 UpdateSema();
4017
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 if (DeserializationListener)
4019 DeserializationListener->ReaderInitialized(this);
4020
4021 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004022 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 // If this AST file is a precompiled preamble, then set the
4024 // preamble file ID of the source manager to the file source file
4025 // from which the preamble was built.
4026 if (Type == MK_Preamble) {
4027 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4028 } else if (Type == MK_MainFile) {
4029 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4030 }
4031 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004032
Guy Benyei11169dd2012-12-18 14:30:41 +00004033 // For any Objective-C class definitions we have already loaded, make sure
4034 // that we load any additional categories.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004035 if (ContextObj) {
4036 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4037 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4038 ObjCClassesLoaded[I],
4039 PreviousGeneration);
4040 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 }
Douglas Gregore060e572013-01-25 01:03:03 +00004042
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004043 if (PP.getHeaderSearchInfo()
4044 .getHeaderSearchOpts()
4045 .ModulesValidateOncePerBuildSession) {
4046 // Now we are certain that the module and all modules it depends on are
4047 // up to date. Create or update timestamp files for modules that are
4048 // located in the module cache (not for PCH files that could be anywhere
4049 // in the filesystem).
4050 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4051 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00004052 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004053 updateModuleTimestamp(*M.Mod);
4054 }
4055 }
4056 }
4057
Guy Benyei11169dd2012-12-18 14:30:41 +00004058 return Success;
4059}
4060
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004061static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004062
Ben Langmuir70a1b812015-03-24 04:43:52 +00004063/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
4064static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004065 return Stream.canSkipToPos(4) &&
4066 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00004067 Stream.Read(8) == 'P' &&
4068 Stream.Read(8) == 'C' &&
4069 Stream.Read(8) == 'H';
4070}
4071
Richard Smith0f99d6a2015-08-09 08:48:41 +00004072static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4073 switch (Kind) {
4074 case MK_PCH:
4075 return 0; // PCH
4076 case MK_ImplicitModule:
4077 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004078 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004079 return 1; // module
4080 case MK_MainFile:
4081 case MK_Preamble:
4082 return 2; // main source file
4083 }
4084 llvm_unreachable("unknown module kind");
4085}
4086
Guy Benyei11169dd2012-12-18 14:30:41 +00004087ASTReader::ASTReadResult
4088ASTReader::ReadASTCore(StringRef FileName,
4089 ModuleKind Type,
4090 SourceLocation ImportLoc,
4091 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004092 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004093 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004094 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 unsigned ClientLoadCapabilities) {
4096 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004098 ModuleManager::AddModuleResult AddResult
4099 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004100 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004101 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004102 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004103
Douglas Gregor7029ce12013-03-19 00:28:20 +00004104 switch (AddResult) {
4105 case ModuleManager::AlreadyLoaded:
4106 return Success;
4107
4108 case ModuleManager::NewlyLoaded:
4109 // Load module file below.
4110 break;
4111
4112 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004113 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004114 // it.
4115 if (ClientLoadCapabilities & ARR_Missing)
4116 return Missing;
4117
4118 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004119 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004120 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004121 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004122 return Failure;
4123
4124 case ModuleManager::OutOfDate:
4125 // We couldn't load the module file because it is out-of-date. If the
4126 // client can handle out-of-date, return it.
4127 if (ClientLoadCapabilities & ARR_OutOfDate)
4128 return OutOfDate;
4129
4130 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004131 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004132 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004133 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 return Failure;
4135 }
4136
Douglas Gregor7029ce12013-03-19 00:28:20 +00004137 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004138
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004140 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004141 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004142 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004143
Guy Benyei11169dd2012-12-18 14:30:41 +00004144 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004145 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004146 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4147 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 return Failure;
4149 }
4150
4151 // This is used for compatibility with older PCH formats.
4152 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004153 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004154 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004155
Chris Lattnerefa77172013-01-20 00:00:22 +00004156 switch (Entry.Kind) {
4157 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004158 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004159 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004160 Error("invalid record at top-level of AST file");
4161 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004162
Chris Lattnerefa77172013-01-20 00:00:22 +00004163 case llvm::BitstreamEntry::SubBlock:
4164 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 }
4166
Chris Lattnerefa77172013-01-20 00:00:22 +00004167 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 case CONTROL_BLOCK_ID:
4169 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004170 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004172 // Check that we didn't try to load a non-module AST file as a module.
4173 //
4174 // FIXME: Should we also perform the converse check? Loading a module as
4175 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004176 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4177 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004178 F.ModuleName.empty()) {
4179 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4180 if (Result != OutOfDate ||
4181 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4182 Diag(diag::err_module_file_not_module) << FileName;
4183 return Result;
4184 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004185 break;
4186
4187 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004188 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 case OutOfDate: return OutOfDate;
4190 case VersionMismatch: return VersionMismatch;
4191 case ConfigurationMismatch: return ConfigurationMismatch;
4192 case HadErrors: return HadErrors;
4193 }
4194 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004195
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 case AST_BLOCK_ID:
4197 if (!HaveReadControlBlock) {
4198 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004199 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 return VersionMismatch;
4201 }
4202
4203 // Record that we've loaded this module.
4204 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4205 return Success;
4206
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004207 case UNHASHED_CONTROL_BLOCK_ID:
4208 // This block is handled using look-ahead during ReadControlBlock. We
4209 // shouldn't get here!
4210 Error("malformed block record in AST file");
4211 return Failure;
4212
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 default:
4214 if (Stream.SkipBlock()) {
4215 Error("malformed block record in AST file");
4216 return Failure;
4217 }
4218 break;
4219 }
4220 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004221
4222 return Success;
4223}
4224
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004225ASTReader::ASTReadResult
4226ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4227 unsigned ClientLoadCapabilities) {
4228 const HeaderSearchOptions &HSOpts =
4229 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4230 bool AllowCompatibleConfigurationMismatch =
4231 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4232
4233 ASTReadResult Result = readUnhashedControlBlockImpl(
4234 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4235 Listener.get(),
4236 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4237
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004238 // If F was directly imported by another module, it's implicitly validated by
4239 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004240 if (DisableValidation || WasImportedBy ||
4241 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4242 return Success;
4243
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004244 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004245 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004246 return Failure;
4247 }
4248
4249 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4250 // If this module has already been finalized in the PCMCache, we're stuck
4251 // with it; we can only load a single version of each module.
4252 //
4253 // This can happen when a module is imported in two contexts: in one, as a
4254 // user module; in another, as a system module (due to an import from
4255 // another module marked with the [system] flag). It usually indicates a
4256 // bug in the module map: this module should also be marked with [system].
4257 //
4258 // If -Wno-system-headers (the default), and the first import is as a
4259 // system module, then validation will fail during the as-user import,
4260 // since -Werror flags won't have been validated. However, it's reasonable
4261 // to treat this consistently as a system module.
4262 //
4263 // If -Wsystem-headers, the PCM on disk was built with
4264 // -Wno-system-headers, and the first import is as a user module, then
4265 // validation will fail during the as-system import since the PCM on disk
4266 // doesn't guarantee that -Werror was respected. However, the -Werror
4267 // flags were checked during the initial as-user import.
4268 if (PCMCache.isBufferFinal(F.FileName)) {
4269 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4270 return Success;
4271 }
4272 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004273
4274 return Result;
4275}
4276
4277ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4278 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4279 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4280 bool ValidateDiagnosticOptions) {
4281 // Initialize a stream.
4282 BitstreamCursor Stream(StreamData);
4283
4284 // Sniff for the signature.
4285 if (!startsWithASTFileMagic(Stream))
4286 return Failure;
4287
4288 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4289 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4290 return Failure;
4291
4292 // Read all of the records in the options block.
4293 RecordData Record;
4294 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004295 while (true) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004296 llvm::BitstreamEntry Entry = Stream.advance();
4297
4298 switch (Entry.Kind) {
4299 case llvm::BitstreamEntry::Error:
4300 case llvm::BitstreamEntry::SubBlock:
4301 return Failure;
4302
4303 case llvm::BitstreamEntry::EndBlock:
4304 return Result;
4305
4306 case llvm::BitstreamEntry::Record:
4307 // The interesting case.
4308 break;
4309 }
4310
4311 // Read and process a record.
4312 Record.clear();
4313 switch (
4314 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004315 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004316 if (F)
4317 std::copy(Record.begin(), Record.end(), F->Signature.data());
4318 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004319 case DIAGNOSTIC_OPTIONS: {
4320 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4321 if (Listener && ValidateDiagnosticOptions &&
4322 !AllowCompatibleConfigurationMismatch &&
4323 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004324 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004325 break;
4326 }
4327 case DIAG_PRAGMA_MAPPINGS:
4328 if (!F)
4329 break;
4330 if (F->PragmaDiagMappings.empty())
4331 F->PragmaDiagMappings.swap(Record);
4332 else
4333 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4334 Record.begin(), Record.end());
4335 break;
4336 }
4337 }
4338}
4339
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004340/// Parse a record and blob containing module file extension metadata.
4341static bool parseModuleFileExtensionMetadata(
4342 const SmallVectorImpl<uint64_t> &Record,
4343 StringRef Blob,
4344 ModuleFileExtensionMetadata &Metadata) {
4345 if (Record.size() < 4) return true;
4346
4347 Metadata.MajorVersion = Record[0];
4348 Metadata.MinorVersion = Record[1];
4349
4350 unsigned BlockNameLen = Record[2];
4351 unsigned UserInfoLen = Record[3];
4352
4353 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4354
4355 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4356 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4357 Blob.data() + BlockNameLen + UserInfoLen);
4358 return false;
4359}
4360
4361ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4362 BitstreamCursor &Stream = F.Stream;
4363
4364 RecordData Record;
4365 while (true) {
4366 llvm::BitstreamEntry Entry = Stream.advance();
4367 switch (Entry.Kind) {
4368 case llvm::BitstreamEntry::SubBlock:
4369 if (Stream.SkipBlock())
4370 return Failure;
4371
4372 continue;
4373
4374 case llvm::BitstreamEntry::EndBlock:
4375 return Success;
4376
4377 case llvm::BitstreamEntry::Error:
4378 return HadErrors;
4379
4380 case llvm::BitstreamEntry::Record:
4381 break;
4382 }
4383
4384 Record.clear();
4385 StringRef Blob;
4386 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4387 switch (RecCode) {
4388 case EXTENSION_METADATA: {
4389 ModuleFileExtensionMetadata Metadata;
4390 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4391 return Failure;
4392
4393 // Find a module file extension with this block name.
4394 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4395 if (Known == ModuleFileExtensions.end()) break;
4396
4397 // Form a reader.
4398 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4399 F, Stream)) {
4400 F.ExtensionReaders.push_back(std::move(Reader));
4401 }
4402
4403 break;
4404 }
4405 }
4406 }
4407
4408 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004409}
4410
Richard Smitha7e2cc62015-05-01 01:53:09 +00004411void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004412 assert(ContextObj && "no context to initialize");
4413 ASTContext &Context = *ContextObj;
4414
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 // If there's a listener, notify them that we "read" the translation unit.
4416 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004417 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 Context.getTranslationUnitDecl());
4419
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 // FIXME: Find a better way to deal with collisions between these
4421 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004422
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 // Load the special types.
4424 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4425 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4426 if (!Context.CFConstantStringTypeDecl)
4427 Context.setCFConstantStringType(GetType(String));
4428 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004429
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4431 QualType FileType = GetType(File);
4432 if (FileType.isNull()) {
4433 Error("FILE type is NULL");
4434 return;
4435 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004436
Guy Benyei11169dd2012-12-18 14:30:41 +00004437 if (!Context.FILEDecl) {
4438 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4439 Context.setFILEDecl(Typedef->getDecl());
4440 else {
4441 const TagType *Tag = FileType->getAs<TagType>();
4442 if (!Tag) {
4443 Error("Invalid FILE type in AST file");
4444 return;
4445 }
4446 Context.setFILEDecl(Tag->getDecl());
4447 }
4448 }
4449 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004450
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4452 QualType Jmp_bufType = GetType(Jmp_buf);
4453 if (Jmp_bufType.isNull()) {
4454 Error("jmp_buf type is NULL");
4455 return;
4456 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004457
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 if (!Context.jmp_bufDecl) {
4459 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4460 Context.setjmp_bufDecl(Typedef->getDecl());
4461 else {
4462 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4463 if (!Tag) {
4464 Error("Invalid jmp_buf type in AST file");
4465 return;
4466 }
4467 Context.setjmp_bufDecl(Tag->getDecl());
4468 }
4469 }
4470 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004471
Guy Benyei11169dd2012-12-18 14:30:41 +00004472 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4473 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4474 if (Sigjmp_bufType.isNull()) {
4475 Error("sigjmp_buf type is NULL");
4476 return;
4477 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004478
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 if (!Context.sigjmp_bufDecl) {
4480 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4481 Context.setsigjmp_bufDecl(Typedef->getDecl());
4482 else {
4483 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4484 assert(Tag && "Invalid sigjmp_buf type in AST file");
4485 Context.setsigjmp_bufDecl(Tag->getDecl());
4486 }
4487 }
4488 }
4489
4490 if (unsigned ObjCIdRedef
4491 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4492 if (Context.ObjCIdRedefinitionType.isNull())
4493 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4494 }
4495
4496 if (unsigned ObjCClassRedef
4497 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4498 if (Context.ObjCClassRedefinitionType.isNull())
4499 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4500 }
4501
4502 if (unsigned ObjCSelRedef
4503 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4504 if (Context.ObjCSelRedefinitionType.isNull())
4505 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4506 }
4507
4508 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4509 QualType Ucontext_tType = GetType(Ucontext_t);
4510 if (Ucontext_tType.isNull()) {
4511 Error("ucontext_t type is NULL");
4512 return;
4513 }
4514
4515 if (!Context.ucontext_tDecl) {
4516 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4517 Context.setucontext_tDecl(Typedef->getDecl());
4518 else {
4519 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4520 assert(Tag && "Invalid ucontext_t type in AST file");
4521 Context.setucontext_tDecl(Tag->getDecl());
4522 }
4523 }
4524 }
4525 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004526
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4528
4529 // If there were any CUDA special declarations, deserialize them.
4530 if (!CUDASpecialDeclRefs.empty()) {
4531 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4532 Context.setcudaConfigureCallDecl(
4533 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4534 }
Richard Smith56be7542014-03-21 00:33:59 +00004535
Guy Benyei11169dd2012-12-18 14:30:41 +00004536 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004537 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004538 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004539 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004540 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004541 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004542 if (Import.ImportLoc.isValid())
4543 PP.makeModuleVisible(Imported, Import.ImportLoc);
4544 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004545 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 }
4547 ImportedModules.clear();
4548}
4549
4550void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004551 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004552}
4553
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004554/// \brief Reads and return the signature record from \p PCH's control block, or
4555/// else returns 0.
4556static ASTFileSignature readASTFileSignature(StringRef PCH) {
4557 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004558 if (!startsWithASTFileMagic(Stream))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004559 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004560
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004561 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4562 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4563 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004564
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004565 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004566 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004567 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004568 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004569 if (Entry.Kind != llvm::BitstreamEntry::Record)
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004570 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004571
4572 Record.clear();
4573 StringRef Blob;
4574 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004575 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4576 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004577 }
4578}
4579
Guy Benyei11169dd2012-12-18 14:30:41 +00004580/// \brief Retrieve the name of the original source file name
4581/// directly from the AST file, without actually loading the AST
4582/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004583std::string ASTReader::getOriginalSourceFile(
4584 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004585 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004587 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004589 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4590 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 return std::string();
4592 }
4593
4594 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004595 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004596
4597 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004598 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4600 return std::string();
4601 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004602
Chris Lattnere7b154b2013-01-19 21:39:22 +00004603 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004604 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004605 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4606 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004607 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004608
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004609 // Scan for ORIGINAL_FILE inside the control block.
4610 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004611 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004612 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004613 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4614 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004615
Chris Lattnere7b154b2013-01-19 21:39:22 +00004616 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4617 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4618 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004620
Guy Benyei11169dd2012-12-18 14:30:41 +00004621 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004622 StringRef Blob;
4623 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4624 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004626}
4627
4628namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004629
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 class SimplePCHValidator : public ASTReaderListener {
4631 const LangOptions &ExistingLangOpts;
4632 const TargetOptions &ExistingTargetOpts;
4633 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004634 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004635 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004636
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 public:
4638 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4639 const TargetOptions &ExistingTargetOpts,
4640 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004641 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 FileManager &FileMgr)
4643 : ExistingLangOpts(ExistingLangOpts),
4644 ExistingTargetOpts(ExistingTargetOpts),
4645 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004646 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004647 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00004648
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004649 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4650 bool AllowCompatibleDifferences) override {
4651 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4652 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004654
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004655 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4656 bool AllowCompatibleDifferences) override {
4657 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4658 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004660
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004661 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4662 StringRef SpecificModuleCachePath,
4663 bool Complain) override {
4664 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4665 ExistingModuleCachePath,
4666 nullptr, ExistingLangOpts);
4667 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004668
Craig Topper3e89dfe2014-03-13 02:13:41 +00004669 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4670 bool Complain,
4671 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004672 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004673 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 }
4675 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004676
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004677} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004678
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004679bool ASTReader::readASTFileControlBlock(
4680 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004681 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004682 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004683 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004684 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004685 // FIXME: This allows use of the VFS; we do not allow use of the
4686 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004687 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 if (!Buffer) {
4689 return true;
4690 }
4691
4692 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004693 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4694 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004695
4696 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004697 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004699
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004700 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004701 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004702 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004703
4704 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004705 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004706 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004707 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004708
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004710 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004711 bool DoneWithControlBlock = false;
4712 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004713 llvm::BitstreamEntry Entry = Stream.advance();
4714
4715 switch (Entry.Kind) {
4716 case llvm::BitstreamEntry::SubBlock: {
4717 switch (Entry.ID) {
4718 case OPTIONS_BLOCK_ID: {
4719 std::string IgnoredSuggestedPredefines;
4720 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4721 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004722 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004723 return true;
4724 break;
4725 }
4726
4727 case INPUT_FILES_BLOCK_ID:
4728 InputFilesCursor = Stream;
4729 if (Stream.SkipBlock() ||
4730 (NeedsInputFiles &&
4731 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4732 return true;
4733 break;
4734
4735 default:
4736 if (Stream.SkipBlock())
4737 return true;
4738 break;
4739 }
4740
4741 continue;
4742 }
4743
4744 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004745 DoneWithControlBlock = true;
4746 break;
Richard Smith0516b182015-09-08 19:40:14 +00004747
4748 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004749 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004750
4751 case llvm::BitstreamEntry::Record:
4752 break;
4753 }
4754
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004755 if (DoneWithControlBlock) break;
4756
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004758 StringRef Blob;
4759 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004760 switch ((ControlRecordTypes)RecCode) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004761 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004762 if (Record[0] != VERSION_MAJOR)
4763 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004764 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004765 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004766 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004767 case MODULE_NAME:
4768 Listener.ReadModuleName(Blob);
4769 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004770 case MODULE_DIRECTORY:
4771 ModuleDir = Blob;
4772 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004773 case MODULE_MAP_FILE: {
4774 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004775 auto Path = ReadString(Record, Idx);
4776 ResolveImportedPath(Path, ModuleDir);
4777 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004778 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004779 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004780 case INPUT_FILE_OFFSETS: {
4781 if (!NeedsInputFiles)
4782 break;
4783
4784 unsigned NumInputFiles = Record[0];
4785 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004786 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004787 for (unsigned I = 0; I != NumInputFiles; ++I) {
4788 // Go find this input file.
4789 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004790
4791 if (isSystemFile && !NeedsSystemInputFiles)
4792 break; // the rest are system input files
4793
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004794 BitstreamCursor &Cursor = InputFilesCursor;
4795 SavedStreamPosition SavedPosition(Cursor);
4796 Cursor.JumpToBit(InputFileOffs[I]);
4797
4798 unsigned Code = Cursor.ReadCode();
4799 RecordData Record;
4800 StringRef Blob;
4801 bool shouldContinue = false;
4802 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4803 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004804 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004805 std::string Filename = Blob;
4806 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004807 shouldContinue = Listener.visitInputFile(
4808 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004809 break;
4810 }
4811 if (!shouldContinue)
4812 break;
4813 }
4814 break;
4815 }
4816
Richard Smithd4b230b2014-10-27 23:01:16 +00004817 case IMPORTS: {
4818 if (!NeedsImports)
4819 break;
4820
4821 unsigned Idx = 0, N = Record.size();
4822 while (Idx < N) {
4823 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004824 Idx += 5; // ImportLoc, Size, ModTime, Signature
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004825 SkipString(Record, Idx); // Module name; FIXME: pass to listener?
Richard Smith7ed1bc92014-12-05 22:42:13 +00004826 std::string Filename = ReadString(Record, Idx);
4827 ResolveImportedPath(Filename, ModuleDir);
4828 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004829 }
4830 break;
4831 }
4832
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004833 default:
4834 // No other validation to perform.
4835 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 }
4837 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004838
4839 // Look for module file extension blocks, if requested.
4840 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004841 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004842 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4843 bool DoneWithExtensionBlock = false;
4844 while (!DoneWithExtensionBlock) {
4845 llvm::BitstreamEntry Entry = Stream.advance();
4846
4847 switch (Entry.Kind) {
4848 case llvm::BitstreamEntry::SubBlock:
4849 if (Stream.SkipBlock())
4850 return true;
4851
4852 continue;
4853
4854 case llvm::BitstreamEntry::EndBlock:
4855 DoneWithExtensionBlock = true;
4856 continue;
4857
4858 case llvm::BitstreamEntry::Error:
4859 return true;
4860
4861 case llvm::BitstreamEntry::Record:
4862 break;
4863 }
4864
4865 Record.clear();
4866 StringRef Blob;
4867 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4868 switch (RecCode) {
4869 case EXTENSION_METADATA: {
4870 ModuleFileExtensionMetadata Metadata;
4871 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4872 return true;
4873
4874 Listener.readModuleFileExtension(Metadata);
4875 break;
4876 }
4877 }
4878 }
4879 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004880 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004881 }
4882
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004883 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4884 if (readUnhashedControlBlockImpl(
4885 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4886 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4887 ValidateDiagnosticOptions) != Success)
4888 return true;
4889
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004890 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004891}
4892
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004893bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4894 const PCHContainerReader &PCHContainerRdr,
4895 const LangOptions &LangOpts,
4896 const TargetOptions &TargetOpts,
4897 const PreprocessorOptions &PPOpts,
4898 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004899 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4900 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004901 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004902 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004903 validator,
4904 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004905}
4906
Ben Langmuir2c9af442014-04-10 17:57:43 +00004907ASTReader::ASTReadResult
4908ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 // Enter the submodule block.
4910 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4911 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004912 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 }
4914
4915 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4916 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004917 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 RecordData Record;
4919 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004920 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004921
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004922 switch (Entry.Kind) {
4923 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4924 case llvm::BitstreamEntry::Error:
4925 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004926 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004927 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004928 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004929 case llvm::BitstreamEntry::Record:
4930 // The interesting case.
4931 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004933
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004935 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004937 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4938
4939 if ((Kind == SUBMODULE_METADATA) != First) {
4940 Error("submodule metadata record should be at beginning of block");
4941 return Failure;
4942 }
4943 First = false;
4944
4945 // Submodule information is only valid if we have a current module.
4946 // FIXME: Should we error on these cases?
4947 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4948 Kind != SUBMODULE_DEFINITION)
4949 continue;
4950
4951 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004952 default: // Default behavior: ignore.
4953 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004954
Richard Smith03478d92014-10-23 22:12:14 +00004955 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004956 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004958 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 }
Richard Smith03478d92014-10-23 22:12:14 +00004960
Chris Lattner0e6c9402013-01-20 02:38:54 +00004961 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004962 unsigned Idx = 0;
4963 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4964 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Richard Smithdd8b5332017-09-04 05:37:53 +00004965 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00004966 bool IsFramework = Record[Idx++];
4967 bool IsExplicit = Record[Idx++];
4968 bool IsSystem = Record[Idx++];
4969 bool IsExternC = Record[Idx++];
4970 bool InferSubmodules = Record[Idx++];
4971 bool InferExplicitSubmodules = Record[Idx++];
4972 bool InferExportWildcard = Record[Idx++];
4973 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004974
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004975 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004976 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004978
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 // Retrieve this (sub)module from the module map, creating it if
4980 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004981 CurrentModule =
4982 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4983 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004984
4985 // FIXME: set the definition loc for CurrentModule, or call
4986 // ModMap.setInferredModuleAllowedBy()
4987
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4989 if (GlobalIndex >= SubmodulesLoaded.size() ||
4990 SubmodulesLoaded[GlobalIndex]) {
4991 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004992 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004994
Douglas Gregor7029ce12013-03-19 00:28:20 +00004995 if (!ParentModule) {
4996 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4997 if (CurFile != F.File) {
4998 if (!Diags.isDiagnosticInFlight()) {
4999 Diag(diag::err_module_file_conflict)
5000 << CurrentModule->getTopLevelModuleName()
5001 << CurFile->getName()
5002 << F.File->getName();
5003 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005004 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005005 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005006 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005007
5008 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005009 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005010 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005011
Richard Smithdd8b5332017-09-04 05:37:53 +00005012 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005013 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005014 CurrentModule->IsFromModuleFile = true;
5015 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005016 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005017 CurrentModule->InferSubmodules = InferSubmodules;
5018 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5019 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005020 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00005021 if (DeserializationListener)
5022 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005023
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005025
Richard Smith8a3e39a2016-03-28 21:31:09 +00005026 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005027 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005028 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005029 CurrentModule->UnresolvedConflicts.clear();
5030 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005031
5032 // The module is available unless it's missing a requirement; relevant
5033 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5034 // Missing headers that were present when the module was built do not
5035 // make it unavailable -- if we got this far, this must be an explicitly
5036 // imported module file.
5037 CurrentModule->Requirements.clear();
5038 CurrentModule->MissingHeaders.clear();
5039 CurrentModule->IsMissingRequirement =
5040 ParentModule && ParentModule->IsMissingRequirement;
5041 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005042 break;
5043 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005044
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005046 std::string Filename = Blob;
5047 ResolveImportedPath(F, Filename);
5048 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005050 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5051 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005052 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5053 Error("mismatched umbrella headers in submodule");
5054 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 }
5056 }
5057 break;
5058 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005059
Richard Smith202210b2014-10-24 20:23:01 +00005060 case SUBMODULE_HEADER:
5061 case SUBMODULE_EXCLUDED_HEADER:
5062 case SUBMODULE_PRIVATE_HEADER:
5063 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005064 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5065 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005066 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005067
Richard Smith202210b2014-10-24 20:23:01 +00005068 case SUBMODULE_TEXTUAL_HEADER:
5069 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5070 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5071 // them here.
5072 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005073
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005074 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005075 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005077
5078 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005079 std::string Dirname = Blob;
5080 ResolveImportedPath(F, Dirname);
5081 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005082 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005083 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5084 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005085 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5086 Error("mismatched umbrella directories in submodule");
5087 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 }
5089 }
5090 break;
5091 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005092
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005094 F.BaseSubmoduleID = getTotalNumSubmodules();
5095 F.LocalNumSubmodules = Record[0];
5096 unsigned LocalBaseSubmoduleID = Record[1];
5097 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005098 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 // module.
5100 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005101
5102 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005103 // module.
5104 F.SubmoduleRemap.insertOrReplace(
5105 std::make_pair(LocalBaseSubmoduleID,
5106 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005107
Ben Langmuir52ca6782014-10-20 16:27:32 +00005108 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5109 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 break;
5111 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005112
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005113 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005115 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 Unresolved.File = &F;
5117 Unresolved.Mod = CurrentModule;
5118 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005119 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005121 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 }
5123 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005124
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005125 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005127 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 Unresolved.File = &F;
5129 Unresolved.Mod = CurrentModule;
5130 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005131 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005133 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005135
5136 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 // the parsed, unresolved exports around.
5138 CurrentModule->UnresolvedExports.clear();
5139 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005140
5141 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005142 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5143 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005144 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005145
5146 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005147 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005148 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005149 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005150
5151 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005152 CurrentModule->ConfigMacros.push_back(Blob.str());
5153 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005154
5155 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005156 UnresolvedModuleRef Unresolved;
5157 Unresolved.File = &F;
5158 Unresolved.Mod = CurrentModule;
5159 Unresolved.ID = Record[0];
5160 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5161 Unresolved.IsWildcard = false;
5162 Unresolved.String = Blob;
5163 UnresolvedModuleRefs.push_back(Unresolved);
5164 break;
5165 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005166
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005167 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005168 if (!ContextObj)
5169 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005170 SmallVector<uint32_t, 16> Inits;
5171 for (auto &ID : Record)
5172 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005173 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005174 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005176
5177 case SUBMODULE_EXPORT_AS:
5178 CurrentModule->ExportAsModule = Blob.str();
5179 break;
5180 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 }
5182}
5183
5184/// \brief Parse the record that corresponds to a LangOptions data
5185/// structure.
5186///
5187/// This routine parses the language options from the AST file and then gives
5188/// them to the AST listener if one is set.
5189///
5190/// \returns true if the listener deems the file unacceptable, false otherwise.
5191bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5192 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005193 ASTReaderListener &Listener,
5194 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 LangOptions LangOpts;
5196 unsigned Idx = 0;
5197#define LANGOPT(Name, Bits, Default, Description) \
5198 LangOpts.Name = Record[Idx++];
5199#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5200 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5201#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005202#define SANITIZER(NAME, ID) \
5203 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005204#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005205
Ben Langmuircd98cb72015-06-23 18:20:18 +00005206 for (unsigned N = Record[Idx++]; N; --N)
5207 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5208
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5210 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5211 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005212
Ben Langmuird4a667a2015-06-23 18:20:23 +00005213 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005214
5215 // Comment options.
5216 for (unsigned N = Record[Idx++]; N; --N) {
5217 LangOpts.CommentOpts.BlockCommandNames.push_back(
5218 ReadString(Record, Idx));
5219 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005220 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005221
Samuel Antaoee8fb302016-01-06 13:42:12 +00005222 // OpenMP offloading options.
5223 for (unsigned N = Record[Idx++]; N; --N) {
5224 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5225 }
5226
5227 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5228
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005229 return Listener.ReadLanguageOptions(LangOpts, Complain,
5230 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005231}
5232
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005233bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5234 ASTReaderListener &Listener,
5235 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005236 unsigned Idx = 0;
5237 TargetOptions TargetOpts;
5238 TargetOpts.Triple = ReadString(Record, Idx);
5239 TargetOpts.CPU = ReadString(Record, Idx);
5240 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 for (unsigned N = Record[Idx++]; N; --N) {
5242 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5243 }
5244 for (unsigned N = Record[Idx++]; N; --N) {
5245 TargetOpts.Features.push_back(ReadString(Record, Idx));
5246 }
5247
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005248 return Listener.ReadTargetOptions(TargetOpts, Complain,
5249 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005250}
5251
5252bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5253 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005254 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005255 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005256#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005257#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005258 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005259#include "clang/Basic/DiagnosticOptions.def"
5260
Richard Smith3be1cb22014-08-07 00:24:21 +00005261 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005262 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005263 for (unsigned N = Record[Idx++]; N; --N)
5264 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005265
5266 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5267}
5268
5269bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5270 ASTReaderListener &Listener) {
5271 FileSystemOptions FSOpts;
5272 unsigned Idx = 0;
5273 FSOpts.WorkingDir = ReadString(Record, Idx);
5274 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5275}
5276
5277bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5278 bool Complain,
5279 ASTReaderListener &Listener) {
5280 HeaderSearchOptions HSOpts;
5281 unsigned Idx = 0;
5282 HSOpts.Sysroot = ReadString(Record, Idx);
5283
5284 // Include entries.
5285 for (unsigned N = Record[Idx++]; N; --N) {
5286 std::string Path = ReadString(Record, Idx);
5287 frontend::IncludeDirGroup Group
5288 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 bool IsFramework = Record[Idx++];
5290 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005291 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5292 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 }
5294
5295 // System header prefixes.
5296 for (unsigned N = Record[Idx++]; N; --N) {
5297 std::string Prefix = ReadString(Record, Idx);
5298 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005299 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 }
5301
5302 HSOpts.ResourceDir = ReadString(Record, Idx);
5303 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005304 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005306 HSOpts.ImplicitModuleMaps = Record[Idx++];
5307 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 HSOpts.UseBuiltinIncludes = Record[Idx++];
5309 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5310 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5311 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005312 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005313
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005314 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5315 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005316}
5317
5318bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5319 bool Complain,
5320 ASTReaderListener &Listener,
5321 std::string &SuggestedPredefines) {
5322 PreprocessorOptions PPOpts;
5323 unsigned Idx = 0;
5324
5325 // Macro definitions/undefs
5326 for (unsigned N = Record[Idx++]; N; --N) {
5327 std::string Macro = ReadString(Record, Idx);
5328 bool IsUndef = Record[Idx++];
5329 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5330 }
5331
5332 // Includes
5333 for (unsigned N = Record[Idx++]; N; --N) {
5334 PPOpts.Includes.push_back(ReadString(Record, Idx));
5335 }
5336
5337 // Macro Includes
5338 for (unsigned N = Record[Idx++]; N; --N) {
5339 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5340 }
5341
5342 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005343 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5345 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5346 PPOpts.ObjCXXARCStandardLibrary =
5347 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5348 SuggestedPredefines.clear();
5349 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5350 SuggestedPredefines);
5351}
5352
5353std::pair<ModuleFile *, unsigned>
5354ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5355 GlobalPreprocessedEntityMapType::iterator
5356 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005357 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005358 "Corrupted global preprocessed entity map");
5359 ModuleFile *M = I->second;
5360 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5361 return std::make_pair(M, LocalIndex);
5362}
5363
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005364llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005365ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5366 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5367 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5368 Mod.NumPreprocessedEntities);
5369
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005370 return llvm::make_range(PreprocessingRecord::iterator(),
5371 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005372}
5373
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005374llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005375ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005376 return llvm::make_range(
5377 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5378 ModuleDeclIterator(this, &Mod,
5379 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005380}
5381
5382PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5383 PreprocessedEntityID PPID = Index+1;
5384 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5385 ModuleFile &M = *PPInfo.first;
5386 unsigned LocalIndex = PPInfo.second;
5387 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5388
Guy Benyei11169dd2012-12-18 14:30:41 +00005389 if (!PP.getPreprocessingRecord()) {
5390 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005391 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005392 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005393
5394 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005395 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5396
5397 llvm::BitstreamEntry Entry =
5398 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5399 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005400 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005401
Guy Benyei11169dd2012-12-18 14:30:41 +00005402 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005403 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5404 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005405 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005406 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005407 RecordData Record;
5408 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005409 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5410 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005411 switch (RecType) {
5412 case PPD_MACRO_EXPANSION: {
5413 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005414 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005415 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005416 if (isBuiltin)
5417 Name = getLocalIdentifier(M, Record[1]);
5418 else {
Richard Smith66a81862015-05-04 02:25:31 +00005419 PreprocessedEntityID GlobalID =
5420 getGlobalPreprocessedEntityID(M, Record[1]);
5421 Def = cast<MacroDefinitionRecord>(
5422 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 }
5424
5425 MacroExpansion *ME;
5426 if (isBuiltin)
5427 ME = new (PPRec) MacroExpansion(Name, Range);
5428 else
5429 ME = new (PPRec) MacroExpansion(Def, Range);
5430
5431 return ME;
5432 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005433
Guy Benyei11169dd2012-12-18 14:30:41 +00005434 case PPD_MACRO_DEFINITION: {
5435 // Decode the identifier info and then check again; if the macro is
5436 // still defined and associated with the identifier,
5437 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005438 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005439
5440 if (DeserializationListener)
5441 DeserializationListener->MacroDefinitionRead(PPID, MD);
5442
5443 return MD;
5444 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005445
Guy Benyei11169dd2012-12-18 14:30:41 +00005446 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005447 const char *FullFileNameStart = Blob.data() + Record[0];
5448 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005449 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005450 if (!FullFileName.empty())
5451 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005452
Guy Benyei11169dd2012-12-18 14:30:41 +00005453 // FIXME: Stable encoding
5454 InclusionDirective::InclusionKind Kind
5455 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5456 InclusionDirective *ID
5457 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005458 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005459 Record[1], Record[3],
5460 File,
5461 Range);
5462 return ID;
5463 }
5464 }
5465
5466 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5467}
5468
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005469/// \brief Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005470/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005471///
5472/// \param SLocMapI points at a chunk of a module that contains no
5473/// preprocessed entities or the entities it contains are not the ones we are
5474/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005475PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5476 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5477 ++SLocMapI;
5478 for (GlobalSLocOffsetMapType::const_iterator
5479 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5480 ModuleFile &M = *SLocMapI->second;
5481 if (M.NumPreprocessedEntities)
5482 return M.BasePreprocessedEntityID;
5483 }
5484
5485 return getTotalNumPreprocessedEntities();
5486}
5487
5488namespace {
5489
Guy Benyei11169dd2012-12-18 14:30:41 +00005490struct PPEntityComp {
5491 const ASTReader &Reader;
5492 ModuleFile &M;
5493
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005494 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005495
5496 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5497 SourceLocation LHS = getLoc(L);
5498 SourceLocation RHS = getLoc(R);
5499 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5500 }
5501
5502 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5503 SourceLocation LHS = getLoc(L);
5504 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5505 }
5506
5507 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5508 SourceLocation RHS = getLoc(R);
5509 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5510 }
5511
5512 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005513 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005514 }
5515};
5516
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005517} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005518
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005519PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5520 bool EndsAfter) const {
5521 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005522 return getTotalNumPreprocessedEntities();
5523
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005524 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5525 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005526 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5527 "Corrupted global sloc offset map");
5528
5529 if (SLocMapI->second->NumPreprocessedEntities == 0)
5530 return findNextPreprocessedEntity(SLocMapI);
5531
5532 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005533
5534 using pp_iterator = const PPEntityOffset *;
5535
Guy Benyei11169dd2012-12-18 14:30:41 +00005536 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5537 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5538
5539 size_t Count = M.NumPreprocessedEntities;
5540 size_t Half;
5541 pp_iterator First = pp_begin;
5542 pp_iterator PPI;
5543
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005544 if (EndsAfter) {
5545 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005546 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005547 } else {
5548 // Do a binary search manually instead of using std::lower_bound because
5549 // The end locations of entities may be unordered (when a macro expansion
5550 // is inside another macro argument), but for this case it is not important
5551 // whether we get the first macro expansion or its containing macro.
5552 while (Count > 0) {
5553 Half = Count / 2;
5554 PPI = First;
5555 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005556 if (SourceMgr.isBeforeInTranslationUnit(
5557 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005558 First = PPI;
5559 ++First;
5560 Count = Count - Half - 1;
5561 } else
5562 Count = Half;
5563 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005564 }
5565
5566 if (PPI == pp_end)
5567 return findNextPreprocessedEntity(SLocMapI);
5568
5569 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5570}
5571
Guy Benyei11169dd2012-12-18 14:30:41 +00005572/// \brief Returns a pair of [Begin, End) indices of preallocated
5573/// preprocessed entities that \arg Range encompasses.
5574std::pair<unsigned, unsigned>
5575 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5576 if (Range.isInvalid())
5577 return std::make_pair(0,0);
5578 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5579
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005580 PreprocessedEntityID BeginID =
5581 findPreprocessedEntity(Range.getBegin(), false);
5582 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005583 return std::make_pair(BeginID, EndID);
5584}
5585
5586/// \brief Optionally returns true or false if the preallocated preprocessed
5587/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005588Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005589 FileID FID) {
5590 if (FID.isInvalid())
5591 return false;
5592
5593 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5594 ModuleFile &M = *PPInfo.first;
5595 unsigned LocalIndex = PPInfo.second;
5596 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005597
Richard Smithcb34bd32016-03-27 07:28:06 +00005598 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005599 if (Loc.isInvalid())
5600 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005601
Guy Benyei11169dd2012-12-18 14:30:41 +00005602 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5603 return true;
5604 else
5605 return false;
5606}
5607
5608namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005609
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 /// \brief Visitor used to search for information about a header file.
5611 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005612 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00005613 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005614
Guy Benyei11169dd2012-12-18 14:30:41 +00005615 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005616 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005617
5618 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 HeaderFileInfoLookupTable *Table
5620 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5621 if (!Table)
5622 return false;
5623
5624 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005625 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 if (Pos == Table->end())
5627 return false;
5628
Richard Smithbdf2d932015-07-30 03:37:16 +00005629 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005630 return true;
5631 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005632
David Blaikie05785d12013-02-20 22:23:23 +00005633 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005634 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005635
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005636} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005637
5638HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005639 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005640 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005641 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005642 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005643
Guy Benyei11169dd2012-12-18 14:30:41 +00005644 return HeaderFileInfo();
5645}
5646
5647void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005648 using DiagState = DiagnosticsEngine::DiagState;
5649 SmallVector<DiagState *, 32> DiagStates;
5650
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005651 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005652 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005653 auto &Record = F.PragmaDiagMappings;
5654 if (Record.empty())
5655 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005656
Richard Smithd230de22017-01-26 01:01:01 +00005657 DiagStates.clear();
5658
5659 auto ReadDiagState =
5660 [&](const DiagState &BasedOn, SourceLocation Loc,
5661 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5662 unsigned BackrefID = Record[Idx++];
5663 if (BackrefID != 0)
5664 return DiagStates[BackrefID - 1];
5665
Guy Benyei11169dd2012-12-18 14:30:41 +00005666 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005667 Diag.DiagStates.push_back(BasedOn);
5668 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005669 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005670 unsigned Size = Record[Idx++];
5671 assert(Idx + Size * 2 <= Record.size() &&
5672 "Invalid data, not enough diag/map pairs");
5673 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005674 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005675 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005676 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005677 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5678 continue;
5679
5680 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5681
5682 // If this mapping was specified as a warning but the severity was
5683 // upgraded due to diagnostic settings, simulate the current diagnostic
5684 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005685 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5686 NewMapping.setSeverity(diag::Severity::Warning);
5687 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005688 }
5689
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005690 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005691 }
Richard Smithd230de22017-01-26 01:01:01 +00005692 return NewState;
5693 };
5694
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005695 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005696 DiagState *FirstState;
5697 if (F.Kind == MK_ImplicitModule) {
5698 // Implicitly-built modules are reused with different diagnostic
5699 // settings. Use the initial diagnostic state from Diag to simulate this
5700 // compilation's diagnostic settings.
5701 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5702 DiagStates.push_back(FirstState);
5703
5704 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005705 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005706 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005707 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005708 assert(Idx < Record.size() &&
5709 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005710 } else if (F.isModule()) {
5711 // For an explicit module, preserve the flags from the module build
5712 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5713 // -Wblah flags.
5714 unsigned Flags = Record[Idx++];
5715 DiagState Initial;
5716 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5717 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5718 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5719 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5720 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5721 Initial.ExtBehavior = (diag::Severity)Flags;
5722 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005723
Richard Smithe37391c2017-05-03 00:28:49 +00005724 // Set up the root buffer of the module to start with the initial
5725 // diagnostic state of the module itself, to cover files that contain no
5726 // explicit transitions (for which we did not serialize anything).
5727 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5728 .StateTransitions.push_back({FirstState, 0});
5729 } else {
5730 // For prefix ASTs, start with whatever the user configured on the
5731 // command line.
5732 Idx++; // Skip flags.
5733 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5734 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005735 }
Richard Smithd230de22017-01-26 01:01:01 +00005736
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005737 // Read the state transitions.
5738 unsigned NumLocations = Record[Idx++];
5739 while (NumLocations--) {
5740 assert(Idx < Record.size() &&
5741 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005742 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5743 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5744 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5745 unsigned Transitions = Record[Idx++];
5746
5747 // Note that we don't need to set up Parent/ParentOffset here, because
5748 // we won't be changing the diagnostic state within imported FileIDs
5749 // (other than perhaps appending to the main source file, which has no
5750 // parent).
5751 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5752 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5753 for (unsigned I = 0; I != Transitions; ++I) {
5754 unsigned Offset = Record[Idx++];
5755 auto *State =
5756 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5757 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 }
5759 }
Richard Smithd230de22017-01-26 01:01:01 +00005760
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005761 // Read the final state.
5762 assert(Idx < Record.size() &&
5763 "Invalid data, missing final pragma diagnostic state");
5764 SourceLocation CurStateLoc =
5765 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5766 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5767
5768 if (!F.isModule()) {
5769 Diag.DiagStatesByLoc.CurDiagState = CurState;
5770 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5771
5772 // Preserve the property that the imaginary root file describes the
5773 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00005774 FileID NullFile;
5775 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005776 if (T.empty())
5777 T.push_back({CurState, 0});
5778 else
5779 T[0].State = CurState;
5780 }
5781
Richard Smithd230de22017-01-26 01:01:01 +00005782 // Don't try to read these mappings again.
5783 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005784 }
5785}
5786
5787/// \brief Get the correct cursor and offset for loading a type.
5788ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5789 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5790 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5791 ModuleFile *M = I->second;
5792 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5793}
5794
5795/// \brief Read and return the type with the given index..
5796///
5797/// The index is the type ID, shifted and minus the number of predefs. This
5798/// routine actually reads the record corresponding to the type at the given
5799/// location. It is a helper routine for GetType, which deals with reading type
5800/// IDs.
5801QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005802 assert(ContextObj && "reading type with no AST context");
5803 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005804 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005805 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005806
5807 // Keep track of where we are in the stream, then jump back there
5808 // after reading this type.
5809 SavedStreamPosition SavedPosition(DeclsCursor);
5810
5811 ReadingKindTracker ReadingKind(Read_Type, *this);
5812
5813 // Note that we are loading a type record.
5814 Deserializing AType(this);
5815
5816 unsigned Idx = 0;
5817 DeclsCursor.JumpToBit(Loc.Offset);
5818 RecordData Record;
5819 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005820 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 case TYPE_EXT_QUAL: {
5822 if (Record.size() != 2) {
5823 Error("Incorrect encoding of extended qualifier type");
5824 return QualType();
5825 }
5826 QualType Base = readType(*Loc.F, Record, Idx);
5827 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5828 return Context.getQualifiedType(Base, Quals);
5829 }
5830
5831 case TYPE_COMPLEX: {
5832 if (Record.size() != 1) {
5833 Error("Incorrect encoding of complex type");
5834 return QualType();
5835 }
5836 QualType ElemType = readType(*Loc.F, Record, Idx);
5837 return Context.getComplexType(ElemType);
5838 }
5839
5840 case TYPE_POINTER: {
5841 if (Record.size() != 1) {
5842 Error("Incorrect encoding of pointer type");
5843 return QualType();
5844 }
5845 QualType PointeeType = readType(*Loc.F, Record, Idx);
5846 return Context.getPointerType(PointeeType);
5847 }
5848
Reid Kleckner8a365022013-06-24 17:51:48 +00005849 case TYPE_DECAYED: {
5850 if (Record.size() != 1) {
5851 Error("Incorrect encoding of decayed type");
5852 return QualType();
5853 }
5854 QualType OriginalType = readType(*Loc.F, Record, Idx);
5855 QualType DT = Context.getAdjustedParameterType(OriginalType);
5856 if (!isa<DecayedType>(DT))
5857 Error("Decayed type does not decay");
5858 return DT;
5859 }
5860
Reid Kleckner0503a872013-12-05 01:23:43 +00005861 case TYPE_ADJUSTED: {
5862 if (Record.size() != 2) {
5863 Error("Incorrect encoding of adjusted type");
5864 return QualType();
5865 }
5866 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5867 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5868 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5869 }
5870
Guy Benyei11169dd2012-12-18 14:30:41 +00005871 case TYPE_BLOCK_POINTER: {
5872 if (Record.size() != 1) {
5873 Error("Incorrect encoding of block pointer type");
5874 return QualType();
5875 }
5876 QualType PointeeType = readType(*Loc.F, Record, Idx);
5877 return Context.getBlockPointerType(PointeeType);
5878 }
5879
5880 case TYPE_LVALUE_REFERENCE: {
5881 if (Record.size() != 2) {
5882 Error("Incorrect encoding of lvalue reference type");
5883 return QualType();
5884 }
5885 QualType PointeeType = readType(*Loc.F, Record, Idx);
5886 return Context.getLValueReferenceType(PointeeType, Record[1]);
5887 }
5888
5889 case TYPE_RVALUE_REFERENCE: {
5890 if (Record.size() != 1) {
5891 Error("Incorrect encoding of rvalue reference type");
5892 return QualType();
5893 }
5894 QualType PointeeType = readType(*Loc.F, Record, Idx);
5895 return Context.getRValueReferenceType(PointeeType);
5896 }
5897
5898 case TYPE_MEMBER_POINTER: {
5899 if (Record.size() != 2) {
5900 Error("Incorrect encoding of member pointer type");
5901 return QualType();
5902 }
5903 QualType PointeeType = readType(*Loc.F, Record, Idx);
5904 QualType ClassType = readType(*Loc.F, Record, Idx);
5905 if (PointeeType.isNull() || ClassType.isNull())
5906 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005907
Guy Benyei11169dd2012-12-18 14:30:41 +00005908 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5909 }
5910
5911 case TYPE_CONSTANT_ARRAY: {
5912 QualType ElementType = readType(*Loc.F, Record, Idx);
5913 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5914 unsigned IndexTypeQuals = Record[2];
5915 unsigned Idx = 3;
5916 llvm::APInt Size = ReadAPInt(Record, Idx);
5917 return Context.getConstantArrayType(ElementType, Size,
5918 ASM, IndexTypeQuals);
5919 }
5920
5921 case TYPE_INCOMPLETE_ARRAY: {
5922 QualType ElementType = readType(*Loc.F, Record, Idx);
5923 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5924 unsigned IndexTypeQuals = Record[2];
5925 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5926 }
5927
5928 case TYPE_VARIABLE_ARRAY: {
5929 QualType ElementType = readType(*Loc.F, Record, Idx);
5930 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5931 unsigned IndexTypeQuals = Record[2];
5932 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5933 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5934 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5935 ASM, IndexTypeQuals,
5936 SourceRange(LBLoc, RBLoc));
5937 }
5938
5939 case TYPE_VECTOR: {
5940 if (Record.size() != 3) {
5941 Error("incorrect encoding of vector type in AST file");
5942 return QualType();
5943 }
5944
5945 QualType ElementType = readType(*Loc.F, Record, Idx);
5946 unsigned NumElements = Record[1];
5947 unsigned VecKind = Record[2];
5948 return Context.getVectorType(ElementType, NumElements,
5949 (VectorType::VectorKind)VecKind);
5950 }
5951
5952 case TYPE_EXT_VECTOR: {
5953 if (Record.size() != 3) {
5954 Error("incorrect encoding of extended vector type in AST file");
5955 return QualType();
5956 }
5957
5958 QualType ElementType = readType(*Loc.F, Record, Idx);
5959 unsigned NumElements = Record[1];
5960 return Context.getExtVectorType(ElementType, NumElements);
5961 }
5962
5963 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005964 if (Record.size() != 7) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005965 Error("incorrect encoding of no-proto function type");
5966 return QualType();
5967 }
5968 QualType ResultType = readType(*Loc.F, Record, Idx);
5969 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005970 (CallingConv)Record[4], Record[5], Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005971 return Context.getFunctionNoProtoType(ResultType, Info);
5972 }
5973
5974 case TYPE_FUNCTION_PROTO: {
5975 QualType ResultType = readType(*Loc.F, Record, Idx);
5976
5977 FunctionProtoType::ExtProtoInfo EPI;
5978 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5979 /*hasregparm*/ Record[2],
5980 /*regparm*/ Record[3],
5981 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005982 /*produces*/ Record[5],
5983 /*nocallersavedregs*/ Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005984
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005985 unsigned Idx = 7;
Guy Benyei11169dd2012-12-18 14:30:41 +00005986
5987 EPI.Variadic = Record[Idx++];
5988 EPI.HasTrailingReturn = Record[Idx++];
5989 EPI.TypeQuals = Record[Idx++];
5990 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005991 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005992 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005993
5994 unsigned NumParams = Record[Idx++];
5995 SmallVector<QualType, 16> ParamTypes;
5996 for (unsigned I = 0; I != NumParams; ++I)
5997 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5998
John McCall18afab72016-03-01 00:49:02 +00005999 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6000 if (Idx != Record.size()) {
6001 for (unsigned I = 0; I != NumParams; ++I)
6002 ExtParameterInfos.push_back(
6003 FunctionProtoType::ExtParameterInfo
6004 ::getFromOpaqueValue(Record[Idx++]));
6005 EPI.ExtParameterInfos = ExtParameterInfos.data();
6006 }
6007
6008 assert(Idx == Record.size());
6009
Jordan Rose5c382722013-03-08 21:51:21 +00006010 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006011 }
6012
6013 case TYPE_UNRESOLVED_USING: {
6014 unsigned Idx = 0;
6015 return Context.getTypeDeclType(
6016 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6017 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006018
Guy Benyei11169dd2012-12-18 14:30:41 +00006019 case TYPE_TYPEDEF: {
6020 if (Record.size() != 2) {
6021 Error("incorrect encoding of typedef type");
6022 return QualType();
6023 }
6024 unsigned Idx = 0;
6025 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
6026 QualType Canonical = readType(*Loc.F, Record, Idx);
6027 if (!Canonical.isNull())
6028 Canonical = Context.getCanonicalType(Canonical);
6029 return Context.getTypedefType(Decl, Canonical);
6030 }
6031
6032 case TYPE_TYPEOF_EXPR:
6033 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6034
6035 case TYPE_TYPEOF: {
6036 if (Record.size() != 1) {
6037 Error("incorrect encoding of typeof(type) in AST file");
6038 return QualType();
6039 }
6040 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6041 return Context.getTypeOfType(UnderlyingType);
6042 }
6043
6044 case TYPE_DECLTYPE: {
6045 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6046 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6047 }
6048
6049 case TYPE_UNARY_TRANSFORM: {
6050 QualType BaseType = readType(*Loc.F, Record, Idx);
6051 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6052 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
6053 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6054 }
6055
Richard Smith74aeef52013-04-26 16:15:35 +00006056 case TYPE_AUTO: {
6057 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00006058 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00006059 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00006060 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00006061 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006062
Richard Smith600b5262017-01-26 20:40:47 +00006063 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6064 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6065 QualType Deduced = readType(*Loc.F, Record, Idx);
6066 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6067 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6068 IsDependent);
6069 }
6070
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 case TYPE_RECORD: {
6072 if (Record.size() != 2) {
6073 Error("incorrect encoding of record type");
6074 return QualType();
6075 }
6076 unsigned Idx = 0;
6077 bool IsDependent = Record[Idx++];
6078 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
6079 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6080 QualType T = Context.getRecordType(RD);
6081 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6082 return T;
6083 }
6084
6085 case TYPE_ENUM: {
6086 if (Record.size() != 2) {
6087 Error("incorrect encoding of enum type");
6088 return QualType();
6089 }
6090 unsigned Idx = 0;
6091 bool IsDependent = Record[Idx++];
6092 QualType T
6093 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6094 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6095 return T;
6096 }
6097
6098 case TYPE_ATTRIBUTED: {
6099 if (Record.size() != 3) {
6100 Error("incorrect encoding of attributed type");
6101 return QualType();
6102 }
6103 QualType modifiedType = readType(*Loc.F, Record, Idx);
6104 QualType equivalentType = readType(*Loc.F, Record, Idx);
6105 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
6106 return Context.getAttributedType(kind, modifiedType, equivalentType);
6107 }
6108
6109 case TYPE_PAREN: {
6110 if (Record.size() != 1) {
6111 Error("incorrect encoding of paren type");
6112 return QualType();
6113 }
6114 QualType InnerType = readType(*Loc.F, Record, Idx);
6115 return Context.getParenType(InnerType);
6116 }
6117
6118 case TYPE_PACK_EXPANSION: {
6119 if (Record.size() != 2) {
6120 Error("incorrect encoding of pack expansion type");
6121 return QualType();
6122 }
6123 QualType Pattern = readType(*Loc.F, Record, Idx);
6124 if (Pattern.isNull())
6125 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006126 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 if (Record[1])
6128 NumExpansions = Record[1] - 1;
6129 return Context.getPackExpansionType(Pattern, NumExpansions);
6130 }
6131
6132 case TYPE_ELABORATED: {
6133 unsigned Idx = 0;
6134 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6135 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6136 QualType NamedType = readType(*Loc.F, Record, Idx);
6137 return Context.getElaboratedType(Keyword, NNS, NamedType);
6138 }
6139
6140 case TYPE_OBJC_INTERFACE: {
6141 unsigned Idx = 0;
6142 ObjCInterfaceDecl *ItfD
6143 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6144 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6145 }
6146
Manman Rene6be26c2016-09-13 17:25:08 +00006147 case TYPE_OBJC_TYPE_PARAM: {
6148 unsigned Idx = 0;
6149 ObjCTypeParamDecl *Decl
6150 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6151 unsigned NumProtos = Record[Idx++];
6152 SmallVector<ObjCProtocolDecl*, 4> Protos;
6153 for (unsigned I = 0; I != NumProtos; ++I)
6154 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6155 return Context.getObjCTypeParamType(Decl, Protos);
6156 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006157
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 case TYPE_OBJC_OBJECT: {
6159 unsigned Idx = 0;
6160 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006161 unsigned NumTypeArgs = Record[Idx++];
6162 SmallVector<QualType, 4> TypeArgs;
6163 for (unsigned I = 0; I != NumTypeArgs; ++I)
6164 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 unsigned NumProtos = Record[Idx++];
6166 SmallVector<ObjCProtocolDecl*, 4> Protos;
6167 for (unsigned I = 0; I != NumProtos; ++I)
6168 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006169 bool IsKindOf = Record[Idx++];
6170 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 }
6172
6173 case TYPE_OBJC_OBJECT_POINTER: {
6174 unsigned Idx = 0;
6175 QualType Pointee = readType(*Loc.F, Record, Idx);
6176 return Context.getObjCObjectPointerType(Pointee);
6177 }
6178
6179 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6180 unsigned Idx = 0;
6181 QualType Parm = readType(*Loc.F, Record, Idx);
6182 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006183 return Context.getSubstTemplateTypeParmType(
6184 cast<TemplateTypeParmType>(Parm),
6185 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006186 }
6187
6188 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6189 unsigned Idx = 0;
6190 QualType Parm = readType(*Loc.F, Record, Idx);
6191 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6192 return Context.getSubstTemplateTypeParmPackType(
6193 cast<TemplateTypeParmType>(Parm),
6194 ArgPack);
6195 }
6196
6197 case TYPE_INJECTED_CLASS_NAME: {
6198 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6199 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6200 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6201 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006202 const Type *T = nullptr;
6203 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6204 if (const Type *Existing = DI->getTypeForDecl()) {
6205 T = Existing;
6206 break;
6207 }
6208 }
6209 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006210 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006211 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6212 DI->setTypeForDecl(T);
6213 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006214 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006215 }
6216
6217 case TYPE_TEMPLATE_TYPE_PARM: {
6218 unsigned Idx = 0;
6219 unsigned Depth = Record[Idx++];
6220 unsigned Index = Record[Idx++];
6221 bool Pack = Record[Idx++];
6222 TemplateTypeParmDecl *D
6223 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6224 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6225 }
6226
6227 case TYPE_DEPENDENT_NAME: {
6228 unsigned Idx = 0;
6229 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6230 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006231 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006232 QualType Canon = readType(*Loc.F, Record, Idx);
6233 if (!Canon.isNull())
6234 Canon = Context.getCanonicalType(Canon);
6235 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6236 }
6237
6238 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6239 unsigned Idx = 0;
6240 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6241 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006242 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006243 unsigned NumArgs = Record[Idx++];
6244 SmallVector<TemplateArgument, 8> Args;
6245 Args.reserve(NumArgs);
6246 while (NumArgs--)
6247 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6248 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006249 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006250 }
6251
6252 case TYPE_DEPENDENT_SIZED_ARRAY: {
6253 unsigned Idx = 0;
6254
6255 // ArrayType
6256 QualType ElementType = readType(*Loc.F, Record, Idx);
6257 ArrayType::ArraySizeModifier ASM
6258 = (ArrayType::ArraySizeModifier)Record[Idx++];
6259 unsigned IndexTypeQuals = Record[Idx++];
6260
6261 // DependentSizedArrayType
6262 Expr *NumElts = ReadExpr(*Loc.F);
6263 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6264
6265 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6266 IndexTypeQuals, Brackets);
6267 }
6268
6269 case TYPE_TEMPLATE_SPECIALIZATION: {
6270 unsigned Idx = 0;
6271 bool IsDependent = Record[Idx++];
6272 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6273 SmallVector<TemplateArgument, 8> Args;
6274 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6275 QualType Underlying = readType(*Loc.F, Record, Idx);
6276 QualType T;
6277 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006278 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006279 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006280 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6282 return T;
6283 }
6284
6285 case TYPE_ATOMIC: {
6286 if (Record.size() != 1) {
6287 Error("Incorrect encoding of atomic type");
6288 return QualType();
6289 }
6290 QualType ValueType = readType(*Loc.F, Record, Idx);
6291 return Context.getAtomicType(ValueType);
6292 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006293
Joey Goulye3c85de2016-12-01 11:30:49 +00006294 case TYPE_PIPE: {
6295 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006296 Error("Incorrect encoding of pipe type");
6297 return QualType();
6298 }
6299
6300 // Reading the pipe element type.
6301 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006302 unsigned ReadOnly = Record[1];
6303 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006304 }
6305
Alex Lorenz00aee432017-03-22 10:04:48 +00006306 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6307 unsigned Idx = 0;
6308
6309 // DependentSizedExtVectorType
6310 QualType ElementType = readType(*Loc.F, Record, Idx);
6311 Expr *SizeExpr = ReadExpr(*Loc.F);
6312 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6313
6314 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6315 AttrLoc);
6316 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006317
6318 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6319 unsigned Idx = 0;
6320
6321 // DependentAddressSpaceType
6322 QualType PointeeType = readType(*Loc.F, Record, Idx);
6323 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6324 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6325
6326 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6327 AttrLoc);
6328 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006329 }
6330 llvm_unreachable("Invalid TypeCode!");
6331}
6332
Richard Smith564417a2014-03-20 21:47:22 +00006333void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6334 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006335 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006336 const RecordData &Record, unsigned &Idx) {
6337 ExceptionSpecificationType EST =
6338 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006339 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006340 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006341 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006342 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006343 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006344 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006345 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006346 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006347 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6348 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006349 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006350 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006351 }
6352}
6353
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006354namespace clang {
6355
6356class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006357 ModuleFile *F;
6358 ASTReader *Reader;
6359 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006360 unsigned &Idx;
6361
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006362 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006363 return Reader->ReadSourceLocation(*F, Record, Idx);
6364 }
6365
6366 TypeSourceInfo *GetTypeSourceInfo() {
6367 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6368 }
6369
6370 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6371 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 }
6373
Guy Benyei11169dd2012-12-18 14:30:41 +00006374public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006375 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006376 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006377 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006378
6379 // We want compile-time assurance that we've enumerated all of
6380 // these, so unfortunately we have to declare them first, then
6381 // define them out-of-line.
6382#define ABSTRACT_TYPELOC(CLASS, PARENT)
6383#define TYPELOC(CLASS, PARENT) \
6384 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6385#include "clang/AST/TypeLocNodes.def"
6386
6387 void VisitFunctionTypeLoc(FunctionTypeLoc);
6388 void VisitArrayTypeLoc(ArrayTypeLoc);
6389};
6390
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006391} // namespace clang
6392
Guy Benyei11169dd2012-12-18 14:30:41 +00006393void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6394 // nothing to do
6395}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006396
Guy Benyei11169dd2012-12-18 14:30:41 +00006397void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006398 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006399 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006400 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6401 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6402 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6403 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 }
6405}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006406
Guy Benyei11169dd2012-12-18 14:30:41 +00006407void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006408 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006409}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006410
Guy Benyei11169dd2012-12-18 14:30:41 +00006411void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006412 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006413}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006414
Reid Kleckner8a365022013-06-24 17:51:48 +00006415void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6416 // nothing to do
6417}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006418
Reid Kleckner0503a872013-12-05 01:23:43 +00006419void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6420 // nothing to do
6421}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006422
Guy Benyei11169dd2012-12-18 14:30:41 +00006423void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006424 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006425}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006426
Guy Benyei11169dd2012-12-18 14:30:41 +00006427void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006428 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006429}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006430
Guy Benyei11169dd2012-12-18 14:30:41 +00006431void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006432 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006433}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006434
Guy Benyei11169dd2012-12-18 14:30:41 +00006435void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006436 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006437 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006438}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006439
Guy Benyei11169dd2012-12-18 14:30:41 +00006440void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006441 TL.setLBracketLoc(ReadSourceLocation());
6442 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006443 if (Record[Idx++])
6444 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006445 else
Craig Toppera13603a2014-05-22 05:54:18 +00006446 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006447}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006448
Guy Benyei11169dd2012-12-18 14:30:41 +00006449void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6450 VisitArrayTypeLoc(TL);
6451}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006452
Guy Benyei11169dd2012-12-18 14:30:41 +00006453void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6454 VisitArrayTypeLoc(TL);
6455}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006456
Guy Benyei11169dd2012-12-18 14:30:41 +00006457void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6458 VisitArrayTypeLoc(TL);
6459}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006460
Guy Benyei11169dd2012-12-18 14:30:41 +00006461void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6462 DependentSizedArrayTypeLoc TL) {
6463 VisitArrayTypeLoc(TL);
6464}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006465
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006466void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6467 DependentAddressSpaceTypeLoc TL) {
6468
6469 TL.setAttrNameLoc(ReadSourceLocation());
6470 SourceRange range;
6471 range.setBegin(ReadSourceLocation());
6472 range.setEnd(ReadSourceLocation());
6473 TL.setAttrOperandParensRange(range);
6474 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6475}
6476
Guy Benyei11169dd2012-12-18 14:30:41 +00006477void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6478 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006479 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006480}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006481
Guy Benyei11169dd2012-12-18 14:30:41 +00006482void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006483 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006484}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006485
Guy Benyei11169dd2012-12-18 14:30:41 +00006486void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006487 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006488}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006489
Guy Benyei11169dd2012-12-18 14:30:41 +00006490void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006491 TL.setLocalRangeBegin(ReadSourceLocation());
6492 TL.setLParenLoc(ReadSourceLocation());
6493 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006494 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6495 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006496 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006497 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006498 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006499 }
6500}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006501
Guy Benyei11169dd2012-12-18 14:30:41 +00006502void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6503 VisitFunctionTypeLoc(TL);
6504}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006505
Guy Benyei11169dd2012-12-18 14:30:41 +00006506void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6507 VisitFunctionTypeLoc(TL);
6508}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006509
Guy Benyei11169dd2012-12-18 14:30:41 +00006510void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006511 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006512}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006513
Guy Benyei11169dd2012-12-18 14:30:41 +00006514void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006515 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006516}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006517
Guy Benyei11169dd2012-12-18 14:30:41 +00006518void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006519 TL.setTypeofLoc(ReadSourceLocation());
6520 TL.setLParenLoc(ReadSourceLocation());
6521 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006522}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006523
Guy Benyei11169dd2012-12-18 14:30:41 +00006524void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006525 TL.setTypeofLoc(ReadSourceLocation());
6526 TL.setLParenLoc(ReadSourceLocation());
6527 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006528 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006529}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006530
Guy Benyei11169dd2012-12-18 14:30:41 +00006531void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006532 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006533}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006534
Guy Benyei11169dd2012-12-18 14:30:41 +00006535void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006536 TL.setKWLoc(ReadSourceLocation());
6537 TL.setLParenLoc(ReadSourceLocation());
6538 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006539 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006540}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006541
Guy Benyei11169dd2012-12-18 14:30:41 +00006542void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006543 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006544}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006545
Richard Smith600b5262017-01-26 20:40:47 +00006546void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6547 DeducedTemplateSpecializationTypeLoc TL) {
6548 TL.setTemplateNameLoc(ReadSourceLocation());
6549}
6550
Guy Benyei11169dd2012-12-18 14:30:41 +00006551void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006552 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006553}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006554
Guy Benyei11169dd2012-12-18 14:30:41 +00006555void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006556 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006557}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006558
Guy Benyei11169dd2012-12-18 14:30:41 +00006559void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006560 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006561 if (TL.hasAttrOperand()) {
6562 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006563 range.setBegin(ReadSourceLocation());
6564 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 TL.setAttrOperandParensRange(range);
6566 }
6567 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006568 if (Record[Idx++])
6569 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006570 else
Craig Toppera13603a2014-05-22 05:54:18 +00006571 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006572 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006573 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006574}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006575
Guy Benyei11169dd2012-12-18 14:30:41 +00006576void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006577 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006578}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006579
Guy Benyei11169dd2012-12-18 14:30:41 +00006580void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6581 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006582 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006583}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006584
Guy Benyei11169dd2012-12-18 14:30:41 +00006585void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6586 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006587 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006588}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006589
Guy Benyei11169dd2012-12-18 14:30:41 +00006590void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6591 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006592 TL.setTemplateKeywordLoc(ReadSourceLocation());
6593 TL.setTemplateNameLoc(ReadSourceLocation());
6594 TL.setLAngleLoc(ReadSourceLocation());
6595 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006596 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006597 TL.setArgLocInfo(
6598 i,
6599 Reader->GetTemplateArgumentLocInfo(
6600 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006601}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006602
Guy Benyei11169dd2012-12-18 14:30:41 +00006603void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006604 TL.setLParenLoc(ReadSourceLocation());
6605 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006606}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006607
Guy Benyei11169dd2012-12-18 14:30:41 +00006608void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006609 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006610 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006611}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006612
Guy Benyei11169dd2012-12-18 14:30:41 +00006613void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006614 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006615}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006616
Guy Benyei11169dd2012-12-18 14:30:41 +00006617void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006618 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006619 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006620 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006621}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006622
Guy Benyei11169dd2012-12-18 14:30:41 +00006623void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6624 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006625 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006626 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006627 TL.setTemplateKeywordLoc(ReadSourceLocation());
6628 TL.setTemplateNameLoc(ReadSourceLocation());
6629 TL.setLAngleLoc(ReadSourceLocation());
6630 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006631 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006632 TL.setArgLocInfo(
6633 I,
6634 Reader->GetTemplateArgumentLocInfo(
6635 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006636}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006637
Guy Benyei11169dd2012-12-18 14:30:41 +00006638void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006639 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006640}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006641
Guy Benyei11169dd2012-12-18 14:30:41 +00006642void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006643 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006644}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006645
Manman Rene6be26c2016-09-13 17:25:08 +00006646void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6647 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006648 TL.setProtocolLAngleLoc(ReadSourceLocation());
6649 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006650 }
6651 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006652 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006653}
6654
Guy Benyei11169dd2012-12-18 14:30:41 +00006655void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006656 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006657 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6658 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006659 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006660 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006661 TL.setProtocolLAngleLoc(ReadSourceLocation());
6662 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006663 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006664 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006665}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006666
Guy Benyei11169dd2012-12-18 14:30:41 +00006667void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006668 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006669}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006670
Guy Benyei11169dd2012-12-18 14:30:41 +00006671void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006672 TL.setKWLoc(ReadSourceLocation());
6673 TL.setLParenLoc(ReadSourceLocation());
6674 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006675}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006676
Xiuli Pan9c14e282016-01-09 12:53:17 +00006677void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006678 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006679}
Guy Benyei11169dd2012-12-18 14:30:41 +00006680
David L. Jonesbe1557a2016-12-21 00:17:49 +00006681TypeSourceInfo *
6682ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6683 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006684 QualType InfoTy = readType(F, Record, Idx);
6685 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006686 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006687
6688 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006689 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006690 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6691 TLR.Visit(TL);
6692 return TInfo;
6693}
6694
6695QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006696 assert(ContextObj && "reading type with no AST context");
6697 ASTContext &Context = *ContextObj;
6698
Guy Benyei11169dd2012-12-18 14:30:41 +00006699 unsigned FastQuals = ID & Qualifiers::FastMask;
6700 unsigned Index = ID >> Qualifiers::FastWidth;
6701
6702 if (Index < NUM_PREDEF_TYPE_IDS) {
6703 QualType T;
6704 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006705 case PREDEF_TYPE_NULL_ID:
6706 return QualType();
6707 case PREDEF_TYPE_VOID_ID:
6708 T = Context.VoidTy;
6709 break;
6710 case PREDEF_TYPE_BOOL_ID:
6711 T = Context.BoolTy;
6712 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006713 case PREDEF_TYPE_CHAR_U_ID:
6714 case PREDEF_TYPE_CHAR_S_ID:
6715 // FIXME: Check that the signedness of CharTy is correct!
6716 T = Context.CharTy;
6717 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006718 case PREDEF_TYPE_UCHAR_ID:
6719 T = Context.UnsignedCharTy;
6720 break;
6721 case PREDEF_TYPE_USHORT_ID:
6722 T = Context.UnsignedShortTy;
6723 break;
6724 case PREDEF_TYPE_UINT_ID:
6725 T = Context.UnsignedIntTy;
6726 break;
6727 case PREDEF_TYPE_ULONG_ID:
6728 T = Context.UnsignedLongTy;
6729 break;
6730 case PREDEF_TYPE_ULONGLONG_ID:
6731 T = Context.UnsignedLongLongTy;
6732 break;
6733 case PREDEF_TYPE_UINT128_ID:
6734 T = Context.UnsignedInt128Ty;
6735 break;
6736 case PREDEF_TYPE_SCHAR_ID:
6737 T = Context.SignedCharTy;
6738 break;
6739 case PREDEF_TYPE_WCHAR_ID:
6740 T = Context.WCharTy;
6741 break;
6742 case PREDEF_TYPE_SHORT_ID:
6743 T = Context.ShortTy;
6744 break;
6745 case PREDEF_TYPE_INT_ID:
6746 T = Context.IntTy;
6747 break;
6748 case PREDEF_TYPE_LONG_ID:
6749 T = Context.LongTy;
6750 break;
6751 case PREDEF_TYPE_LONGLONG_ID:
6752 T = Context.LongLongTy;
6753 break;
6754 case PREDEF_TYPE_INT128_ID:
6755 T = Context.Int128Ty;
6756 break;
6757 case PREDEF_TYPE_HALF_ID:
6758 T = Context.HalfTy;
6759 break;
6760 case PREDEF_TYPE_FLOAT_ID:
6761 T = Context.FloatTy;
6762 break;
6763 case PREDEF_TYPE_DOUBLE_ID:
6764 T = Context.DoubleTy;
6765 break;
6766 case PREDEF_TYPE_LONGDOUBLE_ID:
6767 T = Context.LongDoubleTy;
6768 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006769 case PREDEF_TYPE_FLOAT16_ID:
6770 T = Context.Float16Ty;
6771 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006772 case PREDEF_TYPE_FLOAT128_ID:
6773 T = Context.Float128Ty;
6774 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006775 case PREDEF_TYPE_OVERLOAD_ID:
6776 T = Context.OverloadTy;
6777 break;
6778 case PREDEF_TYPE_BOUND_MEMBER:
6779 T = Context.BoundMemberTy;
6780 break;
6781 case PREDEF_TYPE_PSEUDO_OBJECT:
6782 T = Context.PseudoObjectTy;
6783 break;
6784 case PREDEF_TYPE_DEPENDENT_ID:
6785 T = Context.DependentTy;
6786 break;
6787 case PREDEF_TYPE_UNKNOWN_ANY:
6788 T = Context.UnknownAnyTy;
6789 break;
6790 case PREDEF_TYPE_NULLPTR_ID:
6791 T = Context.NullPtrTy;
6792 break;
6793 case PREDEF_TYPE_CHAR16_ID:
6794 T = Context.Char16Ty;
6795 break;
6796 case PREDEF_TYPE_CHAR32_ID:
6797 T = Context.Char32Ty;
6798 break;
6799 case PREDEF_TYPE_OBJC_ID:
6800 T = Context.ObjCBuiltinIdTy;
6801 break;
6802 case PREDEF_TYPE_OBJC_CLASS:
6803 T = Context.ObjCBuiltinClassTy;
6804 break;
6805 case PREDEF_TYPE_OBJC_SEL:
6806 T = Context.ObjCBuiltinSelTy;
6807 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006808#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6809 case PREDEF_TYPE_##Id##_ID: \
6810 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006811 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006812#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006813 case PREDEF_TYPE_SAMPLER_ID:
6814 T = Context.OCLSamplerTy;
6815 break;
6816 case PREDEF_TYPE_EVENT_ID:
6817 T = Context.OCLEventTy;
6818 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006819 case PREDEF_TYPE_CLK_EVENT_ID:
6820 T = Context.OCLClkEventTy;
6821 break;
6822 case PREDEF_TYPE_QUEUE_ID:
6823 T = Context.OCLQueueTy;
6824 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006825 case PREDEF_TYPE_RESERVE_ID_ID:
6826 T = Context.OCLReserveIDTy;
6827 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006828 case PREDEF_TYPE_AUTO_DEDUCT:
6829 T = Context.getAutoDeductType();
6830 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006831 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6832 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006833 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006834 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6835 T = Context.ARCUnbridgedCastTy;
6836 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006837 case PREDEF_TYPE_BUILTIN_FN:
6838 T = Context.BuiltinFnTy;
6839 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006840 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6841 T = Context.OMPArraySectionTy;
6842 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006843 }
6844
6845 assert(!T.isNull() && "Unknown predefined type");
6846 return T.withFastQualifiers(FastQuals);
6847 }
6848
6849 Index -= NUM_PREDEF_TYPE_IDS;
6850 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6851 if (TypesLoaded[Index].isNull()) {
6852 TypesLoaded[Index] = readTypeRecord(Index);
6853 if (TypesLoaded[Index].isNull())
6854 return QualType();
6855
6856 TypesLoaded[Index]->setFromAST();
6857 if (DeserializationListener)
6858 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6859 TypesLoaded[Index]);
6860 }
6861
6862 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6863}
6864
6865QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6866 return GetType(getGlobalTypeID(F, LocalID));
6867}
6868
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006869serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006870ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6871 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6872 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006873
Guy Benyei11169dd2012-12-18 14:30:41 +00006874 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6875 return LocalID;
6876
Richard Smith37a93df2017-02-18 00:32:02 +00006877 if (!F.ModuleOffsetMap.empty())
6878 ReadModuleOffsetMap(F);
6879
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6881 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6882 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006883
Guy Benyei11169dd2012-12-18 14:30:41 +00006884 unsigned GlobalIndex = LocalIndex + I->second;
6885 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6886}
6887
6888TemplateArgumentLocInfo
6889ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6890 TemplateArgument::ArgKind Kind,
6891 const RecordData &Record,
6892 unsigned &Index) {
6893 switch (Kind) {
6894 case TemplateArgument::Expression:
6895 return ReadExpr(F);
6896 case TemplateArgument::Type:
6897 return GetTypeSourceInfo(F, Record, Index);
6898 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006899 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006900 Index);
6901 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6902 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6903 SourceLocation());
6904 }
6905 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006906 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 Index);
6908 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6909 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006910 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006911 EllipsisLoc);
6912 }
6913 case TemplateArgument::Null:
6914 case TemplateArgument::Integral:
6915 case TemplateArgument::Declaration:
6916 case TemplateArgument::NullPtr:
6917 case TemplateArgument::Pack:
6918 // FIXME: Is this right?
6919 return TemplateArgumentLocInfo();
6920 }
6921 llvm_unreachable("unexpected template argument loc");
6922}
6923
6924TemplateArgumentLoc
6925ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6926 const RecordData &Record, unsigned &Index) {
6927 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6928
6929 if (Arg.getKind() == TemplateArgument::Expression) {
6930 if (Record[Index++]) // bool InfoHasSameExpr.
6931 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6932 }
6933 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6934 Record, Index));
6935}
6936
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006937const ASTTemplateArgumentListInfo*
6938ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6939 const RecordData &Record,
6940 unsigned &Index) {
6941 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6942 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6943 unsigned NumArgsAsWritten = Record[Index++];
6944 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6945 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6946 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6947 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6948}
6949
Guy Benyei11169dd2012-12-18 14:30:41 +00006950Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6951 return GetDecl(ID);
6952}
6953
Richard Smith053f6c62014-05-16 23:01:30 +00006954void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006955 if (NumCurrentElementsDeserializing) {
6956 // We arrange to not care about the complete redeclaration chain while we're
6957 // deserializing. Just remember that the AST has marked this one as complete
6958 // but that it's not actually complete yet, so we know we still need to
6959 // complete it later.
6960 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6961 return;
6962 }
6963
Richard Smith053f6c62014-05-16 23:01:30 +00006964 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6965
Richard Smith053f6c62014-05-16 23:01:30 +00006966 // If this is a named declaration, complete it by looking it up
6967 // within its context.
6968 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006969 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006970 // all mergeable entities within it.
6971 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6972 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6973 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006974 if (!getContext().getLangOpts().CPlusPlus &&
6975 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006976 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006977 // the identifier instead. (For C++ modules, we don't store decls
6978 // in the serialized identifier table, so we do the lookup in the TU.)
6979 auto *II = Name.getAsIdentifierInfo();
6980 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006981 if (II->isOutOfDate())
6982 updateOutOfDateIdentifier(*II);
6983 } else
6984 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006985 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006986 // Find all declarations of this kind from the relevant context.
6987 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6988 auto *DC = cast<DeclContext>(DCDecl);
6989 SmallVector<Decl*, 8> Decls;
6990 FindExternalLexicalDecls(
6991 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6992 }
Richard Smith053f6c62014-05-16 23:01:30 +00006993 }
6994 }
Richard Smith50895422015-01-31 03:04:55 +00006995
6996 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6997 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6998 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6999 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7000 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7001 if (auto *Template = FD->getPrimaryTemplate())
7002 Template->LoadLazySpecializations();
7003 }
Richard Smith053f6c62014-05-16 23:01:30 +00007004}
7005
Richard Smithc2bb8182015-03-24 06:36:48 +00007006CXXCtorInitializer **
7007ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7008 RecordLocation Loc = getLocalBitOffset(Offset);
7009 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7010 SavedStreamPosition SavedPosition(Cursor);
7011 Cursor.JumpToBit(Loc.Offset);
7012 ReadingKindTracker ReadingKind(Read_Decl, *this);
7013
7014 RecordData Record;
7015 unsigned Code = Cursor.ReadCode();
7016 unsigned RecCode = Cursor.readRecord(Code, Record);
7017 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
7018 Error("malformed AST file: missing C++ ctor initializers");
7019 return nullptr;
7020 }
7021
7022 unsigned Idx = 0;
7023 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7024}
7025
Guy Benyei11169dd2012-12-18 14:30:41 +00007026CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007027 assert(ContextObj && "reading base specifiers with no AST context");
7028 ASTContext &Context = *ContextObj;
7029
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007031 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 SavedStreamPosition SavedPosition(Cursor);
7033 Cursor.JumpToBit(Loc.Offset);
7034 ReadingKindTracker ReadingKind(Read_Decl, *this);
7035 RecordData Record;
7036 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007037 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00007038 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007039 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007040 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007041 }
7042
7043 unsigned Idx = 0;
7044 unsigned NumBases = Record[Idx++];
7045 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7046 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7047 for (unsigned I = 0; I != NumBases; ++I)
7048 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7049 return Bases;
7050}
7051
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007052serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007053ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7054 if (LocalID < NUM_PREDEF_DECL_IDS)
7055 return LocalID;
7056
Richard Smith37a93df2017-02-18 00:32:02 +00007057 if (!F.ModuleOffsetMap.empty())
7058 ReadModuleOffsetMap(F);
7059
Guy Benyei11169dd2012-12-18 14:30:41 +00007060 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7061 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7062 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007063
Guy Benyei11169dd2012-12-18 14:30:41 +00007064 return LocalID + I->second;
7065}
7066
7067bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7068 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007069 // Predefined decls aren't from any module.
7070 if (ID < NUM_PREDEF_DECL_IDS)
7071 return false;
7072
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007073 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007074 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007075}
7076
Douglas Gregor9f782892013-01-21 15:25:38 +00007077ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007078 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007079 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007080 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7081 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7082 return I->second;
7083}
7084
7085SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7086 if (ID < NUM_PREDEF_DECL_IDS)
7087 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007088
Guy Benyei11169dd2012-12-18 14:30:41 +00007089 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7090
7091 if (Index > DeclsLoaded.size()) {
7092 Error("declaration ID out-of-range for AST file");
7093 return SourceLocation();
7094 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007095
Guy Benyei11169dd2012-12-18 14:30:41 +00007096 if (Decl *D = DeclsLoaded[Index])
7097 return D->getLocation();
7098
Richard Smithcb34bd32016-03-27 07:28:06 +00007099 SourceLocation Loc;
7100 DeclCursorForID(ID, Loc);
7101 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007102}
7103
Richard Smithfe620d22015-03-05 23:24:12 +00007104static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7105 switch (ID) {
7106 case PREDEF_DECL_NULL_ID:
7107 return nullptr;
7108
7109 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7110 return Context.getTranslationUnitDecl();
7111
7112 case PREDEF_DECL_OBJC_ID_ID:
7113 return Context.getObjCIdDecl();
7114
7115 case PREDEF_DECL_OBJC_SEL_ID:
7116 return Context.getObjCSelDecl();
7117
7118 case PREDEF_DECL_OBJC_CLASS_ID:
7119 return Context.getObjCClassDecl();
7120
7121 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7122 return Context.getObjCProtocolDecl();
7123
7124 case PREDEF_DECL_INT_128_ID:
7125 return Context.getInt128Decl();
7126
7127 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7128 return Context.getUInt128Decl();
7129
7130 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7131 return Context.getObjCInstanceTypeDecl();
7132
7133 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7134 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007135
Richard Smith9b88a4c2015-07-27 05:40:23 +00007136 case PREDEF_DECL_VA_LIST_TAG:
7137 return Context.getVaListTagDecl();
7138
Charles Davisc7d5c942015-09-17 20:55:33 +00007139 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7140 return Context.getBuiltinMSVaListDecl();
7141
Richard Smithf19e1272015-03-07 00:04:49 +00007142 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7143 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007144
7145 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7146 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007147
7148 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7149 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007150
7151 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7152 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007153
7154 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7155 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007156 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007157 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007158}
7159
Richard Smithcd45dbc2014-04-19 03:48:30 +00007160Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007161 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007162 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007163 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007164 if (D) {
7165 // Track that we have merged the declaration with ID \p ID into the
7166 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007167 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007168 if (Merged.empty())
7169 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 }
Richard Smithfe620d22015-03-05 23:24:12 +00007171 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007172 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007173
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7175
7176 if (Index >= DeclsLoaded.size()) {
7177 assert(0 && "declaration ID out-of-range for AST file");
7178 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007179 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007180 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007181
7182 return DeclsLoaded[Index];
7183}
7184
7185Decl *ASTReader::GetDecl(DeclID ID) {
7186 if (ID < NUM_PREDEF_DECL_IDS)
7187 return GetExistingDecl(ID);
7188
7189 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7190
7191 if (Index >= DeclsLoaded.size()) {
7192 assert(0 && "declaration ID out-of-range for AST file");
7193 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007194 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007195 }
7196
Guy Benyei11169dd2012-12-18 14:30:41 +00007197 if (!DeclsLoaded[Index]) {
7198 ReadDeclRecord(ID);
7199 if (DeserializationListener)
7200 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7201 }
7202
7203 return DeclsLoaded[Index];
7204}
7205
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007206DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007207 DeclID GlobalID) {
7208 if (GlobalID < NUM_PREDEF_DECL_IDS)
7209 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007210
Guy Benyei11169dd2012-12-18 14:30:41 +00007211 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7212 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7213 ModuleFile *Owner = I->second;
7214
7215 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7216 = M.GlobalToLocalDeclIDs.find(Owner);
7217 if (Pos == M.GlobalToLocalDeclIDs.end())
7218 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007219
Guy Benyei11169dd2012-12-18 14:30:41 +00007220 return GlobalID - Owner->BaseDeclID + Pos->second;
7221}
7222
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007223serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 const RecordData &Record,
7225 unsigned &Idx) {
7226 if (Idx >= Record.size()) {
7227 Error("Corrupted AST file");
7228 return 0;
7229 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007230
Guy Benyei11169dd2012-12-18 14:30:41 +00007231 return getGlobalDeclID(F, Record[Idx++]);
7232}
7233
7234/// \brief Resolve the offset of a statement into a statement.
7235///
7236/// This operation will read a new statement from the external
7237/// source each time it is called, and is meant to be used via a
7238/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7239Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7240 // Switch case IDs are per Decl.
7241 ClearSwitchCaseIDs();
7242
7243 // Offset here is a global offset across the entire chain.
7244 RecordLocation Loc = getLocalBitOffset(Offset);
7245 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007246 assert(NumCurrentElementsDeserializing == 0 &&
7247 "should not be called while already deserializing");
7248 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007249 return ReadStmtFromStream(*Loc.F);
7250}
7251
Richard Smith3cb15722015-08-05 22:41:45 +00007252void ASTReader::FindExternalLexicalDecls(
7253 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7254 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007255 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7256
Richard Smith9ccdd932015-08-06 22:14:12 +00007257 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007258 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7259 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7260 auto K = (Decl::Kind)+LexicalDecls[I];
7261 if (!IsKindWeWant(K))
7262 continue;
7263
7264 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7265
7266 // Don't add predefined declarations to the lexical context more
7267 // than once.
7268 if (ID < NUM_PREDEF_DECL_IDS) {
7269 if (PredefsVisited[ID])
7270 continue;
7271
7272 PredefsVisited[ID] = true;
7273 }
7274
7275 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007276 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007277 if (!DC->isDeclInLexicalTraversal(D))
7278 Decls.push_back(D);
7279 }
7280 }
7281 };
7282
7283 if (isa<TranslationUnitDecl>(DC)) {
7284 for (auto Lexical : TULexicalDecls)
7285 Visit(Lexical.first, Lexical.second);
7286 } else {
7287 auto I = LexicalDecls.find(DC);
7288 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007289 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007290 }
7291
Guy Benyei11169dd2012-12-18 14:30:41 +00007292 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007293}
7294
7295namespace {
7296
7297class DeclIDComp {
7298 ASTReader &Reader;
7299 ModuleFile &Mod;
7300
7301public:
7302 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7303
7304 bool operator()(LocalDeclID L, LocalDeclID R) const {
7305 SourceLocation LHS = getLocation(L);
7306 SourceLocation RHS = getLocation(R);
7307 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7308 }
7309
7310 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7311 SourceLocation RHS = getLocation(R);
7312 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7313 }
7314
7315 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7316 SourceLocation LHS = getLocation(L);
7317 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7318 }
7319
7320 SourceLocation getLocation(LocalDeclID ID) const {
7321 return Reader.getSourceManager().getFileLoc(
7322 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7323 }
7324};
7325
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007326} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007327
7328void ASTReader::FindFileRegionDecls(FileID File,
7329 unsigned Offset, unsigned Length,
7330 SmallVectorImpl<Decl *> &Decls) {
7331 SourceManager &SM = getSourceManager();
7332
7333 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7334 if (I == FileDeclIDs.end())
7335 return;
7336
7337 FileDeclsInfo &DInfo = I->second;
7338 if (DInfo.Decls.empty())
7339 return;
7340
7341 SourceLocation
7342 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7343 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7344
7345 DeclIDComp DIDComp(*this, *DInfo.Mod);
7346 ArrayRef<serialization::LocalDeclID>::iterator
7347 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7348 BeginLoc, DIDComp);
7349 if (BeginIt != DInfo.Decls.begin())
7350 --BeginIt;
7351
7352 // If we are pointing at a top-level decl inside an objc container, we need
7353 // to backtrack until we find it otherwise we will fail to report that the
7354 // region overlaps with an objc container.
7355 while (BeginIt != DInfo.Decls.begin() &&
7356 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7357 ->isTopLevelDeclInObjCContainer())
7358 --BeginIt;
7359
7360 ArrayRef<serialization::LocalDeclID>::iterator
7361 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7362 EndLoc, DIDComp);
7363 if (EndIt != DInfo.Decls.end())
7364 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007365
Guy Benyei11169dd2012-12-18 14:30:41 +00007366 for (ArrayRef<serialization::LocalDeclID>::iterator
7367 DIt = BeginIt; DIt != EndIt; ++DIt)
7368 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7369}
7370
Richard Smith9ce12e32013-02-07 03:30:24 +00007371bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007372ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7373 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007374 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007375 "DeclContext has no visible decls in storage");
7376 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007377 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007378
Richard Smithd88a7f12015-09-01 20:35:42 +00007379 auto It = Lookups.find(DC);
7380 if (It == Lookups.end())
7381 return false;
7382
Richard Smith8c913ec2014-08-14 02:21:01 +00007383 Deserializing LookupResults(this);
7384
Richard Smithd88a7f12015-09-01 20:35:42 +00007385 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007386 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00007387 for (DeclID ID : It->second.Table.find(Name)) {
7388 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7389 if (ND->getDeclName() == Name)
7390 Decls.push_back(ND);
7391 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007392
Guy Benyei11169dd2012-12-18 14:30:41 +00007393 ++NumVisibleDeclContextsRead;
7394 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007395 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007396}
7397
Guy Benyei11169dd2012-12-18 14:30:41 +00007398void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7399 if (!DC->hasExternalVisibleStorage())
7400 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007401
7402 auto It = Lookups.find(DC);
7403 assert(It != Lookups.end() &&
7404 "have external visible storage but no lookup tables");
7405
Craig Topper79be4cd2013-07-05 04:33:53 +00007406 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007407
Richard Smithd88a7f12015-09-01 20:35:42 +00007408 for (DeclID ID : It->second.Table.findAll()) {
7409 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7410 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 }
7412
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 ++NumVisibleDeclContextsRead;
7414
Craig Topper79be4cd2013-07-05 04:33:53 +00007415 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007416 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7417 }
7418 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7419}
7420
Richard Smithd88a7f12015-09-01 20:35:42 +00007421const serialization::reader::DeclContextLookupTable *
7422ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7423 auto I = Lookups.find(Primary);
7424 return I == Lookups.end() ? nullptr : &I->second;
7425}
7426
Guy Benyei11169dd2012-12-18 14:30:41 +00007427/// \brief Under non-PCH compilation the consumer receives the objc methods
7428/// before receiving the implementation, and codegen depends on this.
7429/// We simulate this by deserializing and passing to consumer the methods of the
7430/// implementation before passing the deserialized implementation decl.
7431static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7432 ASTConsumer *Consumer) {
7433 assert(ImplD && Consumer);
7434
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007435 for (auto *I : ImplD->methods())
7436 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007437
7438 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7439}
7440
Guy Benyei11169dd2012-12-18 14:30:41 +00007441void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7442 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7443 PassObjCImplDeclToConsumer(ImplD, Consumer);
7444 else
7445 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7446}
7447
7448void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7449 this->Consumer = Consumer;
7450
Richard Smith9e2341d2015-03-23 03:25:59 +00007451 if (Consumer)
7452 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007453
7454 if (DeserializationListener)
7455 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007456}
7457
7458void ASTReader::PrintStats() {
7459 std::fprintf(stderr, "*** AST File Statistics:\n");
7460
7461 unsigned NumTypesLoaded
7462 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7463 QualType());
7464 unsigned NumDeclsLoaded
7465 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007466 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007467 unsigned NumIdentifiersLoaded
7468 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7469 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007470 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007471 unsigned NumMacrosLoaded
7472 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7473 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007474 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 unsigned NumSelectorsLoaded
7476 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7477 SelectorsLoaded.end(),
7478 Selector());
7479
7480 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7481 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7482 NumSLocEntriesRead, TotalNumSLocEntries,
7483 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7484 if (!TypesLoaded.empty())
7485 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7486 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7487 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7488 if (!DeclsLoaded.empty())
7489 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7490 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7491 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7492 if (!IdentifiersLoaded.empty())
7493 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7494 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7495 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7496 if (!MacrosLoaded.empty())
7497 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7498 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7499 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7500 if (!SelectorsLoaded.empty())
7501 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7502 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7503 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7504 if (TotalNumStatements)
7505 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7506 NumStatementsRead, TotalNumStatements,
7507 ((float)NumStatementsRead/TotalNumStatements * 100));
7508 if (TotalNumMacros)
7509 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7510 NumMacrosRead, TotalNumMacros,
7511 ((float)NumMacrosRead/TotalNumMacros * 100));
7512 if (TotalLexicalDeclContexts)
7513 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7514 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7515 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7516 * 100));
7517 if (TotalVisibleDeclContexts)
7518 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7519 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7520 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7521 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007522 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7524 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7525 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7526 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007527 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007528 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7529 NumMethodPoolHits, NumMethodPoolLookups,
7530 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007531 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007532 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7533 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7534 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7535 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007536 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007537 std::fprintf(stderr,
7538 " %u / %u identifier table lookups succeeded (%f%%)\n",
7539 NumIdentifierLookupHits, NumIdentifierLookups,
7540 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007541
Douglas Gregore060e572013-01-25 01:03:03 +00007542 if (GlobalIndex) {
7543 std::fprintf(stderr, "\n");
7544 GlobalIndex->printStats();
7545 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007546
Guy Benyei11169dd2012-12-18 14:30:41 +00007547 std::fprintf(stderr, "\n");
7548 dump();
7549 std::fprintf(stderr, "\n");
7550}
7551
7552template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007553LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007554dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007555 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007556 InitialCapacity> &Map) {
7557 if (Map.begin() == Map.end())
7558 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007559
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007560 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7561
Guy Benyei11169dd2012-12-18 14:30:41 +00007562 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007563 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007564 I != IEnd; ++I) {
7565 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7566 << "\n";
7567 }
7568}
7569
Yaron Kerencdae9412016-01-29 19:38:18 +00007570LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007571 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7572 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7573 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7574 dumpModuleIDMap("Global type map", GlobalTypeMap);
7575 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7576 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7577 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7578 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7579 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007580 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007581 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007582
Guy Benyei11169dd2012-12-18 14:30:41 +00007583 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007584 for (ModuleFile &M : ModuleMgr)
7585 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007586}
7587
7588/// Return the amount of memory used by memory buffers, breaking down
7589/// by heap-backed versus mmap'ed memory.
7590void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007591 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007592 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007593 size_t bytes = buf->getBufferSize();
7594 switch (buf->getBufferKind()) {
7595 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7596 sizes.malloc_bytes += bytes;
7597 break;
7598 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7599 sizes.mmap_bytes += bytes;
7600 break;
7601 }
7602 }
7603 }
7604}
7605
7606void ASTReader::InitializeSema(Sema &S) {
7607 SemaObj = &S;
7608 S.addExternalSource(this);
7609
7610 // Makes sure any declarations that were deserialized "too early"
7611 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007612 for (uint64_t ID : PreloadedDeclIDs) {
7613 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7614 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007615 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007616 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007617
Richard Smith3d8e97e2013-10-18 06:54:39 +00007618 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007619 if (!FPPragmaOptions.empty()) {
7620 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007621 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007622 }
7623
Yaxun Liu5b746652016-12-18 05:18:55 +00007624 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7625 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7626 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007627
7628 UpdateSema();
7629}
7630
7631void ASTReader::UpdateSema() {
7632 assert(SemaObj && "no Sema to update");
7633
7634 // Load the offsets of the declarations that Sema references.
7635 // They will be lazily deserialized when needed.
7636 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007637 assert(SemaDeclRefs.size() % 3 == 0);
7638 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007639 if (!SemaObj->StdNamespace)
7640 SemaObj->StdNamespace = SemaDeclRefs[I];
7641 if (!SemaObj->StdBadAlloc)
7642 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007643 if (!SemaObj->StdAlignValT)
7644 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007645 }
7646 SemaDeclRefs.clear();
7647 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007648
Nico Weber779355f2016-03-02 23:22:00 +00007649 // Update the state of pragmas. Use the same API as if we had encountered the
7650 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007651 if(OptimizeOffPragmaLocation.isValid())
7652 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007653 if (PragmaMSStructState != -1)
7654 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007655 if (PointersToMembersPragmaLocation.isValid()) {
7656 SemaObj->ActOnPragmaMSPointersToMembers(
7657 (LangOptions::PragmaMSPointersToMembersKind)
7658 PragmaMSPointersToMembersState,
7659 PointersToMembersPragmaLocation);
7660 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007661 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007662
7663 if (PragmaPackCurrentValue) {
7664 // The bottom of the stack might have a default value. It must be adjusted
7665 // to the current value to ensure that the packing state is preserved after
7666 // popping entries that were included/imported from a PCH/module.
7667 bool DropFirst = false;
7668 if (!PragmaPackStack.empty() &&
7669 PragmaPackStack.front().Location.isInvalid()) {
7670 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7671 "Expected a default alignment value");
7672 SemaObj->PackStack.Stack.emplace_back(
7673 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007674 SemaObj->PackStack.CurrentPragmaLocation,
7675 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007676 DropFirst = true;
7677 }
7678 for (const auto &Entry :
7679 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7680 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007681 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007682 if (PragmaPackCurrentLocation.isInvalid()) {
7683 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7684 "Expected a default alignment value");
7685 // Keep the current values.
7686 } else {
7687 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7688 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7689 }
7690 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007691}
7692
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007693IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007694 // Note that we are loading an identifier.
7695 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007696
Douglas Gregor7211ac12013-01-25 23:32:03 +00007697 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007698 NumIdentifierLookups,
7699 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007700
7701 // We don't need to do identifier table lookups in C++ modules (we preload
7702 // all interesting declarations, and don't need to use the scope for name
7703 // lookups). Perform the lookup in PCH files, though, since we don't build
7704 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007705 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007706 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007707 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007708 break;
7709 } else {
7710 // If there is a global index, look there first to determine which modules
7711 // provably do not have any results for this identifier.
7712 GlobalModuleIndex::HitSet Hits;
7713 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7714 if (!loadGlobalIndex()) {
7715 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7716 HitsPtr = &Hits;
7717 }
7718 }
7719
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007720 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007721 }
7722
Guy Benyei11169dd2012-12-18 14:30:41 +00007723 IdentifierInfo *II = Visitor.getIdentifierInfo();
7724 markIdentifierUpToDate(II);
7725 return II;
7726}
7727
7728namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007729
Guy Benyei11169dd2012-12-18 14:30:41 +00007730 /// \brief An identifier-lookup iterator that enumerates all of the
7731 /// identifiers stored within a set of AST files.
7732 class ASTIdentifierIterator : public IdentifierIterator {
7733 /// \brief The AST reader whose identifiers are being enumerated.
7734 const ASTReader &Reader;
7735
7736 /// \brief The current index into the chain of AST files stored in
7737 /// the AST reader.
7738 unsigned Index;
7739
7740 /// \brief The current position within the identifier lookup table
7741 /// of the current AST file.
7742 ASTIdentifierLookupTable::key_iterator Current;
7743
7744 /// \brief The end position within the identifier lookup table of
7745 /// the current AST file.
7746 ASTIdentifierLookupTable::key_iterator End;
7747
Ben Langmuir537c5b52016-05-04 00:53:13 +00007748 /// \brief Whether to skip any modules in the ASTReader.
7749 bool SkipModules;
7750
Guy Benyei11169dd2012-12-18 14:30:41 +00007751 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007752 explicit ASTIdentifierIterator(const ASTReader &Reader,
7753 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007754
Craig Topper3e89dfe2014-03-13 02:13:41 +00007755 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007757
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007758} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007759
Ben Langmuir537c5b52016-05-04 00:53:13 +00007760ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7761 bool SkipModules)
7762 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007763}
7764
7765StringRef ASTIdentifierIterator::Next() {
7766 while (Current == End) {
7767 // If we have exhausted all of our AST files, we're done.
7768 if (Index == 0)
7769 return StringRef();
7770
7771 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007772 ModuleFile &F = Reader.ModuleMgr[Index];
7773 if (SkipModules && F.isModule())
7774 continue;
7775
7776 ASTIdentifierLookupTable *IdTable =
7777 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007778 Current = IdTable->key_begin();
7779 End = IdTable->key_end();
7780 }
7781
7782 // We have any identifiers remaining in the current AST file; return
7783 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007784 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007785 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007786 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007787}
7788
Ben Langmuir537c5b52016-05-04 00:53:13 +00007789namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007790
Ben Langmuir537c5b52016-05-04 00:53:13 +00007791/// A utility for appending two IdentifierIterators.
7792class ChainedIdentifierIterator : public IdentifierIterator {
7793 std::unique_ptr<IdentifierIterator> Current;
7794 std::unique_ptr<IdentifierIterator> Queued;
7795
7796public:
7797 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7798 std::unique_ptr<IdentifierIterator> Second)
7799 : Current(std::move(First)), Queued(std::move(Second)) {}
7800
7801 StringRef Next() override {
7802 if (!Current)
7803 return StringRef();
7804
7805 StringRef result = Current->Next();
7806 if (!result.empty())
7807 return result;
7808
7809 // Try the queued iterator, which may itself be empty.
7810 Current.reset();
7811 std::swap(Current, Queued);
7812 return Next();
7813 }
7814};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007815
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007816} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007817
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007818IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007819 if (!loadGlobalIndex()) {
7820 std::unique_ptr<IdentifierIterator> ReaderIter(
7821 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7822 std::unique_ptr<IdentifierIterator> ModulesIter(
7823 GlobalIndex->createIdentifierIterator());
7824 return new ChainedIdentifierIterator(std::move(ReaderIter),
7825 std::move(ModulesIter));
7826 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007827
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 return new ASTIdentifierIterator(*this);
7829}
7830
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007831namespace clang {
7832namespace serialization {
7833
Guy Benyei11169dd2012-12-18 14:30:41 +00007834 class ReadMethodPoolVisitor {
7835 ASTReader &Reader;
7836 Selector Sel;
7837 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007838 unsigned InstanceBits = 0;
7839 unsigned FactoryBits = 0;
7840 bool InstanceHasMoreThanOneDecl = false;
7841 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007842 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7843 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007844
7845 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007846 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007848 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007849
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007850 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007851 if (!M.SelectorLookupTable)
7852 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007853
Guy Benyei11169dd2012-12-18 14:30:41 +00007854 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007855 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 return true;
7857
Richard Smithbdf2d932015-07-30 03:37:16 +00007858 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007859 ASTSelectorLookupTable *PoolTable
7860 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007861 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007862 if (Pos == PoolTable->end())
7863 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007864
Richard Smithbdf2d932015-07-30 03:37:16 +00007865 ++Reader.NumMethodPoolTableHits;
7866 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007867 // FIXME: Not quite happy with the statistics here. We probably should
7868 // disable this tracking when called via LoadSelector.
7869 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007870 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007871 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007872 if (Reader.DeserializationListener)
7873 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007874
Richard Smithbdf2d932015-07-30 03:37:16 +00007875 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7876 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7877 InstanceBits = Data.InstanceBits;
7878 FactoryBits = Data.FactoryBits;
7879 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7880 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007881 return true;
7882 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007883
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007885 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7886 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 }
7888
7889 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007890 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 return FactoryMethods;
7892 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007893
7894 unsigned getInstanceBits() const { return InstanceBits; }
7895 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007896
Nico Weberff4b35e2014-12-27 22:14:15 +00007897 bool instanceHasMoreThanOneDecl() const {
7898 return InstanceHasMoreThanOneDecl;
7899 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007900
Nico Weberff4b35e2014-12-27 22:14:15 +00007901 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007903
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007904} // namespace serialization
7905} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007906
7907/// \brief Add the given set of methods to the method list.
7908static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7909 ObjCMethodList &List) {
7910 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7911 S.addMethodToGlobalList(&List, Methods[I]);
7912 }
7913}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007914
Guy Benyei11169dd2012-12-18 14:30:41 +00007915void ASTReader::ReadMethodPool(Selector Sel) {
7916 // Get the selector generation and update it to the current generation.
7917 unsigned &Generation = SelectorGeneration[Sel];
7918 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007919 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007920 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007921
Guy Benyei11169dd2012-12-18 14:30:41 +00007922 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007923 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007924 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007925 ModuleMgr.visit(Visitor);
7926
Guy Benyei11169dd2012-12-18 14:30:41 +00007927 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007928 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007929 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007930
7931 ++NumMethodPoolHits;
7932
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 if (!getSema())
7934 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007935
Guy Benyei11169dd2012-12-18 14:30:41 +00007936 Sema &S = *getSema();
7937 Sema::GlobalMethodPool::iterator Pos
7938 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007939
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007940 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007941 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007942 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007943 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007944
7945 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7946 // when building a module we keep every method individually and may need to
7947 // update hasMoreThanOneDecl as we add the methods.
7948 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7949 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007950}
7951
Manman Rena0f31a02016-04-29 19:04:05 +00007952void ASTReader::updateOutOfDateSelector(Selector Sel) {
7953 if (SelectorOutOfDate[Sel])
7954 ReadMethodPool(Sel);
7955}
7956
Guy Benyei11169dd2012-12-18 14:30:41 +00007957void ASTReader::ReadKnownNamespaces(
7958 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7959 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007960
Guy Benyei11169dd2012-12-18 14:30:41 +00007961 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007962 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007963 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7964 Namespaces.push_back(Namespace);
7965 }
7966}
7967
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007968void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007969 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007970 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7971 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007972 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007973 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007974 Undefined.insert(std::make_pair(D, Loc));
7975 }
7976}
Nick Lewycky8334af82013-01-26 00:35:08 +00007977
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007978void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7979 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7980 Exprs) {
7981 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7982 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7983 uint64_t Count = DelayedDeleteExprs[Idx++];
7984 for (uint64_t C = 0; C < Count; ++C) {
7985 SourceLocation DeleteLoc =
7986 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7987 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7988 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7989 }
7990 }
7991}
7992
Guy Benyei11169dd2012-12-18 14:30:41 +00007993void ASTReader::ReadTentativeDefinitions(
7994 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7995 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7996 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7997 if (Var)
7998 TentativeDefs.push_back(Var);
7999 }
8000 TentativeDefinitions.clear();
8001}
8002
8003void ASTReader::ReadUnusedFileScopedDecls(
8004 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8005 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8006 DeclaratorDecl *D
8007 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8008 if (D)
8009 Decls.push_back(D);
8010 }
8011 UnusedFileScopedDecls.clear();
8012}
8013
8014void ASTReader::ReadDelegatingConstructors(
8015 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8016 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8017 CXXConstructorDecl *D
8018 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8019 if (D)
8020 Decls.push_back(D);
8021 }
8022 DelegatingCtorDecls.clear();
8023}
8024
8025void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8026 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8027 TypedefNameDecl *D
8028 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8029 if (D)
8030 Decls.push_back(D);
8031 }
8032 ExtVectorDecls.clear();
8033}
8034
Nico Weber72889432014-09-06 01:25:55 +00008035void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8036 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8037 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8038 ++I) {
8039 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8040 GetDecl(UnusedLocalTypedefNameCandidates[I]));
8041 if (D)
8042 Decls.insert(D);
8043 }
8044 UnusedLocalTypedefNameCandidates.clear();
8045}
8046
Guy Benyei11169dd2012-12-18 14:30:41 +00008047void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008048 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008049 if (ReferencedSelectorsData.empty())
8050 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008051
Guy Benyei11169dd2012-12-18 14:30:41 +00008052 // If there are @selector references added them to its pool. This is for
8053 // implementation of -Wselector.
8054 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8055 unsigned I = 0;
8056 while (I < DataSize) {
8057 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8058 SourceLocation SelLoc
8059 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8060 Sels.push_back(std::make_pair(Sel, SelLoc));
8061 }
8062 ReferencedSelectorsData.clear();
8063}
8064
8065void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008066 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 if (WeakUndeclaredIdentifiers.empty())
8068 return;
8069
8070 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008071 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008072 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008073 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008074 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8075 SourceLocation Loc
8076 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8077 bool Used = WeakUndeclaredIdentifiers[I++];
8078 WeakInfo WI(AliasId, Loc);
8079 WI.setUsed(Used);
8080 WeakIDs.push_back(std::make_pair(WeakId, WI));
8081 }
8082 WeakUndeclaredIdentifiers.clear();
8083}
8084
8085void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8086 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8087 ExternalVTableUse VT;
8088 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8089 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8090 VT.DefinitionRequired = VTableUses[Idx++];
8091 VTables.push_back(VT);
8092 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008093
Guy Benyei11169dd2012-12-18 14:30:41 +00008094 VTableUses.clear();
8095}
8096
8097void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008098 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008099 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8100 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8101 SourceLocation Loc
8102 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8103
8104 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008105 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008106 PendingInstantiations.clear();
8107}
8108
Richard Smithe40f2ba2013-08-07 21:41:30 +00008109void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008110 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8111 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008112 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8113 /* In loop */) {
8114 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
8115
Justin Lebar28f09c52016-10-10 16:26:08 +00008116 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008117 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8118
8119 ModuleFile *F = getOwningModuleFile(LT->D);
8120 assert(F && "No module");
8121
8122 unsigned TokN = LateParsedTemplates[Idx++];
8123 LT->Toks.reserve(TokN);
8124 for (unsigned T = 0; T < TokN; ++T)
8125 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8126
Justin Lebar28f09c52016-10-10 16:26:08 +00008127 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008128 }
8129
8130 LateParsedTemplates.clear();
8131}
8132
Guy Benyei11169dd2012-12-18 14:30:41 +00008133void ASTReader::LoadSelector(Selector Sel) {
8134 // It would be complicated to avoid reading the methods anyway. So don't.
8135 ReadMethodPool(Sel);
8136}
8137
8138void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8139 assert(ID && "Non-zero identifier ID required");
8140 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8141 IdentifiersLoaded[ID - 1] = II;
8142 if (DeserializationListener)
8143 DeserializationListener->IdentifierRead(ID, II);
8144}
8145
8146/// \brief Set the globally-visible declarations associated with the given
8147/// identifier.
8148///
8149/// If the AST reader is currently in a state where the given declaration IDs
8150/// cannot safely be resolved, they are queued until it is safe to resolve
8151/// them.
8152///
8153/// \param II an IdentifierInfo that refers to one or more globally-visible
8154/// declarations.
8155///
8156/// \param DeclIDs the set of declaration IDs with the name @p II that are
8157/// visible at global scope.
8158///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008159/// \param Decls if non-null, this vector will be populated with the set of
8160/// deserialized declarations. These declarations will not be pushed into
8161/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008162void
8163ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8164 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008165 SmallVectorImpl<Decl *> *Decls) {
8166 if (NumCurrentElementsDeserializing && !Decls) {
8167 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 return;
8169 }
8170
8171 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008172 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 // Queue this declaration so that it will be added to the
8174 // translation unit scope and identifier's declaration chain
8175 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00008176 PreloadedDeclIDs.push_back(DeclIDs[I]);
8177 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008178 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008179
8180 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8181
8182 // If we're simply supposed to record the declarations, do so now.
8183 if (Decls) {
8184 Decls->push_back(D);
8185 continue;
8186 }
8187
8188 // Introduce this declaration into the translation-unit scope
8189 // and add it to the declaration chain for this identifier, so
8190 // that (unqualified) name lookup will find it.
8191 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008192 }
8193}
8194
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008195IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008196 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008197 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008198
8199 if (IdentifiersLoaded.empty()) {
8200 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008201 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 }
8203
8204 ID -= 1;
8205 if (!IdentifiersLoaded[ID]) {
8206 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8207 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8208 ModuleFile *M = I->second;
8209 unsigned Index = ID - M->BaseIdentifierID;
8210 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8211
8212 // All of the strings in the AST file are preceded by a 16-bit length.
8213 // Extract that 16-bit length to avoid having to execute strlen().
8214 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8215 // unsigned integers. This is important to avoid integer overflow when
8216 // we cast them to 'unsigned'.
8217 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8218 unsigned StrLen = (((unsigned) StrLenPtr[0])
8219 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008220 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8221 IdentifiersLoaded[ID] = &II;
8222 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008223 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008224 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 }
8226
8227 return IdentifiersLoaded[ID];
8228}
8229
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008230IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8231 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008232}
8233
8234IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8235 if (LocalID < NUM_PREDEF_IDENT_IDS)
8236 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008237
Richard Smith37a93df2017-02-18 00:32:02 +00008238 if (!M.ModuleOffsetMap.empty())
8239 ReadModuleOffsetMap(M);
8240
Guy Benyei11169dd2012-12-18 14:30:41 +00008241 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8242 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008243 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008244 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008245
Guy Benyei11169dd2012-12-18 14:30:41 +00008246 return LocalID + I->second;
8247}
8248
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008249MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008251 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008252
8253 if (MacrosLoaded.empty()) {
8254 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008255 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 }
8257
8258 ID -= NUM_PREDEF_MACRO_IDS;
8259 if (!MacrosLoaded[ID]) {
8260 GlobalMacroMapType::iterator I
8261 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8262 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8263 ModuleFile *M = I->second;
8264 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008265 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008266
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008267 if (DeserializationListener)
8268 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8269 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008270 }
8271
8272 return MacrosLoaded[ID];
8273}
8274
8275MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8276 if (LocalID < NUM_PREDEF_MACRO_IDS)
8277 return LocalID;
8278
Richard Smith37a93df2017-02-18 00:32:02 +00008279 if (!M.ModuleOffsetMap.empty())
8280 ReadModuleOffsetMap(M);
8281
Guy Benyei11169dd2012-12-18 14:30:41 +00008282 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8283 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8284 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8285
8286 return LocalID + I->second;
8287}
8288
8289serialization::SubmoduleID
8290ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8291 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8292 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008293
Richard Smith37a93df2017-02-18 00:32:02 +00008294 if (!M.ModuleOffsetMap.empty())
8295 ReadModuleOffsetMap(M);
8296
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8298 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008299 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008301
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 return LocalID + I->second;
8303}
8304
8305Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8306 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8307 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008308 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008309 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008310
Guy Benyei11169dd2012-12-18 14:30:41 +00008311 if (GlobalID > SubmodulesLoaded.size()) {
8312 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008313 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008314 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008315
Guy Benyei11169dd2012-12-18 14:30:41 +00008316 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8317}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008318
8319Module *ASTReader::getModule(unsigned ID) {
8320 return getSubmodule(ID);
8321}
8322
Richard Smithd88a7f12015-09-01 20:35:42 +00008323ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8324 if (ID & 1) {
8325 // It's a module, look it up by submodule ID.
8326 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8327 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8328 } else {
8329 // It's a prefix (preamble, PCH, ...). Look it up by index.
8330 unsigned IndexFromEnd = ID >> 1;
8331 assert(IndexFromEnd && "got reference to unknown module file");
8332 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8333 }
8334}
8335
8336unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8337 if (!F)
8338 return 1;
8339
8340 // For a file representing a module, use the submodule ID of the top-level
8341 // module as the file ID. For any other kind of file, the number of such
8342 // files loaded beforehand will be the same on reload.
8343 // FIXME: Is this true even if we have an explicit module file and a PCH?
8344 if (F->isModule())
8345 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8346
8347 auto PCHModules = getModuleManager().pch_modules();
8348 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8349 assert(I != PCHModules.end() && "emitting reference to unknown file");
8350 return (I - PCHModules.end()) << 1;
8351}
8352
Adrian Prantl15bcf702015-06-30 17:39:43 +00008353llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8354ASTReader::getSourceDescriptor(unsigned ID) {
8355 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008356 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008357
8358 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008359 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008360 const auto &PCHChain = ModuleMgr.pch_modules();
8361 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008362 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008363 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008364 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8365 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8366 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008367 }
8368 return None;
8369}
8370
David Blaikie1ac9c982017-04-11 21:13:37 +00008371ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008372 auto I = DefinitionSource.find(FD);
8373 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008374 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008375 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008376}
8377
Guy Benyei11169dd2012-12-18 14:30:41 +00008378Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8379 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8380}
8381
8382Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8383 if (ID == 0)
8384 return Selector();
8385
8386 if (ID > SelectorsLoaded.size()) {
8387 Error("selector ID out of range in AST file");
8388 return Selector();
8389 }
8390
Craig Toppera13603a2014-05-22 05:54:18 +00008391 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008392 // Load this selector from the selector table.
8393 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8394 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8395 ModuleFile &M = *I->second;
8396 ASTSelectorLookupTrait Trait(*this, M);
8397 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8398 SelectorsLoaded[ID - 1] =
8399 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8400 if (DeserializationListener)
8401 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8402 }
8403
8404 return SelectorsLoaded[ID - 1];
8405}
8406
8407Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8408 return DecodeSelector(ID);
8409}
8410
8411uint32_t ASTReader::GetNumExternalSelectors() {
8412 // ID 0 (the null selector) is considered an external selector.
8413 return getTotalNumSelectors() + 1;
8414}
8415
8416serialization::SelectorID
8417ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8418 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8419 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008420
Richard Smith37a93df2017-02-18 00:32:02 +00008421 if (!M.ModuleOffsetMap.empty())
8422 ReadModuleOffsetMap(M);
8423
Guy Benyei11169dd2012-12-18 14:30:41 +00008424 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8425 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008426 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008427 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008428
Guy Benyei11169dd2012-12-18 14:30:41 +00008429 return LocalID + I->second;
8430}
8431
8432DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008433ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008434 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008435 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008436 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8437 switch (Kind) {
8438 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008439 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008440
8441 case DeclarationName::ObjCZeroArgSelector:
8442 case DeclarationName::ObjCOneArgSelector:
8443 case DeclarationName::ObjCMultiArgSelector:
8444 return DeclarationName(ReadSelector(F, Record, Idx));
8445
8446 case DeclarationName::CXXConstructorName:
8447 return Context.DeclarationNames.getCXXConstructorName(
8448 Context.getCanonicalType(readType(F, Record, Idx)));
8449
8450 case DeclarationName::CXXDestructorName:
8451 return Context.DeclarationNames.getCXXDestructorName(
8452 Context.getCanonicalType(readType(F, Record, Idx)));
8453
Richard Smith35845152017-02-07 01:37:30 +00008454 case DeclarationName::CXXDeductionGuideName:
8455 return Context.DeclarationNames.getCXXDeductionGuideName(
8456 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8457
Guy Benyei11169dd2012-12-18 14:30:41 +00008458 case DeclarationName::CXXConversionFunctionName:
8459 return Context.DeclarationNames.getCXXConversionFunctionName(
8460 Context.getCanonicalType(readType(F, Record, Idx)));
8461
8462 case DeclarationName::CXXOperatorName:
8463 return Context.DeclarationNames.getCXXOperatorName(
8464 (OverloadedOperatorKind)Record[Idx++]);
8465
8466 case DeclarationName::CXXLiteralOperatorName:
8467 return Context.DeclarationNames.getCXXLiteralOperatorName(
8468 GetIdentifierInfo(F, Record, Idx));
8469
8470 case DeclarationName::CXXUsingDirective:
8471 return DeclarationName::getUsingDirectiveName();
8472 }
8473
8474 llvm_unreachable("Invalid NameKind!");
8475}
8476
8477void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8478 DeclarationNameLoc &DNLoc,
8479 DeclarationName Name,
8480 const RecordData &Record, unsigned &Idx) {
8481 switch (Name.getNameKind()) {
8482 case DeclarationName::CXXConstructorName:
8483 case DeclarationName::CXXDestructorName:
8484 case DeclarationName::CXXConversionFunctionName:
8485 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8486 break;
8487
8488 case DeclarationName::CXXOperatorName:
8489 DNLoc.CXXOperatorName.BeginOpNameLoc
8490 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8491 DNLoc.CXXOperatorName.EndOpNameLoc
8492 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8493 break;
8494
8495 case DeclarationName::CXXLiteralOperatorName:
8496 DNLoc.CXXLiteralOperatorName.OpNameLoc
8497 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8498 break;
8499
8500 case DeclarationName::Identifier:
8501 case DeclarationName::ObjCZeroArgSelector:
8502 case DeclarationName::ObjCOneArgSelector:
8503 case DeclarationName::ObjCMultiArgSelector:
8504 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008505 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 break;
8507 }
8508}
8509
8510void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8511 DeclarationNameInfo &NameInfo,
8512 const RecordData &Record, unsigned &Idx) {
8513 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8514 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8515 DeclarationNameLoc DNLoc;
8516 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8517 NameInfo.setInfo(DNLoc);
8518}
8519
8520void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8521 const RecordData &Record, unsigned &Idx) {
8522 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8523 unsigned NumTPLists = Record[Idx++];
8524 Info.NumTemplParamLists = NumTPLists;
8525 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008526 Info.TemplParamLists =
8527 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008528 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8530 }
8531}
8532
8533TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008534ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008535 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008536 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008537 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8538 switch (Kind) {
8539 case TemplateName::Template:
8540 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8541
8542 case TemplateName::OverloadedTemplate: {
8543 unsigned size = Record[Idx++];
8544 UnresolvedSet<8> Decls;
8545 while (size--)
8546 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8547
8548 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8549 }
8550
8551 case TemplateName::QualifiedTemplate: {
8552 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8553 bool hasTemplKeyword = Record[Idx++];
8554 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8555 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8556 }
8557
8558 case TemplateName::DependentTemplate: {
8559 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8560 if (Record[Idx++]) // isIdentifier
8561 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008562 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008563 Idx));
8564 return Context.getDependentTemplateName(NNS,
8565 (OverloadedOperatorKind)Record[Idx++]);
8566 }
8567
8568 case TemplateName::SubstTemplateTemplateParm: {
8569 TemplateTemplateParmDecl *param
8570 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8571 if (!param) return TemplateName();
8572 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8573 return Context.getSubstTemplateTemplateParm(param, replacement);
8574 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008575
Guy Benyei11169dd2012-12-18 14:30:41 +00008576 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008577 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008578 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8579 if (!Param)
8580 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008581
Guy Benyei11169dd2012-12-18 14:30:41 +00008582 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8583 if (ArgPack.getKind() != TemplateArgument::Pack)
8584 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008585
Guy Benyei11169dd2012-12-18 14:30:41 +00008586 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8587 }
8588 }
8589
8590 llvm_unreachable("Unhandled template name kind!");
8591}
8592
Richard Smith2bb3c342015-08-09 01:05:31 +00008593TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8594 const RecordData &Record,
8595 unsigned &Idx,
8596 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008597 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008598 if (Canonicalize) {
8599 // The caller wants a canonical template argument. Sometimes the AST only
8600 // wants template arguments in canonical form (particularly as the template
8601 // argument lists of template specializations) so ensure we preserve that
8602 // canonical form across serialization.
8603 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8604 return Context.getCanonicalTemplateArgument(Arg);
8605 }
8606
Guy Benyei11169dd2012-12-18 14:30:41 +00008607 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8608 switch (Kind) {
8609 case TemplateArgument::Null:
8610 return TemplateArgument();
8611 case TemplateArgument::Type:
8612 return TemplateArgument(readType(F, Record, Idx));
8613 case TemplateArgument::Declaration: {
8614 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008615 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008616 }
8617 case TemplateArgument::NullPtr:
8618 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8619 case TemplateArgument::Integral: {
8620 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8621 QualType T = readType(F, Record, Idx);
8622 return TemplateArgument(Context, Value, T);
8623 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008624 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008625 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8626 case TemplateArgument::TemplateExpansion: {
8627 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008628 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008629 if (unsigned NumExpansions = Record[Idx++])
8630 NumTemplateExpansions = NumExpansions - 1;
8631 return TemplateArgument(Name, NumTemplateExpansions);
8632 }
8633 case TemplateArgument::Expression:
8634 return TemplateArgument(ReadExpr(F));
8635 case TemplateArgument::Pack: {
8636 unsigned NumArgs = Record[Idx++];
8637 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8638 for (unsigned I = 0; I != NumArgs; ++I)
8639 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008640 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008641 }
8642 }
8643
8644 llvm_unreachable("Unhandled template argument kind!");
8645}
8646
8647TemplateParameterList *
8648ASTReader::ReadTemplateParameterList(ModuleFile &F,
8649 const RecordData &Record, unsigned &Idx) {
8650 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8651 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8652 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8653
8654 unsigned NumParams = Record[Idx++];
8655 SmallVector<NamedDecl *, 16> Params;
8656 Params.reserve(NumParams);
8657 while (NumParams--)
8658 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8659
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008660 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008661 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8662 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008663 return TemplateParams;
8664}
8665
8666void
8667ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008668ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008669 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008670 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008671 unsigned NumTemplateArgs = Record[Idx++];
8672 TemplArgs.reserve(NumTemplateArgs);
8673 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008674 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008675}
8676
8677/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008678void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008679 const RecordData &Record, unsigned &Idx) {
8680 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008681 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008682 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008683 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008684 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008685 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008686 }
8687}
8688
8689CXXBaseSpecifier
8690ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8691 const RecordData &Record, unsigned &Idx) {
8692 bool isVirtual = static_cast<bool>(Record[Idx++]);
8693 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8694 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8695 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8696 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8697 SourceRange Range = ReadSourceRange(F, Record, Idx);
8698 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008699 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008700 EllipsisLoc);
8701 Result.setInheritConstructors(inheritConstructors);
8702 return Result;
8703}
8704
Richard Smithc2bb8182015-03-24 06:36:48 +00008705CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008706ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8707 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008708 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008709 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008710 assert(NumInitializers && "wrote ctor initializers but have no inits");
8711 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8712 for (unsigned i = 0; i != NumInitializers; ++i) {
8713 TypeSourceInfo *TInfo = nullptr;
8714 bool IsBaseVirtual = false;
8715 FieldDecl *Member = nullptr;
8716 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008717
Richard Smithc2bb8182015-03-24 06:36:48 +00008718 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8719 switch (Type) {
8720 case CTOR_INITIALIZER_BASE:
8721 TInfo = GetTypeSourceInfo(F, Record, Idx);
8722 IsBaseVirtual = Record[Idx++];
8723 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008724
Richard Smithc2bb8182015-03-24 06:36:48 +00008725 case CTOR_INITIALIZER_DELEGATING:
8726 TInfo = GetTypeSourceInfo(F, Record, Idx);
8727 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008728
Richard Smithc2bb8182015-03-24 06:36:48 +00008729 case CTOR_INITIALIZER_MEMBER:
8730 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8731 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008732
Richard Smithc2bb8182015-03-24 06:36:48 +00008733 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8734 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8735 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008736 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008737
8738 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8739 Expr *Init = ReadExpr(F);
8740 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8741 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008742
8743 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008744 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008745 BOMInit = new (Context)
8746 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8747 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008748 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008749 BOMInit = new (Context)
8750 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008751 else if (Member)
8752 BOMInit = new (Context)
8753 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8754 Init, RParenLoc);
8755 else
8756 BOMInit = new (Context)
8757 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8758 LParenLoc, Init, RParenLoc);
8759
Richard Smith418ed822016-12-14 19:45:03 +00008760 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008761 unsigned SourceOrder = Record[Idx++];
8762 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008763 }
8764
Richard Smithc2bb8182015-03-24 06:36:48 +00008765 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008766 }
8767
Richard Smithc2bb8182015-03-24 06:36:48 +00008768 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008769}
8770
8771NestedNameSpecifier *
8772ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8773 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008774 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008775 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008776 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008777 for (unsigned I = 0; I != N; ++I) {
8778 NestedNameSpecifier::SpecifierKind Kind
8779 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8780 switch (Kind) {
8781 case NestedNameSpecifier::Identifier: {
8782 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8783 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8784 break;
8785 }
8786
8787 case NestedNameSpecifier::Namespace: {
8788 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8789 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8790 break;
8791 }
8792
8793 case NestedNameSpecifier::NamespaceAlias: {
8794 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8795 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8796 break;
8797 }
8798
8799 case NestedNameSpecifier::TypeSpec:
8800 case NestedNameSpecifier::TypeSpecWithTemplate: {
8801 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8802 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008803 return nullptr;
8804
Guy Benyei11169dd2012-12-18 14:30:41 +00008805 bool Template = Record[Idx++];
8806 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8807 break;
8808 }
8809
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008810 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00008811 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8812 // No associated value, and there can't be a prefix.
8813 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00008814
8815 case NestedNameSpecifier::Super: {
8816 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8817 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8818 break;
8819 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008820 }
8821 Prev = NNS;
8822 }
8823 return NNS;
8824}
8825
8826NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008827ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008828 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008829 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008830 unsigned N = Record[Idx++];
8831 NestedNameSpecifierLocBuilder Builder;
8832 for (unsigned I = 0; I != N; ++I) {
8833 NestedNameSpecifier::SpecifierKind Kind
8834 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8835 switch (Kind) {
8836 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008837 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008838 SourceRange Range = ReadSourceRange(F, Record, Idx);
8839 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8840 break;
8841 }
8842
8843 case NestedNameSpecifier::Namespace: {
8844 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8845 SourceRange Range = ReadSourceRange(F, Record, Idx);
8846 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8847 break;
8848 }
8849
8850 case NestedNameSpecifier::NamespaceAlias: {
8851 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8852 SourceRange Range = ReadSourceRange(F, Record, Idx);
8853 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8854 break;
8855 }
8856
8857 case NestedNameSpecifier::TypeSpec:
8858 case NestedNameSpecifier::TypeSpecWithTemplate: {
8859 bool Template = Record[Idx++];
8860 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8861 if (!T)
8862 return NestedNameSpecifierLoc();
8863 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8864
8865 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008866 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008867 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8868 T->getTypeLoc(), ColonColonLoc);
8869 break;
8870 }
8871
8872 case NestedNameSpecifier::Global: {
8873 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8874 Builder.MakeGlobal(Context, ColonColonLoc);
8875 break;
8876 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008877
8878 case NestedNameSpecifier::Super: {
8879 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8880 SourceRange Range = ReadSourceRange(F, Record, Idx);
8881 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8882 break;
8883 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008884 }
8885 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008886
Guy Benyei11169dd2012-12-18 14:30:41 +00008887 return Builder.getWithLocInContext(Context);
8888}
8889
8890SourceRange
8891ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8892 unsigned &Idx) {
8893 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8894 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8895 return SourceRange(beg, end);
8896}
8897
8898/// \brief Read an integral value
8899llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8900 unsigned BitWidth = Record[Idx++];
8901 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8902 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8903 Idx += NumWords;
8904 return Result;
8905}
8906
8907/// \brief Read a signed integral value
8908llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8909 bool isUnsigned = Record[Idx++];
8910 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8911}
8912
8913/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008914llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8915 const llvm::fltSemantics &Sem,
8916 unsigned &Idx) {
8917 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008918}
8919
8920// \brief Read a string
8921std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8922 unsigned Len = Record[Idx++];
8923 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8924 Idx += Len;
8925 return Result;
8926}
8927
Richard Smith7ed1bc92014-12-05 22:42:13 +00008928std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8929 unsigned &Idx) {
8930 std::string Filename = ReadString(Record, Idx);
8931 ResolveImportedPath(F, Filename);
8932 return Filename;
8933}
8934
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008935VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008936 unsigned &Idx) {
8937 unsigned Major = Record[Idx++];
8938 unsigned Minor = Record[Idx++];
8939 unsigned Subminor = Record[Idx++];
8940 if (Minor == 0)
8941 return VersionTuple(Major);
8942 if (Subminor == 0)
8943 return VersionTuple(Major, Minor - 1);
8944 return VersionTuple(Major, Minor - 1, Subminor - 1);
8945}
8946
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008947CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008948 const RecordData &Record,
8949 unsigned &Idx) {
8950 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00008951 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00008952}
8953
Richard Smith37a93df2017-02-18 00:32:02 +00008954DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008955 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008956}
8957
Richard Smith37a93df2017-02-18 00:32:02 +00008958DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008959 return Diags.Report(Loc, DiagID);
8960}
8961
8962/// \brief Retrieve the identifier table associated with the
8963/// preprocessor.
8964IdentifierTable &ASTReader::getIdentifierTable() {
8965 return PP.getIdentifierTable();
8966}
8967
8968/// \brief Record that the given ID maps to the given switch-case
8969/// statement.
8970void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008971 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008972 "Already have a SwitchCase with this ID");
8973 (*CurrSwitchCaseStmts)[ID] = SC;
8974}
8975
8976/// \brief Retrieve the switch-case statement with the given ID.
8977SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008978 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008979 return (*CurrSwitchCaseStmts)[ID];
8980}
8981
8982void ASTReader::ClearSwitchCaseIDs() {
8983 CurrSwitchCaseStmts->clear();
8984}
8985
8986void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008987 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008988 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008989 for (SmallVectorImpl<std::pair<BitstreamCursor,
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008990 serialization::ModuleFile *>>::iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00008991 I = CommentsCursors.begin(),
8992 E = CommentsCursors.end();
8993 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008994 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008995 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008996 serialization::ModuleFile &F = *I->second;
8997 SavedStreamPosition SavedPosition(Cursor);
8998
8999 RecordData Record;
9000 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009001 llvm::BitstreamEntry Entry =
9002 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009003
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009004 switch (Entry.Kind) {
9005 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9006 case llvm::BitstreamEntry::Error:
9007 Error("malformed block record in AST file");
9008 return;
9009 case llvm::BitstreamEntry::EndBlock:
9010 goto NextCursor;
9011 case llvm::BitstreamEntry::Record:
9012 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009013 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009014 }
9015
9016 // Read a record.
9017 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00009018 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009019 case COMMENTS_RAW_COMMENT: {
9020 unsigned Idx = 0;
9021 SourceRange SR = ReadSourceRange(F, Record, Idx);
9022 RawComment::CommentKind Kind =
9023 (RawComment::CommentKind) Record[Idx++];
9024 bool IsTrailingComment = Record[Idx++];
9025 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009026 Comments.push_back(new (Context) RawComment(
9027 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
9028 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00009029 break;
9030 }
9031 }
9032 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009033 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009034 // De-serialized SourceLocations get negative FileIDs for other modules,
9035 // potentially invalidating the original order. Sort it again.
9036 std::sort(Comments.begin(), Comments.end(),
9037 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009038 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009039 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009040}
9041
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009042void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9043 bool IncludeSystem, bool Complain,
9044 llvm::function_ref<void(const serialization::InputFile &IF,
9045 bool isSystem)> Visitor) {
9046 unsigned NumUserInputs = MF.NumUserInputFiles;
9047 unsigned NumInputs = MF.InputFilesLoaded.size();
9048 assert(NumUserInputs <= NumInputs);
9049 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9050 for (unsigned I = 0; I < N; ++I) {
9051 bool IsSystem = I >= NumUserInputs;
9052 InputFile IF = getInputFile(MF, I+1, Complain);
9053 Visitor(IF, IsSystem);
9054 }
9055}
9056
Richard Smithf3f84612017-06-29 02:19:42 +00009057void ASTReader::visitTopLevelModuleMaps(
9058 serialization::ModuleFile &MF,
9059 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9060 unsigned NumInputs = MF.InputFilesLoaded.size();
9061 for (unsigned I = 0; I < NumInputs; ++I) {
9062 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9063 if (IFI.TopLevelModuleMap)
9064 // FIXME: This unnecessarily re-reads the InputFileInfo.
9065 if (auto *FE = getInputFile(MF, I + 1).getFile())
9066 Visitor(FE);
9067 }
9068}
9069
Richard Smithcd45dbc2014-04-19 03:48:30 +00009070std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9071 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009072 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009073 return M->getFullModuleName();
9074
9075 // Otherwise, use the name of the top-level module the decl is within.
9076 if (ModuleFile *M = getOwningModuleFile(D))
9077 return M->ModuleName;
9078
9079 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009080 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009081}
9082
Guy Benyei11169dd2012-12-18 14:30:41 +00009083void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00009084 while (!PendingIdentifierInfos.empty() ||
9085 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009086 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009087 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009088 // If any identifiers with corresponding top-level declarations have
9089 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009090 using TopLevelDeclsMap =
9091 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009092 TopLevelDeclsMap TopLevelDecls;
9093
Guy Benyei11169dd2012-12-18 14:30:41 +00009094 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009095 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009096 SmallVector<uint32_t, 4> DeclIDs =
9097 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009098 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009099
9100 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009101 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009102
Richard Smith851072e2014-05-19 20:59:20 +00009103 // For each decl chain that we wanted to complete while deserializing, mark
9104 // it as "still needs to be completed".
9105 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9106 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9107 }
9108 PendingIncompleteDeclChains.clear();
9109
Guy Benyei11169dd2012-12-18 14:30:41 +00009110 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00009111 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00009112 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009113 PendingDeclChains.clear();
9114
Douglas Gregor6168bd22013-02-18 15:53:43 +00009115 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00009116 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9117 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009118 IdentifierInfo *II = TLD->first;
9119 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009120 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009121 }
9122 }
9123
Guy Benyei11169dd2012-12-18 14:30:41 +00009124 // Load any pending macro definitions.
9125 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009126 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9127 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9128 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9129 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009130 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009131 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009132 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009133 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009134 resolvePendingMacro(II, Info);
9135 }
9136 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009137 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009138 ++IDIdx) {
9139 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009140 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009141 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009142 }
9143 }
9144 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009145
9146 // Wire up the DeclContexts for Decls that we delayed setting until
9147 // recursive loading is completed.
9148 while (!PendingDeclContextInfos.empty()) {
9149 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9150 PendingDeclContextInfos.pop_front();
9151 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9152 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9153 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9154 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009155
Richard Smithd1c46742014-04-30 02:24:17 +00009156 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009157 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009158 auto Update = PendingUpdateRecords.pop_back_val();
9159 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009160 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009161 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009162 }
Richard Smith8a639892015-01-24 01:07:20 +00009163
9164 // At this point, all update records for loaded decls are in place, so any
9165 // fake class definitions should have become real.
9166 assert(PendingFakeDefinitionData.empty() &&
9167 "faked up a class definition but never saw the real one");
9168
Guy Benyei11169dd2012-12-18 14:30:41 +00009169 // If we deserialized any C++ or Objective-C class definitions, any
9170 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009171 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009172 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00009173 for (Decl *D : PendingDefinitions) {
9174 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00009175 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009176 // Make sure that the TagType points at the definition.
9177 const_cast<TagType*>(TagT)->decl = TD;
9178 }
Richard Smith8ce51082015-03-11 01:44:51 +00009179
Craig Topperc6914d02014-08-25 04:15:02 +00009180 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009181 for (auto *R = getMostRecentExistingDecl(RD); R;
9182 R = R->getPreviousDecl()) {
9183 assert((R == D) ==
9184 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009185 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009186 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009187 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009188 }
9189
9190 continue;
9191 }
Richard Smith8ce51082015-03-11 01:44:51 +00009192
Craig Topperc6914d02014-08-25 04:15:02 +00009193 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009194 // Make sure that the ObjCInterfaceType points at the definition.
9195 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9196 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009197
9198 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9199 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9200
Guy Benyei11169dd2012-12-18 14:30:41 +00009201 continue;
9202 }
Richard Smith8ce51082015-03-11 01:44:51 +00009203
Craig Topperc6914d02014-08-25 04:15:02 +00009204 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009205 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9206 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9207
Guy Benyei11169dd2012-12-18 14:30:41 +00009208 continue;
9209 }
Richard Smith8ce51082015-03-11 01:44:51 +00009210
Craig Topperc6914d02014-08-25 04:15:02 +00009211 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009212 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9213 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009214 }
9215 PendingDefinitions.clear();
9216
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009217 // Load the bodies of any functions or methods we've encountered. We do
9218 // this now (delayed) so that we can be sure that the declaration chains
9219 // have been fully wired up (hasBody relies on this).
9220 // FIXME: We shouldn't require complete redeclaration chains here.
9221 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9222 PBEnd = PendingBodies.end();
9223 PB != PBEnd; ++PB) {
9224 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9225 // FIXME: Check for =delete/=default?
9226 // FIXME: Complain about ODR violations here?
9227 const FunctionDecl *Defn = nullptr;
9228 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9229 FD->setLazyBody(PB->second);
9230 } else
9231 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
9232 continue;
9233 }
9234
9235 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9236 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9237 MD->setLazyBody(PB->second);
9238 }
9239 PendingBodies.clear();
9240
Richard Smith42413142015-05-15 20:05:43 +00009241 // Do some cleanup.
9242 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9243 getContext().deduplicateMergedDefinitonsFor(ND);
9244 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009245}
9246
9247void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00009248 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
9249 return;
9250
Richard Smitha0ce9c42014-07-29 23:23:27 +00009251 // Trigger the import of the full definition of each class that had any
9252 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009253 // These updates may in turn find and diagnose some ODR failures, so take
9254 // ownership of the set first.
9255 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9256 PendingOdrMergeFailures.clear();
9257 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009258 Merge.first->buildLookup();
9259 Merge.first->decls_begin();
9260 Merge.first->bases_begin();
9261 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009262 for (auto &RecordPair : Merge.second) {
9263 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009264 RD->decls_begin();
9265 RD->bases_begin();
9266 RD->vbases_begin();
9267 }
9268 }
9269
9270 // For each declaration from a merged context, check that the canonical
9271 // definition of that context also contains a declaration of the same
9272 // entity.
9273 //
9274 // Caution: this loop does things that might invalidate iterators into
9275 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9276 while (!PendingOdrMergeChecks.empty()) {
9277 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9278
9279 // FIXME: Skip over implicit declarations for now. This matters for things
9280 // like implicitly-declared special member functions. This isn't entirely
9281 // correct; we can end up with multiple unmerged declarations of the same
9282 // implicit entity.
9283 if (D->isImplicit())
9284 continue;
9285
9286 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009287
9288 bool Found = false;
9289 const Decl *DCanon = D->getCanonicalDecl();
9290
Richard Smith01bdb7a2014-08-28 05:44:07 +00009291 for (auto RI : D->redecls()) {
9292 if (RI->getLexicalDeclContext() == CanonDef) {
9293 Found = true;
9294 break;
9295 }
9296 }
9297 if (Found)
9298 continue;
9299
Richard Smith0f4e2c42015-08-06 04:23:48 +00009300 // Quick check failed, time to do the slow thing. Note, we can't just
9301 // look up the name of D in CanonDef here, because the member that is
9302 // in CanonDef might not be found by name lookup (it might have been
9303 // replaced by a more recent declaration in the lookup table), and we
9304 // can't necessarily find it in the redeclaration chain because it might
9305 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009306 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009307 for (auto *CanonMember : CanonDef->decls()) {
9308 if (CanonMember->getCanonicalDecl() == DCanon) {
9309 // This can happen if the declaration is merely mergeable and not
9310 // actually redeclarable (we looked for redeclarations earlier).
9311 //
9312 // FIXME: We should be able to detect this more efficiently, without
9313 // pulling in all of the members of CanonDef.
9314 Found = true;
9315 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009316 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009317 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9318 if (ND->getDeclName() == D->getDeclName())
9319 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009320 }
9321
9322 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009323 // The AST doesn't like TagDecls becoming invalid after they've been
9324 // completed. We only really need to mark FieldDecls as invalid here.
9325 if (!isa<TagDecl>(D))
9326 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009327
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009328 // Ensure we don't accidentally recursively enter deserialization while
9329 // we're producing our diagnostic.
9330 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009331
9332 std::string CanonDefModule =
9333 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9334 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9335 << D << getOwningModuleNameForDiagnostic(D)
9336 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9337
9338 if (Candidates.empty())
9339 Diag(cast<Decl>(CanonDef)->getLocation(),
9340 diag::note_module_odr_violation_no_possible_decls) << D;
9341 else {
9342 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9343 Diag(Candidates[I]->getLocation(),
9344 diag::note_module_odr_violation_possible_decl)
9345 << Candidates[I];
9346 }
9347
9348 DiagnosedOdrMergeFailures.insert(CanonDef);
9349 }
9350 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009351
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009352 if (OdrMergeFailures.empty())
9353 return;
9354
9355 // Ensure we don't accidentally recursively enter deserialization while
9356 // we're producing our diagnostics.
9357 Deserializing RecursionGuard(this);
9358
Richard Smithcd45dbc2014-04-19 03:48:30 +00009359 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009360 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009361 // If we've already pointed out a specific problem with this class, don't
9362 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009363 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009364 continue;
9365
9366 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009367 CXXRecordDecl *FirstRecord = Merge.first;
9368 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009369 for (auto &RecordPair : Merge.second) {
9370 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009371 // Multiple different declarations got merged together; tell the user
9372 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009373 if (FirstRecord == SecondRecord)
9374 continue;
9375
9376 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009377
9378 auto *FirstDD = FirstRecord->DefinitionData;
9379 auto *SecondDD = RecordPair.second;
9380
9381 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9382
9383 // Diagnostics from DefinitionData are emitted here.
9384 if (FirstDD != SecondDD) {
9385 enum ODRDefinitionDataDifference {
9386 NumBases,
9387 NumVBases,
9388 BaseType,
9389 BaseVirtual,
9390 BaseAccess,
9391 };
9392 auto ODRDiagError = [FirstRecord, &FirstModule,
9393 this](SourceLocation Loc, SourceRange Range,
9394 ODRDefinitionDataDifference DiffType) {
9395 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9396 << FirstRecord << FirstModule.empty() << FirstModule << Range
9397 << DiffType;
9398 };
9399 auto ODRDiagNote = [&SecondModule,
9400 this](SourceLocation Loc, SourceRange Range,
9401 ODRDefinitionDataDifference DiffType) {
9402 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9403 << SecondModule << Range << DiffType;
9404 };
9405
9406 ODRHash Hash;
9407 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9408 Hash.clear();
9409 Hash.AddQualType(Ty);
9410 return Hash.CalculateHash();
9411 };
9412
9413 unsigned FirstNumBases = FirstDD->NumBases;
9414 unsigned FirstNumVBases = FirstDD->NumVBases;
9415 unsigned SecondNumBases = SecondDD->NumBases;
9416 unsigned SecondNumVBases = SecondDD->NumVBases;
9417
9418 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9419 unsigned NumBases = DD->NumBases;
9420 if (NumBases == 0) return SourceRange();
9421 auto bases = DD->bases();
9422 return SourceRange(bases[0].getLocStart(),
9423 bases[NumBases - 1].getLocEnd());
9424 };
9425
9426 if (FirstNumBases != SecondNumBases) {
9427 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9428 NumBases)
9429 << FirstNumBases;
9430 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9431 NumBases)
9432 << SecondNumBases;
9433 Diagnosed = true;
9434 break;
9435 }
9436
9437 if (FirstNumVBases != SecondNumVBases) {
9438 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9439 NumVBases)
9440 << FirstNumVBases;
9441 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9442 NumVBases)
9443 << SecondNumVBases;
9444 Diagnosed = true;
9445 break;
9446 }
9447
9448 auto FirstBases = FirstDD->bases();
9449 auto SecondBases = SecondDD->bases();
9450 unsigned i = 0;
9451 for (i = 0; i < FirstNumBases; ++i) {
9452 auto FirstBase = FirstBases[i];
9453 auto SecondBase = SecondBases[i];
9454 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9455 ComputeQualTypeODRHash(SecondBase.getType())) {
9456 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9457 BaseType)
9458 << (i + 1) << FirstBase.getType();
9459 ODRDiagNote(SecondRecord->getLocation(),
9460 SecondBase.getSourceRange(), BaseType)
9461 << (i + 1) << SecondBase.getType();
9462 break;
9463 }
9464
9465 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9466 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9467 BaseVirtual)
9468 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9469 ODRDiagNote(SecondRecord->getLocation(),
9470 SecondBase.getSourceRange(), BaseVirtual)
9471 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9472 break;
9473 }
9474
9475 if (FirstBase.getAccessSpecifierAsWritten() !=
9476 SecondBase.getAccessSpecifierAsWritten()) {
9477 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9478 BaseAccess)
9479 << (i + 1) << FirstBase.getType()
9480 << (int)FirstBase.getAccessSpecifierAsWritten();
9481 ODRDiagNote(SecondRecord->getLocation(),
9482 SecondBase.getSourceRange(), BaseAccess)
9483 << (i + 1) << SecondBase.getType()
9484 << (int)SecondBase.getAccessSpecifierAsWritten();
9485 break;
9486 }
9487 }
9488
9489 if (i != FirstNumBases) {
9490 Diagnosed = true;
9491 break;
9492 }
9493 }
9494
Richard Trieue7f7ed22017-02-22 01:11:25 +00009495 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009496
9497 const ClassTemplateDecl *FirstTemplate =
9498 FirstRecord->getDescribedClassTemplate();
9499 const ClassTemplateDecl *SecondTemplate =
9500 SecondRecord->getDescribedClassTemplate();
9501
9502 assert(!FirstTemplate == !SecondTemplate &&
9503 "Both pointers should be null or non-null");
9504
9505 enum ODRTemplateDifference {
9506 ParamEmptyName,
9507 ParamName,
9508 ParamSingleDefaultArgument,
9509 ParamDifferentDefaultArgument,
9510 };
9511
9512 if (FirstTemplate && SecondTemplate) {
9513 DeclHashes FirstTemplateHashes;
9514 DeclHashes SecondTemplateHashes;
9515 ODRHash Hash;
9516
9517 auto PopulateTemplateParameterHashs =
9518 [&Hash](DeclHashes &Hashes, const ClassTemplateDecl *TD) {
9519 for (auto *D : TD->getTemplateParameters()->asArray()) {
9520 Hash.clear();
9521 Hash.AddSubDecl(D);
9522 Hashes.emplace_back(D, Hash.CalculateHash());
9523 }
9524 };
9525
9526 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9527 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9528
9529 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9530 "Number of template parameters should be equal.");
9531
9532 auto FirstIt = FirstTemplateHashes.begin();
9533 auto FirstEnd = FirstTemplateHashes.end();
9534 auto SecondIt = SecondTemplateHashes.begin();
9535 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9536 if (FirstIt->second == SecondIt->second)
9537 continue;
9538
9539 auto ODRDiagError = [FirstRecord, &FirstModule,
9540 this](SourceLocation Loc, SourceRange Range,
9541 ODRTemplateDifference DiffType) {
9542 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9543 << FirstRecord << FirstModule.empty() << FirstModule << Range
9544 << DiffType;
9545 };
9546 auto ODRDiagNote = [&SecondModule,
9547 this](SourceLocation Loc, SourceRange Range,
9548 ODRTemplateDifference DiffType) {
9549 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9550 << SecondModule << Range << DiffType;
9551 };
9552
9553 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9554 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
9555
9556 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9557 "Parameter Decl's should be the same kind.");
9558
9559 DeclarationName FirstName = FirstDecl->getDeclName();
9560 DeclarationName SecondName = SecondDecl->getDeclName();
9561
9562 if (FirstName != SecondName) {
9563 const bool FirstNameEmpty =
9564 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9565 const bool SecondNameEmpty =
9566 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9567 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9568 "Both template parameters cannot be unnamed.");
9569 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9570 FirstNameEmpty ? ParamEmptyName : ParamName)
9571 << FirstName;
9572 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9573 SecondNameEmpty ? ParamEmptyName : ParamName)
9574 << SecondName;
9575 break;
9576 }
9577
9578 switch (FirstDecl->getKind()) {
9579 default:
9580 llvm_unreachable("Invalid template parameter type.");
9581 case Decl::TemplateTypeParm: {
9582 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9583 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9584 const bool HasFirstDefaultArgument =
9585 FirstParam->hasDefaultArgument() &&
9586 !FirstParam->defaultArgumentWasInherited();
9587 const bool HasSecondDefaultArgument =
9588 SecondParam->hasDefaultArgument() &&
9589 !SecondParam->defaultArgumentWasInherited();
9590
9591 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9592 ODRDiagError(FirstDecl->getLocation(),
9593 FirstDecl->getSourceRange(),
9594 ParamSingleDefaultArgument)
9595 << HasFirstDefaultArgument;
9596 ODRDiagNote(SecondDecl->getLocation(),
9597 SecondDecl->getSourceRange(),
9598 ParamSingleDefaultArgument)
9599 << HasSecondDefaultArgument;
9600 break;
9601 }
9602
9603 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9604 "Expecting default arguments.");
9605
9606 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9607 ParamDifferentDefaultArgument);
9608 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9609 ParamDifferentDefaultArgument);
9610
9611 break;
9612 }
9613 case Decl::NonTypeTemplateParm: {
9614 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9615 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9616 const bool HasFirstDefaultArgument =
9617 FirstParam->hasDefaultArgument() &&
9618 !FirstParam->defaultArgumentWasInherited();
9619 const bool HasSecondDefaultArgument =
9620 SecondParam->hasDefaultArgument() &&
9621 !SecondParam->defaultArgumentWasInherited();
9622
9623 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9624 ODRDiagError(FirstDecl->getLocation(),
9625 FirstDecl->getSourceRange(),
9626 ParamSingleDefaultArgument)
9627 << HasFirstDefaultArgument;
9628 ODRDiagNote(SecondDecl->getLocation(),
9629 SecondDecl->getSourceRange(),
9630 ParamSingleDefaultArgument)
9631 << HasSecondDefaultArgument;
9632 break;
9633 }
9634
9635 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9636 "Expecting default arguments.");
9637
9638 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9639 ParamDifferentDefaultArgument);
9640 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9641 ParamDifferentDefaultArgument);
9642
9643 break;
9644 }
9645 case Decl::TemplateTemplateParm: {
9646 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9647 const auto *SecondParam =
9648 cast<TemplateTemplateParmDecl>(SecondDecl);
9649 const bool HasFirstDefaultArgument =
9650 FirstParam->hasDefaultArgument() &&
9651 !FirstParam->defaultArgumentWasInherited();
9652 const bool HasSecondDefaultArgument =
9653 SecondParam->hasDefaultArgument() &&
9654 !SecondParam->defaultArgumentWasInherited();
9655
9656 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9657 ODRDiagError(FirstDecl->getLocation(),
9658 FirstDecl->getSourceRange(),
9659 ParamSingleDefaultArgument)
9660 << HasFirstDefaultArgument;
9661 ODRDiagNote(SecondDecl->getLocation(),
9662 SecondDecl->getSourceRange(),
9663 ParamSingleDefaultArgument)
9664 << HasSecondDefaultArgument;
9665 break;
9666 }
9667
9668 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9669 "Expecting default arguments.");
9670
9671 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9672 ParamDifferentDefaultArgument);
9673 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9674 ParamDifferentDefaultArgument);
9675
9676 break;
9677 }
9678 }
9679
9680 break;
9681 }
9682
9683 if (FirstIt != FirstEnd) {
9684 Diagnosed = true;
9685 break;
9686 }
9687 }
9688
Richard Trieue7f7ed22017-02-22 01:11:25 +00009689 DeclHashes FirstHashes;
9690 DeclHashes SecondHashes;
9691 ODRHash Hash;
9692
9693 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9694 CXXRecordDecl *Record) {
9695 for (auto *D : Record->decls()) {
9696 // Due to decl merging, the first CXXRecordDecl is the parent of
9697 // Decls in both records.
9698 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9699 continue;
9700 Hash.clear();
9701 Hash.AddSubDecl(D);
9702 Hashes.emplace_back(D, Hash.CalculateHash());
9703 }
9704 };
9705 PopulateHashes(FirstHashes, FirstRecord);
9706 PopulateHashes(SecondHashes, SecondRecord);
9707
9708 // Used with err_module_odr_violation_mismatch_decl and
9709 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009710 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009711 enum {
9712 EndOfClass,
9713 PublicSpecifer,
9714 PrivateSpecifer,
9715 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009716 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009717 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009718 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009719 TypeAlias,
9720 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009721 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009722 Friend,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009723 Other
9724 } FirstDiffType = Other,
9725 SecondDiffType = Other;
9726
9727 auto DifferenceSelector = [](Decl *D) {
9728 assert(D && "valid Decl required");
9729 switch (D->getKind()) {
9730 default:
9731 return Other;
9732 case Decl::AccessSpec:
9733 switch (D->getAccess()) {
9734 case AS_public:
9735 return PublicSpecifer;
9736 case AS_private:
9737 return PrivateSpecifer;
9738 case AS_protected:
9739 return ProtectedSpecifer;
9740 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009741 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009742 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009743 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009744 case Decl::StaticAssert:
9745 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009746 case Decl::Field:
9747 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009748 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +00009749 case Decl::CXXConstructor:
9750 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +00009751 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +00009752 case Decl::TypeAlias:
9753 return TypeAlias;
9754 case Decl::Typedef:
9755 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +00009756 case Decl::Var:
9757 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +00009758 case Decl::Friend:
9759 return Friend;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009760 }
9761 };
9762
9763 Decl *FirstDecl = nullptr;
9764 Decl *SecondDecl = nullptr;
9765 auto FirstIt = FirstHashes.begin();
9766 auto SecondIt = SecondHashes.begin();
9767
9768 // If there is a diagnoseable difference, FirstDiffType and
9769 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9770 // filled in if not EndOfClass.
9771 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009772 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9773 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009774 ++FirstIt;
9775 ++SecondIt;
9776 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009777 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009778
Richard Trieue7f7ed22017-02-22 01:11:25 +00009779 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9780 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9781
9782 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9783 SecondDiffType =
9784 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9785
9786 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009787 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009788
9789 if (FirstDiffType == Other || SecondDiffType == Other) {
9790 // Reaching this point means an unexpected Decl was encountered
9791 // or no difference was detected. This causes a generic error
9792 // message to be emitted.
9793 Diag(FirstRecord->getLocation(),
9794 diag::err_module_odr_violation_different_definitions)
9795 << FirstRecord << FirstModule.empty() << FirstModule;
9796
Richard Trieuca48d362017-06-21 01:43:13 +00009797 if (FirstDecl) {
9798 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9799 << FirstRecord << FirstDecl->getSourceRange();
9800 }
9801
Richard Trieue7f7ed22017-02-22 01:11:25 +00009802 Diag(SecondRecord->getLocation(),
9803 diag::note_module_odr_violation_different_definitions)
9804 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +00009805
9806 if (SecondDecl) {
9807 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9808 << SecondDecl->getSourceRange();
9809 }
9810
Richard Trieue7f7ed22017-02-22 01:11:25 +00009811 Diagnosed = true;
9812 break;
9813 }
9814
9815 if (FirstDiffType != SecondDiffType) {
9816 SourceLocation FirstLoc;
9817 SourceRange FirstRange;
9818 if (FirstDiffType == EndOfClass) {
9819 FirstLoc = FirstRecord->getBraceRange().getEnd();
9820 } else {
9821 FirstLoc = FirstIt->first->getLocation();
9822 FirstRange = FirstIt->first->getSourceRange();
9823 }
9824 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9825 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9826 << FirstDiffType;
9827
9828 SourceLocation SecondLoc;
9829 SourceRange SecondRange;
9830 if (SecondDiffType == EndOfClass) {
9831 SecondLoc = SecondRecord->getBraceRange().getEnd();
9832 } else {
9833 SecondLoc = SecondDecl->getLocation();
9834 SecondRange = SecondDecl->getSourceRange();
9835 }
9836 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9837 << SecondModule << SecondRange << SecondDiffType;
9838 Diagnosed = true;
9839 break;
9840 }
9841
Richard Trieu639d7b62017-02-22 22:22:42 +00009842 assert(FirstDiffType == SecondDiffType);
9843
9844 // Used with err_module_odr_violation_mismatch_decl_diff and
9845 // note_module_odr_violation_mismatch_decl_diff
9846 enum ODRDeclDifference{
9847 StaticAssertCondition,
9848 StaticAssertMessage,
9849 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009850 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009851 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009852 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009853 FieldDifferentWidthBitField,
9854 FieldSingleMutable,
9855 FieldSingleInitializer,
9856 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009857 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009858 MethodDeleted,
9859 MethodVirtual,
9860 MethodStatic,
9861 MethodVolatile,
9862 MethodConst,
9863 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009864 MethodNumberParameters,
9865 MethodParameterType,
9866 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009867 MethodParameterSingleDefaultArgument,
9868 MethodParameterDifferentDefaultArgument,
Richard Trieu11d566a2017-06-12 21:58:22 +00009869 TypedefName,
9870 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009871 VarName,
9872 VarType,
9873 VarSingleInitializer,
9874 VarDifferentInitializer,
9875 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009876 FriendTypeFunction,
9877 FriendType,
9878 FriendFunction,
Richard Trieu639d7b62017-02-22 22:22:42 +00009879 };
9880
9881 // These lambdas have the common portions of the ODR diagnostics. This
9882 // has the same return as Diag(), so addition parameters can be passed
9883 // in with operator<<
9884 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9885 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9886 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9887 << FirstRecord << FirstModule.empty() << FirstModule << Range
9888 << DiffType;
9889 };
9890 auto ODRDiagNote = [&SecondModule, this](
9891 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9892 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9893 << SecondModule << Range << DiffType;
9894 };
9895
9896 auto ComputeODRHash = [&Hash](const Stmt* S) {
9897 assert(S);
9898 Hash.clear();
9899 Hash.AddStmt(S);
9900 return Hash.CalculateHash();
9901 };
9902
Richard Trieu02552272017-05-02 23:58:52 +00009903 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9904 Hash.clear();
9905 Hash.AddQualType(Ty);
9906 return Hash.CalculateHash();
9907 };
9908
Richard Trieu639d7b62017-02-22 22:22:42 +00009909 switch (FirstDiffType) {
9910 case Other:
9911 case EndOfClass:
9912 case PublicSpecifer:
9913 case PrivateSpecifer:
9914 case ProtectedSpecifer:
9915 llvm_unreachable("Invalid diff type");
9916
9917 case StaticAssert: {
9918 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9919 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9920
9921 Expr *FirstExpr = FirstSA->getAssertExpr();
9922 Expr *SecondExpr = SecondSA->getAssertExpr();
9923 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9924 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9925 if (FirstODRHash != SecondODRHash) {
9926 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9927 StaticAssertCondition);
9928 ODRDiagNote(SecondExpr->getLocStart(),
9929 SecondExpr->getSourceRange(), StaticAssertCondition);
9930 Diagnosed = true;
9931 break;
9932 }
9933
9934 StringLiteral *FirstStr = FirstSA->getMessage();
9935 StringLiteral *SecondStr = SecondSA->getMessage();
9936 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9937 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9938 SourceLocation FirstLoc, SecondLoc;
9939 SourceRange FirstRange, SecondRange;
9940 if (FirstStr) {
9941 FirstLoc = FirstStr->getLocStart();
9942 FirstRange = FirstStr->getSourceRange();
9943 } else {
9944 FirstLoc = FirstSA->getLocStart();
9945 FirstRange = FirstSA->getSourceRange();
9946 }
9947 if (SecondStr) {
9948 SecondLoc = SecondStr->getLocStart();
9949 SecondRange = SecondStr->getSourceRange();
9950 } else {
9951 SecondLoc = SecondSA->getLocStart();
9952 SecondRange = SecondSA->getSourceRange();
9953 }
9954 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9955 << (FirstStr == nullptr);
9956 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9957 << (SecondStr == nullptr);
9958 Diagnosed = true;
9959 break;
9960 }
9961
9962 if (FirstStr && SecondStr &&
9963 FirstStr->getString() != SecondStr->getString()) {
9964 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9965 StaticAssertMessage);
9966 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9967 StaticAssertMessage);
9968 Diagnosed = true;
9969 break;
9970 }
9971 break;
9972 }
Richard Trieud0786092017-02-23 00:23:01 +00009973 case Field: {
9974 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9975 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9976 IdentifierInfo *FirstII = FirstField->getIdentifier();
9977 IdentifierInfo *SecondII = SecondField->getIdentifier();
9978 if (FirstII->getName() != SecondII->getName()) {
9979 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9980 FieldName)
9981 << FirstII;
9982 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9983 FieldName)
9984 << SecondII;
9985
9986 Diagnosed = true;
9987 break;
9988 }
Richard Trieu8459ddf2017-02-24 02:59:12 +00009989
Richard Smithdbafb6c2017-06-29 23:23:46 +00009990 assert(getContext().hasSameType(FirstField->getType(),
9991 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +00009992
9993 QualType FirstType = FirstField->getType();
9994 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +00009995 if (ComputeQualTypeODRHash(FirstType) !=
9996 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +00009997 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9998 FieldTypeName)
9999 << FirstII << FirstType;
10000 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10001 FieldTypeName)
10002 << SecondII << SecondType;
10003
10004 Diagnosed = true;
10005 break;
10006 }
10007
Richard Trieu93772fc2017-02-24 20:59:28 +000010008 const bool IsFirstBitField = FirstField->isBitField();
10009 const bool IsSecondBitField = SecondField->isBitField();
10010 if (IsFirstBitField != IsSecondBitField) {
10011 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10012 FieldSingleBitField)
10013 << FirstII << IsFirstBitField;
10014 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10015 FieldSingleBitField)
10016 << SecondII << IsSecondBitField;
10017 Diagnosed = true;
10018 break;
10019 }
10020
10021 if (IsFirstBitField && IsSecondBitField) {
10022 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10023 FieldDifferentWidthBitField)
10024 << FirstII << FirstField->getBitWidth()->getSourceRange();
10025 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10026 FieldDifferentWidthBitField)
10027 << SecondII << SecondField->getBitWidth()->getSourceRange();
10028 Diagnosed = true;
10029 break;
10030 }
10031
Richard Trieu8d543e22017-02-24 23:35:37 +000010032 const bool IsFirstMutable = FirstField->isMutable();
10033 const bool IsSecondMutable = SecondField->isMutable();
10034 if (IsFirstMutable != IsSecondMutable) {
10035 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10036 FieldSingleMutable)
10037 << FirstII << IsFirstMutable;
10038 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10039 FieldSingleMutable)
10040 << SecondII << IsSecondMutable;
10041 Diagnosed = true;
10042 break;
10043 }
10044
10045 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10046 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10047 if ((!FirstInitializer && SecondInitializer) ||
10048 (FirstInitializer && !SecondInitializer)) {
10049 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10050 FieldSingleInitializer)
10051 << FirstII << (FirstInitializer != nullptr);
10052 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10053 FieldSingleInitializer)
10054 << SecondII << (SecondInitializer != nullptr);
10055 Diagnosed = true;
10056 break;
10057 }
10058
10059 if (FirstInitializer && SecondInitializer) {
10060 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10061 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10062 if (FirstInitHash != SecondInitHash) {
10063 ODRDiagError(FirstField->getLocation(),
10064 FirstField->getSourceRange(),
10065 FieldDifferentInitializers)
10066 << FirstII << FirstInitializer->getSourceRange();
10067 ODRDiagNote(SecondField->getLocation(),
10068 SecondField->getSourceRange(),
10069 FieldDifferentInitializers)
10070 << SecondII << SecondInitializer->getSourceRange();
10071 Diagnosed = true;
10072 break;
10073 }
10074 }
10075
Richard Trieud0786092017-02-23 00:23:01 +000010076 break;
10077 }
Richard Trieu48143742017-02-28 21:24:38 +000010078 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010079 enum {
10080 DiagMethod,
10081 DiagConstructor,
10082 DiagDestructor,
10083 } FirstMethodType,
10084 SecondMethodType;
10085 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10086 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10087 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10088 return DiagMethod;
10089 };
Richard Trieu48143742017-02-28 21:24:38 +000010090 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10091 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010092 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10093 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010094 auto FirstName = FirstMethod->getDeclName();
10095 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010096 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010097 ODRDiagError(FirstMethod->getLocation(),
10098 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010099 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010100 ODRDiagNote(SecondMethod->getLocation(),
10101 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010102 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010103
10104 Diagnosed = true;
10105 break;
10106 }
10107
Richard Trieu583e2c12017-03-04 00:08:58 +000010108 const bool FirstDeleted = FirstMethod->isDeleted();
10109 const bool SecondDeleted = SecondMethod->isDeleted();
10110 if (FirstDeleted != SecondDeleted) {
10111 ODRDiagError(FirstMethod->getLocation(),
10112 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010113 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010114
10115 ODRDiagNote(SecondMethod->getLocation(),
10116 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010117 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010118 Diagnosed = true;
10119 break;
10120 }
10121
10122 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10123 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10124 const bool FirstPure = FirstMethod->isPure();
10125 const bool SecondPure = SecondMethod->isPure();
10126 if ((FirstVirtual || SecondVirtual) &&
10127 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10128 ODRDiagError(FirstMethod->getLocation(),
10129 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010130 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010131 ODRDiagNote(SecondMethod->getLocation(),
10132 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010133 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010134 Diagnosed = true;
10135 break;
10136 }
10137
10138 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10139 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10140 // class needs to be checked instead.
10141 const auto FirstStorage = FirstMethod->getStorageClass();
10142 const auto SecondStorage = SecondMethod->getStorageClass();
10143 const bool FirstStatic = FirstStorage == SC_Static;
10144 const bool SecondStatic = SecondStorage == SC_Static;
10145 if (FirstStatic != SecondStatic) {
10146 ODRDiagError(FirstMethod->getLocation(),
10147 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010148 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010149 ODRDiagNote(SecondMethod->getLocation(),
10150 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010151 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010152 Diagnosed = true;
10153 break;
10154 }
10155
10156 const bool FirstVolatile = FirstMethod->isVolatile();
10157 const bool SecondVolatile = SecondMethod->isVolatile();
10158 if (FirstVolatile != SecondVolatile) {
10159 ODRDiagError(FirstMethod->getLocation(),
10160 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010161 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010162 ODRDiagNote(SecondMethod->getLocation(),
10163 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010164 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010165 Diagnosed = true;
10166 break;
10167 }
10168
10169 const bool FirstConst = FirstMethod->isConst();
10170 const bool SecondConst = SecondMethod->isConst();
10171 if (FirstConst != SecondConst) {
10172 ODRDiagError(FirstMethod->getLocation(),
10173 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010174 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010175 ODRDiagNote(SecondMethod->getLocation(),
10176 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010177 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010178 Diagnosed = true;
10179 break;
10180 }
10181
10182 const bool FirstInline = FirstMethod->isInlineSpecified();
10183 const bool SecondInline = SecondMethod->isInlineSpecified();
10184 if (FirstInline != SecondInline) {
10185 ODRDiagError(FirstMethod->getLocation(),
10186 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010187 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010188 ODRDiagNote(SecondMethod->getLocation(),
10189 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010190 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010191 Diagnosed = true;
10192 break;
10193 }
10194
Richard Trieu02552272017-05-02 23:58:52 +000010195 const unsigned FirstNumParameters = FirstMethod->param_size();
10196 const unsigned SecondNumParameters = SecondMethod->param_size();
10197 if (FirstNumParameters != SecondNumParameters) {
10198 ODRDiagError(FirstMethod->getLocation(),
10199 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010200 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010201 ODRDiagNote(SecondMethod->getLocation(),
10202 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010203 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010204 Diagnosed = true;
10205 break;
10206 }
10207
10208 // Need this status boolean to know when break out of the switch.
10209 bool ParameterMismatch = false;
10210 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10211 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10212 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10213
10214 QualType FirstParamType = FirstParam->getType();
10215 QualType SecondParamType = SecondParam->getType();
10216 if (FirstParamType != SecondParamType &&
10217 ComputeQualTypeODRHash(FirstParamType) !=
10218 ComputeQualTypeODRHash(SecondParamType)) {
10219 if (const DecayedType *ParamDecayedType =
10220 FirstParamType->getAs<DecayedType>()) {
10221 ODRDiagError(FirstMethod->getLocation(),
10222 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010223 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10224 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010225 } else {
10226 ODRDiagError(FirstMethod->getLocation(),
10227 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010228 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10229 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010230 }
10231
10232 if (const DecayedType *ParamDecayedType =
10233 SecondParamType->getAs<DecayedType>()) {
10234 ODRDiagNote(SecondMethod->getLocation(),
10235 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010236 << SecondMethodType << SecondName << (I + 1)
10237 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010238 << ParamDecayedType->getOriginalType();
10239 } else {
10240 ODRDiagNote(SecondMethod->getLocation(),
10241 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010242 << SecondMethodType << SecondName << (I + 1)
10243 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010244 }
10245 ParameterMismatch = true;
10246 break;
10247 }
10248
10249 DeclarationName FirstParamName = FirstParam->getDeclName();
10250 DeclarationName SecondParamName = SecondParam->getDeclName();
10251 if (FirstParamName != SecondParamName) {
10252 ODRDiagError(FirstMethod->getLocation(),
10253 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010254 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010255 ODRDiagNote(SecondMethod->getLocation(),
10256 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010257 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010258 ParameterMismatch = true;
10259 break;
10260 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010261
10262 const Expr *FirstInit = FirstParam->getInit();
10263 const Expr *SecondInit = SecondParam->getInit();
10264 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10265 ODRDiagError(FirstMethod->getLocation(),
10266 FirstMethod->getSourceRange(),
10267 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010268 << FirstMethodType << FirstName << (I + 1)
10269 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010270 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10271 ODRDiagNote(SecondMethod->getLocation(),
10272 SecondMethod->getSourceRange(),
10273 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010274 << SecondMethodType << SecondName << (I + 1)
10275 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010276 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10277 ParameterMismatch = true;
10278 break;
10279 }
10280
10281 if (FirstInit && SecondInit &&
10282 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10283 ODRDiagError(FirstMethod->getLocation(),
10284 FirstMethod->getSourceRange(),
10285 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010286 << FirstMethodType << FirstName << (I + 1)
10287 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010288 ODRDiagNote(SecondMethod->getLocation(),
10289 SecondMethod->getSourceRange(),
10290 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010291 << SecondMethodType << SecondName << (I + 1)
10292 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010293 ParameterMismatch = true;
10294 break;
10295
10296 }
Richard Trieu02552272017-05-02 23:58:52 +000010297 }
10298
10299 if (ParameterMismatch) {
10300 Diagnosed = true;
10301 break;
10302 }
10303
Richard Trieu48143742017-02-28 21:24:38 +000010304 break;
10305 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010306 case TypeAlias:
10307 case TypeDef: {
10308 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10309 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
10310 auto FirstName = FirstTD->getDeclName();
10311 auto SecondName = SecondTD->getDeclName();
10312 if (FirstName != SecondName) {
10313 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10314 TypedefName)
10315 << (FirstDiffType == TypeAlias) << FirstName;
10316 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10317 TypedefName)
10318 << (FirstDiffType == TypeAlias) << SecondName;
10319 Diagnosed = true;
10320 break;
10321 }
10322
10323 QualType FirstType = FirstTD->getUnderlyingType();
10324 QualType SecondType = SecondTD->getUnderlyingType();
10325 if (ComputeQualTypeODRHash(FirstType) !=
10326 ComputeQualTypeODRHash(SecondType)) {
10327 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10328 TypedefType)
10329 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10330 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10331 TypedefType)
10332 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10333 Diagnosed = true;
10334 break;
10335 }
10336 break;
10337 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010338 case Var: {
10339 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10340 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
10341 auto FirstName = FirstVD->getDeclName();
10342 auto SecondName = SecondVD->getDeclName();
10343 if (FirstName != SecondName) {
10344 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10345 VarName)
10346 << FirstName;
10347 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10348 VarName)
10349 << SecondName;
10350 Diagnosed = true;
10351 break;
10352 }
10353
10354 QualType FirstType = FirstVD->getType();
10355 QualType SecondType = SecondVD->getType();
10356 if (ComputeQualTypeODRHash(FirstType) !=
10357 ComputeQualTypeODRHash(SecondType)) {
10358 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10359 VarType)
10360 << FirstName << FirstType;
10361 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10362 VarType)
10363 << SecondName << SecondType;
10364 Diagnosed = true;
10365 break;
10366 }
10367
10368 const Expr *FirstInit = FirstVD->getInit();
10369 const Expr *SecondInit = SecondVD->getInit();
10370 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10371 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10372 VarSingleInitializer)
10373 << FirstName << (FirstInit == nullptr)
10374 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10375 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10376 VarSingleInitializer)
10377 << SecondName << (SecondInit == nullptr)
10378 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10379 Diagnosed = true;
10380 break;
10381 }
10382
10383 if (FirstInit && SecondInit &&
10384 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10385 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10386 VarDifferentInitializer)
10387 << FirstName << FirstInit->getSourceRange();
10388 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10389 VarDifferentInitializer)
10390 << SecondName << SecondInit->getSourceRange();
10391 Diagnosed = true;
10392 break;
10393 }
10394
10395 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10396 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10397 if (FirstIsConstexpr != SecondIsConstexpr) {
10398 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10399 VarConstexpr)
10400 << FirstName << FirstIsConstexpr;
10401 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10402 VarConstexpr)
10403 << SecondName << SecondIsConstexpr;
10404 Diagnosed = true;
10405 break;
10406 }
10407 break;
10408 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010409 case Friend: {
10410 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10411 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10412
10413 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10414 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10415
10416 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10417 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10418
10419 if (FirstND && SecondND) {
10420 ODRDiagError(FirstFriend->getFriendLoc(),
10421 FirstFriend->getSourceRange(), FriendFunction)
10422 << FirstND;
10423 ODRDiagNote(SecondFriend->getFriendLoc(),
10424 SecondFriend->getSourceRange(), FriendFunction)
10425 << SecondND;
10426
10427 Diagnosed = true;
10428 break;
10429 }
10430
10431 if (FirstTSI && SecondTSI) {
10432 QualType FirstFriendType = FirstTSI->getType();
10433 QualType SecondFriendType = SecondTSI->getType();
10434 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10435 ComputeQualTypeODRHash(SecondFriendType));
10436 ODRDiagError(FirstFriend->getFriendLoc(),
10437 FirstFriend->getSourceRange(), FriendType)
10438 << FirstFriendType;
10439 ODRDiagNote(SecondFriend->getFriendLoc(),
10440 SecondFriend->getSourceRange(), FriendType)
10441 << SecondFriendType;
10442 Diagnosed = true;
10443 break;
10444 }
10445
10446 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10447 FriendTypeFunction)
10448 << (FirstTSI == nullptr);
10449 ODRDiagNote(SecondFriend->getFriendLoc(),
10450 SecondFriend->getSourceRange(), FriendTypeFunction)
10451 << (SecondTSI == nullptr);
10452
10453 Diagnosed = true;
10454 break;
10455 }
Richard Trieu639d7b62017-02-22 22:22:42 +000010456 }
10457
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000010458 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000010459 continue;
10460
Richard Trieu708859a2017-06-08 00:56:21 +000010461 Diag(FirstDecl->getLocation(),
10462 diag::err_module_odr_violation_mismatch_decl_unknown)
10463 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10464 << FirstDecl->getSourceRange();
10465 Diag(SecondDecl->getLocation(),
10466 diag::note_module_odr_violation_mismatch_decl_unknown)
10467 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000010468 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010469 }
10470
10471 if (!Diagnosed) {
10472 // All definitions are updates to the same declaration. This happens if a
10473 // module instantiates the declaration of a class template specialization
10474 // and two or more other modules instantiate its definition.
10475 //
10476 // FIXME: Indicate which modules had instantiations of this definition.
10477 // FIXME: How can this even happen?
10478 Diag(Merge.first->getLocation(),
10479 diag::err_module_odr_violation_different_instantiations)
10480 << Merge.first;
10481 }
10482 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010483}
10484
Richard Smithce18a182015-07-14 00:26:00 +000010485void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010486 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000010487 ReadTimer->startTimer();
10488}
10489
Guy Benyei11169dd2012-12-18 14:30:41 +000010490void ASTReader::FinishedDeserializing() {
10491 assert(NumCurrentElementsDeserializing &&
10492 "FinishedDeserializing not paired with StartedDeserializing");
10493 if (NumCurrentElementsDeserializing == 1) {
10494 // We decrease NumCurrentElementsDeserializing only after pending actions
10495 // are finished, to avoid recursively re-calling finishPendingActions().
10496 finishPendingActions();
10497 }
10498 --NumCurrentElementsDeserializing;
10499
Richard Smitha0ce9c42014-07-29 23:23:27 +000010500 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010501 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +000010502 while (!PendingExceptionSpecUpdates.empty()) {
10503 auto Updates = std::move(PendingExceptionSpecUpdates);
10504 PendingExceptionSpecUpdates.clear();
10505 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000010506 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000010507 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000010508 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000010509 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000010510 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000010511 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000010512 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000010513 }
Richard Smith9e2341d2015-03-23 03:25:59 +000010514 }
10515
Richard Smithce18a182015-07-14 00:26:00 +000010516 if (ReadTimer)
10517 ReadTimer->stopTimer();
10518
Richard Smith0f4e2c42015-08-06 04:23:48 +000010519 diagnoseOdrViolations();
10520
Richard Smith04d05b52014-03-23 00:27:18 +000010521 // We are not in recursive loading, so it's safe to pass the "interesting"
10522 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010523 if (Consumer)
10524 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000010525 }
10526}
10527
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010528void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010529 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10530 // Remove any fake results before adding any real ones.
10531 auto It = PendingFakeLookupResults.find(II);
10532 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000010533 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000010534 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000010535 // FIXME: this works around module+PCH performance issue.
10536 // Rather than erase the result from the map, which is O(n), just clear
10537 // the vector of NamedDecls.
10538 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000010539 }
10540 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010541
10542 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10543 SemaObj->TUScope->AddDecl(D);
10544 } else if (SemaObj->TUScope) {
10545 // Adding the decl to IdResolver may have failed because it was already in
10546 // (even though it was not added in scope). If it is already in, make sure
10547 // it gets in the scope as well.
10548 if (std::find(SemaObj->IdResolver.begin(Name),
10549 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
10550 SemaObj->TUScope->AddDecl(D);
10551 }
10552}
10553
Richard Smithdbafb6c2017-06-29 23:23:46 +000010554ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000010555 const PCHContainerReader &PCHContainerRdr,
10556 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10557 StringRef isysroot, bool DisableValidation,
10558 bool AllowASTWithCompilerErrors,
10559 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10560 bool UseGlobalIndex,
10561 std::unique_ptr<llvm::Timer> ReadTimer)
10562 : Listener(DisableValidation
10563 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
10564 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000010565 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010566 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Richard Smithdbafb6c2017-06-29 23:23:46 +000010567 ContextObj(Context),
Boris Kolpackovd30446f2017-08-31 06:26:43 +000010568 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
10569 PP.getHeaderSearchInfo()),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000010570 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
10571 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000010572 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000010573 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10574 AllowConfigurationMismatch(AllowConfigurationMismatch),
10575 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010576 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000010577 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000010578
10579 for (const auto &Ext : Extensions) {
10580 auto BlockName = Ext->getExtensionMetadata().BlockName;
10581 auto Known = ModuleFileExtensions.find(BlockName);
10582 if (Known != ModuleFileExtensions.end()) {
10583 Diags.Report(diag::warn_duplicate_module_file_extension)
10584 << BlockName;
10585 continue;
10586 }
10587
10588 ModuleFileExtensions.insert({BlockName, Ext});
10589 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010590}
10591
10592ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000010593 if (OwnsDeserializationListener)
10594 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000010595}
Richard Smith10379092016-05-06 23:14:07 +000010596
10597IdentifierResolver &ASTReader::getIdResolver() {
10598 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10599}
David L. Jonesbe1557a2016-12-21 00:17:49 +000010600
10601unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
10602 unsigned AbbrevID) {
10603 Idx = 0;
10604 Record.clear();
10605 return Cursor.readRecord(AbbrevID, Record);
10606}