blob: 547dda73f7327c1e8a8dccef4bfa18711dbf144b [file] [log] [blame]
Richard Smith9e2341d2015-03-23 03:25:59 +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"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000022#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000023#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000026#include "clang/Basic/DiagnosticOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/Basic/FileManager.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/SourceManagerInternals.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/Version.h"
33#include "clang/Basic/VersionTuple.h"
Ben Langmuirb92de022014-04-29 16:25:26 +000034#include "clang/Frontend/Utils.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000035#include "clang/Lex/HeaderSearch.h"
36#include "clang/Lex/HeaderSearchOptions.h"
37#include "clang/Lex/MacroInfo.h"
38#include "clang/Lex/PreprocessingRecord.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/PreprocessorOptions.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000044#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Serialization/ModuleManager.h"
46#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000047#include "llvm/ADT/Hashing.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "llvm/ADT/StringExtras.h"
49#include "llvm/Bitcode/BitstreamReader.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MemoryBuffer.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000055#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000056#include <algorithm>
Chris Lattner91f373e2013-01-20 00:57:52 +000057#include <cstdio>
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include <iterator>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000059#include <system_error>
Guy Benyei11169dd2012-12-18 14:30:41 +000060
61using namespace clang;
62using namespace clang::serialization;
63using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +000064using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +000065
Ben Langmuircb69b572014-03-07 06:40:32 +000066
67//===----------------------------------------------------------------------===//
68// ChainedASTReaderListener implementation
69//===----------------------------------------------------------------------===//
70
71bool
72ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
73 return First->ReadFullVersionInformation(FullVersion) ||
74 Second->ReadFullVersionInformation(FullVersion);
75}
Ben Langmuir4f5212a2014-04-14 22:12:44 +000076void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77 First->ReadModuleName(ModuleName);
78 Second->ReadModuleName(ModuleName);
79}
80void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81 First->ReadModuleMapFile(ModuleMapPath);
82 Second->ReadModuleMapFile(ModuleMapPath);
83}
Richard Smith1e2cf0d2014-10-31 02:28:58 +000084bool
85ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
86 bool Complain,
87 bool AllowCompatibleDifferences) {
88 return First->ReadLanguageOptions(LangOpts, Complain,
89 AllowCompatibleDifferences) ||
90 Second->ReadLanguageOptions(LangOpts, Complain,
91 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +000092}
Chandler Carruth0d745bc2015-03-14 04:47:43 +000093bool ChainedASTReaderListener::ReadTargetOptions(
94 const TargetOptions &TargetOpts, bool Complain,
95 bool AllowCompatibleDifferences) {
96 return First->ReadTargetOptions(TargetOpts, Complain,
97 AllowCompatibleDifferences) ||
98 Second->ReadTargetOptions(TargetOpts, Complain,
99 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000100}
101bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000102 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000103 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104 Second->ReadDiagnosticOptions(DiagOpts, Complain);
105}
106bool
107ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
108 bool Complain) {
109 return First->ReadFileSystemOptions(FSOpts, Complain) ||
110 Second->ReadFileSystemOptions(FSOpts, Complain);
111}
112
113bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000114 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
115 bool Complain) {
116 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
117 Complain) ||
118 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000120}
121bool ChainedASTReaderListener::ReadPreprocessorOptions(
122 const PreprocessorOptions &PPOpts, bool Complain,
123 std::string &SuggestedPredefines) {
124 return First->ReadPreprocessorOptions(PPOpts, Complain,
125 SuggestedPredefines) ||
126 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
127}
128void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
129 unsigned Value) {
130 First->ReadCounter(M, Value);
131 Second->ReadCounter(M, Value);
132}
133bool ChainedASTReaderListener::needsInputFileVisitation() {
134 return First->needsInputFileVisitation() ||
135 Second->needsInputFileVisitation();
136}
137bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
138 return First->needsSystemInputFileVisitation() ||
139 Second->needsSystemInputFileVisitation();
140}
Richard Smith216a3bd2015-08-13 17:57:10 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
142 ModuleKind Kind) {
143 First->visitModuleFile(Filename, Kind);
144 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000145}
Ben Langmuircb69b572014-03-07 06:40:32 +0000146bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000147 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000148 bool isOverridden,
149 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000150 bool Continue = false;
151 if (First->needsInputFileVisitation() &&
152 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000153 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
154 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000155 if (Second->needsInputFileVisitation() &&
156 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000157 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
158 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000159 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000160}
161
Guy Benyei11169dd2012-12-18 14:30:41 +0000162//===----------------------------------------------------------------------===//
163// PCH validator implementation
164//===----------------------------------------------------------------------===//
165
166ASTReaderListener::~ASTReaderListener() {}
167
168/// \brief Compare the given set of language options against an existing set of
169/// language options.
170///
171/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000172/// \param AllowCompatibleDifferences If true, differences between compatible
173/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000174///
175/// \returns true if the languagae options mis-match, false otherwise.
176static bool checkLanguageOptions(const LangOptions &LangOpts,
177 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000178 DiagnosticsEngine *Diags,
179 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000180#define LANGOPT(Name, Bits, Default, Description) \
181 if (ExistingLangOpts.Name != LangOpts.Name) { \
182 if (Diags) \
183 Diags->Report(diag::err_pch_langopt_mismatch) \
184 << Description << LangOpts.Name << ExistingLangOpts.Name; \
185 return true; \
186 }
187
188#define VALUE_LANGOPT(Name, Bits, Default, Description) \
189 if (ExistingLangOpts.Name != LangOpts.Name) { \
190 if (Diags) \
191 Diags->Report(diag::err_pch_langopt_value_mismatch) \
192 << Description; \
193 return true; \
194 }
195
196#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
197 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
198 if (Diags) \
199 Diags->Report(diag::err_pch_langopt_value_mismatch) \
200 << Description; \
201 return true; \
202 }
203
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000204#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 LANGOPT(Name, Bits, Default, Description)
207
208#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
209 if (!AllowCompatibleDifferences) \
210 ENUM_LANGOPT(Name, Bits, Default, Description)
211
Guy Benyei11169dd2012-12-18 14:30:41 +0000212#define BENIGN_LANGOPT(Name, Bits, Default, Description)
213#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
214#include "clang/Basic/LangOptions.def"
215
Ben Langmuircd98cb72015-06-23 18:20:18 +0000216 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
217 if (Diags)
218 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
219 return true;
220 }
221
Guy Benyei11169dd2012-12-18 14:30:41 +0000222 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
223 if (Diags)
224 Diags->Report(diag::err_pch_langopt_value_mismatch)
225 << "target Objective-C runtime";
226 return true;
227 }
228
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000229 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
230 LangOpts.CommentOpts.BlockCommandNames) {
231 if (Diags)
232 Diags->Report(diag::err_pch_langopt_value_mismatch)
233 << "block command names";
234 return true;
235 }
236
Guy Benyei11169dd2012-12-18 14:30:41 +0000237 return false;
238}
239
240/// \brief Compare the given set of target options against an existing set of
241/// target options.
242///
243/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
244///
245/// \returns true if the target options mis-match, false otherwise.
246static bool checkTargetOptions(const TargetOptions &TargetOpts,
247 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000248 DiagnosticsEngine *Diags,
249 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000250#define CHECK_TARGET_OPT(Field, Name) \
251 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
252 if (Diags) \
253 Diags->Report(diag::err_pch_targetopt_mismatch) \
254 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
255 return true; \
256 }
257
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000258 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000259 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000260 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000261
262 // We can tolerate different CPUs in many cases, notably when one CPU
263 // supports a strict superset of another. When allowing compatible
264 // differences skip this check.
265 if (!AllowCompatibleDifferences)
266 CHECK_TARGET_OPT(CPU, "target CPU");
267
Guy Benyei11169dd2012-12-18 14:30:41 +0000268#undef CHECK_TARGET_OPT
269
270 // Compare feature sets.
271 SmallVector<StringRef, 4> ExistingFeatures(
272 ExistingTargetOpts.FeaturesAsWritten.begin(),
273 ExistingTargetOpts.FeaturesAsWritten.end());
274 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
275 TargetOpts.FeaturesAsWritten.end());
276 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
277 std::sort(ReadFeatures.begin(), ReadFeatures.end());
278
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000279 // We compute the set difference in both directions explicitly so that we can
280 // diagnose the differences differently.
281 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
282 std::set_difference(
283 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
284 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
285 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
286 ExistingFeatures.begin(), ExistingFeatures.end(),
287 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000288
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000289 // If we are allowing compatible differences and the read feature set is
290 // a strict subset of the existing feature set, there is nothing to diagnose.
291 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
292 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000293
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000294 if (Diags) {
295 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000296 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000297 << /* is-existing-feature */ false << Feature;
298 for (StringRef Feature : UnmatchedExistingFeatures)
299 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
300 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000301 }
302
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000303 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000304}
305
306bool
307PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000308 bool Complain,
309 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 const LangOptions &ExistingLangOpts = PP.getLangOpts();
311 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000312 Complain ? &Reader.Diags : nullptr,
313 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000314}
315
316bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317 bool Complain,
318 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000319 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
320 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000321 Complain ? &Reader.Diags : nullptr,
322 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000323}
324
325namespace {
326 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
327 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000328 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
329 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000330}
331
Ben Langmuirb92de022014-04-29 16:25:26 +0000332static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
333 DiagnosticsEngine &Diags,
334 bool Complain) {
335 typedef DiagnosticsEngine::Level Level;
336
337 // Check current mappings for new -Werror mappings, and the stored mappings
338 // for cases that were explicitly mapped to *not* be errors that are now
339 // errors because of options like -Werror.
340 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
341
342 for (DiagnosticsEngine *MappingSource : MappingSources) {
343 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
344 diag::kind DiagID = DiagIDMappingPair.first;
345 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
346 if (CurLevel < DiagnosticsEngine::Error)
347 continue; // not significant
348 Level StoredLevel =
349 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
350 if (StoredLevel < DiagnosticsEngine::Error) {
351 if (Complain)
352 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
353 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
354 return true;
355 }
356 }
357 }
358
359 return false;
360}
361
Alp Tokerac4e8e52014-06-22 21:58:33 +0000362static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
363 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
364 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
365 return true;
366 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000367}
368
369static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
370 DiagnosticsEngine &Diags,
371 bool IsSystem, bool Complain) {
372 // Top-level options
373 if (IsSystem) {
374 if (Diags.getSuppressSystemWarnings())
375 return false;
376 // If -Wsystem-headers was not enabled before, be conservative
377 if (StoredDiags.getSuppressSystemWarnings()) {
378 if (Complain)
379 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
380 return true;
381 }
382 }
383
384 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
385 if (Complain)
386 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
387 return true;
388 }
389
390 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
391 !StoredDiags.getEnableAllWarnings()) {
392 if (Complain)
393 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
394 return true;
395 }
396
397 if (isExtHandlingFromDiagsError(Diags) &&
398 !isExtHandlingFromDiagsError(StoredDiags)) {
399 if (Complain)
400 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
401 return true;
402 }
403
404 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
405}
406
407bool PCHValidator::ReadDiagnosticOptions(
408 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
409 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
410 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
411 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000412 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000413 // This should never fail, because we would have processed these options
414 // before writing them to an ASTFile.
415 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
416
417 ModuleManager &ModuleMgr = Reader.getModuleManager();
418 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
419
420 // If the original import came from a file explicitly generated by the user,
421 // don't check the diagnostic mappings.
422 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000423 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000424 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
425 // the transitive closure of its imports, since unrelated modules cannot be
426 // imported until after this module finishes validation.
427 ModuleFile *TopImport = *ModuleMgr.rbegin();
428 while (!TopImport->ImportedBy.empty())
429 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000430 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000431 return false;
432
433 StringRef ModuleName = TopImport->ModuleName;
434 assert(!ModuleName.empty() && "diagnostic options read before module name");
435
436 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
437 assert(M && "missing module");
438
439 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
440 // contains the union of their flags.
441 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
442}
443
Guy Benyei11169dd2012-12-18 14:30:41 +0000444/// \brief Collect the macro definitions provided by the given preprocessor
445/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000446static void
447collectMacroDefinitions(const PreprocessorOptions &PPOpts,
448 MacroDefinitionsMap &Macros,
449 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000450 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
451 StringRef Macro = PPOpts.Macros[I].first;
452 bool IsUndef = PPOpts.Macros[I].second;
453
454 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
455 StringRef MacroName = MacroPair.first;
456 StringRef MacroBody = MacroPair.second;
457
458 // For an #undef'd macro, we only care about the name.
459 if (IsUndef) {
460 if (MacroNames && !Macros.count(MacroName))
461 MacroNames->push_back(MacroName);
462
463 Macros[MacroName] = std::make_pair("", true);
464 continue;
465 }
466
467 // For a #define'd macro, figure out the actual definition.
468 if (MacroName.size() == Macro.size())
469 MacroBody = "1";
470 else {
471 // Note: GCC drops anything following an end-of-line character.
472 StringRef::size_type End = MacroBody.find_first_of("\n\r");
473 MacroBody = MacroBody.substr(0, End);
474 }
475
476 if (MacroNames && !Macros.count(MacroName))
477 MacroNames->push_back(MacroName);
478 Macros[MacroName] = std::make_pair(MacroBody, false);
479 }
480}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000481
Guy Benyei11169dd2012-12-18 14:30:41 +0000482/// \brief Check the preprocessor options deserialized from the control block
483/// against the preprocessor options in an existing preprocessor.
484///
485/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
486static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
487 const PreprocessorOptions &ExistingPPOpts,
488 DiagnosticsEngine *Diags,
489 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000490 std::string &SuggestedPredefines,
491 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000492 // Check macro definitions.
493 MacroDefinitionsMap ASTFileMacros;
494 collectMacroDefinitions(PPOpts, ASTFileMacros);
495 MacroDefinitionsMap ExistingMacros;
496 SmallVector<StringRef, 4> ExistingMacroNames;
497 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
498
499 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
500 // Dig out the macro definition in the existing preprocessor options.
501 StringRef MacroName = ExistingMacroNames[I];
502 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
503
504 // Check whether we know anything about this macro name or not.
505 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
506 = ASTFileMacros.find(MacroName);
507 if (Known == ASTFileMacros.end()) {
508 // FIXME: Check whether this identifier was referenced anywhere in the
509 // AST file. If so, we should reject the AST file. Unfortunately, this
510 // information isn't in the control block. What shall we do about it?
511
512 if (Existing.second) {
513 SuggestedPredefines += "#undef ";
514 SuggestedPredefines += MacroName.str();
515 SuggestedPredefines += '\n';
516 } else {
517 SuggestedPredefines += "#define ";
518 SuggestedPredefines += MacroName.str();
519 SuggestedPredefines += ' ';
520 SuggestedPredefines += Existing.first.str();
521 SuggestedPredefines += '\n';
522 }
523 continue;
524 }
525
526 // If the macro was defined in one but undef'd in the other, we have a
527 // conflict.
528 if (Existing.second != Known->second.second) {
529 if (Diags) {
530 Diags->Report(diag::err_pch_macro_def_undef)
531 << MacroName << Known->second.second;
532 }
533 return true;
534 }
535
536 // If the macro was #undef'd in both, or if the macro bodies are identical,
537 // it's fine.
538 if (Existing.second || Existing.first == Known->second.first)
539 continue;
540
541 // The macro bodies differ; complain.
542 if (Diags) {
543 Diags->Report(diag::err_pch_macro_def_conflict)
544 << MacroName << Known->second.first << Existing.first;
545 }
546 return true;
547 }
548
549 // Check whether we're using predefines.
550 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
551 if (Diags) {
552 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
553 }
554 return true;
555 }
556
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000557 // Detailed record is important since it is used for the module cache hash.
558 if (LangOpts.Modules &&
559 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
560 if (Diags) {
561 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
562 }
563 return true;
564 }
565
Guy Benyei11169dd2012-12-18 14:30:41 +0000566 // Compute the #include and #include_macros lines we need.
567 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
568 StringRef File = ExistingPPOpts.Includes[I];
569 if (File == ExistingPPOpts.ImplicitPCHInclude)
570 continue;
571
572 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
573 != PPOpts.Includes.end())
574 continue;
575
576 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000577 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 SuggestedPredefines += "\"\n";
579 }
580
581 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
582 StringRef File = ExistingPPOpts.MacroIncludes[I];
583 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
584 File)
585 != PPOpts.MacroIncludes.end())
586 continue;
587
588 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000589 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000590 SuggestedPredefines += "\"\n##\n";
591 }
592
593 return false;
594}
595
596bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
597 bool Complain,
598 std::string &SuggestedPredefines) {
599 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
600
601 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000602 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000604 SuggestedPredefines,
605 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000606}
607
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000608/// Check the header search options deserialized from the control block
609/// against the header search options in an existing preprocessor.
610///
611/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
612static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
613 StringRef SpecificModuleCachePath,
614 StringRef ExistingModuleCachePath,
615 DiagnosticsEngine *Diags,
616 const LangOptions &LangOpts) {
617 if (LangOpts.Modules) {
618 if (SpecificModuleCachePath != ExistingModuleCachePath) {
619 if (Diags)
620 Diags->Report(diag::err_pch_modulecache_mismatch)
621 << SpecificModuleCachePath << ExistingModuleCachePath;
622 return true;
623 }
624 }
625
626 return false;
627}
628
629bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
630 StringRef SpecificModuleCachePath,
631 bool Complain) {
632 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
633 PP.getHeaderSearchInfo().getModuleCachePath(),
634 Complain ? &Reader.Diags : nullptr,
635 PP.getLangOpts());
636}
637
Guy Benyei11169dd2012-12-18 14:30:41 +0000638void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
639 PP.setCounterValue(Value);
640}
641
642//===----------------------------------------------------------------------===//
643// AST reader implementation
644//===----------------------------------------------------------------------===//
645
Nico Weber824285e2014-05-08 04:26:47 +0000646void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
647 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000648 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000649 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000650}
651
652
653
654unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
655 return serialization::ComputeHash(Sel);
656}
657
658
659std::pair<unsigned, unsigned>
660ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000661 using namespace llvm::support;
662 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
663 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 return std::make_pair(KeyLen, DataLen);
665}
666
667ASTSelectorLookupTrait::internal_key_type
668ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000669 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000670 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000671 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
672 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
673 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000674 if (N == 0)
675 return SelTable.getNullarySelector(FirstII);
676 else if (N == 1)
677 return SelTable.getUnarySelector(FirstII);
678
679 SmallVector<IdentifierInfo *, 16> Args;
680 Args.push_back(FirstII);
681 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000682 Args.push_back(Reader.getLocalIdentifier(
683 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000684
685 return SelTable.getSelector(N, Args.data());
686}
687
688ASTSelectorLookupTrait::data_type
689ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
690 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000691 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000692
693 data_type Result;
694
Justin Bogner57ba0b22014-03-28 22:03:24 +0000695 Result.ID = Reader.getGlobalSelectorID(
696 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000697 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
698 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
699 Result.InstanceBits = FullInstanceBits & 0x3;
700 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
701 Result.FactoryBits = FullFactoryBits & 0x3;
702 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
703 unsigned NumInstanceMethods = FullInstanceBits >> 3;
704 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000705
706 // Load instance methods
707 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000708 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
709 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000710 Result.Instance.push_back(Method);
711 }
712
713 // Load factory methods
714 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000715 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
716 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000717 Result.Factory.push_back(Method);
718 }
719
720 return Result;
721}
722
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000723unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
724 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000725}
726
727std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000728ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000729 using namespace llvm::support;
730 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
731 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 return std::make_pair(KeyLen, DataLen);
733}
734
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000735ASTIdentifierLookupTraitBase::internal_key_type
736ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000738 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000739}
740
Douglas Gregordcf25082013-02-11 18:16:18 +0000741/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000742static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
743 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000744 return II.hadMacroDefinition() ||
745 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000746 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000747 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000748 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
749 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000750}
751
Richard Smith76c2f2c2015-07-17 20:09:43 +0000752static bool readBit(unsigned &Bits) {
753 bool Value = Bits & 0x1;
754 Bits >>= 1;
755 return Value;
756}
757
Guy Benyei11169dd2012-12-18 14:30:41 +0000758IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
759 const unsigned char* d,
760 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000761 using namespace llvm::support;
762 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000763 bool IsInteresting = RawID & 0x01;
764
765 // Wipe out the "is interesting" bit.
766 RawID = RawID >> 1;
767
Richard Smith76c2f2c2015-07-17 20:09:43 +0000768 // Build the IdentifierInfo and link the identifier ID with it.
769 IdentifierInfo *II = KnownII;
770 if (!II) {
771 II = &Reader.getIdentifierTable().getOwn(k);
772 KnownII = II;
773 }
774 if (!II->isFromAST()) {
775 II->setIsFromAST();
Richard Smitha534a312015-07-21 23:54:07 +0000776 if (isInterestingIdentifier(Reader, *II, F.isModule()))
Richard Smith76c2f2c2015-07-17 20:09:43 +0000777 II->setChangedSinceDeserialization();
778 }
779 Reader.markIdentifierUpToDate(II);
780
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
782 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000783 // For uninteresting identifiers, there's nothing else to do. Just notify
784 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000785 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000786 return II;
787 }
788
Justin Bogner57ba0b22014-03-28 22:03:24 +0000789 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
790 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000791 bool CPlusPlusOperatorKeyword = readBit(Bits);
792 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000793 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000794 bool Poisoned = readBit(Bits);
795 bool ExtensionToken = readBit(Bits);
796 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000797
798 assert(Bits == 0 && "Extra bits in the identifier?");
799 DataLen -= 8;
800
Guy Benyei11169dd2012-12-18 14:30:41 +0000801 // Set or check the various bits in the IdentifierInfo structure.
802 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000803 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000804 II->revertTokenIDToIdentifier();
805 if (!F.isModule())
806 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
807 else if (HasRevertedBuiltin && II->getBuiltinID()) {
808 II->revertBuiltin();
809 assert((II->hasRevertedBuiltin() ||
810 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
811 "Incorrect ObjC keyword or builtin ID");
812 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 assert(II->isExtensionToken() == ExtensionToken &&
814 "Incorrect extension token flag");
815 (void)ExtensionToken;
816 if (Poisoned)
817 II->setIsPoisoned(true);
818 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
819 "Incorrect C++ operator keyword flag");
820 (void)CPlusPlusOperatorKeyword;
821
822 // If this identifier is a macro, deserialize the macro
823 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000824 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 uint32_t MacroDirectivesOffset =
826 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000827 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000828
Richard Smithd7329392015-04-21 21:46:32 +0000829 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000830 }
831
832 Reader.SetIdentifierInfo(ID, II);
833
834 // Read all of the declarations visible at global scope with this
835 // name.
836 if (DataLen > 0) {
837 SmallVector<uint32_t, 4> DeclIDs;
838 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000839 DeclIDs.push_back(Reader.getGlobalDeclID(
840 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000841 Reader.SetGloballyVisibleDecls(II, DeclIDs);
842 }
843
844 return II;
845}
846
847unsigned
Richard Smith3b637412015-07-14 18:42:41 +0000848ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000849 llvm::FoldingSetNodeID ID;
850 ID.AddInteger(Key.Kind);
851
852 switch (Key.Kind) {
853 case DeclarationName::Identifier:
854 case DeclarationName::CXXLiteralOperatorName:
855 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
856 break;
857 case DeclarationName::ObjCZeroArgSelector:
858 case DeclarationName::ObjCOneArgSelector:
859 case DeclarationName::ObjCMultiArgSelector:
860 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
861 break;
862 case DeclarationName::CXXOperatorName:
863 ID.AddInteger((OverloadedOperatorKind)Key.Data);
864 break;
865 case DeclarationName::CXXConstructorName:
866 case DeclarationName::CXXDestructorName:
867 case DeclarationName::CXXConversionFunctionName:
868 case DeclarationName::CXXUsingDirective:
869 break;
870 }
871
872 return ID.ComputeHash();
873}
874
875ASTDeclContextNameLookupTrait::internal_key_type
876ASTDeclContextNameLookupTrait::GetInternalKey(
Richard Smith3b637412015-07-14 18:42:41 +0000877 const external_key_type& Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 DeclNameKey Key;
879 Key.Kind = Name.getNameKind();
880 switch (Name.getNameKind()) {
881 case DeclarationName::Identifier:
882 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
883 break;
884 case DeclarationName::ObjCZeroArgSelector:
885 case DeclarationName::ObjCOneArgSelector:
886 case DeclarationName::ObjCMultiArgSelector:
887 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
888 break;
889 case DeclarationName::CXXOperatorName:
890 Key.Data = Name.getCXXOverloadedOperator();
891 break;
892 case DeclarationName::CXXLiteralOperatorName:
893 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
894 break;
895 case DeclarationName::CXXConstructorName:
896 case DeclarationName::CXXDestructorName:
897 case DeclarationName::CXXConversionFunctionName:
898 case DeclarationName::CXXUsingDirective:
899 Key.Data = 0;
900 break;
901 }
902
903 return Key;
904}
905
906std::pair<unsigned, unsigned>
907ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 using namespace llvm::support;
909 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
910 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000911 return std::make_pair(KeyLen, DataLen);
912}
913
914ASTDeclContextNameLookupTrait::internal_key_type
915ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000917
918 DeclNameKey Key;
919 Key.Kind = (DeclarationName::NameKind)*d++;
920 switch (Key.Kind) {
921 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 Key.Data = (uint64_t)Reader.getLocalIdentifier(
923 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 break;
925 case DeclarationName::ObjCZeroArgSelector:
926 case DeclarationName::ObjCOneArgSelector:
927 case DeclarationName::ObjCMultiArgSelector:
928 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000929 (uint64_t)Reader.getLocalSelector(
930 F, endian::readNext<uint32_t, little, unaligned>(
931 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000932 break;
933 case DeclarationName::CXXOperatorName:
934 Key.Data = *d++; // OverloadedOperatorKind
935 break;
936 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000937 Key.Data = (uint64_t)Reader.getLocalIdentifier(
938 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 break;
940 case DeclarationName::CXXConstructorName:
941 case DeclarationName::CXXDestructorName:
942 case DeclarationName::CXXConversionFunctionName:
943 case DeclarationName::CXXUsingDirective:
944 Key.Data = 0;
945 break;
946 }
947
948 return Key;
949}
950
Richard Smithf02662d2015-07-30 03:17:16 +0000951ASTDeclContextNameLookupTrait::data_type
952ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
953 const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000955 using namespace llvm::support;
Richard Smithf02662d2015-07-30 03:17:16 +0000956 unsigned NumDecls = DataLen / 4;
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000957 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
958 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 return std::make_pair(Start, Start + NumDecls);
960}
961
Richard Smith0f4e2c42015-08-06 04:23:48 +0000962bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
963 BitstreamCursor &Cursor,
964 uint64_t Offset,
965 DeclContext *DC) {
966 assert(Offset != 0);
967
Guy Benyei11169dd2012-12-18 14:30:41 +0000968 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +0000969 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000970
Richard Smith0f4e2c42015-08-06 04:23:48 +0000971 RecordData Record;
972 StringRef Blob;
973 unsigned Code = Cursor.ReadCode();
974 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
975 if (RecCode != DECL_CONTEXT_LEXICAL) {
976 Error("Expected lexical block");
977 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 }
979
Richard Smith82f8fcd2015-08-06 22:07:25 +0000980 assert(!isa<TranslationUnitDecl>(DC) &&
981 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +0000982 // If we are handling a C++ class template instantiation, we can see multiple
983 // lexical updates for the same record. It's important that we select only one
984 // of them, so that field numbering works properly. Just pick the first one we
985 // see.
986 auto &Lex = LexicalDecls[DC];
987 if (!Lex.first) {
988 Lex = std::make_pair(
989 &M, llvm::makeArrayRef(
990 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
991 Blob.data()),
992 Blob.size() / 4));
993 }
Richard Smith0f4e2c42015-08-06 04:23:48 +0000994 DC->setHasExternalLexicalStorage(true);
995 return false;
996}
Guy Benyei11169dd2012-12-18 14:30:41 +0000997
Richard Smith0f4e2c42015-08-06 04:23:48 +0000998bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
999 BitstreamCursor &Cursor,
1000 uint64_t Offset,
1001 DeclID ID) {
1002 assert(Offset != 0);
1003
1004 SavedStreamPosition SavedPosition(Cursor);
1005 Cursor.JumpToBit(Offset);
1006
1007 RecordData Record;
1008 StringRef Blob;
1009 unsigned Code = Cursor.ReadCode();
1010 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1011 if (RecCode != DECL_CONTEXT_VISIBLE) {
1012 Error("Expected visible lookup table block");
1013 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 }
1015
Richard Smith0f4e2c42015-08-06 04:23:48 +00001016 // We can't safely determine the primary context yet, so delay attaching the
1017 // lookup table until we're done with recursive deserialization.
1018 unsigned BucketOffset = Record[0];
1019 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{
1020 &M, (const unsigned char *)Blob.data(), BucketOffset});
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 return false;
1022}
1023
1024void ASTReader::Error(StringRef Msg) {
1025 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001026 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1027 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001028 Diag(diag::note_module_cache_path)
1029 << PP.getHeaderSearchInfo().getModuleCachePath();
1030 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001031}
1032
1033void ASTReader::Error(unsigned DiagID,
1034 StringRef Arg1, StringRef Arg2) {
1035 if (Diags.isDiagnosticInFlight())
1036 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1037 else
1038 Diag(DiagID) << Arg1 << Arg2;
1039}
1040
1041//===----------------------------------------------------------------------===//
1042// Source Manager Deserialization
1043//===----------------------------------------------------------------------===//
1044
1045/// \brief Read the line table in the source manager block.
1046/// \returns true if there was an error.
1047bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001048 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 unsigned Idx = 0;
1050 LineTableInfo &LineTable = SourceMgr.getLineTable();
1051
1052 // Parse the file names
1053 std::map<int, int> FileIDs;
1054 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1055 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001056 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001057 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1058 }
1059
1060 // Parse the line entries
1061 std::vector<LineEntry> Entries;
1062 while (Idx < Record.size()) {
1063 int FID = Record[Idx++];
1064 assert(FID >= 0 && "Serialized line entries for non-local file.");
1065 // Remap FileID from 1-based old view.
1066 FID += F.SLocEntryBaseID - 1;
1067
1068 // Extract the line entries
1069 unsigned NumEntries = Record[Idx++];
1070 assert(NumEntries && "Numentries is 00000");
1071 Entries.clear();
1072 Entries.reserve(NumEntries);
1073 for (unsigned I = 0; I != NumEntries; ++I) {
1074 unsigned FileOffset = Record[Idx++];
1075 unsigned LineNo = Record[Idx++];
1076 int FilenameID = FileIDs[Record[Idx++]];
1077 SrcMgr::CharacteristicKind FileKind
1078 = (SrcMgr::CharacteristicKind)Record[Idx++];
1079 unsigned IncludeOffset = Record[Idx++];
1080 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1081 FileKind, IncludeOffset));
1082 }
1083 LineTable.AddEntry(FileID::get(FID), Entries);
1084 }
1085
1086 return false;
1087}
1088
1089/// \brief Read a source manager block
1090bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1091 using namespace SrcMgr;
1092
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001093 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001094
1095 // Set the source-location entry cursor to the current position in
1096 // the stream. This cursor will be used to read the contents of the
1097 // source manager block initially, and then lazily read
1098 // source-location entries as needed.
1099 SLocEntryCursor = F.Stream;
1100
1101 // The stream itself is going to skip over the source manager block.
1102 if (F.Stream.SkipBlock()) {
1103 Error("malformed block record in AST file");
1104 return true;
1105 }
1106
1107 // Enter the source manager block.
1108 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1109 Error("malformed source manager block record in AST file");
1110 return true;
1111 }
1112
1113 RecordData Record;
1114 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001115 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1116
1117 switch (E.Kind) {
1118 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1119 case llvm::BitstreamEntry::Error:
1120 Error("malformed block record in AST file");
1121 return true;
1122 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001124 case llvm::BitstreamEntry::Record:
1125 // The interesting case.
1126 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001127 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001128
Guy Benyei11169dd2012-12-18 14:30:41 +00001129 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001130 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001131 StringRef Blob;
1132 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 default: // Default behavior: ignore.
1134 break;
1135
1136 case SM_SLOC_FILE_ENTRY:
1137 case SM_SLOC_BUFFER_ENTRY:
1138 case SM_SLOC_EXPANSION_ENTRY:
1139 // Once we hit one of the source location entries, we're done.
1140 return false;
1141 }
1142 }
1143}
1144
1145/// \brief If a header file is not found at the path that we expect it to be
1146/// and the PCH file was moved from its original location, try to resolve the
1147/// file by assuming that header+PCH were moved together and the header is in
1148/// the same place relative to the PCH.
1149static std::string
1150resolveFileRelativeToOriginalDir(const std::string &Filename,
1151 const std::string &OriginalDir,
1152 const std::string &CurrDir) {
1153 assert(OriginalDir != CurrDir &&
1154 "No point trying to resolve the file if the PCH dir didn't change");
1155 using namespace llvm::sys;
1156 SmallString<128> filePath(Filename);
1157 fs::make_absolute(filePath);
1158 assert(path::is_absolute(OriginalDir));
1159 SmallString<128> currPCHPath(CurrDir);
1160
1161 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1162 fileDirE = path::end(path::parent_path(filePath));
1163 path::const_iterator origDirI = path::begin(OriginalDir),
1164 origDirE = path::end(OriginalDir);
1165 // Skip the common path components from filePath and OriginalDir.
1166 while (fileDirI != fileDirE && origDirI != origDirE &&
1167 *fileDirI == *origDirI) {
1168 ++fileDirI;
1169 ++origDirI;
1170 }
1171 for (; origDirI != origDirE; ++origDirI)
1172 path::append(currPCHPath, "..");
1173 path::append(currPCHPath, fileDirI, fileDirE);
1174 path::append(currPCHPath, path::filename(Filename));
1175 return currPCHPath.str();
1176}
1177
1178bool ASTReader::ReadSLocEntry(int ID) {
1179 if (ID == 0)
1180 return false;
1181
1182 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1183 Error("source location entry ID out-of-range for AST file");
1184 return true;
1185 }
1186
1187 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1188 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001189 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 unsigned BaseOffset = F->SLocEntryBaseOffset;
1191
1192 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001193 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1194 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 Error("incorrectly-formatted source location entry in AST file");
1196 return true;
1197 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001198
Guy Benyei11169dd2012-12-18 14:30:41 +00001199 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001200 StringRef Blob;
1201 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 default:
1203 Error("incorrectly-formatted source location entry in AST file");
1204 return true;
1205
1206 case SM_SLOC_FILE_ENTRY: {
1207 // We will detect whether a file changed and return 'Failure' for it, but
1208 // we will also try to fail gracefully by setting up the SLocEntry.
1209 unsigned InputID = Record[4];
1210 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001211 const FileEntry *File = IF.getFile();
1212 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001213
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001214 // Note that we only check if a File was returned. If it was out-of-date
1215 // we have complained but we will continue creating a FileID to recover
1216 // gracefully.
1217 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001218 return true;
1219
1220 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1221 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1222 // This is the module's main file.
1223 IncludeLoc = getImportLocation(F);
1224 }
1225 SrcMgr::CharacteristicKind
1226 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1227 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1228 ID, BaseOffset + Record[0]);
1229 SrcMgr::FileInfo &FileInfo =
1230 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1231 FileInfo.NumCreatedFIDs = Record[5];
1232 if (Record[3])
1233 FileInfo.setHasLineDirectives();
1234
1235 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1236 unsigned NumFileDecls = Record[7];
1237 if (NumFileDecls) {
1238 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1239 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1240 NumFileDecls));
1241 }
1242
1243 const SrcMgr::ContentCache *ContentCache
1244 = SourceMgr.getOrCreateContentCache(File,
1245 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1246 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1247 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1248 unsigned Code = SLocEntryCursor.ReadCode();
1249 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001250 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001251
1252 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1253 Error("AST record has invalid code");
1254 return true;
1255 }
1256
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001257 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001258 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001259 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001260 }
1261
1262 break;
1263 }
1264
1265 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001266 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001267 unsigned Offset = Record[0];
1268 SrcMgr::CharacteristicKind
1269 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1270 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001271 if (IncludeLoc.isInvalid() &&
1272 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 IncludeLoc = getImportLocation(F);
1274 }
1275 unsigned Code = SLocEntryCursor.ReadCode();
1276 Record.clear();
1277 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001278 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001279
1280 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1281 Error("AST record has invalid code");
1282 return true;
1283 }
1284
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001285 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1286 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001287 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001288 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001289 break;
1290 }
1291
1292 case SM_SLOC_EXPANSION_ENTRY: {
1293 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1294 SourceMgr.createExpansionLoc(SpellingLoc,
1295 ReadSourceLocation(*F, Record[2]),
1296 ReadSourceLocation(*F, Record[3]),
1297 Record[4],
1298 ID,
1299 BaseOffset + Record[0]);
1300 break;
1301 }
1302 }
1303
1304 return false;
1305}
1306
1307std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1308 if (ID == 0)
1309 return std::make_pair(SourceLocation(), "");
1310
1311 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1312 Error("source location entry ID out-of-range for AST file");
1313 return std::make_pair(SourceLocation(), "");
1314 }
1315
1316 // Find which module file this entry lands in.
1317 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001318 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 return std::make_pair(SourceLocation(), "");
1320
1321 // FIXME: Can we map this down to a particular submodule? That would be
1322 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001323 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001324}
1325
1326/// \brief Find the location where the module F is imported.
1327SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1328 if (F->ImportLoc.isValid())
1329 return F->ImportLoc;
1330
1331 // Otherwise we have a PCH. It's considered to be "imported" at the first
1332 // location of its includer.
1333 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001334 // Main file is the importer.
1335 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1336 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001338 return F->ImportedBy[0]->FirstLoc;
1339}
1340
1341/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1342/// specified cursor. Read the abbreviations that are at the top of the block
1343/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001344bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001345 if (Cursor.EnterSubBlock(BlockID)) {
1346 Error("malformed block record in AST file");
1347 return Failure;
1348 }
1349
1350 while (true) {
1351 uint64_t Offset = Cursor.GetCurrentBitNo();
1352 unsigned Code = Cursor.ReadCode();
1353
1354 // We expect all abbrevs to be at the start of the block.
1355 if (Code != llvm::bitc::DEFINE_ABBREV) {
1356 Cursor.JumpToBit(Offset);
1357 return false;
1358 }
1359 Cursor.ReadAbbrevRecord();
1360 }
1361}
1362
Richard Smithe40f2ba2013-08-07 21:41:30 +00001363Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001364 unsigned &Idx) {
1365 Token Tok;
1366 Tok.startToken();
1367 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1368 Tok.setLength(Record[Idx++]);
1369 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1370 Tok.setIdentifierInfo(II);
1371 Tok.setKind((tok::TokenKind)Record[Idx++]);
1372 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1373 return Tok;
1374}
1375
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001376MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001377 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001378
1379 // Keep track of where we are in the stream, then jump back there
1380 // after reading this macro.
1381 SavedStreamPosition SavedPosition(Stream);
1382
1383 Stream.JumpToBit(Offset);
1384 RecordData Record;
1385 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001386 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001387
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001389 // Advance to the next record, but if we get to the end of the block, don't
1390 // pop it (removing all the abbreviations from the cursor) since we want to
1391 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001392 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001393 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1394
1395 switch (Entry.Kind) {
1396 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1397 case llvm::BitstreamEntry::Error:
1398 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001399 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001400 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001401 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001402 case llvm::BitstreamEntry::Record:
1403 // The interesting case.
1404 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 }
1406
1407 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 Record.clear();
1409 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001410 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001412 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001413 case PP_MACRO_DIRECTIVE_HISTORY:
1414 return Macro;
1415
Guy Benyei11169dd2012-12-18 14:30:41 +00001416 case PP_MACRO_OBJECT_LIKE:
1417 case PP_MACRO_FUNCTION_LIKE: {
1418 // If we already have a macro, that means that we've hit the end
1419 // of the definition of the macro we were looking for. We're
1420 // done.
1421 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001422 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001423
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001424 unsigned NextIndex = 1; // Skip identifier ID.
1425 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001427 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001428 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001430 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001431
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1433 // Decode function-like macro info.
1434 bool isC99VarArgs = Record[NextIndex++];
1435 bool isGNUVarArgs = Record[NextIndex++];
1436 bool hasCommaPasting = Record[NextIndex++];
1437 MacroArgs.clear();
1438 unsigned NumArgs = Record[NextIndex++];
1439 for (unsigned i = 0; i != NumArgs; ++i)
1440 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1441
1442 // Install function-like macro info.
1443 MI->setIsFunctionLike();
1444 if (isC99VarArgs) MI->setIsC99Varargs();
1445 if (isGNUVarArgs) MI->setIsGNUVarargs();
1446 if (hasCommaPasting) MI->setHasCommaPasting();
1447 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1448 PP.getPreprocessorAllocator());
1449 }
1450
Guy Benyei11169dd2012-12-18 14:30:41 +00001451 // Remember that we saw this macro last so that we add the tokens that
1452 // form its body to it.
1453 Macro = MI;
1454
1455 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1456 Record[NextIndex]) {
1457 // We have a macro definition. Register the association
1458 PreprocessedEntityID
1459 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1460 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001461 PreprocessingRecord::PPEntityID PPID =
1462 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1463 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1464 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001465 if (PPDef)
1466 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 }
1468
1469 ++NumMacrosRead;
1470 break;
1471 }
1472
1473 case PP_TOKEN: {
1474 // If we see a TOKEN before a PP_MACRO_*, then the file is
1475 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001476 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001477
John McCallf413f5e2013-05-03 00:10:13 +00001478 unsigned Idx = 0;
1479 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 Macro->AddTokenToBody(Tok);
1481 break;
1482 }
1483 }
1484 }
1485}
1486
1487PreprocessedEntityID
1488ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1489 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1490 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1491 assert(I != M.PreprocessedEntityRemap.end()
1492 && "Invalid index into preprocessed entity index remap");
1493
1494 return LocalID + I->second;
1495}
1496
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001497unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1498 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001499}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001500
Guy Benyei11169dd2012-12-18 14:30:41 +00001501HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001502HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1503 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001504 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001505 return ikey;
1506}
Guy Benyei11169dd2012-12-18 14:30:41 +00001507
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001508bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1509 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 return false;
1511
Richard Smith7ed1bc92014-12-05 22:42:13 +00001512 if (llvm::sys::path::is_absolute(a.Filename) &&
1513 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001514 return true;
1515
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001517 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001518 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1519 if (!Key.Imported)
1520 return FileMgr.getFile(Key.Filename);
1521
1522 std::string Resolved = Key.Filename;
1523 Reader.ResolveImportedPath(M, Resolved);
1524 return FileMgr.getFile(Resolved);
1525 };
1526
1527 const FileEntry *FEA = GetFile(a);
1528 const FileEntry *FEB = GetFile(b);
1529 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001530}
1531
1532std::pair<unsigned, unsigned>
1533HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001534 using namespace llvm::support;
1535 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001537 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001539
1540HeaderFileInfoTrait::internal_key_type
1541HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001542 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001543 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001544 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1545 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001546 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001547 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001548 return ikey;
1549}
1550
Guy Benyei11169dd2012-12-18 14:30:41 +00001551HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001552HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 unsigned DataLen) {
1554 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001555 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001556 HeaderFileInfo HFI;
1557 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001558 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1559 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 HFI.isImport = (Flags >> 5) & 0x01;
1561 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1562 HFI.DirInfo = (Flags >> 2) & 0x03;
1563 HFI.Resolved = (Flags >> 1) & 0x01;
1564 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001565 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1566 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1567 M, endian::readNext<uint32_t, little, unaligned>(d));
1568 if (unsigned FrameworkOffset =
1569 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 // The framework offset is 1 greater than the actual offset,
1571 // since 0 is used as an indicator for "no framework name".
1572 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1573 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1574 }
1575
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001576 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001577 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001578 if (LocalSMID) {
1579 // This header is part of a module. Associate it with the module to enable
1580 // implicit module import.
1581 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1582 Module *Mod = Reader.getSubmodule(GlobalSMID);
1583 HFI.isModuleHeader = true;
1584 FileManager &FileMgr = Reader.getFileManager();
1585 ModuleMap &ModMap =
1586 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001587 // FIXME: This information should be propagated through the
1588 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001589 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001590 std::string Filename = key.Filename;
1591 if (key.Imported)
1592 Reader.ResolveImportedPath(M, Filename);
1593 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001594 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001595 }
1596 }
1597
Guy Benyei11169dd2012-12-18 14:30:41 +00001598 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1599 (void)End;
1600
1601 // This HeaderFileInfo was externally loaded.
1602 HFI.External = true;
1603 return HFI;
1604}
1605
Richard Smithd7329392015-04-21 21:46:32 +00001606void ASTReader::addPendingMacro(IdentifierInfo *II,
1607 ModuleFile *M,
1608 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001609 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1610 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001611}
1612
1613void ASTReader::ReadDefinedMacros() {
1614 // Note that we are loading defined macros.
1615 Deserializing Macros(this);
1616
Pete Cooper57d3f142015-07-30 17:22:52 +00001617 for (auto &I : llvm::reverse(ModuleMgr)) {
1618 BitstreamCursor &MacroCursor = I->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001619
1620 // If there was no preprocessor block, skip this file.
1621 if (!MacroCursor.getBitStreamReader())
1622 continue;
1623
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001624 BitstreamCursor Cursor = MacroCursor;
Pete Cooper57d3f142015-07-30 17:22:52 +00001625 Cursor.JumpToBit(I->MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001626
1627 RecordData Record;
1628 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001629 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1630
1631 switch (E.Kind) {
1632 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1633 case llvm::BitstreamEntry::Error:
1634 Error("malformed block record in AST file");
1635 return;
1636 case llvm::BitstreamEntry::EndBlock:
1637 goto NextCursor;
1638
1639 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001640 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001641 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001642 default: // Default behavior: ignore.
1643 break;
1644
1645 case PP_MACRO_OBJECT_LIKE:
1646 case PP_MACRO_FUNCTION_LIKE:
Pete Cooper57d3f142015-07-30 17:22:52 +00001647 getLocalIdentifier(*I, Record[0]);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001648 break;
1649
1650 case PP_TOKEN:
1651 // Ignore tokens.
1652 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001654 break;
1655 }
1656 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001657 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 }
1659}
1660
1661namespace {
1662 /// \brief Visitor class used to look up identifirs in an AST file.
1663 class IdentifierLookupVisitor {
1664 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001665 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001666 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001667 unsigned &NumIdentifierLookups;
1668 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001670
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001672 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1673 unsigned &NumIdentifierLookups,
1674 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001675 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1676 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001677 NumIdentifierLookups(NumIdentifierLookups),
1678 NumIdentifierLookupHits(NumIdentifierLookupHits),
1679 Found()
1680 {
1681 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001682
1683 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001684 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001685 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001686 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001687
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 ASTIdentifierLookupTable *IdTable
1689 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1690 if (!IdTable)
1691 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001692
1693 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001694 Found);
1695 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001696 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001697 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001698 if (Pos == IdTable->end())
1699 return false;
1700
1701 // Dereferencing the iterator has the effect of building the
1702 // IdentifierInfo node and populating it with the various
1703 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001704 ++NumIdentifierLookupHits;
1705 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001706 return true;
1707 }
1708
1709 // \brief Retrieve the identifier info found within the module
1710 // files.
1711 IdentifierInfo *getIdentifierInfo() const { return Found; }
1712 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001713}
Guy Benyei11169dd2012-12-18 14:30:41 +00001714
1715void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1716 // Note that we are loading an identifier.
1717 Deserializing AnIdentifier(this);
1718
1719 unsigned PriorGeneration = 0;
1720 if (getContext().getLangOpts().Modules)
1721 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001722
1723 // If there is a global index, look there first to determine which modules
1724 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001725 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001726 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001727 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001728 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1729 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001730 }
1731 }
1732
Douglas Gregor7211ac12013-01-25 23:32:03 +00001733 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001734 NumIdentifierLookups,
1735 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001736 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001737 markIdentifierUpToDate(&II);
1738}
1739
1740void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1741 if (!II)
1742 return;
1743
1744 II->setOutOfDate(false);
1745
1746 // Update the generation for this identifier.
1747 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001748 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001749}
1750
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001751void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1752 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001753 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001754
1755 BitstreamCursor &Cursor = M.MacroCursor;
1756 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001757 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001758
Richard Smith713369b2015-04-23 20:40:50 +00001759 struct ModuleMacroRecord {
1760 SubmoduleID SubModID;
1761 MacroInfo *MI;
1762 SmallVector<SubmoduleID, 8> Overrides;
1763 };
1764 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001765
Richard Smithd7329392015-04-21 21:46:32 +00001766 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1767 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1768 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001769 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001770 while (true) {
1771 llvm::BitstreamEntry Entry =
1772 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1773 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1774 Error("malformed block record in AST file");
1775 return;
1776 }
1777
1778 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001779 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001780 case PP_MACRO_DIRECTIVE_HISTORY:
1781 break;
1782
1783 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001784 ModuleMacros.push_back(ModuleMacroRecord());
1785 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001786 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1787 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001788 for (int I = 2, N = Record.size(); I != N; ++I)
1789 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001790 continue;
1791 }
1792
1793 default:
1794 Error("malformed block record in AST file");
1795 return;
1796 }
1797
1798 // We found the macro directive history; that's the last record
1799 // for this macro.
1800 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001801 }
1802
Richard Smithd7329392015-04-21 21:46:32 +00001803 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001804 {
1805 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001806 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001807 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001808 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001809 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001810 Module *Mod = getSubmodule(ModID);
1811 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001812 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001813 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001814 }
1815
1816 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001817 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001818 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001819 }
1820 }
1821
1822 // Don't read the directive history for a module; we don't have anywhere
1823 // to put it.
1824 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1825 return;
1826
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001827 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001828 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001829 unsigned Idx = 0, N = Record.size();
1830 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001831 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001832 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001833 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1834 switch (K) {
1835 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001836 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001837 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001838 break;
1839 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001840 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001841 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001842 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001843 }
1844 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001845 bool isPublic = Record[Idx++];
1846 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1847 break;
1848 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001849
1850 if (!Latest)
1851 Latest = MD;
1852 if (Earliest)
1853 Earliest->setPrevious(MD);
1854 Earliest = MD;
1855 }
1856
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001857 if (Latest)
1858 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001859}
1860
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001861ASTReader::InputFileInfo
1862ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001863 // Go find this input file.
1864 BitstreamCursor &Cursor = F.InputFilesCursor;
1865 SavedStreamPosition SavedPosition(Cursor);
1866 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1867
1868 unsigned Code = Cursor.ReadCode();
1869 RecordData Record;
1870 StringRef Blob;
1871
1872 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1873 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1874 "invalid record type for input file");
1875 (void)Result;
1876
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001877 std::string Filename;
1878 off_t StoredSize;
1879 time_t StoredTime;
1880 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001881
Ben Langmuir198c1682014-03-07 07:27:49 +00001882 assert(Record[0] == ID && "Bogus stored ID or offset");
1883 StoredSize = static_cast<off_t>(Record[1]);
1884 StoredTime = static_cast<time_t>(Record[2]);
1885 Overridden = static_cast<bool>(Record[3]);
1886 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001887 ResolveImportedPath(F, Filename);
1888
Hans Wennborg73945142014-03-14 17:45:06 +00001889 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1890 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001891}
1892
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001893InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001894 // If this ID is bogus, just return an empty input file.
1895 if (ID == 0 || ID > F.InputFilesLoaded.size())
1896 return InputFile();
1897
1898 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001899 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001900 return F.InputFilesLoaded[ID-1];
1901
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001902 if (F.InputFilesLoaded[ID-1].isNotFound())
1903 return InputFile();
1904
Guy Benyei11169dd2012-12-18 14:30:41 +00001905 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001906 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 SavedStreamPosition SavedPosition(Cursor);
1908 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1909
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001910 InputFileInfo FI = readInputFileInfo(F, ID);
1911 off_t StoredSize = FI.StoredSize;
1912 time_t StoredTime = FI.StoredTime;
1913 bool Overridden = FI.Overridden;
1914 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001915
Ben Langmuir198c1682014-03-07 07:27:49 +00001916 const FileEntry *File
1917 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1918 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1919
1920 // If we didn't find the file, resolve it relative to the
1921 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001922 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001923 F.OriginalDir != CurrentDir) {
1924 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1925 F.OriginalDir,
1926 CurrentDir);
1927 if (!Resolved.empty())
1928 File = FileMgr.getFile(Resolved);
1929 }
1930
1931 // For an overridden file, create a virtual file with the stored
1932 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001933 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001934 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1935 }
1936
Craig Toppera13603a2014-05-22 05:54:18 +00001937 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001938 if (Complain) {
1939 std::string ErrorStr = "could not find file '";
1940 ErrorStr += Filename;
1941 ErrorStr += "' referenced by AST file";
1942 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001943 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001944 // Record that we didn't find the file.
1945 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1946 return InputFile();
1947 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001948
Ben Langmuir198c1682014-03-07 07:27:49 +00001949 // Check if there was a request to override the contents of the file
1950 // that was part of the precompiled header. Overridding such a file
1951 // can lead to problems when lexing using the source locations from the
1952 // PCH.
1953 SourceManager &SM = getSourceManager();
1954 if (!Overridden && SM.isFileOverridden(File)) {
1955 if (Complain)
1956 Error(diag::err_fe_pch_file_overridden, Filename);
1957 // After emitting the diagnostic, recover by disabling the override so
1958 // that the original file will be used.
1959 SM.disableFileContentsOverride(File);
1960 // The FileEntry is a virtual file entry with the size of the contents
1961 // that would override the original contents. Set it to the original's
1962 // size/time.
1963 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1964 StoredSize, StoredTime);
1965 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001966
Ben Langmuir198c1682014-03-07 07:27:49 +00001967 bool IsOutOfDate = false;
1968
1969 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001970 if (!Overridden && //
1971 (StoredSize != File->getSize() ||
1972#if defined(LLVM_ON_WIN32)
1973 false
1974#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001975 // In our regression testing, the Windows file system seems to
1976 // have inconsistent modification times that sometimes
1977 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001978 //
1979 // This also happens in networked file systems, so disable this
1980 // check if validation is disabled or if we have an explicitly
1981 // built PCM file.
1982 //
1983 // FIXME: Should we also do this for PCH files? They could also
1984 // reasonably get shared across a network during a distributed build.
1985 (StoredTime != File->getModificationTime() && !DisableValidation &&
1986 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001987#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001988 )) {
1989 if (Complain) {
1990 // Build a list of the PCH imports that got us here (in reverse).
1991 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1992 while (ImportStack.back()->ImportedBy.size() > 0)
1993 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001994
Ben Langmuir198c1682014-03-07 07:27:49 +00001995 // The top-level PCH is stale.
1996 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1997 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001998
Ben Langmuir198c1682014-03-07 07:27:49 +00001999 // Print the import stack.
2000 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2001 Diag(diag::note_pch_required_by)
2002 << Filename << ImportStack[0]->FileName;
2003 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002004 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002005 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002006 }
2007
Ben Langmuir198c1682014-03-07 07:27:49 +00002008 if (!Diags.isDiagnosticInFlight())
2009 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 }
2011
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 }
2014
Ben Langmuir198c1682014-03-07 07:27:49 +00002015 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2016
2017 // Note that we've loaded this input file.
2018 F.InputFilesLoaded[ID-1] = IF;
2019 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002020}
2021
Richard Smith7ed1bc92014-12-05 22:42:13 +00002022/// \brief If we are loading a relocatable PCH or module file, and the filename
2023/// is not an absolute path, add the system or module root to the beginning of
2024/// the file name.
2025void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2026 // Resolve relative to the base directory, if we have one.
2027 if (!M.BaseDirectory.empty())
2028 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002029}
2030
Richard Smith7ed1bc92014-12-05 22:42:13 +00002031void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002032 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2033 return;
2034
Richard Smith7ed1bc92014-12-05 22:42:13 +00002035 SmallString<128> Buffer;
2036 llvm::sys::path::append(Buffer, Prefix, Filename);
2037 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002038}
2039
Richard Smith0f99d6a2015-08-09 08:48:41 +00002040static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2041 switch (ARR) {
2042 case ASTReader::Failure: return true;
2043 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2044 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2045 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2046 case ASTReader::ConfigurationMismatch:
2047 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2048 case ASTReader::HadErrors: return true;
2049 case ASTReader::Success: return false;
2050 }
2051
2052 llvm_unreachable("unknown ASTReadResult");
2053}
2054
Guy Benyei11169dd2012-12-18 14:30:41 +00002055ASTReader::ASTReadResult
2056ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002057 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002058 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002059 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002060 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002061
2062 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2063 Error("malformed block record in AST file");
2064 return Failure;
2065 }
2066
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002067 // Should we allow the configuration of the module file to differ from the
2068 // configuration of the current translation unit in a compatible way?
2069 //
2070 // FIXME: Allow this for files explicitly specified with -include-pch too.
2071 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2072
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 // Read all of the records and blocks in the control block.
2074 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002075 unsigned NumInputs = 0;
2076 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002077 while (1) {
2078 llvm::BitstreamEntry Entry = Stream.advance();
2079
2080 switch (Entry.Kind) {
2081 case llvm::BitstreamEntry::Error:
2082 Error("malformed block record in AST file");
2083 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002084 case llvm::BitstreamEntry::EndBlock: {
2085 // Validate input files.
2086 const HeaderSearchOptions &HSOpts =
2087 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002088
Richard Smitha1825302014-10-23 22:18:29 +00002089 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002090 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2091 // loaded module files, ignore missing inputs.
2092 if (!DisableValidation && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002094
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002095 // If we are reading a module, we will create a verification timestamp,
2096 // so we verify all input files. Otherwise, verify only user input
2097 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002098
2099 unsigned N = NumUserInputs;
2100 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002101 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002102 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002103 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002104 N = NumInputs;
2105
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002106 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002107 InputFile IF = getInputFile(F, I+1, Complain);
2108 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002110 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002112
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002113 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002114 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002115
Ben Langmuircb69b572014-03-07 06:40:32 +00002116 if (Listener && Listener->needsInputFileVisitation()) {
2117 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2118 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002119 for (unsigned I = 0; I < N; ++I) {
2120 bool IsSystem = I >= NumUserInputs;
2121 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002122 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2123 F.Kind == MK_ExplicitModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002124 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002125 }
2126
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002128 }
2129
Chris Lattnere7b154b2013-01-19 21:39:22 +00002130 case llvm::BitstreamEntry::SubBlock:
2131 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002132 case INPUT_FILES_BLOCK_ID:
2133 F.InputFilesCursor = Stream;
2134 if (Stream.SkipBlock() || // Skip with the main cursor
2135 // Read the abbreviations
2136 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2137 Error("malformed block record in AST file");
2138 return Failure;
2139 }
2140 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002141
Guy Benyei11169dd2012-12-18 14:30:41 +00002142 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002143 if (Stream.SkipBlock()) {
2144 Error("malformed block record in AST file");
2145 return Failure;
2146 }
2147 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002149
2150 case llvm::BitstreamEntry::Record:
2151 // The interesting case.
2152 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 }
2154
2155 // Read and process a record.
2156 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002157 StringRef Blob;
2158 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002159 case METADATA: {
2160 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2161 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002162 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2163 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002164 return VersionMismatch;
2165 }
2166
2167 bool hasErrors = Record[5];
2168 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2169 Diag(diag::err_pch_with_compiler_errors);
2170 return HadErrors;
2171 }
2172
2173 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002174 // Relative paths in a relocatable PCH are relative to our sysroot.
2175 if (F.RelocatablePCH)
2176 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002177
2178 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002179 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002180 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2181 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002182 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 return VersionMismatch;
2184 }
2185 break;
2186 }
2187
Ben Langmuir487ea142014-10-23 18:05:36 +00002188 case SIGNATURE:
2189 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2190 F.Signature = Record[0];
2191 break;
2192
Guy Benyei11169dd2012-12-18 14:30:41 +00002193 case IMPORTS: {
2194 // Load each of the imported PCH files.
2195 unsigned Idx = 0, N = Record.size();
2196 while (Idx < N) {
2197 // Read information about the AST file.
2198 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2199 // The import location will be the local one for now; we will adjust
2200 // all import locations of module imports after the global source
2201 // location info are setup.
2202 SourceLocation ImportLoc =
2203 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002204 off_t StoredSize = (off_t)Record[Idx++];
2205 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002206 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002207 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002208
Richard Smith0f99d6a2015-08-09 08:48:41 +00002209 // If our client can't cope with us being out of date, we can't cope with
2210 // our dependency being missing.
2211 unsigned Capabilities = ClientLoadCapabilities;
2212 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2213 Capabilities &= ~ARR_Missing;
2214
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002216 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2217 Loaded, StoredSize, StoredModTime,
2218 StoredSignature, Capabilities);
2219
2220 // If we diagnosed a problem, produce a backtrace.
2221 if (isDiagnosedResult(Result, Capabilities))
2222 Diag(diag::note_module_file_imported_by)
2223 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2224
2225 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 case Failure: return Failure;
2227 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002228 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 case OutOfDate: return OutOfDate;
2230 case VersionMismatch: return VersionMismatch;
2231 case ConfigurationMismatch: return ConfigurationMismatch;
2232 case HadErrors: return HadErrors;
2233 case Success: break;
2234 }
2235 }
2236 break;
2237 }
2238
2239 case LANGUAGE_OPTIONS: {
2240 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002241 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002242 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002243 ParseLanguageOptions(Record, Complain, *Listener,
2244 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002245 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002246 return ConfigurationMismatch;
2247 break;
2248 }
2249
2250 case TARGET_OPTIONS: {
2251 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2252 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002253 ParseTargetOptions(Record, Complain, *Listener,
2254 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002255 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 return ConfigurationMismatch;
2257 break;
2258 }
2259
2260 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002261 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002263 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002264 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002265 !DisableValidation)
2266 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 break;
2268 }
2269
2270 case FILE_SYSTEM_OPTIONS: {
2271 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2272 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002273 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002275 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 return ConfigurationMismatch;
2277 break;
2278 }
2279
2280 case HEADER_SEARCH_OPTIONS: {
2281 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2282 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002283 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002285 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 return ConfigurationMismatch;
2287 break;
2288 }
2289
2290 case PREPROCESSOR_OPTIONS: {
2291 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2292 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002293 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 ParsePreprocessorOptions(Record, Complain, *Listener,
2295 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002296 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002297 return ConfigurationMismatch;
2298 break;
2299 }
2300
2301 case ORIGINAL_FILE:
2302 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002303 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002304 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002305 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002306 break;
2307
2308 case ORIGINAL_FILE_ID:
2309 F.OriginalSourceFileID = FileID::get(Record[0]);
2310 break;
2311
2312 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002313 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 break;
2315
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002316 case MODULE_NAME:
2317 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002318 if (Listener)
2319 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002320 break;
2321
Richard Smith223d3f22014-12-06 03:21:08 +00002322 case MODULE_DIRECTORY: {
2323 assert(!F.ModuleName.empty() &&
2324 "MODULE_DIRECTORY found before MODULE_NAME");
2325 // If we've already loaded a module map file covering this module, we may
2326 // have a better path for it (relative to the current build).
2327 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2328 if (M && M->Directory) {
2329 // If we're implicitly loading a module, the base directory can't
2330 // change between the build and use.
2331 if (F.Kind != MK_ExplicitModule) {
2332 const DirectoryEntry *BuildDir =
2333 PP.getFileManager().getDirectory(Blob);
2334 if (!BuildDir || BuildDir != M->Directory) {
2335 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2336 Diag(diag::err_imported_module_relocated)
2337 << F.ModuleName << Blob << M->Directory->getName();
2338 return OutOfDate;
2339 }
2340 }
2341 F.BaseDirectory = M->Directory->getName();
2342 } else {
2343 F.BaseDirectory = Blob;
2344 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002345 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002346 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002347
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002348 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002349 if (ASTReadResult Result =
2350 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2351 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002352 break;
2353
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002354 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002355 NumInputs = Record[0];
2356 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002357 F.InputFileOffsets =
2358 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002359 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002360 break;
2361 }
2362 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002363}
2364
Ben Langmuir2c9af442014-04-10 17:57:43 +00002365ASTReader::ASTReadResult
2366ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002367 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002368
2369 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2370 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002371 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 }
2373
2374 // Read all of the records and blocks for the AST file.
2375 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002376 while (1) {
2377 llvm::BitstreamEntry Entry = Stream.advance();
2378
2379 switch (Entry.Kind) {
2380 case llvm::BitstreamEntry::Error:
2381 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002382 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002384 // Outside of C++, we do not store a lookup map for the translation unit.
2385 // Instead, mark it as needing a lookup map to be built if this module
2386 // contains any declarations lexically within it (which it always does!).
2387 // This usually has no cost, since we very rarely need the lookup map for
2388 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002390 if (DC->hasExternalLexicalStorage() &&
2391 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002393
Ben Langmuir2c9af442014-04-10 17:57:43 +00002394 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002395 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002396 case llvm::BitstreamEntry::SubBlock:
2397 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 case DECLTYPES_BLOCK_ID:
2399 // We lazily load the decls block, but we want to set up the
2400 // DeclsCursor cursor to point into it. Clone our current bitcode
2401 // cursor to it, enter the block and read the abbrevs in that block.
2402 // With the main cursor, we just skip over it.
2403 F.DeclsCursor = Stream;
2404 if (Stream.SkipBlock() || // Skip with the main cursor.
2405 // Read the abbrevs.
2406 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2407 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002408 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 }
2410 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002411
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 case PREPROCESSOR_BLOCK_ID:
2413 F.MacroCursor = Stream;
2414 if (!PP.getExternalSource())
2415 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002416
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 if (Stream.SkipBlock() ||
2418 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2419 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002420 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 }
2422 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2423 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 case PREPROCESSOR_DETAIL_BLOCK_ID:
2426 F.PreprocessorDetailCursor = Stream;
2427 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002428 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002430 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002431 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002432 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002434 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2435
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 if (!PP.getPreprocessingRecord())
2437 PP.createPreprocessingRecord();
2438 if (!PP.getPreprocessingRecord()->getExternalSource())
2439 PP.getPreprocessingRecord()->SetExternalSource(*this);
2440 break;
2441
2442 case SOURCE_MANAGER_BLOCK_ID:
2443 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002444 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002445 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002446
Guy Benyei11169dd2012-12-18 14:30:41 +00002447 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002448 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2449 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002451
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002453 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 if (Stream.SkipBlock() ||
2455 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2456 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002457 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002458 }
2459 CommentsCursors.push_back(std::make_pair(C, &F));
2460 break;
2461 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002462
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002464 if (Stream.SkipBlock()) {
2465 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002466 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002467 }
2468 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 }
2470 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002471
2472 case llvm::BitstreamEntry::Record:
2473 // The interesting case.
2474 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 }
2476
2477 // Read and process a record.
2478 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002479 StringRef Blob;
2480 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 default: // Default behavior: ignore.
2482 break;
2483
2484 case TYPE_OFFSET: {
2485 if (F.LocalNumTypes != 0) {
2486 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002487 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002489 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 F.LocalNumTypes = Record[0];
2491 unsigned LocalBaseTypeIndex = Record[1];
2492 F.BaseTypeIndex = getTotalNumTypes();
2493
2494 if (F.LocalNumTypes > 0) {
2495 // Introduce the global -> local mapping for types within this module.
2496 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2497
2498 // Introduce the local -> global mapping for types within this module.
2499 F.TypeRemap.insertOrReplace(
2500 std::make_pair(LocalBaseTypeIndex,
2501 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002502
2503 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002504 }
2505 break;
2506 }
2507
2508 case DECL_OFFSET: {
2509 if (F.LocalNumDecls != 0) {
2510 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002511 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002513 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002514 F.LocalNumDecls = Record[0];
2515 unsigned LocalBaseDeclID = Record[1];
2516 F.BaseDeclID = getTotalNumDecls();
2517
2518 if (F.LocalNumDecls > 0) {
2519 // Introduce the global -> local mapping for declarations within this
2520 // module.
2521 GlobalDeclMap.insert(
2522 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2523
2524 // Introduce the local -> global mapping for declarations within this
2525 // module.
2526 F.DeclRemap.insertOrReplace(
2527 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2528
2529 // Introduce the global -> local mapping for declarations within this
2530 // module.
2531 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002532
Ben Langmuir52ca6782014-10-20 16:27:32 +00002533 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2534 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 break;
2536 }
2537
2538 case TU_UPDATE_LEXICAL: {
2539 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002540 LexicalContents Contents(
2541 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2542 Blob.data()),
2543 static_cast<unsigned int>(Blob.size() / 4));
2544 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 TU->setHasExternalLexicalStorage(true);
2546 break;
2547 }
2548
2549 case UPDATE_VISIBLE: {
2550 unsigned Idx = 0;
2551 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002552 auto *Data = (const unsigned char*)Blob.data();
2553 unsigned BucketOffset = Record[Idx++];
2554 PendingVisibleUpdates[ID].push_back(
2555 PendingVisibleUpdate{&F, Data, BucketOffset});
2556 // If we've already loaded the decl, perform the updates when we finish
2557 // loading this block.
2558 if (Decl *D = GetExistingDecl(ID))
2559 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 break;
2561 }
2562
2563 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002564 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002566 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2567 (const unsigned char *)F.IdentifierTableData + Record[0],
2568 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2569 (const unsigned char *)F.IdentifierTableData,
2570 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002571
2572 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2573 }
2574 break;
2575
2576 case IDENTIFIER_OFFSET: {
2577 if (F.LocalNumIdentifiers != 0) {
2578 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002579 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002581 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002582 F.LocalNumIdentifiers = Record[0];
2583 unsigned LocalBaseIdentifierID = Record[1];
2584 F.BaseIdentifierID = getTotalNumIdentifiers();
2585
2586 if (F.LocalNumIdentifiers > 0) {
2587 // Introduce the global -> local mapping for identifiers within this
2588 // module.
2589 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2590 &F));
2591
2592 // Introduce the local -> global mapping for identifiers within this
2593 // module.
2594 F.IdentifierRemap.insertOrReplace(
2595 std::make_pair(LocalBaseIdentifierID,
2596 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002597
Ben Langmuir52ca6782014-10-20 16:27:32 +00002598 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2599 + F.LocalNumIdentifiers);
2600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002601 break;
2602 }
2603
Richard Smith33e0f7e2015-07-22 02:08:40 +00002604 case INTERESTING_IDENTIFIERS:
2605 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2606 break;
2607
Ben Langmuir332aafe2014-01-31 01:06:56 +00002608 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002609 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2610 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002612 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 break;
2614
2615 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002616 if (SpecialTypes.empty()) {
2617 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2618 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2619 break;
2620 }
2621
2622 if (SpecialTypes.size() != Record.size()) {
2623 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002624 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002625 }
2626
2627 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2628 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2629 if (!SpecialTypes[I])
2630 SpecialTypes[I] = ID;
2631 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2632 // merge step?
2633 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002634 break;
2635
2636 case STATISTICS:
2637 TotalNumStatements += Record[0];
2638 TotalNumMacros += Record[1];
2639 TotalLexicalDeclContexts += Record[2];
2640 TotalVisibleDeclContexts += Record[3];
2641 break;
2642
2643 case UNUSED_FILESCOPED_DECLS:
2644 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2645 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2646 break;
2647
2648 case DELEGATING_CTORS:
2649 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2650 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2651 break;
2652
2653 case WEAK_UNDECLARED_IDENTIFIERS:
2654 if (Record.size() % 4 != 0) {
2655 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002656 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 }
2658
2659 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2660 // files. This isn't the way to do it :)
2661 WeakUndeclaredIdentifiers.clear();
2662
2663 // Translate the weak, undeclared identifiers into global IDs.
2664 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2665 WeakUndeclaredIdentifiers.push_back(
2666 getGlobalIdentifierID(F, Record[I++]));
2667 WeakUndeclaredIdentifiers.push_back(
2668 getGlobalIdentifierID(F, Record[I++]));
2669 WeakUndeclaredIdentifiers.push_back(
2670 ReadSourceLocation(F, Record, I).getRawEncoding());
2671 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2672 }
2673 break;
2674
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002676 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002677 F.LocalNumSelectors = Record[0];
2678 unsigned LocalBaseSelectorID = Record[1];
2679 F.BaseSelectorID = getTotalNumSelectors();
2680
2681 if (F.LocalNumSelectors > 0) {
2682 // Introduce the global -> local mapping for selectors within this
2683 // module.
2684 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2685
2686 // Introduce the local -> global mapping for selectors within this
2687 // module.
2688 F.SelectorRemap.insertOrReplace(
2689 std::make_pair(LocalBaseSelectorID,
2690 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002691
2692 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 }
2694 break;
2695 }
2696
2697 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002698 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 if (Record[0])
2700 F.SelectorLookupTable
2701 = ASTSelectorLookupTable::Create(
2702 F.SelectorLookupTableData + Record[0],
2703 F.SelectorLookupTableData,
2704 ASTSelectorLookupTrait(*this, F));
2705 TotalNumMethodPoolEntries += Record[1];
2706 break;
2707
2708 case REFERENCED_SELECTOR_POOL:
2709 if (!Record.empty()) {
2710 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2711 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2712 Record[Idx++]));
2713 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2714 getRawEncoding());
2715 }
2716 }
2717 break;
2718
2719 case PP_COUNTER_VALUE:
2720 if (!Record.empty() && Listener)
2721 Listener->ReadCounter(F, Record[0]);
2722 break;
2723
2724 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002725 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 F.NumFileSortedDecls = Record[0];
2727 break;
2728
2729 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002730 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002731 F.LocalNumSLocEntries = Record[0];
2732 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002733 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002734 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002736 if (!F.SLocEntryBaseID) {
2737 Error("ran out of source locations");
2738 break;
2739 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 // Make our entry in the range map. BaseID is negative and growing, so
2741 // we invert it. Because we invert it, though, we need the other end of
2742 // the range.
2743 unsigned RangeStart =
2744 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2745 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2746 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2747
2748 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2749 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2750 GlobalSLocOffsetMap.insert(
2751 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2752 - SLocSpaceSize,&F));
2753
2754 // Initialize the remapping table.
2755 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002756 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002758 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002759 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2760
2761 TotalNumSLocEntries += F.LocalNumSLocEntries;
2762 break;
2763 }
2764
2765 case MODULE_OFFSET_MAP: {
2766 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002767 const unsigned char *Data = (const unsigned char*)Blob.data();
2768 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002769
2770 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2771 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2772 F.SLocRemap.insert(std::make_pair(0U, 0));
2773 F.SLocRemap.insert(std::make_pair(2U, 1));
2774 }
2775
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002777 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2778 RemapBuilder;
2779 RemapBuilder SLocRemap(F.SLocRemap);
2780 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2781 RemapBuilder MacroRemap(F.MacroRemap);
2782 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2783 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2784 RemapBuilder SelectorRemap(F.SelectorRemap);
2785 RemapBuilder DeclRemap(F.DeclRemap);
2786 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002787
2788 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002789 using namespace llvm::support;
2790 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 StringRef Name = StringRef((const char*)Data, Len);
2792 Data += Len;
2793 ModuleFile *OM = ModuleMgr.lookup(Name);
2794 if (!OM) {
2795 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002796 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 }
2798
Justin Bogner57ba0b22014-03-28 22:03:24 +00002799 uint32_t SLocOffset =
2800 endian::readNext<uint32_t, little, unaligned>(Data);
2801 uint32_t IdentifierIDOffset =
2802 endian::readNext<uint32_t, little, unaligned>(Data);
2803 uint32_t MacroIDOffset =
2804 endian::readNext<uint32_t, little, unaligned>(Data);
2805 uint32_t PreprocessedEntityIDOffset =
2806 endian::readNext<uint32_t, little, unaligned>(Data);
2807 uint32_t SubmoduleIDOffset =
2808 endian::readNext<uint32_t, little, unaligned>(Data);
2809 uint32_t SelectorIDOffset =
2810 endian::readNext<uint32_t, little, unaligned>(Data);
2811 uint32_t DeclIDOffset =
2812 endian::readNext<uint32_t, little, unaligned>(Data);
2813 uint32_t TypeIndexOffset =
2814 endian::readNext<uint32_t, little, unaligned>(Data);
2815
Ben Langmuir785180e2014-10-20 16:27:30 +00002816 uint32_t None = std::numeric_limits<uint32_t>::max();
2817
2818 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2819 RemapBuilder &Remap) {
2820 if (Offset != None)
2821 Remap.insert(std::make_pair(Offset,
2822 static_cast<int>(BaseOffset - Offset)));
2823 };
2824 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2825 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2826 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2827 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2828 PreprocessedEntityRemap);
2829 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2830 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2831 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2832 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002833
2834 // Global -> local mappings.
2835 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2836 }
2837 break;
2838 }
2839
2840 case SOURCE_MANAGER_LINE_TABLE:
2841 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002842 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002843 break;
2844
2845 case SOURCE_LOCATION_PRELOADS: {
2846 // Need to transform from the local view (1-based IDs) to the global view,
2847 // which is based off F.SLocEntryBaseID.
2848 if (!F.PreloadSLocEntries.empty()) {
2849 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002850 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 }
2852
2853 F.PreloadSLocEntries.swap(Record);
2854 break;
2855 }
2856
2857 case EXT_VECTOR_DECLS:
2858 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2859 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2860 break;
2861
2862 case VTABLE_USES:
2863 if (Record.size() % 3 != 0) {
2864 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002865 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 }
2867
2868 // Later tables overwrite earlier ones.
2869 // FIXME: Modules will have some trouble with this. This is clearly not
2870 // the right way to do this.
2871 VTableUses.clear();
2872
2873 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2874 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2875 VTableUses.push_back(
2876 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2877 VTableUses.push_back(Record[Idx++]);
2878 }
2879 break;
2880
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 case PENDING_IMPLICIT_INSTANTIATIONS:
2882 if (PendingInstantiations.size() % 2 != 0) {
2883 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002884 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 }
2886
2887 if (Record.size() % 2 != 0) {
2888 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002889 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002890 }
2891
2892 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2893 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2894 PendingInstantiations.push_back(
2895 ReadSourceLocation(F, Record, I).getRawEncoding());
2896 }
2897 break;
2898
2899 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002900 if (Record.size() != 2) {
2901 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002902 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002903 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2905 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2906 break;
2907
2908 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002909 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2910 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2911 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002912
2913 unsigned LocalBasePreprocessedEntityID = Record[0];
2914
2915 unsigned StartingID;
2916 if (!PP.getPreprocessingRecord())
2917 PP.createPreprocessingRecord();
2918 if (!PP.getPreprocessingRecord()->getExternalSource())
2919 PP.getPreprocessingRecord()->SetExternalSource(*this);
2920 StartingID
2921 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002922 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 F.BasePreprocessedEntityID = StartingID;
2924
2925 if (F.NumPreprocessedEntities > 0) {
2926 // Introduce the global -> local mapping for preprocessed entities in
2927 // this module.
2928 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2929
2930 // Introduce the local -> global mapping for preprocessed entities in
2931 // this module.
2932 F.PreprocessedEntityRemap.insertOrReplace(
2933 std::make_pair(LocalBasePreprocessedEntityID,
2934 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2935 }
2936
2937 break;
2938 }
2939
2940 case DECL_UPDATE_OFFSETS: {
2941 if (Record.size() % 2 != 0) {
2942 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002943 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002945 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2946 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2947 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2948
2949 // If we've already loaded the decl, perform the updates when we finish
2950 // loading this block.
2951 if (Decl *D = GetExistingDecl(ID))
2952 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2953 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002954 break;
2955 }
2956
2957 case DECL_REPLACEMENTS: {
2958 if (Record.size() % 3 != 0) {
2959 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002960 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 }
2962 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2963 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2964 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2965 break;
2966 }
2967
2968 case OBJC_CATEGORIES_MAP: {
2969 if (F.LocalNumObjCCategoriesInMap != 0) {
2970 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002971 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002972 }
2973
2974 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002975 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 break;
2977 }
2978
2979 case OBJC_CATEGORIES:
2980 F.ObjCCategories.swap(Record);
2981 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002982
Guy Benyei11169dd2012-12-18 14:30:41 +00002983 case CXX_BASE_SPECIFIER_OFFSETS: {
2984 if (F.LocalNumCXXBaseSpecifiers != 0) {
2985 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002986 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002988
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002990 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002991 break;
2992 }
2993
2994 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2995 if (F.LocalNumCXXCtorInitializers != 0) {
2996 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2997 return Failure;
2998 }
2999
3000 F.LocalNumCXXCtorInitializers = Record[0];
3001 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003002 break;
3003 }
3004
3005 case DIAG_PRAGMA_MAPPINGS:
3006 if (F.PragmaDiagMappings.empty())
3007 F.PragmaDiagMappings.swap(Record);
3008 else
3009 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3010 Record.begin(), Record.end());
3011 break;
3012
3013 case CUDA_SPECIAL_DECL_REFS:
3014 // Later tables overwrite earlier ones.
3015 // FIXME: Modules will have trouble with this.
3016 CUDASpecialDeclRefs.clear();
3017 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3018 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3019 break;
3020
3021 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003022 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 if (Record[0]) {
3025 F.HeaderFileInfoTable
3026 = HeaderFileInfoLookupTable::Create(
3027 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3028 (const unsigned char *)F.HeaderFileInfoTableData,
3029 HeaderFileInfoTrait(*this, F,
3030 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003031 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003032
3033 PP.getHeaderSearchInfo().SetExternalSource(this);
3034 if (!PP.getHeaderSearchInfo().getExternalLookup())
3035 PP.getHeaderSearchInfo().SetExternalLookup(this);
3036 }
3037 break;
3038 }
3039
3040 case FP_PRAGMA_OPTIONS:
3041 // Later tables overwrite earlier ones.
3042 FPPragmaOptions.swap(Record);
3043 break;
3044
3045 case OPENCL_EXTENSIONS:
3046 // Later tables overwrite earlier ones.
3047 OpenCLExtensions.swap(Record);
3048 break;
3049
3050 case TENTATIVE_DEFINITIONS:
3051 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3052 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3053 break;
3054
3055 case KNOWN_NAMESPACES:
3056 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3057 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3058 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003059
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003060 case UNDEFINED_BUT_USED:
3061 if (UndefinedButUsed.size() % 2 != 0) {
3062 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003063 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003064 }
3065
3066 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003067 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003068 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003069 }
3070 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003071 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3072 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003073 ReadSourceLocation(F, Record, I).getRawEncoding());
3074 }
3075 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003076 case DELETE_EXPRS_TO_ANALYZE:
3077 for (unsigned I = 0, N = Record.size(); I != N;) {
3078 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3079 const uint64_t Count = Record[I++];
3080 DelayedDeleteExprs.push_back(Count);
3081 for (uint64_t C = 0; C < Count; ++C) {
3082 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3083 bool IsArrayForm = Record[I++] == 1;
3084 DelayedDeleteExprs.push_back(IsArrayForm);
3085 }
3086 }
3087 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003088
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003090 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 // If we aren't loading a module (which has its own exports), make
3092 // all of the imported modules visible.
3093 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003094 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3095 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3096 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3097 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003098 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 }
3100 }
3101 break;
3102 }
3103
3104 case LOCAL_REDECLARATIONS: {
3105 F.RedeclarationChains.swap(Record);
3106 break;
3107 }
3108
3109 case LOCAL_REDECLARATIONS_MAP: {
3110 if (F.LocalNumRedeclarationsInMap != 0) {
3111 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003112 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 }
3114
3115 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003116 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 break;
3118 }
3119
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 case MACRO_OFFSET: {
3121 if (F.LocalNumMacros != 0) {
3122 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003123 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003125 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003126 F.LocalNumMacros = Record[0];
3127 unsigned LocalBaseMacroID = Record[1];
3128 F.BaseMacroID = getTotalNumMacros();
3129
3130 if (F.LocalNumMacros > 0) {
3131 // Introduce the global -> local mapping for macros within this module.
3132 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3133
3134 // Introduce the local -> global mapping for macros within this module.
3135 F.MacroRemap.insertOrReplace(
3136 std::make_pair(LocalBaseMacroID,
3137 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003138
3139 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 }
3141 break;
3142 }
3143
Richard Smithe40f2ba2013-08-07 21:41:30 +00003144 case LATE_PARSED_TEMPLATE: {
3145 LateParsedTemplates.append(Record.begin(), Record.end());
3146 break;
3147 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003148
3149 case OPTIMIZE_PRAGMA_OPTIONS:
3150 if (Record.size() != 1) {
3151 Error("invalid pragma optimize record");
3152 return Failure;
3153 }
3154 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3155 break;
Nico Weber72889432014-09-06 01:25:55 +00003156
3157 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3158 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3159 UnusedLocalTypedefNameCandidates.push_back(
3160 getGlobalDeclID(F, Record[I]));
3161 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003162 }
3163 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003164}
3165
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003166ASTReader::ASTReadResult
3167ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3168 const ModuleFile *ImportedBy,
3169 unsigned ClientLoadCapabilities) {
3170 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003171 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003172
Richard Smithe842a472014-10-22 02:05:46 +00003173 if (F.Kind == MK_ExplicitModule) {
3174 // For an explicitly-loaded module, we don't care whether the original
3175 // module map file exists or matches.
3176 return Success;
3177 }
3178
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003179 // Try to resolve ModuleName in the current header search context and
3180 // verify that it is found in the same module map file as we saved. If the
3181 // top-level AST file is a main file, skip this check because there is no
3182 // usable header search context.
3183 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003184 "MODULE_NAME should come before MODULE_MAP_FILE");
3185 if (F.Kind == MK_ImplicitModule &&
3186 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3187 // An implicitly-loaded module file should have its module listed in some
3188 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003189 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003190 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3191 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3192 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003193 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003194 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3195 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3196 // This module was defined by an imported (explicit) module.
3197 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3198 << ASTFE->getName();
3199 else
3200 // This module was built with a different module map.
3201 Diag(diag::err_imported_module_not_found)
3202 << F.ModuleName << F.FileName << ImportedBy->FileName
3203 << F.ModuleMapPath;
3204 }
3205 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003206 }
3207
Richard Smithe842a472014-10-22 02:05:46 +00003208 assert(M->Name == F.ModuleName && "found module with different name");
3209
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003210 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003211 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003212 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3213 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003214 assert(ImportedBy && "top-level import should be verified");
3215 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3216 Diag(diag::err_imported_module_modmap_changed)
3217 << F.ModuleName << ImportedBy->FileName
3218 << ModMap->getName() << F.ModuleMapPath;
3219 return OutOfDate;
3220 }
3221
3222 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3223 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3224 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003225 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003226 const FileEntry *F =
3227 FileMgr.getFile(Filename, false, false);
3228 if (F == nullptr) {
3229 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3230 Error("could not find file '" + Filename +"' referenced by AST file");
3231 return OutOfDate;
3232 }
3233 AdditionalStoredMaps.insert(F);
3234 }
3235
3236 // Check any additional module map files (e.g. module.private.modulemap)
3237 // that are not in the pcm.
3238 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3239 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3240 // Remove files that match
3241 // Note: SmallPtrSet::erase is really remove
3242 if (!AdditionalStoredMaps.erase(ModMap)) {
3243 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3244 Diag(diag::err_module_different_modmap)
3245 << F.ModuleName << /*new*/0 << ModMap->getName();
3246 return OutOfDate;
3247 }
3248 }
3249 }
3250
3251 // Check any additional module map files that are in the pcm, but not
3252 // found in header search. Cases that match are already removed.
3253 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3254 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3255 Diag(diag::err_module_different_modmap)
3256 << F.ModuleName << /*not new*/1 << ModMap->getName();
3257 return OutOfDate;
3258 }
3259 }
3260
3261 if (Listener)
3262 Listener->ReadModuleMapFile(F.ModuleMapPath);
3263 return Success;
3264}
3265
3266
Douglas Gregorc1489562013-02-12 23:36:21 +00003267/// \brief Move the given method to the back of the global list of methods.
3268static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3269 // Find the entry for this selector in the method pool.
3270 Sema::GlobalMethodPool::iterator Known
3271 = S.MethodPool.find(Method->getSelector());
3272 if (Known == S.MethodPool.end())
3273 return;
3274
3275 // Retrieve the appropriate method list.
3276 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3277 : Known->second.second;
3278 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003279 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003280 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003281 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003282 Found = true;
3283 } else {
3284 // Keep searching.
3285 continue;
3286 }
3287 }
3288
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003289 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003290 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003291 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003292 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003293 }
3294}
3295
Richard Smithde711422015-04-23 21:20:19 +00003296void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003297 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003298 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003299 bool wasHidden = D->Hidden;
3300 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003301
Richard Smith49f906a2014-03-01 00:08:04 +00003302 if (wasHidden && SemaObj) {
3303 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3304 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003305 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 }
3307 }
3308}
3309
Richard Smith49f906a2014-03-01 00:08:04 +00003310void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003311 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003312 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003314 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003315 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003316 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003317 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003318
3319 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003320 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 // there is nothing more to do.
3322 continue;
3323 }
Richard Smith49f906a2014-03-01 00:08:04 +00003324
Guy Benyei11169dd2012-12-18 14:30:41 +00003325 if (!Mod->isAvailable()) {
3326 // Modules that aren't available cannot be made visible.
3327 continue;
3328 }
3329
3330 // Update the module's name visibility.
3331 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003332
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 // If we've already deserialized any names from this module,
3334 // mark them as visible.
3335 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3336 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003337 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003339 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003340 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3341 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003342 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003343
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003345 SmallVector<Module *, 16> Exports;
3346 Mod->getExportedModules(Exports);
3347 for (SmallVectorImpl<Module *>::iterator
3348 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3349 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003350 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003351 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 }
3353 }
3354}
3355
Douglas Gregore060e572013-01-25 01:03:03 +00003356bool ASTReader::loadGlobalIndex() {
3357 if (GlobalIndex)
3358 return false;
3359
3360 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3361 !Context.getLangOpts().Modules)
3362 return true;
3363
3364 // Try to load the global index.
3365 TriedLoadingGlobalIndex = true;
3366 StringRef ModuleCachePath
3367 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3368 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003369 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003370 if (!Result.first)
3371 return true;
3372
3373 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003374 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003375 return false;
3376}
3377
3378bool ASTReader::isGlobalIndexUnavailable() const {
3379 return Context.getLangOpts().Modules && UseGlobalIndex &&
3380 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3381}
3382
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003383static void updateModuleTimestamp(ModuleFile &MF) {
3384 // Overwrite the timestamp file contents so that file's mtime changes.
3385 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003386 std::error_code EC;
3387 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3388 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003389 return;
3390 OS << "Timestamp file\n";
3391}
3392
Guy Benyei11169dd2012-12-18 14:30:41 +00003393ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3394 ModuleKind Type,
3395 SourceLocation ImportLoc,
3396 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003397 llvm::SaveAndRestore<SourceLocation>
3398 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3399
Richard Smithd1c46742014-04-30 02:24:17 +00003400 // Defer any pending actions until we get to the end of reading the AST file.
3401 Deserializing AnASTFile(this);
3402
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003404 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003405
3406 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003407 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003408 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003409 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003410 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 ClientLoadCapabilities)) {
3412 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003413 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003414 case OutOfDate:
3415 case VersionMismatch:
3416 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003417 case HadErrors: {
3418 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3419 for (const ImportedModule &IM : Loaded)
3420 LoadedSet.insert(IM.Mod);
3421
Douglas Gregor7029ce12013-03-19 00:28:20 +00003422 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003423 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003424 Context.getLangOpts().Modules
3425 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003426 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003427
3428 // If we find that any modules are unusable, the global index is going
3429 // to be out-of-date. Just remove it.
3430 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003431 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003433 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003434 case Success:
3435 break;
3436 }
3437
3438 // Here comes stuff that we only do once the entire chain is loaded.
3439
3440 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003441 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3442 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003443 M != MEnd; ++M) {
3444 ModuleFile &F = *M->Mod;
3445
3446 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003447 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3448 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003449
3450 // Once read, set the ModuleFile bit base offset and update the size in
3451 // bits of all files we've seen.
3452 F.GlobalBitOffset = TotalModulesSizeInBits;
3453 TotalModulesSizeInBits += F.SizeInBits;
3454 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3455
3456 // Preload SLocEntries.
3457 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3458 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3459 // Load it through the SourceManager and don't call ReadSLocEntry()
3460 // directly because the entry may have already been loaded in which case
3461 // calling ReadSLocEntry() directly would trigger an assertion in
3462 // SourceManager.
3463 SourceMgr.getLoadedSLocEntryByID(Index);
3464 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003465
3466 // Preload all the pending interesting identifiers by marking them out of
3467 // date.
3468 for (auto Offset : F.PreloadIdentifierOffsets) {
3469 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3470 F.IdentifierTableData + Offset);
3471
3472 ASTIdentifierLookupTrait Trait(*this, F);
3473 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3474 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3475 PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
3476 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003477 }
3478
Douglas Gregor603cd862013-03-22 18:50:14 +00003479 // Setup the import locations and notify the module manager that we've
3480 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003481 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3482 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 M != MEnd; ++M) {
3484 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003485
3486 ModuleMgr.moduleFileAccepted(&F);
3487
3488 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003489 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 if (!M->ImportedBy)
3491 F.ImportLoc = M->ImportLoc;
3492 else
3493 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3494 M->ImportLoc.getRawEncoding());
3495 }
3496
Richard Smith33e0f7e2015-07-22 02:08:40 +00003497 if (!Context.getLangOpts().CPlusPlus ||
3498 (Type != MK_ImplicitModule && Type != MK_ExplicitModule)) {
3499 // Mark all of the identifiers in the identifier table as being out of date,
3500 // so that various accessors know to check the loaded modules when the
3501 // identifier is used.
3502 //
3503 // For C++ modules, we don't need information on many identifiers (just
3504 // those that provide macros or are poisoned), so we mark all of
3505 // the interesting ones via PreloadIdentifierOffsets.
3506 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3507 IdEnd = PP.getIdentifierTable().end();
3508 Id != IdEnd; ++Id)
3509 Id->second->setOutOfDate(true);
3510 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003511
3512 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003513 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3514 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3516 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003517
3518 switch (Unresolved.Kind) {
3519 case UnresolvedModuleRef::Conflict:
3520 if (ResolvedMod) {
3521 Module::Conflict Conflict;
3522 Conflict.Other = ResolvedMod;
3523 Conflict.Message = Unresolved.String.str();
3524 Unresolved.Mod->Conflicts.push_back(Conflict);
3525 }
3526 continue;
3527
3528 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003530 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003531 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003532
Douglas Gregorfb912652013-03-20 21:10:35 +00003533 case UnresolvedModuleRef::Export:
3534 if (ResolvedMod || Unresolved.IsWildcard)
3535 Unresolved.Mod->Exports.push_back(
3536 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3537 continue;
3538 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003539 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003540 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003541
3542 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3543 // Might be unnecessary as use declarations are only used to build the
3544 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003545
3546 InitializeContext();
3547
Richard Smith3d8e97e2013-10-18 06:54:39 +00003548 if (SemaObj)
3549 UpdateSema();
3550
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 if (DeserializationListener)
3552 DeserializationListener->ReaderInitialized(this);
3553
3554 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3555 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3556 PrimaryModule.OriginalSourceFileID
3557 = FileID::get(PrimaryModule.SLocEntryBaseID
3558 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3559
3560 // If this AST file is a precompiled preamble, then set the
3561 // preamble file ID of the source manager to the file source file
3562 // from which the preamble was built.
3563 if (Type == MK_Preamble) {
3564 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3565 } else if (Type == MK_MainFile) {
3566 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3567 }
3568 }
3569
3570 // For any Objective-C class definitions we have already loaded, make sure
3571 // that we load any additional categories.
3572 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3573 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3574 ObjCClassesLoaded[I],
3575 PreviousGeneration);
3576 }
Douglas Gregore060e572013-01-25 01:03:03 +00003577
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003578 if (PP.getHeaderSearchInfo()
3579 .getHeaderSearchOpts()
3580 .ModulesValidateOncePerBuildSession) {
3581 // Now we are certain that the module and all modules it depends on are
3582 // up to date. Create or update timestamp files for modules that are
3583 // located in the module cache (not for PCH files that could be anywhere
3584 // in the filesystem).
3585 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3586 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003587 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003588 updateModuleTimestamp(*M.Mod);
3589 }
3590 }
3591 }
3592
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 return Success;
3594}
3595
Ben Langmuir487ea142014-10-23 18:05:36 +00003596static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3597
Ben Langmuir70a1b812015-03-24 04:43:52 +00003598/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3599static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3600 return Stream.Read(8) == 'C' &&
3601 Stream.Read(8) == 'P' &&
3602 Stream.Read(8) == 'C' &&
3603 Stream.Read(8) == 'H';
3604}
3605
Richard Smith0f99d6a2015-08-09 08:48:41 +00003606static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3607 switch (Kind) {
3608 case MK_PCH:
3609 return 0; // PCH
3610 case MK_ImplicitModule:
3611 case MK_ExplicitModule:
3612 return 1; // module
3613 case MK_MainFile:
3614 case MK_Preamble:
3615 return 2; // main source file
3616 }
3617 llvm_unreachable("unknown module kind");
3618}
3619
Guy Benyei11169dd2012-12-18 14:30:41 +00003620ASTReader::ASTReadResult
3621ASTReader::ReadASTCore(StringRef FileName,
3622 ModuleKind Type,
3623 SourceLocation ImportLoc,
3624 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003625 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003626 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003627 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 unsigned ClientLoadCapabilities) {
3629 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003631 ModuleManager::AddModuleResult AddResult
3632 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003633 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003634 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003635 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003636
Douglas Gregor7029ce12013-03-19 00:28:20 +00003637 switch (AddResult) {
3638 case ModuleManager::AlreadyLoaded:
3639 return Success;
3640
3641 case ModuleManager::NewlyLoaded:
3642 // Load module file below.
3643 break;
3644
3645 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003646 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003647 // it.
3648 if (ClientLoadCapabilities & ARR_Missing)
3649 return Missing;
3650
3651 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003652 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3653 << FileName << ErrorStr.empty()
3654 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003655 return Failure;
3656
3657 case ModuleManager::OutOfDate:
3658 // We couldn't load the module file because it is out-of-date. If the
3659 // client can handle out-of-date, return it.
3660 if (ClientLoadCapabilities & ARR_OutOfDate)
3661 return OutOfDate;
3662
3663 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003664 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
3665 << FileName << ErrorStr.empty()
3666 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003667 return Failure;
3668 }
3669
Douglas Gregor7029ce12013-03-19 00:28:20 +00003670 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003671
3672 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3673 // module?
3674 if (FileName != "-") {
3675 CurrentDir = llvm::sys::path::parent_path(FileName);
3676 if (CurrentDir.empty()) CurrentDir = ".";
3677 }
3678
3679 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003680 BitstreamCursor &Stream = F.Stream;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003681 PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003682 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003683 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3684
Guy Benyei11169dd2012-12-18 14:30:41 +00003685 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003686 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003687 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3688 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 return Failure;
3690 }
3691
3692 // This is used for compatibility with older PCH formats.
3693 bool HaveReadControlBlock = false;
3694
Chris Lattnerefa77172013-01-20 00:00:22 +00003695 while (1) {
3696 llvm::BitstreamEntry Entry = Stream.advance();
3697
3698 switch (Entry.Kind) {
3699 case llvm::BitstreamEntry::Error:
3700 case llvm::BitstreamEntry::EndBlock:
3701 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003702 Error("invalid record at top-level of AST file");
3703 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003704
3705 case llvm::BitstreamEntry::SubBlock:
3706 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003707 }
3708
Guy Benyei11169dd2012-12-18 14:30:41 +00003709 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003710 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3712 if (Stream.ReadBlockInfoBlock()) {
3713 Error("malformed BlockInfoBlock in AST file");
3714 return Failure;
3715 }
3716 break;
3717 case CONTROL_BLOCK_ID:
3718 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003719 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003721 // Check that we didn't try to load a non-module AST file as a module.
3722 //
3723 // FIXME: Should we also perform the converse check? Loading a module as
3724 // a PCH file sort of works, but it's a bit wonky.
3725 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule) &&
3726 F.ModuleName.empty()) {
3727 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3728 if (Result != OutOfDate ||
3729 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3730 Diag(diag::err_module_file_not_module) << FileName;
3731 return Result;
3732 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 break;
3734
3735 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003736 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 case OutOfDate: return OutOfDate;
3738 case VersionMismatch: return VersionMismatch;
3739 case ConfigurationMismatch: return ConfigurationMismatch;
3740 case HadErrors: return HadErrors;
3741 }
3742 break;
3743 case AST_BLOCK_ID:
3744 if (!HaveReadControlBlock) {
3745 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003746 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 return VersionMismatch;
3748 }
3749
3750 // Record that we've loaded this module.
3751 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3752 return Success;
3753
3754 default:
3755 if (Stream.SkipBlock()) {
3756 Error("malformed block record in AST file");
3757 return Failure;
3758 }
3759 break;
3760 }
3761 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003762}
3763
Richard Smitha7e2cc62015-05-01 01:53:09 +00003764void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003765 // If there's a listener, notify them that we "read" the translation unit.
3766 if (DeserializationListener)
3767 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3768 Context.getTranslationUnitDecl());
3769
Guy Benyei11169dd2012-12-18 14:30:41 +00003770 // FIXME: Find a better way to deal with collisions between these
3771 // built-in types. Right now, we just ignore the problem.
3772
3773 // Load the special types.
3774 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3775 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3776 if (!Context.CFConstantStringTypeDecl)
3777 Context.setCFConstantStringType(GetType(String));
3778 }
3779
3780 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3781 QualType FileType = GetType(File);
3782 if (FileType.isNull()) {
3783 Error("FILE type is NULL");
3784 return;
3785 }
3786
3787 if (!Context.FILEDecl) {
3788 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3789 Context.setFILEDecl(Typedef->getDecl());
3790 else {
3791 const TagType *Tag = FileType->getAs<TagType>();
3792 if (!Tag) {
3793 Error("Invalid FILE type in AST file");
3794 return;
3795 }
3796 Context.setFILEDecl(Tag->getDecl());
3797 }
3798 }
3799 }
3800
3801 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3802 QualType Jmp_bufType = GetType(Jmp_buf);
3803 if (Jmp_bufType.isNull()) {
3804 Error("jmp_buf type is NULL");
3805 return;
3806 }
3807
3808 if (!Context.jmp_bufDecl) {
3809 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3810 Context.setjmp_bufDecl(Typedef->getDecl());
3811 else {
3812 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3813 if (!Tag) {
3814 Error("Invalid jmp_buf type in AST file");
3815 return;
3816 }
3817 Context.setjmp_bufDecl(Tag->getDecl());
3818 }
3819 }
3820 }
3821
3822 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3823 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3824 if (Sigjmp_bufType.isNull()) {
3825 Error("sigjmp_buf type is NULL");
3826 return;
3827 }
3828
3829 if (!Context.sigjmp_bufDecl) {
3830 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3831 Context.setsigjmp_bufDecl(Typedef->getDecl());
3832 else {
3833 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3834 assert(Tag && "Invalid sigjmp_buf type in AST file");
3835 Context.setsigjmp_bufDecl(Tag->getDecl());
3836 }
3837 }
3838 }
3839
3840 if (unsigned ObjCIdRedef
3841 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3842 if (Context.ObjCIdRedefinitionType.isNull())
3843 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3844 }
3845
3846 if (unsigned ObjCClassRedef
3847 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3848 if (Context.ObjCClassRedefinitionType.isNull())
3849 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3850 }
3851
3852 if (unsigned ObjCSelRedef
3853 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3854 if (Context.ObjCSelRedefinitionType.isNull())
3855 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3856 }
3857
3858 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3859 QualType Ucontext_tType = GetType(Ucontext_t);
3860 if (Ucontext_tType.isNull()) {
3861 Error("ucontext_t type is NULL");
3862 return;
3863 }
3864
3865 if (!Context.ucontext_tDecl) {
3866 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3867 Context.setucontext_tDecl(Typedef->getDecl());
3868 else {
3869 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3870 assert(Tag && "Invalid ucontext_t type in AST file");
3871 Context.setucontext_tDecl(Tag->getDecl());
3872 }
3873 }
3874 }
3875 }
3876
3877 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3878
3879 // If there were any CUDA special declarations, deserialize them.
3880 if (!CUDASpecialDeclRefs.empty()) {
3881 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3882 Context.setcudaConfigureCallDecl(
3883 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3884 }
Richard Smith56be7542014-03-21 00:33:59 +00003885
Guy Benyei11169dd2012-12-18 14:30:41 +00003886 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003887 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003888 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003889 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003890 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003891 /*ImportLoc=*/Import.ImportLoc);
3892 PP.makeModuleVisible(Imported, Import.ImportLoc);
3893 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003894 }
3895 ImportedModules.clear();
3896}
3897
3898void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003899 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003900}
3901
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003902/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3903/// cursor into the start of the given block ID, returning false on success and
3904/// true on failure.
3905static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003906 while (1) {
3907 llvm::BitstreamEntry Entry = Cursor.advance();
3908 switch (Entry.Kind) {
3909 case llvm::BitstreamEntry::Error:
3910 case llvm::BitstreamEntry::EndBlock:
3911 return true;
3912
3913 case llvm::BitstreamEntry::Record:
3914 // Ignore top-level records.
3915 Cursor.skipRecord(Entry.ID);
3916 break;
3917
3918 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003919 if (Entry.ID == BlockID) {
3920 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003921 return true;
3922 // Found it!
3923 return false;
3924 }
3925
3926 if (Cursor.SkipBlock())
3927 return true;
3928 }
3929 }
3930}
3931
Ben Langmuir70a1b812015-03-24 04:43:52 +00003932/// \brief Reads and return the signature record from \p StreamFile's control
3933/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003934static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3935 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003936 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003937 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003938
3939 // Scan for the CONTROL_BLOCK_ID block.
3940 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3941 return 0;
3942
3943 // Scan for SIGNATURE inside the control block.
3944 ASTReader::RecordData Record;
3945 while (1) {
3946 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3947 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3948 Entry.Kind != llvm::BitstreamEntry::Record)
3949 return 0;
3950
3951 Record.clear();
3952 StringRef Blob;
3953 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3954 return Record[0];
3955 }
3956}
3957
Guy Benyei11169dd2012-12-18 14:30:41 +00003958/// \brief Retrieve the name of the original source file name
3959/// directly from the AST file, without actually loading the AST
3960/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003961std::string ASTReader::getOriginalSourceFile(
3962 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003963 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003964 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003965 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003966 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003967 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3968 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003969 return std::string();
3970 }
3971
3972 // Initialize the stream
3973 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00003974 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003975 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003976
3977 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003978 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3980 return std::string();
3981 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003982
Chris Lattnere7b154b2013-01-19 21:39:22 +00003983 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003984 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003985 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3986 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003988
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003989 // Scan for ORIGINAL_FILE inside the control block.
3990 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003991 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003992 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003993 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3994 return std::string();
3995
3996 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3997 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3998 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00004000
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004002 StringRef Blob;
4003 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4004 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004006}
4007
4008namespace {
4009 class SimplePCHValidator : public ASTReaderListener {
4010 const LangOptions &ExistingLangOpts;
4011 const TargetOptions &ExistingTargetOpts;
4012 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004013 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004014 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004015
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 public:
4017 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4018 const TargetOptions &ExistingTargetOpts,
4019 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004020 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 FileManager &FileMgr)
4022 : ExistingLangOpts(ExistingLangOpts),
4023 ExistingTargetOpts(ExistingTargetOpts),
4024 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004025 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004026 FileMgr(FileMgr)
4027 {
4028 }
4029
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004030 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4031 bool AllowCompatibleDifferences) override {
4032 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4033 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004034 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004035 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4036 bool AllowCompatibleDifferences) override {
4037 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4038 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004040 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4041 StringRef SpecificModuleCachePath,
4042 bool Complain) override {
4043 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4044 ExistingModuleCachePath,
4045 nullptr, ExistingLangOpts);
4046 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00004047 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4048 bool Complain,
4049 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004050 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004051 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004052 }
4053 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004054}
Guy Benyei11169dd2012-12-18 14:30:41 +00004055
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004056bool ASTReader::readASTFileControlBlock(
4057 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004058 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004059 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004060 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004061 // FIXME: This allows use of the VFS; we do not allow use of the
4062 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004063 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004064 if (!Buffer) {
4065 return true;
4066 }
4067
4068 // Initialize the stream
4069 llvm::BitstreamReader StreamFile;
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004070 PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00004071 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00004072
4073 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004074 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004076
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004077 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004078 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004079 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004080
4081 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004082 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004083 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004084 BitstreamCursor InputFilesCursor;
4085 if (NeedsInputFiles) {
4086 InputFilesCursor = Stream;
4087 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4088 return true;
4089
4090 // Read the abbreviations
4091 while (true) {
4092 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4093 unsigned Code = InputFilesCursor.ReadCode();
4094
4095 // We expect all abbrevs to be at the start of the block.
4096 if (Code != llvm::bitc::DEFINE_ABBREV) {
4097 InputFilesCursor.JumpToBit(Offset);
4098 break;
4099 }
4100 InputFilesCursor.ReadAbbrevRecord();
4101 }
4102 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004103
4104 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004106 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004107 while (1) {
4108 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4109 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4110 return false;
4111
4112 if (Entry.Kind != llvm::BitstreamEntry::Record)
4113 return true;
4114
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004116 StringRef Blob;
4117 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004118 switch ((ControlRecordTypes)RecCode) {
4119 case METADATA: {
4120 if (Record[0] != VERSION_MAJOR)
4121 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004122
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004123 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004124 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004125
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004126 break;
4127 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004128 case MODULE_NAME:
4129 Listener.ReadModuleName(Blob);
4130 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004131 case MODULE_DIRECTORY:
4132 ModuleDir = Blob;
4133 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004134 case MODULE_MAP_FILE: {
4135 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004136 auto Path = ReadString(Record, Idx);
4137 ResolveImportedPath(Path, ModuleDir);
4138 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004139 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004140 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004141 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004142 if (ParseLanguageOptions(Record, false, Listener,
4143 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004144 return true;
4145 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004146
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004147 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004148 if (ParseTargetOptions(Record, false, Listener,
4149 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004150 return true;
4151 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004152
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004153 case DIAGNOSTIC_OPTIONS:
4154 if (ParseDiagnosticOptions(Record, false, Listener))
4155 return true;
4156 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004157
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004158 case FILE_SYSTEM_OPTIONS:
4159 if (ParseFileSystemOptions(Record, false, Listener))
4160 return true;
4161 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004162
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004163 case HEADER_SEARCH_OPTIONS:
4164 if (ParseHeaderSearchOptions(Record, false, Listener))
4165 return true;
4166 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004167
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004168 case PREPROCESSOR_OPTIONS: {
4169 std::string IgnoredSuggestedPredefines;
4170 if (ParsePreprocessorOptions(Record, false, Listener,
4171 IgnoredSuggestedPredefines))
4172 return true;
4173 break;
4174 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004175
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004176 case INPUT_FILE_OFFSETS: {
4177 if (!NeedsInputFiles)
4178 break;
4179
4180 unsigned NumInputFiles = Record[0];
4181 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004182 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004183 for (unsigned I = 0; I != NumInputFiles; ++I) {
4184 // Go find this input file.
4185 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004186
4187 if (isSystemFile && !NeedsSystemInputFiles)
4188 break; // the rest are system input files
4189
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004190 BitstreamCursor &Cursor = InputFilesCursor;
4191 SavedStreamPosition SavedPosition(Cursor);
4192 Cursor.JumpToBit(InputFileOffs[I]);
4193
4194 unsigned Code = Cursor.ReadCode();
4195 RecordData Record;
4196 StringRef Blob;
4197 bool shouldContinue = false;
4198 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4199 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004200 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004201 std::string Filename = Blob;
4202 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004203 shouldContinue = Listener.visitInputFile(
4204 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004205 break;
4206 }
4207 if (!shouldContinue)
4208 break;
4209 }
4210 break;
4211 }
4212
Richard Smithd4b230b2014-10-27 23:01:16 +00004213 case IMPORTS: {
4214 if (!NeedsImports)
4215 break;
4216
4217 unsigned Idx = 0, N = Record.size();
4218 while (Idx < N) {
4219 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004220 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004221 std::string Filename = ReadString(Record, Idx);
4222 ResolveImportedPath(Filename, ModuleDir);
4223 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004224 }
4225 break;
4226 }
4227
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004228 default:
4229 // No other validation to perform.
4230 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004231 }
4232 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004233}
4234
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004235bool ASTReader::isAcceptableASTFile(
4236 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004237 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004238 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4239 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004240 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4241 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004242 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004243 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004244}
4245
Ben Langmuir2c9af442014-04-10 17:57:43 +00004246ASTReader::ASTReadResult
4247ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004248 // Enter the submodule block.
4249 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4250 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004251 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 }
4253
4254 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4255 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004256 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004257 RecordData Record;
4258 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004259 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4260
4261 switch (Entry.Kind) {
4262 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4263 case llvm::BitstreamEntry::Error:
4264 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004265 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004266 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004267 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004268 case llvm::BitstreamEntry::Record:
4269 // The interesting case.
4270 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004271 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004272
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004274 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004275 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004276 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4277
4278 if ((Kind == SUBMODULE_METADATA) != First) {
4279 Error("submodule metadata record should be at beginning of block");
4280 return Failure;
4281 }
4282 First = false;
4283
4284 // Submodule information is only valid if we have a current module.
4285 // FIXME: Should we error on these cases?
4286 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4287 Kind != SUBMODULE_DEFINITION)
4288 continue;
4289
4290 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 default: // Default behavior: ignore.
4292 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004293
Richard Smith03478d92014-10-23 22:12:14 +00004294 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004295 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004297 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 }
Richard Smith03478d92014-10-23 22:12:14 +00004299
Chris Lattner0e6c9402013-01-20 02:38:54 +00004300 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004301 unsigned Idx = 0;
4302 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4303 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4304 bool IsFramework = Record[Idx++];
4305 bool IsExplicit = Record[Idx++];
4306 bool IsSystem = Record[Idx++];
4307 bool IsExternC = Record[Idx++];
4308 bool InferSubmodules = Record[Idx++];
4309 bool InferExplicitSubmodules = Record[Idx++];
4310 bool InferExportWildcard = Record[Idx++];
4311 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004312
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004313 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004314 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004315 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004316
Guy Benyei11169dd2012-12-18 14:30:41 +00004317 // Retrieve this (sub)module from the module map, creating it if
4318 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004319 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004320 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004321
4322 // FIXME: set the definition loc for CurrentModule, or call
4323 // ModMap.setInferredModuleAllowedBy()
4324
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4326 if (GlobalIndex >= SubmodulesLoaded.size() ||
4327 SubmodulesLoaded[GlobalIndex]) {
4328 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004329 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004330 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004331
Douglas Gregor7029ce12013-03-19 00:28:20 +00004332 if (!ParentModule) {
4333 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4334 if (CurFile != F.File) {
4335 if (!Diags.isDiagnosticInFlight()) {
4336 Diag(diag::err_module_file_conflict)
4337 << CurrentModule->getTopLevelModuleName()
4338 << CurFile->getName()
4339 << F.File->getName();
4340 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004341 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004342 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004343 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004344
4345 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004346 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004347
Adrian Prantl15bcf702015-06-30 17:39:43 +00004348 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 CurrentModule->IsFromModuleFile = true;
4350 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004351 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004352 CurrentModule->InferSubmodules = InferSubmodules;
4353 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4354 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004355 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 if (DeserializationListener)
4357 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4358
4359 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004360
Douglas Gregorfb912652013-03-20 21:10:35 +00004361 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004362 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004363 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004364 CurrentModule->UnresolvedConflicts.clear();
4365 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 break;
4367 }
4368
4369 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004370 std::string Filename = Blob;
4371 ResolveImportedPath(F, Filename);
4372 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004374 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4375 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004376 // This can be a spurious difference caused by changing the VFS to
4377 // point to a different copy of the file, and it is too late to
4378 // to rebuild safely.
4379 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4380 // after input file validation only real problems would remain and we
4381 // could just error. For now, assume it's okay.
4382 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004383 }
4384 }
4385 break;
4386 }
4387
Richard Smith202210b2014-10-24 20:23:01 +00004388 case SUBMODULE_HEADER:
4389 case SUBMODULE_EXCLUDED_HEADER:
4390 case SUBMODULE_PRIVATE_HEADER:
4391 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004392 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4393 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004394 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004395
Richard Smith202210b2014-10-24 20:23:01 +00004396 case SUBMODULE_TEXTUAL_HEADER:
4397 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4398 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4399 // them here.
4400 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004401
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004403 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 break;
4405 }
4406
4407 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004408 std::string Dirname = Blob;
4409 ResolveImportedPath(F, Dirname);
4410 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004411 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004412 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4413 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004414 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4415 Error("mismatched umbrella directories in submodule");
4416 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004417 }
4418 }
4419 break;
4420 }
4421
4422 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 F.BaseSubmoduleID = getTotalNumSubmodules();
4424 F.LocalNumSubmodules = Record[0];
4425 unsigned LocalBaseSubmoduleID = Record[1];
4426 if (F.LocalNumSubmodules > 0) {
4427 // Introduce the global -> local mapping for submodules within this
4428 // module.
4429 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4430
4431 // Introduce the local -> global mapping for submodules within this
4432 // module.
4433 F.SubmoduleRemap.insertOrReplace(
4434 std::make_pair(LocalBaseSubmoduleID,
4435 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004436
Ben Langmuir52ca6782014-10-20 16:27:32 +00004437 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4438 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004439 break;
4440 }
4441
4442 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004444 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004445 Unresolved.File = &F;
4446 Unresolved.Mod = CurrentModule;
4447 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004448 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004449 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004450 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 }
4452 break;
4453 }
4454
4455 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004456 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004457 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 Unresolved.File = &F;
4459 Unresolved.Mod = CurrentModule;
4460 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004461 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004463 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 }
4465
4466 // Once we've loaded the set of exports, there's no reason to keep
4467 // the parsed, unresolved exports around.
4468 CurrentModule->UnresolvedExports.clear();
4469 break;
4470 }
4471 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004472 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004473 Context.getTargetInfo());
4474 break;
4475 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004476
4477 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004478 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004479 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004480 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004481
4482 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004483 CurrentModule->ConfigMacros.push_back(Blob.str());
4484 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004485
4486 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004487 UnresolvedModuleRef Unresolved;
4488 Unresolved.File = &F;
4489 Unresolved.Mod = CurrentModule;
4490 Unresolved.ID = Record[0];
4491 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4492 Unresolved.IsWildcard = false;
4493 Unresolved.String = Blob;
4494 UnresolvedModuleRefs.push_back(Unresolved);
4495 break;
4496 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 }
4498 }
4499}
4500
4501/// \brief Parse the record that corresponds to a LangOptions data
4502/// structure.
4503///
4504/// This routine parses the language options from the AST file and then gives
4505/// them to the AST listener if one is set.
4506///
4507/// \returns true if the listener deems the file unacceptable, false otherwise.
4508bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4509 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004510 ASTReaderListener &Listener,
4511 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 LangOptions LangOpts;
4513 unsigned Idx = 0;
4514#define LANGOPT(Name, Bits, Default, Description) \
4515 LangOpts.Name = Record[Idx++];
4516#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4517 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4518#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004519#define SANITIZER(NAME, ID) \
4520 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004521#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004522
Ben Langmuircd98cb72015-06-23 18:20:18 +00004523 for (unsigned N = Record[Idx++]; N; --N)
4524 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4525
Guy Benyei11169dd2012-12-18 14:30:41 +00004526 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4527 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4528 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004529
Ben Langmuird4a667a2015-06-23 18:20:23 +00004530 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004531
4532 // Comment options.
4533 for (unsigned N = Record[Idx++]; N; --N) {
4534 LangOpts.CommentOpts.BlockCommandNames.push_back(
4535 ReadString(Record, Idx));
4536 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004537 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004538
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004539 return Listener.ReadLanguageOptions(LangOpts, Complain,
4540 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004541}
4542
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004543bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4544 ASTReaderListener &Listener,
4545 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004546 unsigned Idx = 0;
4547 TargetOptions TargetOpts;
4548 TargetOpts.Triple = ReadString(Record, Idx);
4549 TargetOpts.CPU = ReadString(Record, Idx);
4550 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004551 for (unsigned N = Record[Idx++]; N; --N) {
4552 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4553 }
4554 for (unsigned N = Record[Idx++]; N; --N) {
4555 TargetOpts.Features.push_back(ReadString(Record, Idx));
4556 }
4557
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004558 return Listener.ReadTargetOptions(TargetOpts, Complain,
4559 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004560}
4561
4562bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4563 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004564 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004565 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004566#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004567#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004568 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004569#include "clang/Basic/DiagnosticOptions.def"
4570
Richard Smith3be1cb22014-08-07 00:24:21 +00004571 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004572 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004573 for (unsigned N = Record[Idx++]; N; --N)
4574 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004575
4576 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4577}
4578
4579bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4580 ASTReaderListener &Listener) {
4581 FileSystemOptions FSOpts;
4582 unsigned Idx = 0;
4583 FSOpts.WorkingDir = ReadString(Record, Idx);
4584 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4585}
4586
4587bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4588 bool Complain,
4589 ASTReaderListener &Listener) {
4590 HeaderSearchOptions HSOpts;
4591 unsigned Idx = 0;
4592 HSOpts.Sysroot = ReadString(Record, Idx);
4593
4594 // Include entries.
4595 for (unsigned N = Record[Idx++]; N; --N) {
4596 std::string Path = ReadString(Record, Idx);
4597 frontend::IncludeDirGroup Group
4598 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004599 bool IsFramework = Record[Idx++];
4600 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004601 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4602 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 }
4604
4605 // System header prefixes.
4606 for (unsigned N = Record[Idx++]; N; --N) {
4607 std::string Prefix = ReadString(Record, Idx);
4608 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004609 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004610 }
4611
4612 HSOpts.ResourceDir = ReadString(Record, Idx);
4613 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004614 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 HSOpts.DisableModuleHash = Record[Idx++];
4616 HSOpts.UseBuiltinIncludes = Record[Idx++];
4617 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4618 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4619 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004620 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004621
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004622 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4623 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004624}
4625
4626bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4627 bool Complain,
4628 ASTReaderListener &Listener,
4629 std::string &SuggestedPredefines) {
4630 PreprocessorOptions PPOpts;
4631 unsigned Idx = 0;
4632
4633 // Macro definitions/undefs
4634 for (unsigned N = Record[Idx++]; N; --N) {
4635 std::string Macro = ReadString(Record, Idx);
4636 bool IsUndef = Record[Idx++];
4637 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4638 }
4639
4640 // Includes
4641 for (unsigned N = Record[Idx++]; N; --N) {
4642 PPOpts.Includes.push_back(ReadString(Record, Idx));
4643 }
4644
4645 // Macro Includes
4646 for (unsigned N = Record[Idx++]; N; --N) {
4647 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4648 }
4649
4650 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004651 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4653 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4654 PPOpts.ObjCXXARCStandardLibrary =
4655 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4656 SuggestedPredefines.clear();
4657 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4658 SuggestedPredefines);
4659}
4660
4661std::pair<ModuleFile *, unsigned>
4662ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4663 GlobalPreprocessedEntityMapType::iterator
4664 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4665 assert(I != GlobalPreprocessedEntityMap.end() &&
4666 "Corrupted global preprocessed entity map");
4667 ModuleFile *M = I->second;
4668 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4669 return std::make_pair(M, LocalIndex);
4670}
4671
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004672llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004673ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4674 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4675 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4676 Mod.NumPreprocessedEntities);
4677
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004678 return llvm::make_range(PreprocessingRecord::iterator(),
4679 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004680}
4681
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004682llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004683ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004684 return llvm::make_range(
4685 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4686 ModuleDeclIterator(this, &Mod,
4687 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004688}
4689
4690PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4691 PreprocessedEntityID PPID = Index+1;
4692 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4693 ModuleFile &M = *PPInfo.first;
4694 unsigned LocalIndex = PPInfo.second;
4695 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4696
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 if (!PP.getPreprocessingRecord()) {
4698 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004699 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004700 }
4701
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004702 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4703 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4704
4705 llvm::BitstreamEntry Entry =
4706 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4707 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004708 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004709
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 // Read the record.
4711 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4712 ReadSourceLocation(M, PPOffs.End));
4713 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004714 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 RecordData Record;
4716 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004717 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4718 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 switch (RecType) {
4720 case PPD_MACRO_EXPANSION: {
4721 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004722 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004723 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004724 if (isBuiltin)
4725 Name = getLocalIdentifier(M, Record[1]);
4726 else {
Richard Smith66a81862015-05-04 02:25:31 +00004727 PreprocessedEntityID GlobalID =
4728 getGlobalPreprocessedEntityID(M, Record[1]);
4729 Def = cast<MacroDefinitionRecord>(
4730 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004731 }
4732
4733 MacroExpansion *ME;
4734 if (isBuiltin)
4735 ME = new (PPRec) MacroExpansion(Name, Range);
4736 else
4737 ME = new (PPRec) MacroExpansion(Def, Range);
4738
4739 return ME;
4740 }
4741
4742 case PPD_MACRO_DEFINITION: {
4743 // Decode the identifier info and then check again; if the macro is
4744 // still defined and associated with the identifier,
4745 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004746 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004747
4748 if (DeserializationListener)
4749 DeserializationListener->MacroDefinitionRead(PPID, MD);
4750
4751 return MD;
4752 }
4753
4754 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004755 const char *FullFileNameStart = Blob.data() + Record[0];
4756 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004757 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 if (!FullFileName.empty())
4759 File = PP.getFileManager().getFile(FullFileName);
4760
4761 // FIXME: Stable encoding
4762 InclusionDirective::InclusionKind Kind
4763 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4764 InclusionDirective *ID
4765 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004766 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 Record[1], Record[3],
4768 File,
4769 Range);
4770 return ID;
4771 }
4772 }
4773
4774 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4775}
4776
4777/// \brief \arg SLocMapI points at a chunk of a module that contains no
4778/// preprocessed entities or the entities it contains are not the ones we are
4779/// looking for. Find the next module that contains entities and return the ID
4780/// of the first entry.
4781PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4782 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4783 ++SLocMapI;
4784 for (GlobalSLocOffsetMapType::const_iterator
4785 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4786 ModuleFile &M = *SLocMapI->second;
4787 if (M.NumPreprocessedEntities)
4788 return M.BasePreprocessedEntityID;
4789 }
4790
4791 return getTotalNumPreprocessedEntities();
4792}
4793
4794namespace {
4795
4796template <unsigned PPEntityOffset::*PPLoc>
4797struct PPEntityComp {
4798 const ASTReader &Reader;
4799 ModuleFile &M;
4800
4801 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4802
4803 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4804 SourceLocation LHS = getLoc(L);
4805 SourceLocation RHS = getLoc(R);
4806 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4807 }
4808
4809 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4810 SourceLocation LHS = getLoc(L);
4811 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4812 }
4813
4814 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4815 SourceLocation RHS = getLoc(R);
4816 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4817 }
4818
4819 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4820 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4821 }
4822};
4823
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004824}
Guy Benyei11169dd2012-12-18 14:30:41 +00004825
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004826PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4827 bool EndsAfter) const {
4828 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004829 return getTotalNumPreprocessedEntities();
4830
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004831 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4832 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004833 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4834 "Corrupted global sloc offset map");
4835
4836 if (SLocMapI->second->NumPreprocessedEntities == 0)
4837 return findNextPreprocessedEntity(SLocMapI);
4838
4839 ModuleFile &M = *SLocMapI->second;
4840 typedef const PPEntityOffset *pp_iterator;
4841 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4842 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4843
4844 size_t Count = M.NumPreprocessedEntities;
4845 size_t Half;
4846 pp_iterator First = pp_begin;
4847 pp_iterator PPI;
4848
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004849 if (EndsAfter) {
4850 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4851 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4852 } else {
4853 // Do a binary search manually instead of using std::lower_bound because
4854 // The end locations of entities may be unordered (when a macro expansion
4855 // is inside another macro argument), but for this case it is not important
4856 // whether we get the first macro expansion or its containing macro.
4857 while (Count > 0) {
4858 Half = Count / 2;
4859 PPI = First;
4860 std::advance(PPI, Half);
4861 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4862 Loc)) {
4863 First = PPI;
4864 ++First;
4865 Count = Count - Half - 1;
4866 } else
4867 Count = Half;
4868 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 }
4870
4871 if (PPI == pp_end)
4872 return findNextPreprocessedEntity(SLocMapI);
4873
4874 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4875}
4876
Guy Benyei11169dd2012-12-18 14:30:41 +00004877/// \brief Returns a pair of [Begin, End) indices of preallocated
4878/// preprocessed entities that \arg Range encompasses.
4879std::pair<unsigned, unsigned>
4880 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4881 if (Range.isInvalid())
4882 return std::make_pair(0,0);
4883 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4884
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004885 PreprocessedEntityID BeginID =
4886 findPreprocessedEntity(Range.getBegin(), false);
4887 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 return std::make_pair(BeginID, EndID);
4889}
4890
4891/// \brief Optionally returns true or false if the preallocated preprocessed
4892/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004893Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 FileID FID) {
4895 if (FID.isInvalid())
4896 return false;
4897
4898 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4899 ModuleFile &M = *PPInfo.first;
4900 unsigned LocalIndex = PPInfo.second;
4901 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4902
4903 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4904 if (Loc.isInvalid())
4905 return false;
4906
4907 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4908 return true;
4909 else
4910 return false;
4911}
4912
4913namespace {
4914 /// \brief Visitor used to search for information about a header file.
4915 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004916 const FileEntry *FE;
4917
David Blaikie05785d12013-02-20 22:23:23 +00004918 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004919
4920 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004921 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4922 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004923
4924 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 HeaderFileInfoLookupTable *Table
4926 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4927 if (!Table)
4928 return false;
4929
4930 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00004931 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 if (Pos == Table->end())
4933 return false;
4934
Richard Smithbdf2d932015-07-30 03:37:16 +00004935 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 return true;
4937 }
4938
David Blaikie05785d12013-02-20 22:23:23 +00004939 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004940 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004941}
Guy Benyei11169dd2012-12-18 14:30:41 +00004942
4943HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004944 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00004945 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004946 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004947 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004948
4949 return HeaderFileInfo();
4950}
4951
4952void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4953 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004954 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004955 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4956 ModuleFile &F = *(*I);
4957 unsigned Idx = 0;
4958 DiagStates.clear();
4959 assert(!Diag.DiagStates.empty());
4960 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4961 while (Idx < F.PragmaDiagMappings.size()) {
4962 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4963 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4964 if (DiagStateID != 0) {
4965 Diag.DiagStatePoints.push_back(
4966 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4967 FullSourceLoc(Loc, SourceMgr)));
4968 continue;
4969 }
4970
4971 assert(DiagStateID == 0);
4972 // A new DiagState was created here.
4973 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4974 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4975 DiagStates.push_back(NewState);
4976 Diag.DiagStatePoints.push_back(
4977 DiagnosticsEngine::DiagStatePoint(NewState,
4978 FullSourceLoc(Loc, SourceMgr)));
4979 while (1) {
4980 assert(Idx < F.PragmaDiagMappings.size() &&
4981 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4982 if (Idx >= F.PragmaDiagMappings.size()) {
4983 break; // Something is messed up but at least avoid infinite loop in
4984 // release build.
4985 }
4986 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4987 if (DiagID == (unsigned)-1) {
4988 break; // no more diag/map pairs for this location.
4989 }
Alp Tokerc726c362014-06-10 09:31:37 +00004990 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4991 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4992 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 }
4994 }
4995 }
4996}
4997
4998/// \brief Get the correct cursor and offset for loading a type.
4999ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5000 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5001 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5002 ModuleFile *M = I->second;
5003 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5004}
5005
5006/// \brief Read and return the type with the given index..
5007///
5008/// The index is the type ID, shifted and minus the number of predefs. This
5009/// routine actually reads the record corresponding to the type at the given
5010/// location. It is a helper routine for GetType, which deals with reading type
5011/// IDs.
5012QualType ASTReader::readTypeRecord(unsigned Index) {
5013 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005014 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005015
5016 // Keep track of where we are in the stream, then jump back there
5017 // after reading this type.
5018 SavedStreamPosition SavedPosition(DeclsCursor);
5019
5020 ReadingKindTracker ReadingKind(Read_Type, *this);
5021
5022 // Note that we are loading a type record.
5023 Deserializing AType(this);
5024
5025 unsigned Idx = 0;
5026 DeclsCursor.JumpToBit(Loc.Offset);
5027 RecordData Record;
5028 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005029 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case TYPE_EXT_QUAL: {
5031 if (Record.size() != 2) {
5032 Error("Incorrect encoding of extended qualifier type");
5033 return QualType();
5034 }
5035 QualType Base = readType(*Loc.F, Record, Idx);
5036 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5037 return Context.getQualifiedType(Base, Quals);
5038 }
5039
5040 case TYPE_COMPLEX: {
5041 if (Record.size() != 1) {
5042 Error("Incorrect encoding of complex type");
5043 return QualType();
5044 }
5045 QualType ElemType = readType(*Loc.F, Record, Idx);
5046 return Context.getComplexType(ElemType);
5047 }
5048
5049 case TYPE_POINTER: {
5050 if (Record.size() != 1) {
5051 Error("Incorrect encoding of pointer type");
5052 return QualType();
5053 }
5054 QualType PointeeType = readType(*Loc.F, Record, Idx);
5055 return Context.getPointerType(PointeeType);
5056 }
5057
Reid Kleckner8a365022013-06-24 17:51:48 +00005058 case TYPE_DECAYED: {
5059 if (Record.size() != 1) {
5060 Error("Incorrect encoding of decayed type");
5061 return QualType();
5062 }
5063 QualType OriginalType = readType(*Loc.F, Record, Idx);
5064 QualType DT = Context.getAdjustedParameterType(OriginalType);
5065 if (!isa<DecayedType>(DT))
5066 Error("Decayed type does not decay");
5067 return DT;
5068 }
5069
Reid Kleckner0503a872013-12-05 01:23:43 +00005070 case TYPE_ADJUSTED: {
5071 if (Record.size() != 2) {
5072 Error("Incorrect encoding of adjusted type");
5073 return QualType();
5074 }
5075 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5076 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5077 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5078 }
5079
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 case TYPE_BLOCK_POINTER: {
5081 if (Record.size() != 1) {
5082 Error("Incorrect encoding of block pointer type");
5083 return QualType();
5084 }
5085 QualType PointeeType = readType(*Loc.F, Record, Idx);
5086 return Context.getBlockPointerType(PointeeType);
5087 }
5088
5089 case TYPE_LVALUE_REFERENCE: {
5090 if (Record.size() != 2) {
5091 Error("Incorrect encoding of lvalue reference type");
5092 return QualType();
5093 }
5094 QualType PointeeType = readType(*Loc.F, Record, Idx);
5095 return Context.getLValueReferenceType(PointeeType, Record[1]);
5096 }
5097
5098 case TYPE_RVALUE_REFERENCE: {
5099 if (Record.size() != 1) {
5100 Error("Incorrect encoding of rvalue reference type");
5101 return QualType();
5102 }
5103 QualType PointeeType = readType(*Loc.F, Record, Idx);
5104 return Context.getRValueReferenceType(PointeeType);
5105 }
5106
5107 case TYPE_MEMBER_POINTER: {
5108 if (Record.size() != 2) {
5109 Error("Incorrect encoding of member pointer type");
5110 return QualType();
5111 }
5112 QualType PointeeType = readType(*Loc.F, Record, Idx);
5113 QualType ClassType = readType(*Loc.F, Record, Idx);
5114 if (PointeeType.isNull() || ClassType.isNull())
5115 return QualType();
5116
5117 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5118 }
5119
5120 case TYPE_CONSTANT_ARRAY: {
5121 QualType ElementType = readType(*Loc.F, Record, Idx);
5122 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5123 unsigned IndexTypeQuals = Record[2];
5124 unsigned Idx = 3;
5125 llvm::APInt Size = ReadAPInt(Record, Idx);
5126 return Context.getConstantArrayType(ElementType, Size,
5127 ASM, IndexTypeQuals);
5128 }
5129
5130 case TYPE_INCOMPLETE_ARRAY: {
5131 QualType ElementType = readType(*Loc.F, Record, Idx);
5132 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5133 unsigned IndexTypeQuals = Record[2];
5134 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5135 }
5136
5137 case TYPE_VARIABLE_ARRAY: {
5138 QualType ElementType = readType(*Loc.F, Record, Idx);
5139 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5140 unsigned IndexTypeQuals = Record[2];
5141 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5142 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5143 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5144 ASM, IndexTypeQuals,
5145 SourceRange(LBLoc, RBLoc));
5146 }
5147
5148 case TYPE_VECTOR: {
5149 if (Record.size() != 3) {
5150 Error("incorrect encoding of vector type in AST file");
5151 return QualType();
5152 }
5153
5154 QualType ElementType = readType(*Loc.F, Record, Idx);
5155 unsigned NumElements = Record[1];
5156 unsigned VecKind = Record[2];
5157 return Context.getVectorType(ElementType, NumElements,
5158 (VectorType::VectorKind)VecKind);
5159 }
5160
5161 case TYPE_EXT_VECTOR: {
5162 if (Record.size() != 3) {
5163 Error("incorrect encoding of extended vector type in AST file");
5164 return QualType();
5165 }
5166
5167 QualType ElementType = readType(*Loc.F, Record, Idx);
5168 unsigned NumElements = Record[1];
5169 return Context.getExtVectorType(ElementType, NumElements);
5170 }
5171
5172 case TYPE_FUNCTION_NO_PROTO: {
5173 if (Record.size() != 6) {
5174 Error("incorrect encoding of no-proto function type");
5175 return QualType();
5176 }
5177 QualType ResultType = readType(*Loc.F, Record, Idx);
5178 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5179 (CallingConv)Record[4], Record[5]);
5180 return Context.getFunctionNoProtoType(ResultType, Info);
5181 }
5182
5183 case TYPE_FUNCTION_PROTO: {
5184 QualType ResultType = readType(*Loc.F, Record, Idx);
5185
5186 FunctionProtoType::ExtProtoInfo EPI;
5187 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5188 /*hasregparm*/ Record[2],
5189 /*regparm*/ Record[3],
5190 static_cast<CallingConv>(Record[4]),
5191 /*produces*/ Record[5]);
5192
5193 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005194
5195 EPI.Variadic = Record[Idx++];
5196 EPI.HasTrailingReturn = Record[Idx++];
5197 EPI.TypeQuals = Record[Idx++];
5198 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005199 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005200 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005201
5202 unsigned NumParams = Record[Idx++];
5203 SmallVector<QualType, 16> ParamTypes;
5204 for (unsigned I = 0; I != NumParams; ++I)
5205 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5206
Jordan Rose5c382722013-03-08 21:51:21 +00005207 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005208 }
5209
5210 case TYPE_UNRESOLVED_USING: {
5211 unsigned Idx = 0;
5212 return Context.getTypeDeclType(
5213 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5214 }
5215
5216 case TYPE_TYPEDEF: {
5217 if (Record.size() != 2) {
5218 Error("incorrect encoding of typedef type");
5219 return QualType();
5220 }
5221 unsigned Idx = 0;
5222 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5223 QualType Canonical = readType(*Loc.F, Record, Idx);
5224 if (!Canonical.isNull())
5225 Canonical = Context.getCanonicalType(Canonical);
5226 return Context.getTypedefType(Decl, Canonical);
5227 }
5228
5229 case TYPE_TYPEOF_EXPR:
5230 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5231
5232 case TYPE_TYPEOF: {
5233 if (Record.size() != 1) {
5234 Error("incorrect encoding of typeof(type) in AST file");
5235 return QualType();
5236 }
5237 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5238 return Context.getTypeOfType(UnderlyingType);
5239 }
5240
5241 case TYPE_DECLTYPE: {
5242 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5243 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5244 }
5245
5246 case TYPE_UNARY_TRANSFORM: {
5247 QualType BaseType = readType(*Loc.F, Record, Idx);
5248 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5249 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5250 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5251 }
5252
Richard Smith74aeef52013-04-26 16:15:35 +00005253 case TYPE_AUTO: {
5254 QualType Deduced = readType(*Loc.F, Record, Idx);
5255 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005256 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005257 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005258 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005259
5260 case TYPE_RECORD: {
5261 if (Record.size() != 2) {
5262 Error("incorrect encoding of record type");
5263 return QualType();
5264 }
5265 unsigned Idx = 0;
5266 bool IsDependent = Record[Idx++];
5267 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5268 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5269 QualType T = Context.getRecordType(RD);
5270 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5271 return T;
5272 }
5273
5274 case TYPE_ENUM: {
5275 if (Record.size() != 2) {
5276 Error("incorrect encoding of enum type");
5277 return QualType();
5278 }
5279 unsigned Idx = 0;
5280 bool IsDependent = Record[Idx++];
5281 QualType T
5282 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5283 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5284 return T;
5285 }
5286
5287 case TYPE_ATTRIBUTED: {
5288 if (Record.size() != 3) {
5289 Error("incorrect encoding of attributed type");
5290 return QualType();
5291 }
5292 QualType modifiedType = readType(*Loc.F, Record, Idx);
5293 QualType equivalentType = readType(*Loc.F, Record, Idx);
5294 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5295 return Context.getAttributedType(kind, modifiedType, equivalentType);
5296 }
5297
5298 case TYPE_PAREN: {
5299 if (Record.size() != 1) {
5300 Error("incorrect encoding of paren type");
5301 return QualType();
5302 }
5303 QualType InnerType = readType(*Loc.F, Record, Idx);
5304 return Context.getParenType(InnerType);
5305 }
5306
5307 case TYPE_PACK_EXPANSION: {
5308 if (Record.size() != 2) {
5309 Error("incorrect encoding of pack expansion type");
5310 return QualType();
5311 }
5312 QualType Pattern = readType(*Loc.F, Record, Idx);
5313 if (Pattern.isNull())
5314 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005315 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005316 if (Record[1])
5317 NumExpansions = Record[1] - 1;
5318 return Context.getPackExpansionType(Pattern, NumExpansions);
5319 }
5320
5321 case TYPE_ELABORATED: {
5322 unsigned Idx = 0;
5323 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5324 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5325 QualType NamedType = readType(*Loc.F, Record, Idx);
5326 return Context.getElaboratedType(Keyword, NNS, NamedType);
5327 }
5328
5329 case TYPE_OBJC_INTERFACE: {
5330 unsigned Idx = 0;
5331 ObjCInterfaceDecl *ItfD
5332 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5333 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5334 }
5335
5336 case TYPE_OBJC_OBJECT: {
5337 unsigned Idx = 0;
5338 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005339 unsigned NumTypeArgs = Record[Idx++];
5340 SmallVector<QualType, 4> TypeArgs;
5341 for (unsigned I = 0; I != NumTypeArgs; ++I)
5342 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005343 unsigned NumProtos = Record[Idx++];
5344 SmallVector<ObjCProtocolDecl*, 4> Protos;
5345 for (unsigned I = 0; I != NumProtos; ++I)
5346 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005347 bool IsKindOf = Record[Idx++];
5348 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005349 }
5350
5351 case TYPE_OBJC_OBJECT_POINTER: {
5352 unsigned Idx = 0;
5353 QualType Pointee = readType(*Loc.F, Record, Idx);
5354 return Context.getObjCObjectPointerType(Pointee);
5355 }
5356
5357 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5358 unsigned Idx = 0;
5359 QualType Parm = readType(*Loc.F, Record, Idx);
5360 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005361 return Context.getSubstTemplateTypeParmType(
5362 cast<TemplateTypeParmType>(Parm),
5363 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 }
5365
5366 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5367 unsigned Idx = 0;
5368 QualType Parm = readType(*Loc.F, Record, Idx);
5369 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5370 return Context.getSubstTemplateTypeParmPackType(
5371 cast<TemplateTypeParmType>(Parm),
5372 ArgPack);
5373 }
5374
5375 case TYPE_INJECTED_CLASS_NAME: {
5376 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5377 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5378 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5379 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005380 const Type *T = nullptr;
5381 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5382 if (const Type *Existing = DI->getTypeForDecl()) {
5383 T = Existing;
5384 break;
5385 }
5386 }
5387 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005388 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005389 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5390 DI->setTypeForDecl(T);
5391 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005392 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 }
5394
5395 case TYPE_TEMPLATE_TYPE_PARM: {
5396 unsigned Idx = 0;
5397 unsigned Depth = Record[Idx++];
5398 unsigned Index = Record[Idx++];
5399 bool Pack = Record[Idx++];
5400 TemplateTypeParmDecl *D
5401 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5402 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5403 }
5404
5405 case TYPE_DEPENDENT_NAME: {
5406 unsigned Idx = 0;
5407 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5408 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005409 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005410 QualType Canon = readType(*Loc.F, Record, Idx);
5411 if (!Canon.isNull())
5412 Canon = Context.getCanonicalType(Canon);
5413 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5414 }
5415
5416 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5417 unsigned Idx = 0;
5418 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5419 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005420 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005421 unsigned NumArgs = Record[Idx++];
5422 SmallVector<TemplateArgument, 8> Args;
5423 Args.reserve(NumArgs);
5424 while (NumArgs--)
5425 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5426 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5427 Args.size(), Args.data());
5428 }
5429
5430 case TYPE_DEPENDENT_SIZED_ARRAY: {
5431 unsigned Idx = 0;
5432
5433 // ArrayType
5434 QualType ElementType = readType(*Loc.F, Record, Idx);
5435 ArrayType::ArraySizeModifier ASM
5436 = (ArrayType::ArraySizeModifier)Record[Idx++];
5437 unsigned IndexTypeQuals = Record[Idx++];
5438
5439 // DependentSizedArrayType
5440 Expr *NumElts = ReadExpr(*Loc.F);
5441 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5442
5443 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5444 IndexTypeQuals, Brackets);
5445 }
5446
5447 case TYPE_TEMPLATE_SPECIALIZATION: {
5448 unsigned Idx = 0;
5449 bool IsDependent = Record[Idx++];
5450 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5451 SmallVector<TemplateArgument, 8> Args;
5452 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5453 QualType Underlying = readType(*Loc.F, Record, Idx);
5454 QualType T;
5455 if (Underlying.isNull())
5456 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5457 Args.size());
5458 else
5459 T = Context.getTemplateSpecializationType(Name, Args.data(),
5460 Args.size(), Underlying);
5461 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5462 return T;
5463 }
5464
5465 case TYPE_ATOMIC: {
5466 if (Record.size() != 1) {
5467 Error("Incorrect encoding of atomic type");
5468 return QualType();
5469 }
5470 QualType ValueType = readType(*Loc.F, Record, Idx);
5471 return Context.getAtomicType(ValueType);
5472 }
5473 }
5474 llvm_unreachable("Invalid TypeCode!");
5475}
5476
Richard Smith564417a2014-03-20 21:47:22 +00005477void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5478 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005479 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005480 const RecordData &Record, unsigned &Idx) {
5481 ExceptionSpecificationType EST =
5482 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005483 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005484 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005485 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005486 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005487 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005488 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005489 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005490 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005491 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5492 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005493 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005494 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005495 }
5496}
5497
Guy Benyei11169dd2012-12-18 14:30:41 +00005498class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5499 ASTReader &Reader;
5500 ModuleFile &F;
5501 const ASTReader::RecordData &Record;
5502 unsigned &Idx;
5503
5504 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5505 unsigned &I) {
5506 return Reader.ReadSourceLocation(F, R, I);
5507 }
5508
5509 template<typename T>
5510 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5511 return Reader.ReadDeclAs<T>(F, Record, Idx);
5512 }
5513
5514public:
5515 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5516 const ASTReader::RecordData &Record, unsigned &Idx)
5517 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5518 { }
5519
5520 // We want compile-time assurance that we've enumerated all of
5521 // these, so unfortunately we have to declare them first, then
5522 // define them out-of-line.
5523#define ABSTRACT_TYPELOC(CLASS, PARENT)
5524#define TYPELOC(CLASS, PARENT) \
5525 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5526#include "clang/AST/TypeLocNodes.def"
5527
5528 void VisitFunctionTypeLoc(FunctionTypeLoc);
5529 void VisitArrayTypeLoc(ArrayTypeLoc);
5530};
5531
5532void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5533 // nothing to do
5534}
5535void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5536 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5537 if (TL.needsExtraLocalData()) {
5538 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5539 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5540 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5541 TL.setModeAttr(Record[Idx++]);
5542 }
5543}
5544void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5545 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5546}
5547void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5548 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5549}
Reid Kleckner8a365022013-06-24 17:51:48 +00005550void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5551 // nothing to do
5552}
Reid Kleckner0503a872013-12-05 01:23:43 +00005553void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5554 // nothing to do
5555}
Guy Benyei11169dd2012-12-18 14:30:41 +00005556void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5557 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5558}
5559void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5560 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5561}
5562void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5563 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5564}
5565void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5566 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5567 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5568}
5569void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5570 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5571 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5572 if (Record[Idx++])
5573 TL.setSizeExpr(Reader.ReadExpr(F));
5574 else
Craig Toppera13603a2014-05-22 05:54:18 +00005575 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005576}
5577void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5578 VisitArrayTypeLoc(TL);
5579}
5580void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5581 VisitArrayTypeLoc(TL);
5582}
5583void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5584 VisitArrayTypeLoc(TL);
5585}
5586void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5587 DependentSizedArrayTypeLoc TL) {
5588 VisitArrayTypeLoc(TL);
5589}
5590void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5591 DependentSizedExtVectorTypeLoc TL) {
5592 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5593}
5594void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5595 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5596}
5597void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5598 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5599}
5600void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5601 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5602 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5603 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5604 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005605 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5606 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005607 }
5608}
5609void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5610 VisitFunctionTypeLoc(TL);
5611}
5612void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5613 VisitFunctionTypeLoc(TL);
5614}
5615void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5616 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5617}
5618void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5619 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5620}
5621void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5622 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5623 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5624 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5625}
5626void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5627 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5628 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5629 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5630 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5631}
5632void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5633 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5634}
5635void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5636 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5637 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5638 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5639 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5640}
5641void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5642 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5643}
5644void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5645 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5646}
5647void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5648 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5649}
5650void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5651 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5652 if (TL.hasAttrOperand()) {
5653 SourceRange range;
5654 range.setBegin(ReadSourceLocation(Record, Idx));
5655 range.setEnd(ReadSourceLocation(Record, Idx));
5656 TL.setAttrOperandParensRange(range);
5657 }
5658 if (TL.hasAttrExprOperand()) {
5659 if (Record[Idx++])
5660 TL.setAttrExprOperand(Reader.ReadExpr(F));
5661 else
Craig Toppera13603a2014-05-22 05:54:18 +00005662 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005663 } else if (TL.hasAttrEnumOperand())
5664 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5665}
5666void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5667 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5668}
5669void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5670 SubstTemplateTypeParmTypeLoc TL) {
5671 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5672}
5673void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5674 SubstTemplateTypeParmPackTypeLoc TL) {
5675 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5676}
5677void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5678 TemplateSpecializationTypeLoc TL) {
5679 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5680 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5681 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5682 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5683 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5684 TL.setArgLocInfo(i,
5685 Reader.GetTemplateArgumentLocInfo(F,
5686 TL.getTypePtr()->getArg(i).getKind(),
5687 Record, Idx));
5688}
5689void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5690 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5691 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5692}
5693void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5694 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5695 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5696}
5697void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5698 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5699}
5700void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5701 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5702 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5703 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5704}
5705void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5706 DependentTemplateSpecializationTypeLoc TL) {
5707 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5708 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5709 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5710 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5711 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5712 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5713 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5714 TL.setArgLocInfo(I,
5715 Reader.GetTemplateArgumentLocInfo(F,
5716 TL.getTypePtr()->getArg(I).getKind(),
5717 Record, Idx));
5718}
5719void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5720 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5721}
5722void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5723 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5724}
5725void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5726 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005727 TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5728 TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5729 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5730 TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5731 TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5732 TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005733 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5734 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5735}
5736void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5737 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5738}
5739void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5740 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5741 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5742 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5743}
5744
5745TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5746 const RecordData &Record,
5747 unsigned &Idx) {
5748 QualType InfoTy = readType(F, Record, Idx);
5749 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005750 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005751
5752 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5753 TypeLocReader TLR(*this, F, Record, Idx);
5754 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5755 TLR.Visit(TL);
5756 return TInfo;
5757}
5758
5759QualType ASTReader::GetType(TypeID ID) {
5760 unsigned FastQuals = ID & Qualifiers::FastMask;
5761 unsigned Index = ID >> Qualifiers::FastWidth;
5762
5763 if (Index < NUM_PREDEF_TYPE_IDS) {
5764 QualType T;
5765 switch ((PredefinedTypeIDs)Index) {
5766 case PREDEF_TYPE_NULL_ID: return QualType();
5767 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5768 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5769
5770 case PREDEF_TYPE_CHAR_U_ID:
5771 case PREDEF_TYPE_CHAR_S_ID:
5772 // FIXME: Check that the signedness of CharTy is correct!
5773 T = Context.CharTy;
5774 break;
5775
5776 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5777 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5778 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5779 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5780 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5781 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5782 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5783 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5784 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5785 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5786 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5787 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5788 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5789 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5790 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5791 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5792 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5793 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5794 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5795 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5796 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5797 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5798 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5799 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5800 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5801 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5802 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5803 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005804 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5805 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5806 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5807 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5808 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5809 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005810 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005811 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005812 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5813
5814 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5815 T = Context.getAutoRRefDeductType();
5816 break;
5817
5818 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5819 T = Context.ARCUnbridgedCastTy;
5820 break;
5821
Guy Benyei11169dd2012-12-18 14:30:41 +00005822 case PREDEF_TYPE_BUILTIN_FN:
5823 T = Context.BuiltinFnTy;
5824 break;
5825 }
5826
5827 assert(!T.isNull() && "Unknown predefined type");
5828 return T.withFastQualifiers(FastQuals);
5829 }
5830
5831 Index -= NUM_PREDEF_TYPE_IDS;
5832 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5833 if (TypesLoaded[Index].isNull()) {
5834 TypesLoaded[Index] = readTypeRecord(Index);
5835 if (TypesLoaded[Index].isNull())
5836 return QualType();
5837
5838 TypesLoaded[Index]->setFromAST();
5839 if (DeserializationListener)
5840 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5841 TypesLoaded[Index]);
5842 }
5843
5844 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5845}
5846
5847QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5848 return GetType(getGlobalTypeID(F, LocalID));
5849}
5850
5851serialization::TypeID
5852ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5853 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5854 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5855
5856 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5857 return LocalID;
5858
5859 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5860 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5861 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5862
5863 unsigned GlobalIndex = LocalIndex + I->second;
5864 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5865}
5866
5867TemplateArgumentLocInfo
5868ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5869 TemplateArgument::ArgKind Kind,
5870 const RecordData &Record,
5871 unsigned &Index) {
5872 switch (Kind) {
5873 case TemplateArgument::Expression:
5874 return ReadExpr(F);
5875 case TemplateArgument::Type:
5876 return GetTypeSourceInfo(F, Record, Index);
5877 case TemplateArgument::Template: {
5878 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5879 Index);
5880 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5881 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5882 SourceLocation());
5883 }
5884 case TemplateArgument::TemplateExpansion: {
5885 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5886 Index);
5887 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5888 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5889 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5890 EllipsisLoc);
5891 }
5892 case TemplateArgument::Null:
5893 case TemplateArgument::Integral:
5894 case TemplateArgument::Declaration:
5895 case TemplateArgument::NullPtr:
5896 case TemplateArgument::Pack:
5897 // FIXME: Is this right?
5898 return TemplateArgumentLocInfo();
5899 }
5900 llvm_unreachable("unexpected template argument loc");
5901}
5902
5903TemplateArgumentLoc
5904ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5905 const RecordData &Record, unsigned &Index) {
5906 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5907
5908 if (Arg.getKind() == TemplateArgument::Expression) {
5909 if (Record[Index++]) // bool InfoHasSameExpr.
5910 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5911 }
5912 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5913 Record, Index));
5914}
5915
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005916const ASTTemplateArgumentListInfo*
5917ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5918 const RecordData &Record,
5919 unsigned &Index) {
5920 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5921 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5922 unsigned NumArgsAsWritten = Record[Index++];
5923 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5924 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5925 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5926 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5927}
5928
Guy Benyei11169dd2012-12-18 14:30:41 +00005929Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5930 return GetDecl(ID);
5931}
5932
Richard Smith50895422015-01-31 03:04:55 +00005933template<typename TemplateSpecializationDecl>
5934static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5935 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5936 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5937}
5938
Richard Smith053f6c62014-05-16 23:01:30 +00005939void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005940 if (NumCurrentElementsDeserializing) {
5941 // We arrange to not care about the complete redeclaration chain while we're
5942 // deserializing. Just remember that the AST has marked this one as complete
5943 // but that it's not actually complete yet, so we know we still need to
5944 // complete it later.
5945 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5946 return;
5947 }
5948
Richard Smith053f6c62014-05-16 23:01:30 +00005949 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5950
Richard Smith053f6c62014-05-16 23:01:30 +00005951 // If this is a named declaration, complete it by looking it up
5952 // within its context.
5953 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005954 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005955 // all mergeable entities within it.
5956 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5957 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5958 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00005959 if (!getContext().getLangOpts().CPlusPlus &&
5960 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00005961 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00005962 // the identifier instead. (For C++ modules, we don't store decls
5963 // in the serialized identifier table, so we do the lookup in the TU.)
5964 auto *II = Name.getAsIdentifierInfo();
5965 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00005966 if (II->isOutOfDate())
5967 updateOutOfDateIdentifier(*II);
5968 } else
5969 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005970 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00005971 // Find all declarations of this kind from the relevant context.
5972 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5973 auto *DC = cast<DeclContext>(DCDecl);
5974 SmallVector<Decl*, 8> Decls;
5975 FindExternalLexicalDecls(
5976 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5977 }
Richard Smith053f6c62014-05-16 23:01:30 +00005978 }
5979 }
Richard Smith50895422015-01-31 03:04:55 +00005980
5981 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5982 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5983 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5984 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5985 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5986 if (auto *Template = FD->getPrimaryTemplate())
5987 Template->LoadLazySpecializations();
5988 }
Richard Smith053f6c62014-05-16 23:01:30 +00005989}
5990
Richard Smithc2bb8182015-03-24 06:36:48 +00005991uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5992 const RecordData &Record,
5993 unsigned &Idx) {
5994 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5995 Error("malformed AST file: missing C++ ctor initializers");
5996 return 0;
5997 }
5998
5999 unsigned LocalID = Record[Idx++];
6000 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
6001}
6002
6003CXXCtorInitializer **
6004ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6005 RecordLocation Loc = getLocalBitOffset(Offset);
6006 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6007 SavedStreamPosition SavedPosition(Cursor);
6008 Cursor.JumpToBit(Loc.Offset);
6009 ReadingKindTracker ReadingKind(Read_Decl, *this);
6010
6011 RecordData Record;
6012 unsigned Code = Cursor.ReadCode();
6013 unsigned RecCode = Cursor.readRecord(Code, Record);
6014 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6015 Error("malformed AST file: missing C++ ctor initializers");
6016 return nullptr;
6017 }
6018
6019 unsigned Idx = 0;
6020 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6021}
6022
Richard Smithcd45dbc2014-04-19 03:48:30 +00006023uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6024 const RecordData &Record,
6025 unsigned &Idx) {
6026 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6027 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006029 }
6030
Guy Benyei11169dd2012-12-18 14:30:41 +00006031 unsigned LocalID = Record[Idx++];
6032 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6033}
6034
6035CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6036 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006037 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006038 SavedStreamPosition SavedPosition(Cursor);
6039 Cursor.JumpToBit(Loc.Offset);
6040 ReadingKindTracker ReadingKind(Read_Decl, *this);
6041 RecordData Record;
6042 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006043 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006044 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006045 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006046 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 }
6048
6049 unsigned Idx = 0;
6050 unsigned NumBases = Record[Idx++];
6051 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6052 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6053 for (unsigned I = 0; I != NumBases; ++I)
6054 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6055 return Bases;
6056}
6057
6058serialization::DeclID
6059ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6060 if (LocalID < NUM_PREDEF_DECL_IDS)
6061 return LocalID;
6062
6063 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6064 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6065 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6066
6067 return LocalID + I->second;
6068}
6069
6070bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6071 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006072 // Predefined decls aren't from any module.
6073 if (ID < NUM_PREDEF_DECL_IDS)
6074 return false;
6075
Richard Smithbcda1a92015-07-12 23:51:20 +00006076 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6077 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006078}
6079
Douglas Gregor9f782892013-01-21 15:25:38 +00006080ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006082 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006083 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6084 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6085 return I->second;
6086}
6087
6088SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6089 if (ID < NUM_PREDEF_DECL_IDS)
6090 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006091
Guy Benyei11169dd2012-12-18 14:30:41 +00006092 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6093
6094 if (Index > DeclsLoaded.size()) {
6095 Error("declaration ID out-of-range for AST file");
6096 return SourceLocation();
6097 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006098
Guy Benyei11169dd2012-12-18 14:30:41 +00006099 if (Decl *D = DeclsLoaded[Index])
6100 return D->getLocation();
6101
6102 unsigned RawLocation = 0;
6103 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6104 return ReadSourceLocation(*Rec.F, RawLocation);
6105}
6106
Richard Smithfe620d22015-03-05 23:24:12 +00006107static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6108 switch (ID) {
6109 case PREDEF_DECL_NULL_ID:
6110 return nullptr;
6111
6112 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6113 return Context.getTranslationUnitDecl();
6114
6115 case PREDEF_DECL_OBJC_ID_ID:
6116 return Context.getObjCIdDecl();
6117
6118 case PREDEF_DECL_OBJC_SEL_ID:
6119 return Context.getObjCSelDecl();
6120
6121 case PREDEF_DECL_OBJC_CLASS_ID:
6122 return Context.getObjCClassDecl();
6123
6124 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6125 return Context.getObjCProtocolDecl();
6126
6127 case PREDEF_DECL_INT_128_ID:
6128 return Context.getInt128Decl();
6129
6130 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6131 return Context.getUInt128Decl();
6132
6133 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6134 return Context.getObjCInstanceTypeDecl();
6135
6136 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6137 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006138
Richard Smith9b88a4c2015-07-27 05:40:23 +00006139 case PREDEF_DECL_VA_LIST_TAG:
6140 return Context.getVaListTagDecl();
6141
Richard Smithf19e1272015-03-07 00:04:49 +00006142 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6143 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006144 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006145 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006146}
6147
Richard Smithcd45dbc2014-04-19 03:48:30 +00006148Decl *ASTReader::GetExistingDecl(DeclID ID) {
6149 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006150 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6151 if (D) {
6152 // Track that we have merged the declaration with ID \p ID into the
6153 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006154 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006155 if (Merged.empty())
6156 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 }
Richard Smithfe620d22015-03-05 23:24:12 +00006158 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006159 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006160
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6162
6163 if (Index >= DeclsLoaded.size()) {
6164 assert(0 && "declaration ID out-of-range for AST file");
6165 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006166 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006168
6169 return DeclsLoaded[Index];
6170}
6171
6172Decl *ASTReader::GetDecl(DeclID ID) {
6173 if (ID < NUM_PREDEF_DECL_IDS)
6174 return GetExistingDecl(ID);
6175
6176 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6177
6178 if (Index >= DeclsLoaded.size()) {
6179 assert(0 && "declaration ID out-of-range for AST file");
6180 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006181 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006182 }
6183
Guy Benyei11169dd2012-12-18 14:30:41 +00006184 if (!DeclsLoaded[Index]) {
6185 ReadDeclRecord(ID);
6186 if (DeserializationListener)
6187 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6188 }
6189
6190 return DeclsLoaded[Index];
6191}
6192
6193DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6194 DeclID GlobalID) {
6195 if (GlobalID < NUM_PREDEF_DECL_IDS)
6196 return GlobalID;
6197
6198 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6199 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6200 ModuleFile *Owner = I->second;
6201
6202 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6203 = M.GlobalToLocalDeclIDs.find(Owner);
6204 if (Pos == M.GlobalToLocalDeclIDs.end())
6205 return 0;
6206
6207 return GlobalID - Owner->BaseDeclID + Pos->second;
6208}
6209
6210serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6211 const RecordData &Record,
6212 unsigned &Idx) {
6213 if (Idx >= Record.size()) {
6214 Error("Corrupted AST file");
6215 return 0;
6216 }
6217
6218 return getGlobalDeclID(F, Record[Idx++]);
6219}
6220
6221/// \brief Resolve the offset of a statement into a statement.
6222///
6223/// This operation will read a new statement from the external
6224/// source each time it is called, and is meant to be used via a
6225/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6226Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6227 // Switch case IDs are per Decl.
6228 ClearSwitchCaseIDs();
6229
6230 // Offset here is a global offset across the entire chain.
6231 RecordLocation Loc = getLocalBitOffset(Offset);
6232 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6233 return ReadStmtFromStream(*Loc.F);
6234}
6235
Richard Smith3cb15722015-08-05 22:41:45 +00006236void ASTReader::FindExternalLexicalDecls(
6237 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6238 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006239 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6240
Richard Smith9ccdd932015-08-06 22:14:12 +00006241 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006242 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6243 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6244 auto K = (Decl::Kind)+LexicalDecls[I];
6245 if (!IsKindWeWant(K))
6246 continue;
6247
6248 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6249
6250 // Don't add predefined declarations to the lexical context more
6251 // than once.
6252 if (ID < NUM_PREDEF_DECL_IDS) {
6253 if (PredefsVisited[ID])
6254 continue;
6255
6256 PredefsVisited[ID] = true;
6257 }
6258
6259 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006260 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006261 if (!DC->isDeclInLexicalTraversal(D))
6262 Decls.push_back(D);
6263 }
6264 }
6265 };
6266
6267 if (isa<TranslationUnitDecl>(DC)) {
6268 for (auto Lexical : TULexicalDecls)
6269 Visit(Lexical.first, Lexical.second);
6270 } else {
6271 auto I = LexicalDecls.find(DC);
6272 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006273 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006274 }
6275
Guy Benyei11169dd2012-12-18 14:30:41 +00006276 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006277}
6278
6279namespace {
6280
6281class DeclIDComp {
6282 ASTReader &Reader;
6283 ModuleFile &Mod;
6284
6285public:
6286 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6287
6288 bool operator()(LocalDeclID L, LocalDeclID R) const {
6289 SourceLocation LHS = getLocation(L);
6290 SourceLocation RHS = getLocation(R);
6291 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6292 }
6293
6294 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6295 SourceLocation RHS = getLocation(R);
6296 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6297 }
6298
6299 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6300 SourceLocation LHS = getLocation(L);
6301 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6302 }
6303
6304 SourceLocation getLocation(LocalDeclID ID) const {
6305 return Reader.getSourceManager().getFileLoc(
6306 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6307 }
6308};
6309
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006310}
Guy Benyei11169dd2012-12-18 14:30:41 +00006311
6312void ASTReader::FindFileRegionDecls(FileID File,
6313 unsigned Offset, unsigned Length,
6314 SmallVectorImpl<Decl *> &Decls) {
6315 SourceManager &SM = getSourceManager();
6316
6317 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6318 if (I == FileDeclIDs.end())
6319 return;
6320
6321 FileDeclsInfo &DInfo = I->second;
6322 if (DInfo.Decls.empty())
6323 return;
6324
6325 SourceLocation
6326 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6327 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6328
6329 DeclIDComp DIDComp(*this, *DInfo.Mod);
6330 ArrayRef<serialization::LocalDeclID>::iterator
6331 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6332 BeginLoc, DIDComp);
6333 if (BeginIt != DInfo.Decls.begin())
6334 --BeginIt;
6335
6336 // If we are pointing at a top-level decl inside an objc container, we need
6337 // to backtrack until we find it otherwise we will fail to report that the
6338 // region overlaps with an objc container.
6339 while (BeginIt != DInfo.Decls.begin() &&
6340 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6341 ->isTopLevelDeclInObjCContainer())
6342 --BeginIt;
6343
6344 ArrayRef<serialization::LocalDeclID>::iterator
6345 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6346 EndLoc, DIDComp);
6347 if (EndIt != DInfo.Decls.end())
6348 ++EndIt;
6349
6350 for (ArrayRef<serialization::LocalDeclID>::iterator
6351 DIt = BeginIt; DIt != EndIt; ++DIt)
6352 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6353}
6354
Richard Smith3b637412015-07-14 18:42:41 +00006355/// \brief Retrieve the "definitive" module file for the definition of the
6356/// given declaration context, if there is one.
6357///
6358/// The "definitive" module file is the only place where we need to look to
6359/// find information about the declarations within the given declaration
6360/// context. For example, C++ and Objective-C classes, C structs/unions, and
6361/// Objective-C protocols, categories, and extensions are all defined in a
6362/// single place in the source code, so they have definitive module files
6363/// associated with them. C++ namespaces, on the other hand, can have
6364/// definitions in multiple different module files.
6365///
6366/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6367/// NDEBUG checking.
6368static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6369 ASTReader &Reader) {
6370 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6371 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6372
6373 return nullptr;
6374}
6375
Guy Benyei11169dd2012-12-18 14:30:41 +00006376namespace {
6377 /// \brief ModuleFile visitor used to perform name lookup into a
6378 /// declaration context.
6379 class DeclContextNameLookupVisitor {
6380 ASTReader &Reader;
Richard Smithf13c68d2015-08-06 21:05:21 +00006381 const DeclContext *Context;
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 DeclarationName Name;
Richard Smith3b637412015-07-14 18:42:41 +00006383 ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6384 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00006385 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006386 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006387
6388 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006389 DeclContextNameLookupVisitor(ASTReader &Reader,
Richard Smithf13c68d2015-08-06 21:05:21 +00006390 const DeclContext *Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00006391 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006392 SmallVectorImpl<NamedDecl *> &Decls,
6393 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
Richard Smithf13c68d2015-08-06 21:05:21 +00006394 : Reader(Reader), Context(Context), Name(Name),
Richard Smith3b637412015-07-14 18:42:41 +00006395 NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6396 NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6397 Decls(Decls), DeclSet(DeclSet) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006398
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006399 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006400 // Check whether we have any visible declaration information for
6401 // this context in this module.
Richard Smithf13c68d2015-08-06 21:05:21 +00006402 auto Info = M.DeclContextInfos.find(Context);
6403 if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006405
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006407 ASTDeclContextNameLookupTable *LookupTable =
Richard Smithf13c68d2015-08-06 21:05:21 +00006408 Info->second.NameLookupTableData;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006409 ASTDeclContextNameLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00006410 LookupTable->find_hashed(NameKey, NameHash);
Guy Benyei11169dd2012-12-18 14:30:41 +00006411 if (Pos == LookupTable->end())
6412 return false;
6413
6414 bool FoundAnything = false;
6415 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6416 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006417 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006418 if (!ND)
6419 continue;
6420
Richard Smithbdf2d932015-07-30 03:37:16 +00006421 if (ND->getDeclName() != Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 // A name might be null because the decl's redeclarable part is
6423 // currently read before reading its name. The lookup is triggered by
6424 // building that decl (likely indirectly), and so it is later in the
6425 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006426 // FIXME: This should not happen; deserializing declarations should
6427 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006428 continue;
6429 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006430
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 // Record this declaration.
6432 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006433 if (DeclSet.insert(ND).second)
6434 Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006435 }
6436
6437 return FoundAnything;
6438 }
6439 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006440}
Guy Benyei11169dd2012-12-18 14:30:41 +00006441
Richard Smith9ce12e32013-02-07 03:30:24 +00006442bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006443ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6444 DeclarationName Name) {
6445 assert(DC->hasExternalVisibleStorage() &&
6446 "DeclContext has no visible decls in storage");
6447 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006448 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006449
Richard Smith8c913ec2014-08-14 02:21:01 +00006450 Deserializing LookupResults(this);
6451
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006453 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006454
Richard Smithf13c68d2015-08-06 21:05:21 +00006455 DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006456
Richard Smithf13c68d2015-08-06 21:05:21 +00006457 // If we can definitively determine which module file to look into,
6458 // only look there. Otherwise, look in all module files.
6459 if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6460 Visitor(*Definitive);
6461 else
6462 ModuleMgr.visit(Visitor);
Richard Smithcd45dbc2014-04-19 03:48:30 +00006463
Guy Benyei11169dd2012-12-18 14:30:41 +00006464 ++NumVisibleDeclContextsRead;
6465 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006466 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006467}
6468
6469namespace {
6470 /// \brief ModuleFile visitor used to retrieve all visible names in a
6471 /// declaration context.
6472 class DeclContextAllNamesVisitor {
6473 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006474 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006475 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006476 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006477 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006478
6479 public:
6480 DeclContextAllNamesVisitor(ASTReader &Reader,
6481 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006482 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006483 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006484
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006485 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006486 // Check whether we have any visible declaration information for
6487 // this context in this module.
6488 ModuleFile::DeclContextInfosMap::iterator Info;
6489 bool FoundInfo = false;
Richard Smithbdf2d932015-07-30 03:37:16 +00006490 for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6491 Info = M.DeclContextInfos.find(Contexts[I]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 if (Info != M.DeclContextInfos.end() &&
6493 Info->second.NameLookupTableData) {
6494 FoundInfo = true;
6495 break;
6496 }
6497 }
6498
6499 if (!FoundInfo)
6500 return false;
6501
Richard Smith52e3fba2014-03-11 07:17:35 +00006502 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006503 Info->second.NameLookupTableData;
6504 bool FoundAnything = false;
6505 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006506 I = LookupTable->data_begin(), E = LookupTable->data_end();
6507 I != E;
6508 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006509 ASTDeclContextNameLookupTrait::data_type Data = *I;
6510 for (; Data.first != Data.second; ++Data.first) {
Richard Smithbdf2d932015-07-30 03:37:16 +00006511 NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 if (!ND)
6513 continue;
6514
6515 // Record this declaration.
6516 FoundAnything = true;
Richard Smithbdf2d932015-07-30 03:37:16 +00006517 if (DeclSet.insert(ND).second)
6518 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 }
6520 }
6521
Richard Smithbdf2d932015-07-30 03:37:16 +00006522 return FoundAnything && !VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006523 }
6524 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006525}
Guy Benyei11169dd2012-12-18 14:30:41 +00006526
6527void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6528 if (!DC->hasExternalVisibleStorage())
6529 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006530 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006531
6532 // Compute the declaration contexts we need to look into. Multiple such
6533 // declaration contexts occur when two declaration contexts from disjoint
6534 // modules get merged, e.g., when two namespaces with the same name are
6535 // independently defined in separate modules.
6536 SmallVector<const DeclContext *, 2> Contexts;
6537 Contexts.push_back(DC);
6538
6539 if (DC->isNamespace()) {
Richard Smith5fc18a92015-07-12 23:43:21 +00006540 KeyDeclsMap::iterator Key =
6541 KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6542 if (Key != KeyDecls.end()) {
6543 for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6544 Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
Guy Benyei11169dd2012-12-18 14:30:41 +00006545 }
6546 }
6547
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006548 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6549 /*VisitAll=*/DC->isFileContext());
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006550 ModuleMgr.visit(Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006551 ++NumVisibleDeclContextsRead;
6552
Craig Topper79be4cd2013-07-05 04:33:53 +00006553 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006554 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6555 }
6556 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6557}
6558
6559/// \brief Under non-PCH compilation the consumer receives the objc methods
6560/// before receiving the implementation, and codegen depends on this.
6561/// We simulate this by deserializing and passing to consumer the methods of the
6562/// implementation before passing the deserialized implementation decl.
6563static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6564 ASTConsumer *Consumer) {
6565 assert(ImplD && Consumer);
6566
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006567 for (auto *I : ImplD->methods())
6568 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006569
6570 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6571}
6572
6573void ASTReader::PassInterestingDeclsToConsumer() {
6574 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006575
6576 if (PassingDeclsToConsumer)
6577 return;
6578
6579 // Guard variable to avoid recursively redoing the process of passing
6580 // decls to consumer.
6581 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6582 true);
6583
Richard Smith9e2341d2015-03-23 03:25:59 +00006584 // Ensure that we've loaded all potentially-interesting declarations
6585 // that need to be eagerly loaded.
6586 for (auto ID : EagerlyDeserializedDecls)
6587 GetDecl(ID);
6588 EagerlyDeserializedDecls.clear();
6589
Guy Benyei11169dd2012-12-18 14:30:41 +00006590 while (!InterestingDecls.empty()) {
6591 Decl *D = InterestingDecls.front();
6592 InterestingDecls.pop_front();
6593
6594 PassInterestingDeclToConsumer(D);
6595 }
6596}
6597
6598void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6599 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6600 PassObjCImplDeclToConsumer(ImplD, Consumer);
6601 else
6602 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6603}
6604
6605void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6606 this->Consumer = Consumer;
6607
Richard Smith9e2341d2015-03-23 03:25:59 +00006608 if (Consumer)
6609 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006610
6611 if (DeserializationListener)
6612 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006613}
6614
6615void ASTReader::PrintStats() {
6616 std::fprintf(stderr, "*** AST File Statistics:\n");
6617
6618 unsigned NumTypesLoaded
6619 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6620 QualType());
6621 unsigned NumDeclsLoaded
6622 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006623 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 unsigned NumIdentifiersLoaded
6625 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6626 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006627 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 unsigned NumMacrosLoaded
6629 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6630 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006631 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 unsigned NumSelectorsLoaded
6633 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6634 SelectorsLoaded.end(),
6635 Selector());
6636
6637 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6638 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6639 NumSLocEntriesRead, TotalNumSLocEntries,
6640 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6641 if (!TypesLoaded.empty())
6642 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6643 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6644 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6645 if (!DeclsLoaded.empty())
6646 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6647 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6648 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6649 if (!IdentifiersLoaded.empty())
6650 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6651 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6652 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6653 if (!MacrosLoaded.empty())
6654 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6655 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6656 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6657 if (!SelectorsLoaded.empty())
6658 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6659 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6660 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6661 if (TotalNumStatements)
6662 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6663 NumStatementsRead, TotalNumStatements,
6664 ((float)NumStatementsRead/TotalNumStatements * 100));
6665 if (TotalNumMacros)
6666 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6667 NumMacrosRead, TotalNumMacros,
6668 ((float)NumMacrosRead/TotalNumMacros * 100));
6669 if (TotalLexicalDeclContexts)
6670 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6671 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6672 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6673 * 100));
6674 if (TotalVisibleDeclContexts)
6675 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6676 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6677 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6678 * 100));
6679 if (TotalNumMethodPoolEntries) {
6680 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6681 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6682 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6683 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006684 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006685 if (NumMethodPoolLookups) {
6686 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6687 NumMethodPoolHits, NumMethodPoolLookups,
6688 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6689 }
6690 if (NumMethodPoolTableLookups) {
6691 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6692 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6693 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6694 * 100.0));
6695 }
6696
Douglas Gregor00a50f72013-01-25 00:38:33 +00006697 if (NumIdentifierLookupHits) {
6698 std::fprintf(stderr,
6699 " %u / %u identifier table lookups succeeded (%f%%)\n",
6700 NumIdentifierLookupHits, NumIdentifierLookups,
6701 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6702 }
6703
Douglas Gregore060e572013-01-25 01:03:03 +00006704 if (GlobalIndex) {
6705 std::fprintf(stderr, "\n");
6706 GlobalIndex->printStats();
6707 }
6708
Guy Benyei11169dd2012-12-18 14:30:41 +00006709 std::fprintf(stderr, "\n");
6710 dump();
6711 std::fprintf(stderr, "\n");
6712}
6713
6714template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6715static void
6716dumpModuleIDMap(StringRef Name,
6717 const ContinuousRangeMap<Key, ModuleFile *,
6718 InitialCapacity> &Map) {
6719 if (Map.begin() == Map.end())
6720 return;
6721
6722 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6723 llvm::errs() << Name << ":\n";
6724 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6725 I != IEnd; ++I) {
6726 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6727 << "\n";
6728 }
6729}
6730
6731void ASTReader::dump() {
6732 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6733 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6734 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6735 dumpModuleIDMap("Global type map", GlobalTypeMap);
6736 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6737 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6738 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6739 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6740 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6741 dumpModuleIDMap("Global preprocessed entity map",
6742 GlobalPreprocessedEntityMap);
6743
6744 llvm::errs() << "\n*** PCH/Modules Loaded:";
6745 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6746 MEnd = ModuleMgr.end();
6747 M != MEnd; ++M)
6748 (*M)->dump();
6749}
6750
6751/// Return the amount of memory used by memory buffers, breaking down
6752/// by heap-backed versus mmap'ed memory.
6753void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6754 for (ModuleConstIterator I = ModuleMgr.begin(),
6755 E = ModuleMgr.end(); I != E; ++I) {
6756 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6757 size_t bytes = buf->getBufferSize();
6758 switch (buf->getBufferKind()) {
6759 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6760 sizes.malloc_bytes += bytes;
6761 break;
6762 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6763 sizes.mmap_bytes += bytes;
6764 break;
6765 }
6766 }
6767 }
6768}
6769
6770void ASTReader::InitializeSema(Sema &S) {
6771 SemaObj = &S;
6772 S.addExternalSource(this);
6773
6774 // Makes sure any declarations that were deserialized "too early"
6775 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006776 for (uint64_t ID : PreloadedDeclIDs) {
6777 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6778 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006779 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006780 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006781
Richard Smith3d8e97e2013-10-18 06:54:39 +00006782 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006783 if (!FPPragmaOptions.empty()) {
6784 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6785 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6786 }
6787
Richard Smith3d8e97e2013-10-18 06:54:39 +00006788 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006789 if (!OpenCLExtensions.empty()) {
6790 unsigned I = 0;
6791#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6792#include "clang/Basic/OpenCLExtensions.def"
6793
6794 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6795 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006796
6797 UpdateSema();
6798}
6799
6800void ASTReader::UpdateSema() {
6801 assert(SemaObj && "no Sema to update");
6802
6803 // Load the offsets of the declarations that Sema references.
6804 // They will be lazily deserialized when needed.
6805 if (!SemaDeclRefs.empty()) {
6806 assert(SemaDeclRefs.size() % 2 == 0);
6807 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6808 if (!SemaObj->StdNamespace)
6809 SemaObj->StdNamespace = SemaDeclRefs[I];
6810 if (!SemaObj->StdBadAlloc)
6811 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6812 }
6813 SemaDeclRefs.clear();
6814 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006815
6816 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6817 // encountered the pragma in the source.
6818 if(OptimizeOffPragmaLocation.isValid())
6819 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006820}
6821
Richard Smitha8d5b6a2015-07-17 19:51:03 +00006822IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006823 // Note that we are loading an identifier.
6824 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006825
Douglas Gregor7211ac12013-01-25 23:32:03 +00006826 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006827 NumIdentifierLookups,
6828 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006829
6830 // We don't need to do identifier table lookups in C++ modules (we preload
6831 // all interesting declarations, and don't need to use the scope for name
6832 // lookups). Perform the lookup in PCH files, though, since we don't build
6833 // a complete initial identifier table if we're carrying on from a PCH.
6834 if (Context.getLangOpts().CPlusPlus) {
6835 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006836 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00006837 break;
6838 } else {
6839 // If there is a global index, look there first to determine which modules
6840 // provably do not have any results for this identifier.
6841 GlobalModuleIndex::HitSet Hits;
6842 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6843 if (!loadGlobalIndex()) {
6844 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6845 HitsPtr = &Hits;
6846 }
6847 }
6848
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006849 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00006850 }
6851
Guy Benyei11169dd2012-12-18 14:30:41 +00006852 IdentifierInfo *II = Visitor.getIdentifierInfo();
6853 markIdentifierUpToDate(II);
6854 return II;
6855}
6856
6857namespace clang {
6858 /// \brief An identifier-lookup iterator that enumerates all of the
6859 /// identifiers stored within a set of AST files.
6860 class ASTIdentifierIterator : public IdentifierIterator {
6861 /// \brief The AST reader whose identifiers are being enumerated.
6862 const ASTReader &Reader;
6863
6864 /// \brief The current index into the chain of AST files stored in
6865 /// the AST reader.
6866 unsigned Index;
6867
6868 /// \brief The current position within the identifier lookup table
6869 /// of the current AST file.
6870 ASTIdentifierLookupTable::key_iterator Current;
6871
6872 /// \brief The end position within the identifier lookup table of
6873 /// the current AST file.
6874 ASTIdentifierLookupTable::key_iterator End;
6875
6876 public:
6877 explicit ASTIdentifierIterator(const ASTReader &Reader);
6878
Craig Topper3e89dfe2014-03-13 02:13:41 +00006879 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006880 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006881}
Guy Benyei11169dd2012-12-18 14:30:41 +00006882
6883ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6884 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6885 ASTIdentifierLookupTable *IdTable
6886 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6887 Current = IdTable->key_begin();
6888 End = IdTable->key_end();
6889}
6890
6891StringRef ASTIdentifierIterator::Next() {
6892 while (Current == End) {
6893 // If we have exhausted all of our AST files, we're done.
6894 if (Index == 0)
6895 return StringRef();
6896
6897 --Index;
6898 ASTIdentifierLookupTable *IdTable
6899 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6900 IdentifierLookupTable;
6901 Current = IdTable->key_begin();
6902 End = IdTable->key_end();
6903 }
6904
6905 // We have any identifiers remaining in the current AST file; return
6906 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006907 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006909 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006910}
6911
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006912IdentifierIterator *ASTReader::getIdentifiers() {
6913 if (!loadGlobalIndex())
6914 return GlobalIndex->createIdentifierIterator();
6915
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 return new ASTIdentifierIterator(*this);
6917}
6918
6919namespace clang { namespace serialization {
6920 class ReadMethodPoolVisitor {
6921 ASTReader &Reader;
6922 Selector Sel;
6923 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006924 unsigned InstanceBits;
6925 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006926 bool InstanceHasMoreThanOneDecl;
6927 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006928 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6929 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006930
6931 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006932 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006933 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006934 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006935 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6936 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006937
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006938 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 if (!M.SelectorLookupTable)
6940 return false;
6941
6942 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00006943 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00006944 return true;
6945
Richard Smithbdf2d932015-07-30 03:37:16 +00006946 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 ASTSelectorLookupTable *PoolTable
6948 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00006949 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 if (Pos == PoolTable->end())
6951 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006952
Richard Smithbdf2d932015-07-30 03:37:16 +00006953 ++Reader.NumMethodPoolTableHits;
6954 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006955 // FIXME: Not quite happy with the statistics here. We probably should
6956 // disable this tracking when called via LoadSelector.
6957 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00006958 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00006960 if (Reader.DeserializationListener)
6961 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006962
Richard Smithbdf2d932015-07-30 03:37:16 +00006963 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6964 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6965 InstanceBits = Data.InstanceBits;
6966 FactoryBits = Data.FactoryBits;
6967 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6968 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 return true;
6970 }
6971
6972 /// \brief Retrieve the instance methods found by this visitor.
6973 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6974 return InstanceMethods;
6975 }
6976
6977 /// \brief Retrieve the instance methods found by this visitor.
6978 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6979 return FactoryMethods;
6980 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006981
6982 unsigned getInstanceBits() const { return InstanceBits; }
6983 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006984 bool instanceHasMoreThanOneDecl() const {
6985 return InstanceHasMoreThanOneDecl;
6986 }
6987 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006989} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006990
6991/// \brief Add the given set of methods to the method list.
6992static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6993 ObjCMethodList &List) {
6994 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6995 S.addMethodToGlobalList(&List, Methods[I]);
6996 }
6997}
6998
6999void ASTReader::ReadMethodPool(Selector Sel) {
7000 // Get the selector generation and update it to the current generation.
7001 unsigned &Generation = SelectorGeneration[Sel];
7002 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007003 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00007004
7005 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007006 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007008 ModuleMgr.visit(Visitor);
7009
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007011 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007012 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007013
7014 ++NumMethodPoolHits;
7015
Guy Benyei11169dd2012-12-18 14:30:41 +00007016 if (!getSema())
7017 return;
7018
7019 Sema &S = *getSema();
7020 Sema::GlobalMethodPool::iterator Pos
7021 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007022
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007023 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007024 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007025 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007026 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007027
7028 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7029 // when building a module we keep every method individually and may need to
7030 // update hasMoreThanOneDecl as we add the methods.
7031 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7032 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007033}
7034
7035void ASTReader::ReadKnownNamespaces(
7036 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7037 Namespaces.clear();
7038
7039 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7040 if (NamespaceDecl *Namespace
7041 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7042 Namespaces.push_back(Namespace);
7043 }
7044}
7045
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007046void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007047 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007048 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7049 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007050 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007051 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007052 Undefined.insert(std::make_pair(D, Loc));
7053 }
7054}
Nick Lewycky8334af82013-01-26 00:35:08 +00007055
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007056void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7057 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7058 Exprs) {
7059 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7060 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7061 uint64_t Count = DelayedDeleteExprs[Idx++];
7062 for (uint64_t C = 0; C < Count; ++C) {
7063 SourceLocation DeleteLoc =
7064 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7065 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7066 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7067 }
7068 }
7069}
7070
Guy Benyei11169dd2012-12-18 14:30:41 +00007071void ASTReader::ReadTentativeDefinitions(
7072 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7073 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7074 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7075 if (Var)
7076 TentativeDefs.push_back(Var);
7077 }
7078 TentativeDefinitions.clear();
7079}
7080
7081void ASTReader::ReadUnusedFileScopedDecls(
7082 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7083 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7084 DeclaratorDecl *D
7085 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7086 if (D)
7087 Decls.push_back(D);
7088 }
7089 UnusedFileScopedDecls.clear();
7090}
7091
7092void ASTReader::ReadDelegatingConstructors(
7093 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7094 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7095 CXXConstructorDecl *D
7096 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7097 if (D)
7098 Decls.push_back(D);
7099 }
7100 DelegatingCtorDecls.clear();
7101}
7102
7103void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7104 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7105 TypedefNameDecl *D
7106 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7107 if (D)
7108 Decls.push_back(D);
7109 }
7110 ExtVectorDecls.clear();
7111}
7112
Nico Weber72889432014-09-06 01:25:55 +00007113void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7114 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7115 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7116 ++I) {
7117 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7118 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7119 if (D)
7120 Decls.insert(D);
7121 }
7122 UnusedLocalTypedefNameCandidates.clear();
7123}
7124
Guy Benyei11169dd2012-12-18 14:30:41 +00007125void ASTReader::ReadReferencedSelectors(
7126 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7127 if (ReferencedSelectorsData.empty())
7128 return;
7129
7130 // If there are @selector references added them to its pool. This is for
7131 // implementation of -Wselector.
7132 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7133 unsigned I = 0;
7134 while (I < DataSize) {
7135 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7136 SourceLocation SelLoc
7137 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7138 Sels.push_back(std::make_pair(Sel, SelLoc));
7139 }
7140 ReferencedSelectorsData.clear();
7141}
7142
7143void ASTReader::ReadWeakUndeclaredIdentifiers(
7144 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7145 if (WeakUndeclaredIdentifiers.empty())
7146 return;
7147
7148 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7149 IdentifierInfo *WeakId
7150 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7151 IdentifierInfo *AliasId
7152 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7153 SourceLocation Loc
7154 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7155 bool Used = WeakUndeclaredIdentifiers[I++];
7156 WeakInfo WI(AliasId, Loc);
7157 WI.setUsed(Used);
7158 WeakIDs.push_back(std::make_pair(WeakId, WI));
7159 }
7160 WeakUndeclaredIdentifiers.clear();
7161}
7162
7163void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7164 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7165 ExternalVTableUse VT;
7166 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7167 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7168 VT.DefinitionRequired = VTableUses[Idx++];
7169 VTables.push_back(VT);
7170 }
7171
7172 VTableUses.clear();
7173}
7174
7175void ASTReader::ReadPendingInstantiations(
7176 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7177 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7178 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7179 SourceLocation Loc
7180 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7181
7182 Pending.push_back(std::make_pair(D, Loc));
7183 }
7184 PendingInstantiations.clear();
7185}
7186
Richard Smithe40f2ba2013-08-07 21:41:30 +00007187void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007188 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007189 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7190 /* In loop */) {
7191 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7192
7193 LateParsedTemplate *LT = new LateParsedTemplate;
7194 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7195
7196 ModuleFile *F = getOwningModuleFile(LT->D);
7197 assert(F && "No module");
7198
7199 unsigned TokN = LateParsedTemplates[Idx++];
7200 LT->Toks.reserve(TokN);
7201 for (unsigned T = 0; T < TokN; ++T)
7202 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7203
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007204 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007205 }
7206
7207 LateParsedTemplates.clear();
7208}
7209
Guy Benyei11169dd2012-12-18 14:30:41 +00007210void ASTReader::LoadSelector(Selector Sel) {
7211 // It would be complicated to avoid reading the methods anyway. So don't.
7212 ReadMethodPool(Sel);
7213}
7214
7215void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7216 assert(ID && "Non-zero identifier ID required");
7217 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7218 IdentifiersLoaded[ID - 1] = II;
7219 if (DeserializationListener)
7220 DeserializationListener->IdentifierRead(ID, II);
7221}
7222
7223/// \brief Set the globally-visible declarations associated with the given
7224/// identifier.
7225///
7226/// If the AST reader is currently in a state where the given declaration IDs
7227/// cannot safely be resolved, they are queued until it is safe to resolve
7228/// them.
7229///
7230/// \param II an IdentifierInfo that refers to one or more globally-visible
7231/// declarations.
7232///
7233/// \param DeclIDs the set of declaration IDs with the name @p II that are
7234/// visible at global scope.
7235///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007236/// \param Decls if non-null, this vector will be populated with the set of
7237/// deserialized declarations. These declarations will not be pushed into
7238/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007239void
7240ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7241 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007242 SmallVectorImpl<Decl *> *Decls) {
7243 if (NumCurrentElementsDeserializing && !Decls) {
7244 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007245 return;
7246 }
7247
7248 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007249 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007250 // Queue this declaration so that it will be added to the
7251 // translation unit scope and identifier's declaration chain
7252 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007253 PreloadedDeclIDs.push_back(DeclIDs[I]);
7254 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007256
7257 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7258
7259 // If we're simply supposed to record the declarations, do so now.
7260 if (Decls) {
7261 Decls->push_back(D);
7262 continue;
7263 }
7264
7265 // Introduce this declaration into the translation-unit scope
7266 // and add it to the declaration chain for this identifier, so
7267 // that (unqualified) name lookup will find it.
7268 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007269 }
7270}
7271
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007272IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007273 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007274 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007275
7276 if (IdentifiersLoaded.empty()) {
7277 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007278 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007279 }
7280
7281 ID -= 1;
7282 if (!IdentifiersLoaded[ID]) {
7283 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7284 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7285 ModuleFile *M = I->second;
7286 unsigned Index = ID - M->BaseIdentifierID;
7287 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7288
7289 // All of the strings in the AST file are preceded by a 16-bit length.
7290 // Extract that 16-bit length to avoid having to execute strlen().
7291 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7292 // unsigned integers. This is important to avoid integer overflow when
7293 // we cast them to 'unsigned'.
7294 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7295 unsigned StrLen = (((unsigned) StrLenPtr[0])
7296 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007297 IdentifiersLoaded[ID]
7298 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007299 if (DeserializationListener)
7300 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7301 }
7302
7303 return IdentifiersLoaded[ID];
7304}
7305
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007306IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7307 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007308}
7309
7310IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7311 if (LocalID < NUM_PREDEF_IDENT_IDS)
7312 return LocalID;
7313
7314 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7315 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7316 assert(I != M.IdentifierRemap.end()
7317 && "Invalid index into identifier index remap");
7318
7319 return LocalID + I->second;
7320}
7321
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007322MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007323 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007324 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007325
7326 if (MacrosLoaded.empty()) {
7327 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007328 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007329 }
7330
7331 ID -= NUM_PREDEF_MACRO_IDS;
7332 if (!MacrosLoaded[ID]) {
7333 GlobalMacroMapType::iterator I
7334 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7335 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7336 ModuleFile *M = I->second;
7337 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007338 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7339
7340 if (DeserializationListener)
7341 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7342 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007343 }
7344
7345 return MacrosLoaded[ID];
7346}
7347
7348MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7349 if (LocalID < NUM_PREDEF_MACRO_IDS)
7350 return LocalID;
7351
7352 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7353 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7354 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7355
7356 return LocalID + I->second;
7357}
7358
7359serialization::SubmoduleID
7360ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7361 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7362 return LocalID;
7363
7364 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7365 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7366 assert(I != M.SubmoduleRemap.end()
7367 && "Invalid index into submodule index remap");
7368
7369 return LocalID + I->second;
7370}
7371
7372Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7373 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7374 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007375 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007376 }
7377
7378 if (GlobalID > SubmodulesLoaded.size()) {
7379 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007380 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007381 }
7382
7383 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7384}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007385
7386Module *ASTReader::getModule(unsigned ID) {
7387 return getSubmodule(ID);
7388}
7389
Adrian Prantl15bcf702015-06-30 17:39:43 +00007390ExternalASTSource::ASTSourceDescriptor
7391ASTReader::getSourceDescriptor(const Module &M) {
7392 StringRef Dir, Filename;
7393 if (M.Directory)
7394 Dir = M.Directory->getName();
7395 if (auto *File = M.getASTFile())
7396 Filename = File->getName();
7397 return ASTReader::ASTSourceDescriptor{
7398 M.getFullModuleName(), Dir, Filename,
7399 M.Signature
7400 };
7401}
7402
7403llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7404ASTReader::getSourceDescriptor(unsigned ID) {
7405 if (const Module *M = getSubmodule(ID))
7406 return getSourceDescriptor(*M);
7407
7408 // If there is only a single PCH, return it instead.
7409 // Chained PCH are not suported.
7410 if (ModuleMgr.size() == 1) {
7411 ModuleFile &MF = ModuleMgr.getPrimaryModule();
7412 return ASTReader::ASTSourceDescriptor{
7413 MF.OriginalSourceFileName, MF.OriginalDir,
7414 MF.FileName,
7415 MF.Signature
7416 };
7417 }
7418 return None;
7419}
7420
Guy Benyei11169dd2012-12-18 14:30:41 +00007421Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7422 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7423}
7424
7425Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7426 if (ID == 0)
7427 return Selector();
7428
7429 if (ID > SelectorsLoaded.size()) {
7430 Error("selector ID out of range in AST file");
7431 return Selector();
7432 }
7433
Craig Toppera13603a2014-05-22 05:54:18 +00007434 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007435 // Load this selector from the selector table.
7436 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7437 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7438 ModuleFile &M = *I->second;
7439 ASTSelectorLookupTrait Trait(*this, M);
7440 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7441 SelectorsLoaded[ID - 1] =
7442 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7443 if (DeserializationListener)
7444 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7445 }
7446
7447 return SelectorsLoaded[ID - 1];
7448}
7449
7450Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7451 return DecodeSelector(ID);
7452}
7453
7454uint32_t ASTReader::GetNumExternalSelectors() {
7455 // ID 0 (the null selector) is considered an external selector.
7456 return getTotalNumSelectors() + 1;
7457}
7458
7459serialization::SelectorID
7460ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7461 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7462 return LocalID;
7463
7464 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7465 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7466 assert(I != M.SelectorRemap.end()
7467 && "Invalid index into selector index remap");
7468
7469 return LocalID + I->second;
7470}
7471
7472DeclarationName
7473ASTReader::ReadDeclarationName(ModuleFile &F,
7474 const RecordData &Record, unsigned &Idx) {
7475 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7476 switch (Kind) {
7477 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007478 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007479
7480 case DeclarationName::ObjCZeroArgSelector:
7481 case DeclarationName::ObjCOneArgSelector:
7482 case DeclarationName::ObjCMultiArgSelector:
7483 return DeclarationName(ReadSelector(F, Record, Idx));
7484
7485 case DeclarationName::CXXConstructorName:
7486 return Context.DeclarationNames.getCXXConstructorName(
7487 Context.getCanonicalType(readType(F, Record, Idx)));
7488
7489 case DeclarationName::CXXDestructorName:
7490 return Context.DeclarationNames.getCXXDestructorName(
7491 Context.getCanonicalType(readType(F, Record, Idx)));
7492
7493 case DeclarationName::CXXConversionFunctionName:
7494 return Context.DeclarationNames.getCXXConversionFunctionName(
7495 Context.getCanonicalType(readType(F, Record, Idx)));
7496
7497 case DeclarationName::CXXOperatorName:
7498 return Context.DeclarationNames.getCXXOperatorName(
7499 (OverloadedOperatorKind)Record[Idx++]);
7500
7501 case DeclarationName::CXXLiteralOperatorName:
7502 return Context.DeclarationNames.getCXXLiteralOperatorName(
7503 GetIdentifierInfo(F, Record, Idx));
7504
7505 case DeclarationName::CXXUsingDirective:
7506 return DeclarationName::getUsingDirectiveName();
7507 }
7508
7509 llvm_unreachable("Invalid NameKind!");
7510}
7511
7512void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7513 DeclarationNameLoc &DNLoc,
7514 DeclarationName Name,
7515 const RecordData &Record, unsigned &Idx) {
7516 switch (Name.getNameKind()) {
7517 case DeclarationName::CXXConstructorName:
7518 case DeclarationName::CXXDestructorName:
7519 case DeclarationName::CXXConversionFunctionName:
7520 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7521 break;
7522
7523 case DeclarationName::CXXOperatorName:
7524 DNLoc.CXXOperatorName.BeginOpNameLoc
7525 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7526 DNLoc.CXXOperatorName.EndOpNameLoc
7527 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7528 break;
7529
7530 case DeclarationName::CXXLiteralOperatorName:
7531 DNLoc.CXXLiteralOperatorName.OpNameLoc
7532 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7533 break;
7534
7535 case DeclarationName::Identifier:
7536 case DeclarationName::ObjCZeroArgSelector:
7537 case DeclarationName::ObjCOneArgSelector:
7538 case DeclarationName::ObjCMultiArgSelector:
7539 case DeclarationName::CXXUsingDirective:
7540 break;
7541 }
7542}
7543
7544void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7545 DeclarationNameInfo &NameInfo,
7546 const RecordData &Record, unsigned &Idx) {
7547 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7548 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7549 DeclarationNameLoc DNLoc;
7550 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7551 NameInfo.setInfo(DNLoc);
7552}
7553
7554void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7555 const RecordData &Record, unsigned &Idx) {
7556 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7557 unsigned NumTPLists = Record[Idx++];
7558 Info.NumTemplParamLists = NumTPLists;
7559 if (NumTPLists) {
7560 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7561 for (unsigned i=0; i != NumTPLists; ++i)
7562 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7563 }
7564}
7565
7566TemplateName
7567ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7568 unsigned &Idx) {
7569 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7570 switch (Kind) {
7571 case TemplateName::Template:
7572 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7573
7574 case TemplateName::OverloadedTemplate: {
7575 unsigned size = Record[Idx++];
7576 UnresolvedSet<8> Decls;
7577 while (size--)
7578 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7579
7580 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7581 }
7582
7583 case TemplateName::QualifiedTemplate: {
7584 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7585 bool hasTemplKeyword = Record[Idx++];
7586 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7587 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7588 }
7589
7590 case TemplateName::DependentTemplate: {
7591 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7592 if (Record[Idx++]) // isIdentifier
7593 return Context.getDependentTemplateName(NNS,
7594 GetIdentifierInfo(F, Record,
7595 Idx));
7596 return Context.getDependentTemplateName(NNS,
7597 (OverloadedOperatorKind)Record[Idx++]);
7598 }
7599
7600 case TemplateName::SubstTemplateTemplateParm: {
7601 TemplateTemplateParmDecl *param
7602 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7603 if (!param) return TemplateName();
7604 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7605 return Context.getSubstTemplateTemplateParm(param, replacement);
7606 }
7607
7608 case TemplateName::SubstTemplateTemplateParmPack: {
7609 TemplateTemplateParmDecl *Param
7610 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7611 if (!Param)
7612 return TemplateName();
7613
7614 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7615 if (ArgPack.getKind() != TemplateArgument::Pack)
7616 return TemplateName();
7617
7618 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7619 }
7620 }
7621
7622 llvm_unreachable("Unhandled template name kind!");
7623}
7624
Richard Smith2bb3c342015-08-09 01:05:31 +00007625TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7626 const RecordData &Record,
7627 unsigned &Idx,
7628 bool Canonicalize) {
7629 if (Canonicalize) {
7630 // The caller wants a canonical template argument. Sometimes the AST only
7631 // wants template arguments in canonical form (particularly as the template
7632 // argument lists of template specializations) so ensure we preserve that
7633 // canonical form across serialization.
7634 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7635 return Context.getCanonicalTemplateArgument(Arg);
7636 }
7637
Guy Benyei11169dd2012-12-18 14:30:41 +00007638 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7639 switch (Kind) {
7640 case TemplateArgument::Null:
7641 return TemplateArgument();
7642 case TemplateArgument::Type:
7643 return TemplateArgument(readType(F, Record, Idx));
7644 case TemplateArgument::Declaration: {
7645 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007646 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007647 }
7648 case TemplateArgument::NullPtr:
7649 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7650 case TemplateArgument::Integral: {
7651 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7652 QualType T = readType(F, Record, Idx);
7653 return TemplateArgument(Context, Value, T);
7654 }
7655 case TemplateArgument::Template:
7656 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7657 case TemplateArgument::TemplateExpansion: {
7658 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007659 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007660 if (unsigned NumExpansions = Record[Idx++])
7661 NumTemplateExpansions = NumExpansions - 1;
7662 return TemplateArgument(Name, NumTemplateExpansions);
7663 }
7664 case TemplateArgument::Expression:
7665 return TemplateArgument(ReadExpr(F));
7666 case TemplateArgument::Pack: {
7667 unsigned NumArgs = Record[Idx++];
7668 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7669 for (unsigned I = 0; I != NumArgs; ++I)
7670 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00007671 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 }
7673 }
7674
7675 llvm_unreachable("Unhandled template argument kind!");
7676}
7677
7678TemplateParameterList *
7679ASTReader::ReadTemplateParameterList(ModuleFile &F,
7680 const RecordData &Record, unsigned &Idx) {
7681 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7682 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7683 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7684
7685 unsigned NumParams = Record[Idx++];
7686 SmallVector<NamedDecl *, 16> Params;
7687 Params.reserve(NumParams);
7688 while (NumParams--)
7689 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7690
7691 TemplateParameterList* TemplateParams =
7692 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7693 Params.data(), Params.size(), RAngleLoc);
7694 return TemplateParams;
7695}
7696
7697void
7698ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007699ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00007701 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007702 unsigned NumTemplateArgs = Record[Idx++];
7703 TemplArgs.reserve(NumTemplateArgs);
7704 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00007705 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00007706}
7707
7708/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007709void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 const RecordData &Record, unsigned &Idx) {
7711 unsigned NumDecls = Record[Idx++];
7712 Set.reserve(Context, NumDecls);
7713 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007714 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007716 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007717 }
7718}
7719
7720CXXBaseSpecifier
7721ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7722 const RecordData &Record, unsigned &Idx) {
7723 bool isVirtual = static_cast<bool>(Record[Idx++]);
7724 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7725 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7726 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7727 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7728 SourceRange Range = ReadSourceRange(F, Record, Idx);
7729 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7730 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7731 EllipsisLoc);
7732 Result.setInheritConstructors(inheritConstructors);
7733 return Result;
7734}
7735
Richard Smithc2bb8182015-03-24 06:36:48 +00007736CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007737ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7738 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007739 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007740 assert(NumInitializers && "wrote ctor initializers but have no inits");
7741 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7742 for (unsigned i = 0; i != NumInitializers; ++i) {
7743 TypeSourceInfo *TInfo = nullptr;
7744 bool IsBaseVirtual = false;
7745 FieldDecl *Member = nullptr;
7746 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007747
Richard Smithc2bb8182015-03-24 06:36:48 +00007748 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7749 switch (Type) {
7750 case CTOR_INITIALIZER_BASE:
7751 TInfo = GetTypeSourceInfo(F, Record, Idx);
7752 IsBaseVirtual = Record[Idx++];
7753 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007754
Richard Smithc2bb8182015-03-24 06:36:48 +00007755 case CTOR_INITIALIZER_DELEGATING:
7756 TInfo = GetTypeSourceInfo(F, Record, Idx);
7757 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007758
Richard Smithc2bb8182015-03-24 06:36:48 +00007759 case CTOR_INITIALIZER_MEMBER:
7760 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7761 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007762
Richard Smithc2bb8182015-03-24 06:36:48 +00007763 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7764 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7765 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007766 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007767
7768 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7769 Expr *Init = ReadExpr(F);
7770 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7771 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7772 bool IsWritten = Record[Idx++];
7773 unsigned SourceOrderOrNumArrayIndices;
7774 SmallVector<VarDecl *, 8> Indices;
7775 if (IsWritten) {
7776 SourceOrderOrNumArrayIndices = Record[Idx++];
7777 } else {
7778 SourceOrderOrNumArrayIndices = Record[Idx++];
7779 Indices.reserve(SourceOrderOrNumArrayIndices);
7780 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7781 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7782 }
7783
7784 CXXCtorInitializer *BOMInit;
7785 if (Type == CTOR_INITIALIZER_BASE) {
7786 BOMInit = new (Context)
7787 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7788 RParenLoc, MemberOrEllipsisLoc);
7789 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7790 BOMInit = new (Context)
7791 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7792 } else if (IsWritten) {
7793 if (Member)
7794 BOMInit = new (Context) CXXCtorInitializer(
7795 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7796 else
7797 BOMInit = new (Context)
7798 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7799 LParenLoc, Init, RParenLoc);
7800 } else {
7801 if (IndirectMember) {
7802 assert(Indices.empty() && "Indirect field improperly initialized");
7803 BOMInit = new (Context)
7804 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7805 LParenLoc, Init, RParenLoc);
7806 } else {
7807 BOMInit = CXXCtorInitializer::Create(
7808 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7809 Indices.data(), Indices.size());
7810 }
7811 }
7812
7813 if (IsWritten)
7814 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7815 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007816 }
7817
Richard Smithc2bb8182015-03-24 06:36:48 +00007818 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007819}
7820
7821NestedNameSpecifier *
7822ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7823 const RecordData &Record, unsigned &Idx) {
7824 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007825 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007826 for (unsigned I = 0; I != N; ++I) {
7827 NestedNameSpecifier::SpecifierKind Kind
7828 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7829 switch (Kind) {
7830 case NestedNameSpecifier::Identifier: {
7831 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7832 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7833 break;
7834 }
7835
7836 case NestedNameSpecifier::Namespace: {
7837 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7838 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7839 break;
7840 }
7841
7842 case NestedNameSpecifier::NamespaceAlias: {
7843 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7844 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7845 break;
7846 }
7847
7848 case NestedNameSpecifier::TypeSpec:
7849 case NestedNameSpecifier::TypeSpecWithTemplate: {
7850 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7851 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007852 return nullptr;
7853
Guy Benyei11169dd2012-12-18 14:30:41 +00007854 bool Template = Record[Idx++];
7855 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7856 break;
7857 }
7858
7859 case NestedNameSpecifier::Global: {
7860 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7861 // No associated value, and there can't be a prefix.
7862 break;
7863 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007864
7865 case NestedNameSpecifier::Super: {
7866 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7867 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7868 break;
7869 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007870 }
7871 Prev = NNS;
7872 }
7873 return NNS;
7874}
7875
7876NestedNameSpecifierLoc
7877ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7878 unsigned &Idx) {
7879 unsigned N = Record[Idx++];
7880 NestedNameSpecifierLocBuilder Builder;
7881 for (unsigned I = 0; I != N; ++I) {
7882 NestedNameSpecifier::SpecifierKind Kind
7883 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7884 switch (Kind) {
7885 case NestedNameSpecifier::Identifier: {
7886 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7887 SourceRange Range = ReadSourceRange(F, Record, Idx);
7888 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7889 break;
7890 }
7891
7892 case NestedNameSpecifier::Namespace: {
7893 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7894 SourceRange Range = ReadSourceRange(F, Record, Idx);
7895 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7896 break;
7897 }
7898
7899 case NestedNameSpecifier::NamespaceAlias: {
7900 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7901 SourceRange Range = ReadSourceRange(F, Record, Idx);
7902 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7903 break;
7904 }
7905
7906 case NestedNameSpecifier::TypeSpec:
7907 case NestedNameSpecifier::TypeSpecWithTemplate: {
7908 bool Template = Record[Idx++];
7909 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7910 if (!T)
7911 return NestedNameSpecifierLoc();
7912 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7913
7914 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7915 Builder.Extend(Context,
7916 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7917 T->getTypeLoc(), ColonColonLoc);
7918 break;
7919 }
7920
7921 case NestedNameSpecifier::Global: {
7922 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7923 Builder.MakeGlobal(Context, ColonColonLoc);
7924 break;
7925 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007926
7927 case NestedNameSpecifier::Super: {
7928 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7929 SourceRange Range = ReadSourceRange(F, Record, Idx);
7930 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7931 break;
7932 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007933 }
7934 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007935
Guy Benyei11169dd2012-12-18 14:30:41 +00007936 return Builder.getWithLocInContext(Context);
7937}
7938
7939SourceRange
7940ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7941 unsigned &Idx) {
7942 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7943 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7944 return SourceRange(beg, end);
7945}
7946
7947/// \brief Read an integral value
7948llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7949 unsigned BitWidth = Record[Idx++];
7950 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7951 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7952 Idx += NumWords;
7953 return Result;
7954}
7955
7956/// \brief Read a signed integral value
7957llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7958 bool isUnsigned = Record[Idx++];
7959 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7960}
7961
7962/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007963llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7964 const llvm::fltSemantics &Sem,
7965 unsigned &Idx) {
7966 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007967}
7968
7969// \brief Read a string
7970std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7971 unsigned Len = Record[Idx++];
7972 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7973 Idx += Len;
7974 return Result;
7975}
7976
Richard Smith7ed1bc92014-12-05 22:42:13 +00007977std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7978 unsigned &Idx) {
7979 std::string Filename = ReadString(Record, Idx);
7980 ResolveImportedPath(F, Filename);
7981 return Filename;
7982}
7983
Guy Benyei11169dd2012-12-18 14:30:41 +00007984VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7985 unsigned &Idx) {
7986 unsigned Major = Record[Idx++];
7987 unsigned Minor = Record[Idx++];
7988 unsigned Subminor = Record[Idx++];
7989 if (Minor == 0)
7990 return VersionTuple(Major);
7991 if (Subminor == 0)
7992 return VersionTuple(Major, Minor - 1);
7993 return VersionTuple(Major, Minor - 1, Subminor - 1);
7994}
7995
7996CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7997 const RecordData &Record,
7998 unsigned &Idx) {
7999 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8000 return CXXTemporary::Create(Context, Decl);
8001}
8002
8003DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008004 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008005}
8006
8007DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8008 return Diags.Report(Loc, DiagID);
8009}
8010
8011/// \brief Retrieve the identifier table associated with the
8012/// preprocessor.
8013IdentifierTable &ASTReader::getIdentifierTable() {
8014 return PP.getIdentifierTable();
8015}
8016
8017/// \brief Record that the given ID maps to the given switch-case
8018/// statement.
8019void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008020 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008021 "Already have a SwitchCase with this ID");
8022 (*CurrSwitchCaseStmts)[ID] = SC;
8023}
8024
8025/// \brief Retrieve the switch-case statement with the given ID.
8026SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008027 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 return (*CurrSwitchCaseStmts)[ID];
8029}
8030
8031void ASTReader::ClearSwitchCaseIDs() {
8032 CurrSwitchCaseStmts->clear();
8033}
8034
8035void ASTReader::ReadComments() {
8036 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008037 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 serialization::ModuleFile *> >::iterator
8039 I = CommentsCursors.begin(),
8040 E = CommentsCursors.end();
8041 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008042 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008043 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 serialization::ModuleFile &F = *I->second;
8045 SavedStreamPosition SavedPosition(Cursor);
8046
8047 RecordData Record;
8048 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008049 llvm::BitstreamEntry Entry =
8050 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008051
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008052 switch (Entry.Kind) {
8053 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8054 case llvm::BitstreamEntry::Error:
8055 Error("malformed block record in AST file");
8056 return;
8057 case llvm::BitstreamEntry::EndBlock:
8058 goto NextCursor;
8059 case llvm::BitstreamEntry::Record:
8060 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008062 }
8063
8064 // Read a record.
8065 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008066 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 case COMMENTS_RAW_COMMENT: {
8068 unsigned Idx = 0;
8069 SourceRange SR = ReadSourceRange(F, Record, Idx);
8070 RawComment::CommentKind Kind =
8071 (RawComment::CommentKind) Record[Idx++];
8072 bool IsTrailingComment = Record[Idx++];
8073 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008074 Comments.push_back(new (Context) RawComment(
8075 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8076 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008077 break;
8078 }
8079 }
8080 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008081 NextCursor:
8082 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008083 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008084}
8085
Richard Smithcd45dbc2014-04-19 03:48:30 +00008086std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8087 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008088 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008089 return M->getFullModuleName();
8090
8091 // Otherwise, use the name of the top-level module the decl is within.
8092 if (ModuleFile *M = getOwningModuleFile(D))
8093 return M->ModuleName;
8094
8095 // Not from a module.
8096 return "";
8097}
8098
Guy Benyei11169dd2012-12-18 14:30:41 +00008099void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008100 while (!PendingIdentifierInfos.empty() ||
8101 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008102 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008103 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 // If any identifiers with corresponding top-level declarations have
8105 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008106 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8107 TopLevelDeclsMap;
8108 TopLevelDeclsMap TopLevelDecls;
8109
Guy Benyei11169dd2012-12-18 14:30:41 +00008110 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008111 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008112 SmallVector<uint32_t, 4> DeclIDs =
8113 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008114 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008115
8116 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008117 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008118
Richard Smith851072e2014-05-19 20:59:20 +00008119 // For each decl chain that we wanted to complete while deserializing, mark
8120 // it as "still needs to be completed".
8121 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8122 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8123 }
8124 PendingIncompleteDeclChains.clear();
8125
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008127 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008128 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008129 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008130 }
8131 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008132 PendingDeclChains.clear();
8133
Richard Smith9b88a4c2015-07-27 05:40:23 +00008134 assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8135
Douglas Gregor6168bd22013-02-18 15:53:43 +00008136 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008137 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8138 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008139 IdentifierInfo *II = TLD->first;
8140 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008141 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008142 }
8143 }
8144
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 // Load any pending macro definitions.
8146 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008147 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8148 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8149 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8150 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008151 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008152 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008153 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008154 if (Info.M->Kind != MK_ImplicitModule &&
8155 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008156 resolvePendingMacro(II, Info);
8157 }
8158 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008159 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008160 ++IDIdx) {
8161 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008162 if (Info.M->Kind == MK_ImplicitModule ||
8163 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008164 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008165 }
8166 }
8167 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008168
8169 // Wire up the DeclContexts for Decls that we delayed setting until
8170 // recursive loading is completed.
8171 while (!PendingDeclContextInfos.empty()) {
8172 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8173 PendingDeclContextInfos.pop_front();
8174 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8175 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8176 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8177 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008178
Richard Smithd1c46742014-04-30 02:24:17 +00008179 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008180 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008181 auto Update = PendingUpdateRecords.pop_back_val();
8182 ReadingKindTracker ReadingKind(Read_Decl, *this);
8183 loadDeclUpdateRecords(Update.first, Update.second);
8184 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008185 }
Richard Smith8a639892015-01-24 01:07:20 +00008186
8187 // At this point, all update records for loaded decls are in place, so any
8188 // fake class definitions should have become real.
8189 assert(PendingFakeDefinitionData.empty() &&
8190 "faked up a class definition but never saw the real one");
8191
Guy Benyei11169dd2012-12-18 14:30:41 +00008192 // If we deserialized any C++ or Objective-C class definitions, any
8193 // Objective-C protocol definitions, or any redeclarable templates, make sure
8194 // that all redeclarations point to the definitions. Note that this can only
8195 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008196 for (Decl *D : PendingDefinitions) {
8197 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008198 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008199 // Make sure that the TagType points at the definition.
8200 const_cast<TagType*>(TagT)->decl = TD;
8201 }
Richard Smith8ce51082015-03-11 01:44:51 +00008202
Craig Topperc6914d02014-08-25 04:15:02 +00008203 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008204 for (auto *R = getMostRecentExistingDecl(RD); R;
8205 R = R->getPreviousDecl()) {
8206 assert((R == D) ==
8207 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008208 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008209 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008210 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 }
8212
8213 continue;
8214 }
Richard Smith8ce51082015-03-11 01:44:51 +00008215
Craig Topperc6914d02014-08-25 04:15:02 +00008216 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008217 // Make sure that the ObjCInterfaceType points at the definition.
8218 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8219 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008220
8221 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8222 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8223
Guy Benyei11169dd2012-12-18 14:30:41 +00008224 continue;
8225 }
Richard Smith8ce51082015-03-11 01:44:51 +00008226
Craig Topperc6914d02014-08-25 04:15:02 +00008227 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008228 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8229 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8230
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 continue;
8232 }
Richard Smith8ce51082015-03-11 01:44:51 +00008233
Craig Topperc6914d02014-08-25 04:15:02 +00008234 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008235 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8236 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008237 }
8238 PendingDefinitions.clear();
8239
8240 // Load the bodies of any functions or methods we've encountered. We do
8241 // this now (delayed) so that we can be sure that the declaration chains
8242 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008243 // FIXME: There seems to be no point in delaying this, it does not depend
8244 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8246 PBEnd = PendingBodies.end();
8247 PB != PBEnd; ++PB) {
8248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8249 // FIXME: Check for =delete/=default?
8250 // FIXME: Complain about ODR violations here?
8251 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8252 FD->setLazyBody(PB->second);
8253 continue;
8254 }
8255
8256 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8257 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8258 MD->setLazyBody(PB->second);
8259 }
8260 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008261
8262 // Do some cleanup.
8263 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8264 getContext().deduplicateMergedDefinitonsFor(ND);
8265 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008266}
8267
8268void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008269 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8270 return;
8271
Richard Smitha0ce9c42014-07-29 23:23:27 +00008272 // Trigger the import of the full definition of each class that had any
8273 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008274 // These updates may in turn find and diagnose some ODR failures, so take
8275 // ownership of the set first.
8276 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8277 PendingOdrMergeFailures.clear();
8278 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008279 Merge.first->buildLookup();
8280 Merge.first->decls_begin();
8281 Merge.first->bases_begin();
8282 Merge.first->vbases_begin();
8283 for (auto *RD : Merge.second) {
8284 RD->decls_begin();
8285 RD->bases_begin();
8286 RD->vbases_begin();
8287 }
8288 }
8289
8290 // For each declaration from a merged context, check that the canonical
8291 // definition of that context also contains a declaration of the same
8292 // entity.
8293 //
8294 // Caution: this loop does things that might invalidate iterators into
8295 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8296 while (!PendingOdrMergeChecks.empty()) {
8297 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8298
8299 // FIXME: Skip over implicit declarations for now. This matters for things
8300 // like implicitly-declared special member functions. This isn't entirely
8301 // correct; we can end up with multiple unmerged declarations of the same
8302 // implicit entity.
8303 if (D->isImplicit())
8304 continue;
8305
8306 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008307
8308 bool Found = false;
8309 const Decl *DCanon = D->getCanonicalDecl();
8310
Richard Smith01bdb7a2014-08-28 05:44:07 +00008311 for (auto RI : D->redecls()) {
8312 if (RI->getLexicalDeclContext() == CanonDef) {
8313 Found = true;
8314 break;
8315 }
8316 }
8317 if (Found)
8318 continue;
8319
Richard Smith0f4e2c42015-08-06 04:23:48 +00008320 // Quick check failed, time to do the slow thing. Note, we can't just
8321 // look up the name of D in CanonDef here, because the member that is
8322 // in CanonDef might not be found by name lookup (it might have been
8323 // replaced by a more recent declaration in the lookup table), and we
8324 // can't necessarily find it in the redeclaration chain because it might
8325 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008326 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008327 for (auto *CanonMember : CanonDef->decls()) {
8328 if (CanonMember->getCanonicalDecl() == DCanon) {
8329 // This can happen if the declaration is merely mergeable and not
8330 // actually redeclarable (we looked for redeclarations earlier).
8331 //
8332 // FIXME: We should be able to detect this more efficiently, without
8333 // pulling in all of the members of CanonDef.
8334 Found = true;
8335 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008336 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008337 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8338 if (ND->getDeclName() == D->getDeclName())
8339 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008340 }
8341
8342 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008343 // The AST doesn't like TagDecls becoming invalid after they've been
8344 // completed. We only really need to mark FieldDecls as invalid here.
8345 if (!isa<TagDecl>(D))
8346 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008347
8348 // Ensure we don't accidentally recursively enter deserialization while
8349 // we're producing our diagnostic.
8350 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008351
8352 std::string CanonDefModule =
8353 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8354 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8355 << D << getOwningModuleNameForDiagnostic(D)
8356 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8357
8358 if (Candidates.empty())
8359 Diag(cast<Decl>(CanonDef)->getLocation(),
8360 diag::note_module_odr_violation_no_possible_decls) << D;
8361 else {
8362 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8363 Diag(Candidates[I]->getLocation(),
8364 diag::note_module_odr_violation_possible_decl)
8365 << Candidates[I];
8366 }
8367
8368 DiagnosedOdrMergeFailures.insert(CanonDef);
8369 }
8370 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008371
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008372 if (OdrMergeFailures.empty())
8373 return;
8374
8375 // Ensure we don't accidentally recursively enter deserialization while
8376 // we're producing our diagnostics.
8377 Deserializing RecursionGuard(this);
8378
Richard Smithcd45dbc2014-04-19 03:48:30 +00008379 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008380 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008381 // If we've already pointed out a specific problem with this class, don't
8382 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008383 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008384 continue;
8385
8386 bool Diagnosed = false;
8387 for (auto *RD : Merge.second) {
8388 // Multiple different declarations got merged together; tell the user
8389 // where they came from.
8390 if (Merge.first != RD) {
8391 // FIXME: Walk the definition, figure out what's different,
8392 // and diagnose that.
8393 if (!Diagnosed) {
8394 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8395 Diag(Merge.first->getLocation(),
8396 diag::err_module_odr_violation_different_definitions)
8397 << Merge.first << Module.empty() << Module;
8398 Diagnosed = true;
8399 }
8400
8401 Diag(RD->getLocation(),
8402 diag::note_module_odr_violation_different_definitions)
8403 << getOwningModuleNameForDiagnostic(RD);
8404 }
8405 }
8406
8407 if (!Diagnosed) {
8408 // All definitions are updates to the same declaration. This happens if a
8409 // module instantiates the declaration of a class template specialization
8410 // and two or more other modules instantiate its definition.
8411 //
8412 // FIXME: Indicate which modules had instantiations of this definition.
8413 // FIXME: How can this even happen?
8414 Diag(Merge.first->getLocation(),
8415 diag::err_module_odr_violation_different_instantiations)
8416 << Merge.first;
8417 }
8418 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008419}
8420
Richard Smithce18a182015-07-14 00:26:00 +00008421void ASTReader::StartedDeserializing() {
8422 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8423 ReadTimer->startTimer();
8424}
8425
Guy Benyei11169dd2012-12-18 14:30:41 +00008426void ASTReader::FinishedDeserializing() {
8427 assert(NumCurrentElementsDeserializing &&
8428 "FinishedDeserializing not paired with StartedDeserializing");
8429 if (NumCurrentElementsDeserializing == 1) {
8430 // We decrease NumCurrentElementsDeserializing only after pending actions
8431 // are finished, to avoid recursively re-calling finishPendingActions().
8432 finishPendingActions();
8433 }
8434 --NumCurrentElementsDeserializing;
8435
Richard Smitha0ce9c42014-07-29 23:23:27 +00008436 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008437 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008438 while (!PendingExceptionSpecUpdates.empty()) {
8439 auto Updates = std::move(PendingExceptionSpecUpdates);
8440 PendingExceptionSpecUpdates.clear();
8441 for (auto Update : Updates) {
8442 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8443 SemaObj->UpdateExceptionSpec(Update.second,
8444 FPT->getExtProtoInfo().ExceptionSpec);
8445 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008446 }
8447
Richard Smithce18a182015-07-14 00:26:00 +00008448 if (ReadTimer)
8449 ReadTimer->stopTimer();
8450
Richard Smith0f4e2c42015-08-06 04:23:48 +00008451 diagnoseOdrViolations();
8452
Richard Smith04d05b52014-03-23 00:27:18 +00008453 // We are not in recursive loading, so it's safe to pass the "interesting"
8454 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008455 if (Consumer)
8456 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008457 }
8458}
8459
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008460void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008461 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8462 // Remove any fake results before adding any real ones.
8463 auto It = PendingFakeLookupResults.find(II);
8464 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008465 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008466 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008467 // FIXME: this works around module+PCH performance issue.
8468 // Rather than erase the result from the map, which is O(n), just clear
8469 // the vector of NamedDecls.
8470 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008471 }
8472 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008473
8474 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8475 SemaObj->TUScope->AddDecl(D);
8476 } else if (SemaObj->TUScope) {
8477 // Adding the decl to IdResolver may have failed because it was already in
8478 // (even though it was not added in scope). If it is already in, make sure
8479 // it gets in the scope as well.
8480 if (std::find(SemaObj->IdResolver.begin(Name),
8481 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8482 SemaObj->TUScope->AddDecl(D);
8483 }
8484}
8485
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008486ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008487 const PCHContainerReader &PCHContainerRdr,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008488 StringRef isysroot, bool DisableValidation,
8489 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008490 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Richard Smithce18a182015-07-14 00:26:00 +00008491 bool UseGlobalIndex,
8492 std::unique_ptr<llvm::Timer> ReadTimer)
Craig Toppera13603a2014-05-22 05:54:18 +00008493 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008494 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008495 FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008496 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
Adrian Prantlfb2398d2015-07-17 01:19:54 +00008497 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
Richard Smithce18a182015-07-14 00:26:00 +00008498 ReadTimer(std::move(ReadTimer)),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008499 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008500 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8501 AllowConfigurationMismatch(AllowConfigurationMismatch),
8502 ValidateSystemInputs(ValidateSystemInputs),
8503 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008504 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8505 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8506 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8507 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008508 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8509 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8510 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8511 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8512 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8513 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008514 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008515 SourceMgr.setExternalSLocEntrySource(this);
8516}
8517
8518ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008519 if (OwnsDeserializationListener)
8520 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00008521}