blob: 7242793be22025966ed35ec24860ce03fa0b24e0 [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}
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000141void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
142 First->visitModuleFile(Filename);
143 Second->visitModuleFile(Filename);
144}
Ben Langmuircb69b572014-03-07 06:40:32 +0000145bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000146 bool isSystem,
147 bool isOverridden) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000148 bool Continue = false;
149 if (First->needsInputFileVisitation() &&
150 (!isSystem || First->needsSystemInputFileVisitation()))
151 Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
152 if (Second->needsInputFileVisitation() &&
153 (!isSystem || Second->needsSystemInputFileVisitation()))
154 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
155 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000156}
157
Guy Benyei11169dd2012-12-18 14:30:41 +0000158//===----------------------------------------------------------------------===//
159// PCH validator implementation
160//===----------------------------------------------------------------------===//
161
162ASTReaderListener::~ASTReaderListener() {}
163
164/// \brief Compare the given set of language options against an existing set of
165/// language options.
166///
167/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000168/// \param AllowCompatibleDifferences If true, differences between compatible
169/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000170///
171/// \returns true if the languagae options mis-match, false otherwise.
172static bool checkLanguageOptions(const LangOptions &LangOpts,
173 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000174 DiagnosticsEngine *Diags,
175 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000176#define LANGOPT(Name, Bits, Default, Description) \
177 if (ExistingLangOpts.Name != LangOpts.Name) { \
178 if (Diags) \
179 Diags->Report(diag::err_pch_langopt_mismatch) \
180 << Description << LangOpts.Name << ExistingLangOpts.Name; \
181 return true; \
182 }
183
184#define VALUE_LANGOPT(Name, Bits, Default, Description) \
185 if (ExistingLangOpts.Name != LangOpts.Name) { \
186 if (Diags) \
187 Diags->Report(diag::err_pch_langopt_value_mismatch) \
188 << Description; \
189 return true; \
190 }
191
192#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
193 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
194 if (Diags) \
195 Diags->Report(diag::err_pch_langopt_value_mismatch) \
196 << Description; \
197 return true; \
198 }
199
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000200#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
201 if (!AllowCompatibleDifferences) \
202 LANGOPT(Name, Bits, Default, Description)
203
204#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
205 if (!AllowCompatibleDifferences) \
206 ENUM_LANGOPT(Name, Bits, Default, Description)
207
Guy Benyei11169dd2012-12-18 14:30:41 +0000208#define BENIGN_LANGOPT(Name, Bits, Default, Description)
209#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
210#include "clang/Basic/LangOptions.def"
211
212 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
213 if (Diags)
214 Diags->Report(diag::err_pch_langopt_value_mismatch)
215 << "target Objective-C runtime";
216 return true;
217 }
218
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000219 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
220 LangOpts.CommentOpts.BlockCommandNames) {
221 if (Diags)
222 Diags->Report(diag::err_pch_langopt_value_mismatch)
223 << "block command names";
224 return true;
225 }
226
Guy Benyei11169dd2012-12-18 14:30:41 +0000227 return false;
228}
229
230/// \brief Compare the given set of target options against an existing set of
231/// target options.
232///
233/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
234///
235/// \returns true if the target options mis-match, false otherwise.
236static bool checkTargetOptions(const TargetOptions &TargetOpts,
237 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000238 DiagnosticsEngine *Diags,
239 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000240#define CHECK_TARGET_OPT(Field, Name) \
241 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
242 if (Diags) \
243 Diags->Report(diag::err_pch_targetopt_mismatch) \
244 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
245 return true; \
246 }
247
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000248 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000249 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000250 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000251
252 // We can tolerate different CPUs in many cases, notably when one CPU
253 // supports a strict superset of another. When allowing compatible
254 // differences skip this check.
255 if (!AllowCompatibleDifferences)
256 CHECK_TARGET_OPT(CPU, "target CPU");
257
Guy Benyei11169dd2012-12-18 14:30:41 +0000258#undef CHECK_TARGET_OPT
259
260 // Compare feature sets.
261 SmallVector<StringRef, 4> ExistingFeatures(
262 ExistingTargetOpts.FeaturesAsWritten.begin(),
263 ExistingTargetOpts.FeaturesAsWritten.end());
264 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
265 TargetOpts.FeaturesAsWritten.end());
266 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
267 std::sort(ReadFeatures.begin(), ReadFeatures.end());
268
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000269 // We compute the set difference in both directions explicitly so that we can
270 // diagnose the differences differently.
271 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
272 std::set_difference(
273 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
274 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
275 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
276 ExistingFeatures.begin(), ExistingFeatures.end(),
277 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000278
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000279 // If we are allowing compatible differences and the read feature set is
280 // a strict subset of the existing feature set, there is nothing to diagnose.
281 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
282 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000283
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000284 if (Diags) {
285 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000286 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000287 << /* is-existing-feature */ false << Feature;
288 for (StringRef Feature : UnmatchedExistingFeatures)
289 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
290 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000291 }
292
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000293 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000294}
295
296bool
297PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000298 bool Complain,
299 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000300 const LangOptions &ExistingLangOpts = PP.getLangOpts();
301 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000302 Complain ? &Reader.Diags : nullptr,
303 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000304}
305
306bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000307 bool Complain,
308 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000309 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
310 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000311 Complain ? &Reader.Diags : nullptr,
312 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000313}
314
315namespace {
316 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
317 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000318 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
319 DeclsMap;
Guy Benyei11169dd2012-12-18 14:30:41 +0000320}
321
Ben Langmuirb92de022014-04-29 16:25:26 +0000322static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
323 DiagnosticsEngine &Diags,
324 bool Complain) {
325 typedef DiagnosticsEngine::Level Level;
326
327 // Check current mappings for new -Werror mappings, and the stored mappings
328 // for cases that were explicitly mapped to *not* be errors that are now
329 // errors because of options like -Werror.
330 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
331
332 for (DiagnosticsEngine *MappingSource : MappingSources) {
333 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
334 diag::kind DiagID = DiagIDMappingPair.first;
335 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
336 if (CurLevel < DiagnosticsEngine::Error)
337 continue; // not significant
338 Level StoredLevel =
339 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
340 if (StoredLevel < DiagnosticsEngine::Error) {
341 if (Complain)
342 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
343 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
344 return true;
345 }
346 }
347 }
348
349 return false;
350}
351
Alp Tokerac4e8e52014-06-22 21:58:33 +0000352static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
353 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
354 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
355 return true;
356 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000357}
358
359static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
360 DiagnosticsEngine &Diags,
361 bool IsSystem, bool Complain) {
362 // Top-level options
363 if (IsSystem) {
364 if (Diags.getSuppressSystemWarnings())
365 return false;
366 // If -Wsystem-headers was not enabled before, be conservative
367 if (StoredDiags.getSuppressSystemWarnings()) {
368 if (Complain)
369 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
370 return true;
371 }
372 }
373
374 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
375 if (Complain)
376 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
377 return true;
378 }
379
380 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
381 !StoredDiags.getEnableAllWarnings()) {
382 if (Complain)
383 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
384 return true;
385 }
386
387 if (isExtHandlingFromDiagsError(Diags) &&
388 !isExtHandlingFromDiagsError(StoredDiags)) {
389 if (Complain)
390 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
391 return true;
392 }
393
394 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
395}
396
397bool PCHValidator::ReadDiagnosticOptions(
398 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
399 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
400 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
401 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000402 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000403 // This should never fail, because we would have processed these options
404 // before writing them to an ASTFile.
405 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
406
407 ModuleManager &ModuleMgr = Reader.getModuleManager();
408 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
409
410 // If the original import came from a file explicitly generated by the user,
411 // don't check the diagnostic mappings.
412 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000413 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000414 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
415 // the transitive closure of its imports, since unrelated modules cannot be
416 // imported until after this module finishes validation.
417 ModuleFile *TopImport = *ModuleMgr.rbegin();
418 while (!TopImport->ImportedBy.empty())
419 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000420 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000421 return false;
422
423 StringRef ModuleName = TopImport->ModuleName;
424 assert(!ModuleName.empty() && "diagnostic options read before module name");
425
426 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
427 assert(M && "missing module");
428
429 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
430 // contains the union of their flags.
431 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
432}
433
Guy Benyei11169dd2012-12-18 14:30:41 +0000434/// \brief Collect the macro definitions provided by the given preprocessor
435/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000436static void
437collectMacroDefinitions(const PreprocessorOptions &PPOpts,
438 MacroDefinitionsMap &Macros,
439 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000440 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
441 StringRef Macro = PPOpts.Macros[I].first;
442 bool IsUndef = PPOpts.Macros[I].second;
443
444 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
445 StringRef MacroName = MacroPair.first;
446 StringRef MacroBody = MacroPair.second;
447
448 // For an #undef'd macro, we only care about the name.
449 if (IsUndef) {
450 if (MacroNames && !Macros.count(MacroName))
451 MacroNames->push_back(MacroName);
452
453 Macros[MacroName] = std::make_pair("", true);
454 continue;
455 }
456
457 // For a #define'd macro, figure out the actual definition.
458 if (MacroName.size() == Macro.size())
459 MacroBody = "1";
460 else {
461 // Note: GCC drops anything following an end-of-line character.
462 StringRef::size_type End = MacroBody.find_first_of("\n\r");
463 MacroBody = MacroBody.substr(0, End);
464 }
465
466 if (MacroNames && !Macros.count(MacroName))
467 MacroNames->push_back(MacroName);
468 Macros[MacroName] = std::make_pair(MacroBody, false);
469 }
470}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000471
Guy Benyei11169dd2012-12-18 14:30:41 +0000472/// \brief Check the preprocessor options deserialized from the control block
473/// against the preprocessor options in an existing preprocessor.
474///
475/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
476static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
477 const PreprocessorOptions &ExistingPPOpts,
478 DiagnosticsEngine *Diags,
479 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000480 std::string &SuggestedPredefines,
481 const LangOptions &LangOpts) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000482 // Check macro definitions.
483 MacroDefinitionsMap ASTFileMacros;
484 collectMacroDefinitions(PPOpts, ASTFileMacros);
485 MacroDefinitionsMap ExistingMacros;
486 SmallVector<StringRef, 4> ExistingMacroNames;
487 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
488
489 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
490 // Dig out the macro definition in the existing preprocessor options.
491 StringRef MacroName = ExistingMacroNames[I];
492 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
493
494 // Check whether we know anything about this macro name or not.
495 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
496 = ASTFileMacros.find(MacroName);
497 if (Known == ASTFileMacros.end()) {
498 // FIXME: Check whether this identifier was referenced anywhere in the
499 // AST file. If so, we should reject the AST file. Unfortunately, this
500 // information isn't in the control block. What shall we do about it?
501
502 if (Existing.second) {
503 SuggestedPredefines += "#undef ";
504 SuggestedPredefines += MacroName.str();
505 SuggestedPredefines += '\n';
506 } else {
507 SuggestedPredefines += "#define ";
508 SuggestedPredefines += MacroName.str();
509 SuggestedPredefines += ' ';
510 SuggestedPredefines += Existing.first.str();
511 SuggestedPredefines += '\n';
512 }
513 continue;
514 }
515
516 // If the macro was defined in one but undef'd in the other, we have a
517 // conflict.
518 if (Existing.second != Known->second.second) {
519 if (Diags) {
520 Diags->Report(diag::err_pch_macro_def_undef)
521 << MacroName << Known->second.second;
522 }
523 return true;
524 }
525
526 // If the macro was #undef'd in both, or if the macro bodies are identical,
527 // it's fine.
528 if (Existing.second || Existing.first == Known->second.first)
529 continue;
530
531 // The macro bodies differ; complain.
532 if (Diags) {
533 Diags->Report(diag::err_pch_macro_def_conflict)
534 << MacroName << Known->second.first << Existing.first;
535 }
536 return true;
537 }
538
539 // Check whether we're using predefines.
540 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
541 if (Diags) {
542 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
543 }
544 return true;
545 }
546
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000547 // Detailed record is important since it is used for the module cache hash.
548 if (LangOpts.Modules &&
549 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
550 if (Diags) {
551 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
552 }
553 return true;
554 }
555
Guy Benyei11169dd2012-12-18 14:30:41 +0000556 // Compute the #include and #include_macros lines we need.
557 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
558 StringRef File = ExistingPPOpts.Includes[I];
559 if (File == ExistingPPOpts.ImplicitPCHInclude)
560 continue;
561
562 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
563 != PPOpts.Includes.end())
564 continue;
565
566 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000567 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000568 SuggestedPredefines += "\"\n";
569 }
570
571 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
572 StringRef File = ExistingPPOpts.MacroIncludes[I];
573 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
574 File)
575 != PPOpts.MacroIncludes.end())
576 continue;
577
578 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000579 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000580 SuggestedPredefines += "\"\n##\n";
581 }
582
583 return false;
584}
585
586bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
587 bool Complain,
588 std::string &SuggestedPredefines) {
589 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
590
591 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000592 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000593 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000594 SuggestedPredefines,
595 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000596}
597
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000598/// Check the header search options deserialized from the control block
599/// against the header search options in an existing preprocessor.
600///
601/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
602static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
603 StringRef SpecificModuleCachePath,
604 StringRef ExistingModuleCachePath,
605 DiagnosticsEngine *Diags,
606 const LangOptions &LangOpts) {
607 if (LangOpts.Modules) {
608 if (SpecificModuleCachePath != ExistingModuleCachePath) {
609 if (Diags)
610 Diags->Report(diag::err_pch_modulecache_mismatch)
611 << SpecificModuleCachePath << ExistingModuleCachePath;
612 return true;
613 }
614 }
615
616 return false;
617}
618
619bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
620 StringRef SpecificModuleCachePath,
621 bool Complain) {
622 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
623 PP.getHeaderSearchInfo().getModuleCachePath(),
624 Complain ? &Reader.Diags : nullptr,
625 PP.getLangOpts());
626}
627
Guy Benyei11169dd2012-12-18 14:30:41 +0000628void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
629 PP.setCounterValue(Value);
630}
631
632//===----------------------------------------------------------------------===//
633// AST reader implementation
634//===----------------------------------------------------------------------===//
635
Nico Weber824285e2014-05-08 04:26:47 +0000636void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
637 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000639 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000640}
641
642
643
644unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
645 return serialization::ComputeHash(Sel);
646}
647
648
649std::pair<unsigned, unsigned>
650ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000651 using namespace llvm::support;
652 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
653 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000654 return std::make_pair(KeyLen, DataLen);
655}
656
657ASTSelectorLookupTrait::internal_key_type
658ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000659 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000660 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000661 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
662 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
663 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 if (N == 0)
665 return SelTable.getNullarySelector(FirstII);
666 else if (N == 1)
667 return SelTable.getUnarySelector(FirstII);
668
669 SmallVector<IdentifierInfo *, 16> Args;
670 Args.push_back(FirstII);
671 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000672 Args.push_back(Reader.getLocalIdentifier(
673 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000674
675 return SelTable.getSelector(N, Args.data());
676}
677
678ASTSelectorLookupTrait::data_type
679ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
680 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000681 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000682
683 data_type Result;
684
Justin Bogner57ba0b22014-03-28 22:03:24 +0000685 Result.ID = Reader.getGlobalSelectorID(
686 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000687 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
688 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
689 Result.InstanceBits = FullInstanceBits & 0x3;
690 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
691 Result.FactoryBits = FullFactoryBits & 0x3;
692 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
693 unsigned NumInstanceMethods = FullInstanceBits >> 3;
694 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000695
696 // Load instance methods
697 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000698 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
699 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000700 Result.Instance.push_back(Method);
701 }
702
703 // Load factory methods
704 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000705 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
706 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 Result.Factory.push_back(Method);
708 }
709
710 return Result;
711}
712
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000713unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
714 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000715}
716
717std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000718ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000719 using namespace llvm::support;
720 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
721 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 return std::make_pair(KeyLen, DataLen);
723}
724
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000725ASTIdentifierLookupTraitBase::internal_key_type
726ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000728 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000729}
730
Douglas Gregordcf25082013-02-11 18:16:18 +0000731/// \brief Whether the given identifier is "interesting".
732static bool isInterestingIdentifier(IdentifierInfo &II) {
733 return II.isPoisoned() ||
734 II.isExtensionToken() ||
735 II.getObjCOrBuiltinID() ||
736 II.hasRevertedTokenIDToIdentifier() ||
737 II.hadMacroDefinition() ||
738 II.getFETokenInfo<void>();
739}
740
Guy Benyei11169dd2012-12-18 14:30:41 +0000741IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
742 const unsigned char* d,
743 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000744 using namespace llvm::support;
745 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000746 bool IsInteresting = RawID & 0x01;
747
748 // Wipe out the "is interesting" bit.
749 RawID = RawID >> 1;
750
751 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
752 if (!IsInteresting) {
753 // For uninteresting identifiers, just build the IdentifierInfo
754 // and associate it with the persistent ID.
755 IdentifierInfo *II = KnownII;
756 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000757 II = &Reader.getIdentifierTable().getOwn(k);
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 KnownII = II;
759 }
760 Reader.SetIdentifierInfo(ID, II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000761 if (!II->isFromAST()) {
762 bool WasInteresting = isInterestingIdentifier(*II);
763 II->setIsFromAST();
764 if (WasInteresting)
765 II->setChangedSinceDeserialization();
766 }
767 Reader.markIdentifierUpToDate(II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000768 return II;
769 }
770
Justin Bogner57ba0b22014-03-28 22:03:24 +0000771 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
772 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 bool CPlusPlusOperatorKeyword = Bits & 0x01;
774 Bits >>= 1;
775 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
776 Bits >>= 1;
777 bool Poisoned = Bits & 0x01;
778 Bits >>= 1;
779 bool ExtensionToken = Bits & 0x01;
780 Bits >>= 1;
781 bool hadMacroDefinition = Bits & 0x01;
782 Bits >>= 1;
783
784 assert(Bits == 0 && "Extra bits in the identifier?");
785 DataLen -= 8;
786
787 // Build the IdentifierInfo itself and link the identifier ID with
788 // the new IdentifierInfo.
789 IdentifierInfo *II = KnownII;
790 if (!II) {
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000791 II = &Reader.getIdentifierTable().getOwn(StringRef(k));
Guy Benyei11169dd2012-12-18 14:30:41 +0000792 KnownII = II;
793 }
794 Reader.markIdentifierUpToDate(II);
Douglas Gregordcf25082013-02-11 18:16:18 +0000795 if (!II->isFromAST()) {
796 bool WasInteresting = isInterestingIdentifier(*II);
797 II->setIsFromAST();
798 if (WasInteresting)
799 II->setChangedSinceDeserialization();
800 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000801
802 // Set or check the various bits in the IdentifierInfo structure.
803 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000804 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 II->RevertTokenIDToIdentifier();
806 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
807 assert(II->isExtensionToken() == ExtensionToken &&
808 "Incorrect extension token flag");
809 (void)ExtensionToken;
810 if (Poisoned)
811 II->setIsPoisoned(true);
812 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
813 "Incorrect C++ operator keyword flag");
814 (void)CPlusPlusOperatorKeyword;
815
816 // If this identifier is a macro, deserialize the macro
817 // definition.
818 if (hadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000819 uint32_t MacroDirectivesOffset =
820 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000821 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000822
Richard Smithd7329392015-04-21 21:46:32 +0000823 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 }
825
826 Reader.SetIdentifierInfo(ID, II);
827
828 // Read all of the declarations visible at global scope with this
829 // name.
830 if (DataLen > 0) {
831 SmallVector<uint32_t, 4> DeclIDs;
832 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000833 DeclIDs.push_back(Reader.getGlobalDeclID(
834 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 Reader.SetGloballyVisibleDecls(II, DeclIDs);
836 }
837
838 return II;
839}
840
841unsigned
842ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
843 llvm::FoldingSetNodeID ID;
844 ID.AddInteger(Key.Kind);
845
846 switch (Key.Kind) {
847 case DeclarationName::Identifier:
848 case DeclarationName::CXXLiteralOperatorName:
849 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
850 break;
851 case DeclarationName::ObjCZeroArgSelector:
852 case DeclarationName::ObjCOneArgSelector:
853 case DeclarationName::ObjCMultiArgSelector:
854 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
855 break;
856 case DeclarationName::CXXOperatorName:
857 ID.AddInteger((OverloadedOperatorKind)Key.Data);
858 break;
859 case DeclarationName::CXXConstructorName:
860 case DeclarationName::CXXDestructorName:
861 case DeclarationName::CXXConversionFunctionName:
862 case DeclarationName::CXXUsingDirective:
863 break;
864 }
865
866 return ID.ComputeHash();
867}
868
869ASTDeclContextNameLookupTrait::internal_key_type
870ASTDeclContextNameLookupTrait::GetInternalKey(
871 const external_key_type& Name) const {
872 DeclNameKey Key;
873 Key.Kind = Name.getNameKind();
874 switch (Name.getNameKind()) {
875 case DeclarationName::Identifier:
876 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
877 break;
878 case DeclarationName::ObjCZeroArgSelector:
879 case DeclarationName::ObjCOneArgSelector:
880 case DeclarationName::ObjCMultiArgSelector:
881 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
882 break;
883 case DeclarationName::CXXOperatorName:
884 Key.Data = Name.getCXXOverloadedOperator();
885 break;
886 case DeclarationName::CXXLiteralOperatorName:
887 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
888 break;
889 case DeclarationName::CXXConstructorName:
890 case DeclarationName::CXXDestructorName:
891 case DeclarationName::CXXConversionFunctionName:
892 case DeclarationName::CXXUsingDirective:
893 Key.Data = 0;
894 break;
895 }
896
897 return Key;
898}
899
900std::pair<unsigned, unsigned>
901ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000902 using namespace llvm::support;
903 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
904 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000905 return std::make_pair(KeyLen, DataLen);
906}
907
908ASTDeclContextNameLookupTrait::internal_key_type
909ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000910 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000911
912 DeclNameKey Key;
913 Key.Kind = (DeclarationName::NameKind)*d++;
914 switch (Key.Kind) {
915 case DeclarationName::Identifier:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000916 Key.Data = (uint64_t)Reader.getLocalIdentifier(
917 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000918 break;
919 case DeclarationName::ObjCZeroArgSelector:
920 case DeclarationName::ObjCOneArgSelector:
921 case DeclarationName::ObjCMultiArgSelector:
922 Key.Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +0000923 (uint64_t)Reader.getLocalSelector(
924 F, endian::readNext<uint32_t, little, unaligned>(
925 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000926 break;
927 case DeclarationName::CXXOperatorName:
928 Key.Data = *d++; // OverloadedOperatorKind
929 break;
930 case DeclarationName::CXXLiteralOperatorName:
Justin Bogner57ba0b22014-03-28 22:03:24 +0000931 Key.Data = (uint64_t)Reader.getLocalIdentifier(
932 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 break;
934 case DeclarationName::CXXConstructorName:
935 case DeclarationName::CXXDestructorName:
936 case DeclarationName::CXXConversionFunctionName:
937 case DeclarationName::CXXUsingDirective:
938 Key.Data = 0;
939 break;
940 }
941
942 return Key;
943}
944
945ASTDeclContextNameLookupTrait::data_type
946ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
947 const unsigned char* d,
948 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000949 using namespace llvm::support;
950 unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
Argyrios Kyrtzidisc57e5032013-01-11 22:29:49 +0000951 LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
952 const_cast<unsigned char *>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 return std::make_pair(Start, Start + NumDecls);
954}
955
956bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000957 BitstreamCursor &Cursor,
Guy Benyei11169dd2012-12-18 14:30:41 +0000958 const std::pair<uint64_t, uint64_t> &Offsets,
959 DeclContextInfo &Info) {
960 SavedStreamPosition SavedPosition(Cursor);
961 // First the lexical decls.
962 if (Offsets.first != 0) {
963 Cursor.JumpToBit(Offsets.first);
964
965 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000966 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000968 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 if (RecCode != DECL_CONTEXT_LEXICAL) {
970 Error("Expected lexical block");
971 return true;
972 }
973
Chris Lattner0e6c9402013-01-20 02:38:54 +0000974 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
975 Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 }
977
978 // Now the lookup table.
979 if (Offsets.second != 0) {
980 Cursor.JumpToBit(Offsets.second);
981
982 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +0000983 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +0000985 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 if (RecCode != DECL_CONTEXT_VISIBLE) {
987 Error("Expected visible lookup table block");
988 return true;
989 }
Justin Bognerda4e6502014-04-14 16:34:29 +0000990 Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
991 (const unsigned char *)Blob.data() + Record[0],
992 (const unsigned char *)Blob.data() + sizeof(uint32_t),
993 (const unsigned char *)Blob.data(),
994 ASTDeclContextNameLookupTrait(*this, M));
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 }
996
997 return false;
998}
999
1000void ASTReader::Error(StringRef Msg) {
1001 Error(diag::err_fe_pch_malformed, Msg);
Douglas Gregor940e8052013-05-10 22:15:13 +00001002 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1003 Diag(diag::note_module_cache_path)
1004 << PP.getHeaderSearchInfo().getModuleCachePath();
1005 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001006}
1007
1008void ASTReader::Error(unsigned DiagID,
1009 StringRef Arg1, StringRef Arg2) {
1010 if (Diags.isDiagnosticInFlight())
1011 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1012 else
1013 Diag(DiagID) << Arg1 << Arg2;
1014}
1015
1016//===----------------------------------------------------------------------===//
1017// Source Manager Deserialization
1018//===----------------------------------------------------------------------===//
1019
1020/// \brief Read the line table in the source manager block.
1021/// \returns true if there was an error.
1022bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001023 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001024 unsigned Idx = 0;
1025 LineTableInfo &LineTable = SourceMgr.getLineTable();
1026
1027 // Parse the file names
1028 std::map<int, int> FileIDs;
1029 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1030 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001031 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1033 }
1034
1035 // Parse the line entries
1036 std::vector<LineEntry> Entries;
1037 while (Idx < Record.size()) {
1038 int FID = Record[Idx++];
1039 assert(FID >= 0 && "Serialized line entries for non-local file.");
1040 // Remap FileID from 1-based old view.
1041 FID += F.SLocEntryBaseID - 1;
1042
1043 // Extract the line entries
1044 unsigned NumEntries = Record[Idx++];
1045 assert(NumEntries && "Numentries is 00000");
1046 Entries.clear();
1047 Entries.reserve(NumEntries);
1048 for (unsigned I = 0; I != NumEntries; ++I) {
1049 unsigned FileOffset = Record[Idx++];
1050 unsigned LineNo = Record[Idx++];
1051 int FilenameID = FileIDs[Record[Idx++]];
1052 SrcMgr::CharacteristicKind FileKind
1053 = (SrcMgr::CharacteristicKind)Record[Idx++];
1054 unsigned IncludeOffset = Record[Idx++];
1055 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1056 FileKind, IncludeOffset));
1057 }
1058 LineTable.AddEntry(FileID::get(FID), Entries);
1059 }
1060
1061 return false;
1062}
1063
1064/// \brief Read a source manager block
1065bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1066 using namespace SrcMgr;
1067
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001068 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001069
1070 // Set the source-location entry cursor to the current position in
1071 // the stream. This cursor will be used to read the contents of the
1072 // source manager block initially, and then lazily read
1073 // source-location entries as needed.
1074 SLocEntryCursor = F.Stream;
1075
1076 // The stream itself is going to skip over the source manager block.
1077 if (F.Stream.SkipBlock()) {
1078 Error("malformed block record in AST file");
1079 return true;
1080 }
1081
1082 // Enter the source manager block.
1083 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1084 Error("malformed source manager block record in AST file");
1085 return true;
1086 }
1087
1088 RecordData Record;
1089 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001090 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1091
1092 switch (E.Kind) {
1093 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1094 case llvm::BitstreamEntry::Error:
1095 Error("malformed block record in AST file");
1096 return true;
1097 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001099 case llvm::BitstreamEntry::Record:
1100 // The interesting case.
1101 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001103
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001106 StringRef Blob;
1107 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 default: // Default behavior: ignore.
1109 break;
1110
1111 case SM_SLOC_FILE_ENTRY:
1112 case SM_SLOC_BUFFER_ENTRY:
1113 case SM_SLOC_EXPANSION_ENTRY:
1114 // Once we hit one of the source location entries, we're done.
1115 return false;
1116 }
1117 }
1118}
1119
1120/// \brief If a header file is not found at the path that we expect it to be
1121/// and the PCH file was moved from its original location, try to resolve the
1122/// file by assuming that header+PCH were moved together and the header is in
1123/// the same place relative to the PCH.
1124static std::string
1125resolveFileRelativeToOriginalDir(const std::string &Filename,
1126 const std::string &OriginalDir,
1127 const std::string &CurrDir) {
1128 assert(OriginalDir != CurrDir &&
1129 "No point trying to resolve the file if the PCH dir didn't change");
1130 using namespace llvm::sys;
1131 SmallString<128> filePath(Filename);
1132 fs::make_absolute(filePath);
1133 assert(path::is_absolute(OriginalDir));
1134 SmallString<128> currPCHPath(CurrDir);
1135
1136 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1137 fileDirE = path::end(path::parent_path(filePath));
1138 path::const_iterator origDirI = path::begin(OriginalDir),
1139 origDirE = path::end(OriginalDir);
1140 // Skip the common path components from filePath and OriginalDir.
1141 while (fileDirI != fileDirE && origDirI != origDirE &&
1142 *fileDirI == *origDirI) {
1143 ++fileDirI;
1144 ++origDirI;
1145 }
1146 for (; origDirI != origDirE; ++origDirI)
1147 path::append(currPCHPath, "..");
1148 path::append(currPCHPath, fileDirI, fileDirE);
1149 path::append(currPCHPath, path::filename(Filename));
1150 return currPCHPath.str();
1151}
1152
1153bool ASTReader::ReadSLocEntry(int ID) {
1154 if (ID == 0)
1155 return false;
1156
1157 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1158 Error("source location entry ID out-of-range for AST file");
1159 return true;
1160 }
1161
1162 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1163 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001164 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 unsigned BaseOffset = F->SLocEntryBaseOffset;
1166
1167 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001168 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1169 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 Error("incorrectly-formatted source location entry in AST file");
1171 return true;
1172 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001173
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001175 StringRef Blob;
1176 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 default:
1178 Error("incorrectly-formatted source location entry in AST file");
1179 return true;
1180
1181 case SM_SLOC_FILE_ENTRY: {
1182 // We will detect whether a file changed and return 'Failure' for it, but
1183 // we will also try to fail gracefully by setting up the SLocEntry.
1184 unsigned InputID = Record[4];
1185 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001186 const FileEntry *File = IF.getFile();
1187 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001188
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001189 // Note that we only check if a File was returned. If it was out-of-date
1190 // we have complained but we will continue creating a FileID to recover
1191 // gracefully.
1192 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001193 return true;
1194
1195 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1196 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1197 // This is the module's main file.
1198 IncludeLoc = getImportLocation(F);
1199 }
1200 SrcMgr::CharacteristicKind
1201 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1202 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1203 ID, BaseOffset + Record[0]);
1204 SrcMgr::FileInfo &FileInfo =
1205 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1206 FileInfo.NumCreatedFIDs = Record[5];
1207 if (Record[3])
1208 FileInfo.setHasLineDirectives();
1209
1210 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1211 unsigned NumFileDecls = Record[7];
1212 if (NumFileDecls) {
1213 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1214 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1215 NumFileDecls));
1216 }
1217
1218 const SrcMgr::ContentCache *ContentCache
1219 = SourceMgr.getOrCreateContentCache(File,
1220 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1221 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1222 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1223 unsigned Code = SLocEntryCursor.ReadCode();
1224 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001225 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001226
1227 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1228 Error("AST record has invalid code");
1229 return true;
1230 }
1231
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001232 std::unique_ptr<llvm::MemoryBuffer> Buffer
Chris Lattner0e6c9402013-01-20 02:38:54 +00001233 = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
David Blaikie49cc3182014-08-27 20:54:45 +00001234 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 }
1236
1237 break;
1238 }
1239
1240 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001241 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001242 unsigned Offset = Record[0];
1243 SrcMgr::CharacteristicKind
1244 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1245 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Richard Smithe842a472014-10-22 02:05:46 +00001246 if (IncludeLoc.isInvalid() &&
1247 (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001248 IncludeLoc = getImportLocation(F);
1249 }
1250 unsigned Code = SLocEntryCursor.ReadCode();
1251 Record.clear();
1252 unsigned RecCode
Chris Lattner0e6c9402013-01-20 02:38:54 +00001253 = SLocEntryCursor.readRecord(Code, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00001254
1255 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1256 Error("AST record has invalid code");
1257 return true;
1258 }
1259
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001260 std::unique_ptr<llvm::MemoryBuffer> Buffer =
1261 llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
David Blaikie50a5f972014-08-29 07:59:55 +00001262 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001263 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001264 break;
1265 }
1266
1267 case SM_SLOC_EXPANSION_ENTRY: {
1268 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1269 SourceMgr.createExpansionLoc(SpellingLoc,
1270 ReadSourceLocation(*F, Record[2]),
1271 ReadSourceLocation(*F, Record[3]),
1272 Record[4],
1273 ID,
1274 BaseOffset + Record[0]);
1275 break;
1276 }
1277 }
1278
1279 return false;
1280}
1281
1282std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1283 if (ID == 0)
1284 return std::make_pair(SourceLocation(), "");
1285
1286 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1287 Error("source location entry ID out-of-range for AST file");
1288 return std::make_pair(SourceLocation(), "");
1289 }
1290
1291 // Find which module file this entry lands in.
1292 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Richard Smithe842a472014-10-22 02:05:46 +00001293 if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 return std::make_pair(SourceLocation(), "");
1295
1296 // FIXME: Can we map this down to a particular submodule? That would be
1297 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001298 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001299}
1300
1301/// \brief Find the location where the module F is imported.
1302SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1303 if (F->ImportLoc.isValid())
1304 return F->ImportLoc;
1305
1306 // Otherwise we have a PCH. It's considered to be "imported" at the first
1307 // location of its includer.
1308 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001309 // Main file is the importer.
1310 assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1311 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 return F->ImportedBy[0]->FirstLoc;
1314}
1315
1316/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1317/// specified cursor. Read the abbreviations that are at the top of the block
1318/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001319bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001320 if (Cursor.EnterSubBlock(BlockID)) {
1321 Error("malformed block record in AST file");
1322 return Failure;
1323 }
1324
1325 while (true) {
1326 uint64_t Offset = Cursor.GetCurrentBitNo();
1327 unsigned Code = Cursor.ReadCode();
1328
1329 // We expect all abbrevs to be at the start of the block.
1330 if (Code != llvm::bitc::DEFINE_ABBREV) {
1331 Cursor.JumpToBit(Offset);
1332 return false;
1333 }
1334 Cursor.ReadAbbrevRecord();
1335 }
1336}
1337
Richard Smithe40f2ba2013-08-07 21:41:30 +00001338Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001339 unsigned &Idx) {
1340 Token Tok;
1341 Tok.startToken();
1342 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1343 Tok.setLength(Record[Idx++]);
1344 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1345 Tok.setIdentifierInfo(II);
1346 Tok.setKind((tok::TokenKind)Record[Idx++]);
1347 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1348 return Tok;
1349}
1350
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001351MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001352 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001353
1354 // Keep track of where we are in the stream, then jump back there
1355 // after reading this macro.
1356 SavedStreamPosition SavedPosition(Stream);
1357
1358 Stream.JumpToBit(Offset);
1359 RecordData Record;
1360 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001361 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001362
Guy Benyei11169dd2012-12-18 14:30:41 +00001363 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001364 // Advance to the next record, but if we get to the end of the block, don't
1365 // pop it (removing all the abbreviations from the cursor) since we want to
1366 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001367 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001368 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1369
1370 switch (Entry.Kind) {
1371 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1372 case llvm::BitstreamEntry::Error:
1373 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001374 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001375 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001376 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001377 case llvm::BitstreamEntry::Record:
1378 // The interesting case.
1379 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 }
1381
1382 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 Record.clear();
1384 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001385 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001387 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001388 case PP_MACRO_DIRECTIVE_HISTORY:
1389 return Macro;
1390
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 case PP_MACRO_OBJECT_LIKE:
1392 case PP_MACRO_FUNCTION_LIKE: {
1393 // If we already have a macro, that means that we've hit the end
1394 // of the definition of the macro we were looking for. We're
1395 // done.
1396 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001397 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001398
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001399 unsigned NextIndex = 1; // Skip identifier ID.
1400 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001401 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001402 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001403 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001405 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001406
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1408 // Decode function-like macro info.
1409 bool isC99VarArgs = Record[NextIndex++];
1410 bool isGNUVarArgs = Record[NextIndex++];
1411 bool hasCommaPasting = Record[NextIndex++];
1412 MacroArgs.clear();
1413 unsigned NumArgs = Record[NextIndex++];
1414 for (unsigned i = 0; i != NumArgs; ++i)
1415 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1416
1417 // Install function-like macro info.
1418 MI->setIsFunctionLike();
1419 if (isC99VarArgs) MI->setIsC99Varargs();
1420 if (isGNUVarArgs) MI->setIsGNUVarargs();
1421 if (hasCommaPasting) MI->setHasCommaPasting();
1422 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1423 PP.getPreprocessorAllocator());
1424 }
1425
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 // Remember that we saw this macro last so that we add the tokens that
1427 // form its body to it.
1428 Macro = MI;
1429
1430 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1431 Record[NextIndex]) {
1432 // We have a macro definition. Register the association
1433 PreprocessedEntityID
1434 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1435 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001436 PreprocessingRecord::PPEntityID PPID =
1437 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1438 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1439 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001440 if (PPDef)
1441 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001442 }
1443
1444 ++NumMacrosRead;
1445 break;
1446 }
1447
1448 case PP_TOKEN: {
1449 // If we see a TOKEN before a PP_MACRO_*, then the file is
1450 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001451 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001452
John McCallf413f5e2013-05-03 00:10:13 +00001453 unsigned Idx = 0;
1454 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 Macro->AddTokenToBody(Tok);
1456 break;
1457 }
1458 }
1459 }
1460}
1461
1462PreprocessedEntityID
1463ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1464 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1465 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1466 assert(I != M.PreprocessedEntityRemap.end()
1467 && "Invalid index into preprocessed entity index remap");
1468
1469 return LocalID + I->second;
1470}
1471
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001472unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1473 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001474}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001475
Guy Benyei11169dd2012-12-18 14:30:41 +00001476HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001477HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1478 internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
Richard Smith7ed1bc92014-12-05 22:42:13 +00001479 FE->getName(), /*Imported*/false };
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001480 return ikey;
1481}
Guy Benyei11169dd2012-12-18 14:30:41 +00001482
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001483bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1484 if (a.Size != b.Size || a.ModTime != b.ModTime)
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 return false;
1486
Richard Smith7ed1bc92014-12-05 22:42:13 +00001487 if (llvm::sys::path::is_absolute(a.Filename) &&
1488 strcmp(a.Filename, b.Filename) == 0)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001489 return true;
1490
Guy Benyei11169dd2012-12-18 14:30:41 +00001491 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001492 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001493 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1494 if (!Key.Imported)
1495 return FileMgr.getFile(Key.Filename);
1496
1497 std::string Resolved = Key.Filename;
1498 Reader.ResolveImportedPath(M, Resolved);
1499 return FileMgr.getFile(Resolved);
1500 };
1501
1502 const FileEntry *FEA = GetFile(a);
1503 const FileEntry *FEB = GetFile(b);
1504 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001505}
1506
1507std::pair<unsigned, unsigned>
1508HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001509 using namespace llvm::support;
1510 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001512 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001513}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001514
1515HeaderFileInfoTrait::internal_key_type
1516HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001517 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001518 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001519 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1520 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001521 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001522 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001523 return ikey;
1524}
1525
Guy Benyei11169dd2012-12-18 14:30:41 +00001526HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001527HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001528 unsigned DataLen) {
1529 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001530 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 HeaderFileInfo HFI;
1532 unsigned Flags = *d++;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00001533 HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1534 ((Flags >> 6) & 0x03);
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 HFI.isImport = (Flags >> 5) & 0x01;
1536 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1537 HFI.DirInfo = (Flags >> 2) & 0x03;
1538 HFI.Resolved = (Flags >> 1) & 0x01;
1539 HFI.IndexHeaderMapHeader = Flags & 0x01;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001540 HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1541 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1542 M, endian::readNext<uint32_t, little, unaligned>(d));
1543 if (unsigned FrameworkOffset =
1544 endian::readNext<uint32_t, little, unaligned>(d)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 // The framework offset is 1 greater than the actual offset,
1546 // since 0 is used as an indicator for "no framework name".
1547 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1548 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1549 }
1550
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001551 if (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001552 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001553 if (LocalSMID) {
1554 // This header is part of a module. Associate it with the module to enable
1555 // implicit module import.
1556 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1557 Module *Mod = Reader.getSubmodule(GlobalSMID);
1558 HFI.isModuleHeader = true;
1559 FileManager &FileMgr = Reader.getFileManager();
1560 ModuleMap &ModMap =
1561 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001562 // FIXME: This information should be propagated through the
1563 // SUBMODULE_HEADER etc records rather than from here.
Richard Smith3c1a41a2014-12-02 00:08:08 +00001564 // FIXME: We don't ever mark excluded headers.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001565 std::string Filename = key.Filename;
1566 if (key.Imported)
1567 Reader.ResolveImportedPath(M, Filename);
1568 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Hans Wennborg0101b542014-12-02 02:13:09 +00001569 ModMap.addHeader(Mod, H, HFI.getHeaderRole());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001570 }
1571 }
1572
Guy Benyei11169dd2012-12-18 14:30:41 +00001573 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1574 (void)End;
1575
1576 // This HeaderFileInfo was externally loaded.
1577 HFI.External = true;
1578 return HFI;
1579}
1580
Richard Smithd7329392015-04-21 21:46:32 +00001581void ASTReader::addPendingMacro(IdentifierInfo *II,
1582 ModuleFile *M,
1583 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001584 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1585 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001586}
1587
1588void ASTReader::ReadDefinedMacros() {
1589 // Note that we are loading defined macros.
1590 Deserializing Macros(this);
1591
1592 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1593 E = ModuleMgr.rend(); I != E; ++I) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001594 BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001595
1596 // If there was no preprocessor block, skip this file.
1597 if (!MacroCursor.getBitStreamReader())
1598 continue;
1599
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001600 BitstreamCursor Cursor = MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 Cursor.JumpToBit((*I)->MacroStartOffset);
1602
1603 RecordData Record;
1604 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001605 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1606
1607 switch (E.Kind) {
1608 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1609 case llvm::BitstreamEntry::Error:
1610 Error("malformed block record in AST file");
1611 return;
1612 case llvm::BitstreamEntry::EndBlock:
1613 goto NextCursor;
1614
1615 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001616 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001617 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001618 default: // Default behavior: ignore.
1619 break;
1620
1621 case PP_MACRO_OBJECT_LIKE:
1622 case PP_MACRO_FUNCTION_LIKE:
1623 getLocalIdentifier(**I, Record[0]);
1624 break;
1625
1626 case PP_TOKEN:
1627 // Ignore tokens.
1628 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001630 break;
1631 }
1632 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001633 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 }
1635}
1636
1637namespace {
1638 /// \brief Visitor class used to look up identifirs in an AST file.
1639 class IdentifierLookupVisitor {
1640 StringRef Name;
1641 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001642 unsigned &NumIdentifierLookups;
1643 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001645
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001647 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1648 unsigned &NumIdentifierLookups,
1649 unsigned &NumIdentifierLookupHits)
Douglas Gregor7211ac12013-01-25 23:32:03 +00001650 : Name(Name), PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001651 NumIdentifierLookups(NumIdentifierLookups),
1652 NumIdentifierLookupHits(NumIdentifierLookupHits),
1653 Found()
1654 {
1655 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001656
1657 static bool visit(ModuleFile &M, void *UserData) {
1658 IdentifierLookupVisitor *This
1659 = static_cast<IdentifierLookupVisitor *>(UserData);
1660
1661 // If we've already searched this module file, skip it now.
1662 if (M.Generation <= This->PriorGeneration)
1663 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001664
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 ASTIdentifierLookupTable *IdTable
1666 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1667 if (!IdTable)
1668 return false;
1669
1670 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1671 M, This->Found);
Douglas Gregor00a50f72013-01-25 00:38:33 +00001672 ++This->NumIdentifierLookups;
1673 ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001674 if (Pos == IdTable->end())
1675 return false;
1676
1677 // Dereferencing the iterator has the effect of building the
1678 // IdentifierInfo node and populating it with the various
1679 // declarations it needs.
Douglas Gregor00a50f72013-01-25 00:38:33 +00001680 ++This->NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 This->Found = *Pos;
1682 return true;
1683 }
1684
1685 // \brief Retrieve the identifier info found within the module
1686 // files.
1687 IdentifierInfo *getIdentifierInfo() const { return Found; }
1688 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001689}
Guy Benyei11169dd2012-12-18 14:30:41 +00001690
1691void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1692 // Note that we are loading an identifier.
1693 Deserializing AnIdentifier(this);
1694
1695 unsigned PriorGeneration = 0;
1696 if (getContext().getLangOpts().Modules)
1697 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001698
1699 // If there is a global index, look there first to determine which modules
1700 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001701 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001702 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001703 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001704 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1705 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001706 }
1707 }
1708
Douglas Gregor7211ac12013-01-25 23:32:03 +00001709 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001710 NumIdentifierLookups,
1711 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00001712 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 markIdentifierUpToDate(&II);
1714}
1715
1716void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1717 if (!II)
1718 return;
1719
1720 II->setOutOfDate(false);
1721
1722 // Update the generation for this identifier.
1723 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001724 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001725}
1726
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1728 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001729 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001730
1731 BitstreamCursor &Cursor = M.MacroCursor;
1732 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001733 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001734
Richard Smith713369b2015-04-23 20:40:50 +00001735 struct ModuleMacroRecord {
1736 SubmoduleID SubModID;
1737 MacroInfo *MI;
1738 SmallVector<SubmoduleID, 8> Overrides;
1739 };
1740 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001741
Richard Smithd7329392015-04-21 21:46:32 +00001742 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1743 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1744 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001745 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001746 while (true) {
1747 llvm::BitstreamEntry Entry =
1748 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1749 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1750 Error("malformed block record in AST file");
1751 return;
1752 }
1753
1754 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001755 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001756 case PP_MACRO_DIRECTIVE_HISTORY:
1757 break;
1758
1759 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001760 ModuleMacros.push_back(ModuleMacroRecord());
1761 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001762 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1763 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001764 for (int I = 2, N = Record.size(); I != N; ++I)
1765 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001766 continue;
1767 }
1768
1769 default:
1770 Error("malformed block record in AST file");
1771 return;
1772 }
1773
1774 // We found the macro directive history; that's the last record
1775 // for this macro.
1776 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001777 }
1778
Richard Smithd7329392015-04-21 21:46:32 +00001779 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001780 {
1781 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001782 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001783 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001784 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001785 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001786 Module *Mod = getSubmodule(ModID);
1787 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001788 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001789 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001790 }
1791
1792 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001793 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001794 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001795 }
1796 }
1797
1798 // Don't read the directive history for a module; we don't have anywhere
1799 // to put it.
1800 if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1801 return;
1802
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001803 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001804 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001805 unsigned Idx = 0, N = Record.size();
1806 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001807 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001808 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001809 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1810 switch (K) {
1811 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001812 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001813 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001814 break;
1815 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001816 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001817 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001818 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001819 }
1820 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001821 bool isPublic = Record[Idx++];
1822 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1823 break;
1824 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001825
1826 if (!Latest)
1827 Latest = MD;
1828 if (Earliest)
1829 Earliest->setPrevious(MD);
1830 Earliest = MD;
1831 }
1832
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001833 if (Latest)
1834 PP.setLoadedMacroDirective(II, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001835}
1836
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001837ASTReader::InputFileInfo
1838ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001839 // Go find this input file.
1840 BitstreamCursor &Cursor = F.InputFilesCursor;
1841 SavedStreamPosition SavedPosition(Cursor);
1842 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1843
1844 unsigned Code = Cursor.ReadCode();
1845 RecordData Record;
1846 StringRef Blob;
1847
1848 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1849 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1850 "invalid record type for input file");
1851 (void)Result;
1852
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001853 std::string Filename;
1854 off_t StoredSize;
1855 time_t StoredTime;
1856 bool Overridden;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001857
Ben Langmuir198c1682014-03-07 07:27:49 +00001858 assert(Record[0] == ID && "Bogus stored ID or offset");
1859 StoredSize = static_cast<off_t>(Record[1]);
1860 StoredTime = static_cast<time_t>(Record[2]);
1861 Overridden = static_cast<bool>(Record[3]);
1862 Filename = Blob;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001863 ResolveImportedPath(F, Filename);
1864
Hans Wennborg73945142014-03-14 17:45:06 +00001865 InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1866 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001867}
1868
1869std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001870 return readInputFileInfo(F, ID).Filename;
Ben Langmuir198c1682014-03-07 07:27:49 +00001871}
1872
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001873InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001874 // If this ID is bogus, just return an empty input file.
1875 if (ID == 0 || ID > F.InputFilesLoaded.size())
1876 return InputFile();
1877
1878 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001879 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 return F.InputFilesLoaded[ID-1];
1881
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00001882 if (F.InputFilesLoaded[ID-1].isNotFound())
1883 return InputFile();
1884
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001886 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 SavedStreamPosition SavedPosition(Cursor);
1888 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1889
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001890 InputFileInfo FI = readInputFileInfo(F, ID);
1891 off_t StoredSize = FI.StoredSize;
1892 time_t StoredTime = FI.StoredTime;
1893 bool Overridden = FI.Overridden;
1894 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001895
Ben Langmuir198c1682014-03-07 07:27:49 +00001896 const FileEntry *File
1897 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1898 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1899
1900 // If we didn't find the file, resolve it relative to the
1901 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00001902 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00001903 F.OriginalDir != CurrentDir) {
1904 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1905 F.OriginalDir,
1906 CurrentDir);
1907 if (!Resolved.empty())
1908 File = FileMgr.getFile(Resolved);
1909 }
1910
1911 // For an overridden file, create a virtual file with the stored
1912 // size/timestamp.
Craig Toppera13603a2014-05-22 05:54:18 +00001913 if (Overridden && File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001914 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1915 }
1916
Craig Toppera13603a2014-05-22 05:54:18 +00001917 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001918 if (Complain) {
1919 std::string ErrorStr = "could not find file '";
1920 ErrorStr += Filename;
1921 ErrorStr += "' referenced by AST file";
1922 Error(ErrorStr.c_str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 }
Ben Langmuir198c1682014-03-07 07:27:49 +00001924 // Record that we didn't find the file.
1925 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1926 return InputFile();
1927 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001928
Ben Langmuir198c1682014-03-07 07:27:49 +00001929 // Check if there was a request to override the contents of the file
1930 // that was part of the precompiled header. Overridding such a file
1931 // can lead to problems when lexing using the source locations from the
1932 // PCH.
1933 SourceManager &SM = getSourceManager();
1934 if (!Overridden && SM.isFileOverridden(File)) {
1935 if (Complain)
1936 Error(diag::err_fe_pch_file_overridden, Filename);
1937 // After emitting the diagnostic, recover by disabling the override so
1938 // that the original file will be used.
1939 SM.disableFileContentsOverride(File);
1940 // The FileEntry is a virtual file entry with the size of the contents
1941 // that would override the original contents. Set it to the original's
1942 // size/time.
1943 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1944 StoredSize, StoredTime);
1945 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001946
Ben Langmuir198c1682014-03-07 07:27:49 +00001947 bool IsOutOfDate = false;
1948
1949 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00001950 if (!Overridden && //
1951 (StoredSize != File->getSize() ||
1952#if defined(LLVM_ON_WIN32)
1953 false
1954#else
Ben Langmuir198c1682014-03-07 07:27:49 +00001955 // In our regression testing, the Windows file system seems to
1956 // have inconsistent modification times that sometimes
1957 // erroneously trigger this error-handling path.
Richard Smith96fdab62014-10-28 16:24:08 +00001958 //
1959 // This also happens in networked file systems, so disable this
1960 // check if validation is disabled or if we have an explicitly
1961 // built PCM file.
1962 //
1963 // FIXME: Should we also do this for PCH files? They could also
1964 // reasonably get shared across a network during a distributed build.
1965 (StoredTime != File->getModificationTime() && !DisableValidation &&
1966 F.Kind != MK_ExplicitModule)
Guy Benyei11169dd2012-12-18 14:30:41 +00001967#endif
Ben Langmuir198c1682014-03-07 07:27:49 +00001968 )) {
1969 if (Complain) {
1970 // Build a list of the PCH imports that got us here (in reverse).
1971 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1972 while (ImportStack.back()->ImportedBy.size() > 0)
1973 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00001974
Ben Langmuir198c1682014-03-07 07:27:49 +00001975 // The top-level PCH is stale.
1976 StringRef TopLevelPCHName(ImportStack.back()->FileName);
1977 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00001978
Ben Langmuir198c1682014-03-07 07:27:49 +00001979 // Print the import stack.
1980 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1981 Diag(diag::note_pch_required_by)
1982 << Filename << ImportStack[0]->FileName;
1983 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00001984 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00001985 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00001986 }
1987
Ben Langmuir198c1682014-03-07 07:27:49 +00001988 if (!Diags.isDiagnosticInFlight())
1989 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00001990 }
1991
Ben Langmuir198c1682014-03-07 07:27:49 +00001992 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 }
1994
Ben Langmuir198c1682014-03-07 07:27:49 +00001995 InputFile IF = InputFile(File, Overridden, IsOutOfDate);
1996
1997 // Note that we've loaded this input file.
1998 F.InputFilesLoaded[ID-1] = IF;
1999 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002000}
2001
Richard Smith7ed1bc92014-12-05 22:42:13 +00002002/// \brief If we are loading a relocatable PCH or module file, and the filename
2003/// is not an absolute path, add the system or module root to the beginning of
2004/// the file name.
2005void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2006 // Resolve relative to the base directory, if we have one.
2007 if (!M.BaseDirectory.empty())
2008 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002009}
2010
Richard Smith7ed1bc92014-12-05 22:42:13 +00002011void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002012 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2013 return;
2014
Richard Smith7ed1bc92014-12-05 22:42:13 +00002015 SmallString<128> Buffer;
2016 llvm::sys::path::append(Buffer, Prefix, Filename);
2017 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002018}
2019
2020ASTReader::ASTReadResult
2021ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002022 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002023 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002024 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002025 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002026
2027 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2028 Error("malformed block record in AST file");
2029 return Failure;
2030 }
2031
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002032 // Should we allow the configuration of the module file to differ from the
2033 // configuration of the current translation unit in a compatible way?
2034 //
2035 // FIXME: Allow this for files explicitly specified with -include-pch too.
2036 bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2037
Guy Benyei11169dd2012-12-18 14:30:41 +00002038 // Read all of the records and blocks in the control block.
2039 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002040 unsigned NumInputs = 0;
2041 unsigned NumUserInputs = 0;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002042 while (1) {
2043 llvm::BitstreamEntry Entry = Stream.advance();
2044
2045 switch (Entry.Kind) {
2046 case llvm::BitstreamEntry::Error:
2047 Error("malformed block record in AST file");
2048 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002049 case llvm::BitstreamEntry::EndBlock: {
2050 // Validate input files.
2051 const HeaderSearchOptions &HSOpts =
2052 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002053
Richard Smitha1825302014-10-23 22:18:29 +00002054 // All user input files reside at the index range [0, NumUserInputs), and
2055 // system input files reside at [NumUserInputs, NumInputs).
Ben Langmuiracb803e2014-11-10 22:13:10 +00002056 if (!DisableValidation) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002057 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002058
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002059 // If we are reading a module, we will create a verification timestamp,
2060 // so we verify all input files. Otherwise, verify only user input
2061 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002062
2063 unsigned N = NumUserInputs;
2064 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002065 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002066 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002067 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002068 N = NumInputs;
2069
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002070 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002071 InputFile IF = getInputFile(F, I+1, Complain);
2072 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002073 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002075 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002076
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002077 if (Listener)
2078 Listener->visitModuleFile(F.FileName);
2079
Ben Langmuircb69b572014-03-07 06:40:32 +00002080 if (Listener && Listener->needsInputFileVisitation()) {
2081 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2082 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002083 for (unsigned I = 0; I < N; ++I) {
2084 bool IsSystem = I >= NumUserInputs;
2085 InputFileInfo FI = readInputFileInfo(F, I+1);
2086 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2087 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002088 }
2089
Guy Benyei11169dd2012-12-18 14:30:41 +00002090 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002091 }
2092
Chris Lattnere7b154b2013-01-19 21:39:22 +00002093 case llvm::BitstreamEntry::SubBlock:
2094 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002095 case INPUT_FILES_BLOCK_ID:
2096 F.InputFilesCursor = Stream;
2097 if (Stream.SkipBlock() || // Skip with the main cursor
2098 // Read the abbreviations
2099 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2100 Error("malformed block record in AST file");
2101 return Failure;
2102 }
2103 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002104
Guy Benyei11169dd2012-12-18 14:30:41 +00002105 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002106 if (Stream.SkipBlock()) {
2107 Error("malformed block record in AST file");
2108 return Failure;
2109 }
2110 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002112
2113 case llvm::BitstreamEntry::Record:
2114 // The interesting case.
2115 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002116 }
2117
2118 // Read and process a record.
2119 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002120 StringRef Blob;
2121 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002122 case METADATA: {
2123 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2124 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002125 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2126 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002127 return VersionMismatch;
2128 }
2129
2130 bool hasErrors = Record[5];
2131 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2132 Diag(diag::err_pch_with_compiler_errors);
2133 return HadErrors;
2134 }
2135
2136 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002137 // Relative paths in a relocatable PCH are relative to our sysroot.
2138 if (F.RelocatablePCH)
2139 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002140
2141 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002142 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002143 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2144 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002145 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 return VersionMismatch;
2147 }
2148 break;
2149 }
2150
Ben Langmuir487ea142014-10-23 18:05:36 +00002151 case SIGNATURE:
2152 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2153 F.Signature = Record[0];
2154 break;
2155
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 case IMPORTS: {
2157 // Load each of the imported PCH files.
2158 unsigned Idx = 0, N = Record.size();
2159 while (Idx < N) {
2160 // Read information about the AST file.
2161 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2162 // The import location will be the local one for now; we will adjust
2163 // all import locations of module imports after the global source
2164 // location info are setup.
2165 SourceLocation ImportLoc =
2166 SourceLocation::getFromRawEncoding(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002167 off_t StoredSize = (off_t)Record[Idx++];
2168 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002169 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002170 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002171
2172 // Load the AST file.
2173 switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00002174 StoredSize, StoredModTime, StoredSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00002175 ClientLoadCapabilities)) {
2176 case Failure: return Failure;
2177 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002178 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002179 case OutOfDate: return OutOfDate;
2180 case VersionMismatch: return VersionMismatch;
2181 case ConfigurationMismatch: return ConfigurationMismatch;
2182 case HadErrors: return HadErrors;
2183 case Success: break;
2184 }
2185 }
2186 break;
2187 }
2188
Richard Smith7f330cd2015-03-18 01:42:29 +00002189 case KNOWN_MODULE_FILES:
2190 break;
2191
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 case LANGUAGE_OPTIONS: {
2193 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002194 // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
Guy Benyei11169dd2012-12-18 14:30:41 +00002195 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002196 ParseLanguageOptions(Record, Complain, *Listener,
2197 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002198 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 return ConfigurationMismatch;
2200 break;
2201 }
2202
2203 case TARGET_OPTIONS: {
2204 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2205 if (Listener && &F == *ModuleMgr.begin() &&
Chandler Carruth0d745bc2015-03-14 04:47:43 +00002206 ParseTargetOptions(Record, Complain, *Listener,
2207 AllowCompatibleConfigurationMismatch) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002208 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002209 return ConfigurationMismatch;
2210 break;
2211 }
2212
2213 case DIAGNOSTIC_OPTIONS: {
Ben Langmuirb92de022014-04-29 16:25:26 +00002214 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002216 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 ParseDiagnosticOptions(Record, Complain, *Listener) &&
Ben Langmuirb92de022014-04-29 16:25:26 +00002218 !DisableValidation)
2219 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00002220 break;
2221 }
2222
2223 case FILE_SYSTEM_OPTIONS: {
2224 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2225 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002226 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002227 ParseFileSystemOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002228 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 return ConfigurationMismatch;
2230 break;
2231 }
2232
2233 case HEADER_SEARCH_OPTIONS: {
2234 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2235 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002236 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002237 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002238 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 return ConfigurationMismatch;
2240 break;
2241 }
2242
2243 case PREPROCESSOR_OPTIONS: {
2244 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2245 if (Listener && &F == *ModuleMgr.begin() &&
Richard Smith1e2cf0d2014-10-31 02:28:58 +00002246 !AllowCompatibleConfigurationMismatch &&
Guy Benyei11169dd2012-12-18 14:30:41 +00002247 ParsePreprocessorOptions(Record, Complain, *Listener,
2248 SuggestedPredefines) &&
Ben Langmuir2cb4a782014-02-05 22:21:15 +00002249 !DisableValidation && !AllowConfigurationMismatch)
Guy Benyei11169dd2012-12-18 14:30:41 +00002250 return ConfigurationMismatch;
2251 break;
2252 }
2253
2254 case ORIGINAL_FILE:
2255 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002256 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002258 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002259 break;
2260
2261 case ORIGINAL_FILE_ID:
2262 F.OriginalSourceFileID = FileID::get(Record[0]);
2263 break;
2264
2265 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002266 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 break;
2268
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002269 case MODULE_NAME:
2270 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002271 if (Listener)
2272 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002273 break;
2274
Richard Smith223d3f22014-12-06 03:21:08 +00002275 case MODULE_DIRECTORY: {
2276 assert(!F.ModuleName.empty() &&
2277 "MODULE_DIRECTORY found before MODULE_NAME");
2278 // If we've already loaded a module map file covering this module, we may
2279 // have a better path for it (relative to the current build).
2280 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2281 if (M && M->Directory) {
2282 // If we're implicitly loading a module, the base directory can't
2283 // change between the build and use.
2284 if (F.Kind != MK_ExplicitModule) {
2285 const DirectoryEntry *BuildDir =
2286 PP.getFileManager().getDirectory(Blob);
2287 if (!BuildDir || BuildDir != M->Directory) {
2288 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2289 Diag(diag::err_imported_module_relocated)
2290 << F.ModuleName << Blob << M->Directory->getName();
2291 return OutOfDate;
2292 }
2293 }
2294 F.BaseDirectory = M->Directory->getName();
2295 } else {
2296 F.BaseDirectory = Blob;
2297 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002298 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002299 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002300
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002301 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002302 if (ASTReadResult Result =
2303 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2304 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002305 break;
2306
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002307 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002308 NumInputs = Record[0];
2309 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002310 F.InputFileOffsets =
2311 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002312 F.InputFilesLoaded.resize(NumInputs);
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 break;
2314 }
2315 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002316}
2317
Ben Langmuir2c9af442014-04-10 17:57:43 +00002318ASTReader::ASTReadResult
2319ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002320 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002321
2322 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2323 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002324 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002325 }
2326
2327 // Read all of the records and blocks for the AST file.
2328 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002329 while (1) {
2330 llvm::BitstreamEntry Entry = Stream.advance();
2331
2332 switch (Entry.Kind) {
2333 case llvm::BitstreamEntry::Error:
2334 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002335 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002336 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002337 // Outside of C++, we do not store a lookup map for the translation unit.
2338 // Instead, mark it as needing a lookup map to be built if this module
2339 // contains any declarations lexically within it (which it always does!).
2340 // This usually has no cost, since we very rarely need the lookup map for
2341 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002343 if (DC->hasExternalLexicalStorage() &&
2344 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002345 DC->setMustBuildLookupTable();
Chris Lattnere7b154b2013-01-19 21:39:22 +00002346
Ben Langmuir2c9af442014-04-10 17:57:43 +00002347 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002349 case llvm::BitstreamEntry::SubBlock:
2350 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002351 case DECLTYPES_BLOCK_ID:
2352 // We lazily load the decls block, but we want to set up the
2353 // DeclsCursor cursor to point into it. Clone our current bitcode
2354 // cursor to it, enter the block and read the abbrevs in that block.
2355 // With the main cursor, we just skip over it.
2356 F.DeclsCursor = Stream;
2357 if (Stream.SkipBlock() || // Skip with the main cursor.
2358 // Read the abbrevs.
2359 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2360 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002361 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 }
2363 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002364
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 case PREPROCESSOR_BLOCK_ID:
2366 F.MacroCursor = Stream;
2367 if (!PP.getExternalSource())
2368 PP.setExternalSource(this);
Chris Lattnere7b154b2013-01-19 21:39:22 +00002369
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 if (Stream.SkipBlock() ||
2371 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2372 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002373 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 }
2375 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2376 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002377
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 case PREPROCESSOR_DETAIL_BLOCK_ID:
2379 F.PreprocessorDetailCursor = Stream;
2380 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002381 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002382 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002383 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002384 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002385 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002387 = F.PreprocessorDetailCursor.GetCurrentBitNo();
2388
Guy Benyei11169dd2012-12-18 14:30:41 +00002389 if (!PP.getPreprocessingRecord())
2390 PP.createPreprocessingRecord();
2391 if (!PP.getPreprocessingRecord()->getExternalSource())
2392 PP.getPreprocessingRecord()->SetExternalSource(*this);
2393 break;
2394
2395 case SOURCE_MANAGER_BLOCK_ID:
2396 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002397 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002399
Guy Benyei11169dd2012-12-18 14:30:41 +00002400 case SUBMODULE_BLOCK_ID:
Ben Langmuir2c9af442014-04-10 17:57:43 +00002401 if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2402 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 break;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002404
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002406 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 if (Stream.SkipBlock() ||
2408 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2409 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002410 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 }
2412 CommentsCursors.push_back(std::make_pair(C, &F));
2413 break;
2414 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002415
Guy Benyei11169dd2012-12-18 14:30:41 +00002416 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002417 if (Stream.SkipBlock()) {
2418 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002419 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002420 }
2421 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 }
2423 continue;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424
2425 case llvm::BitstreamEntry::Record:
2426 // The interesting case.
2427 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 }
2429
2430 // Read and process a record.
2431 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002432 StringRef Blob;
2433 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 default: // Default behavior: ignore.
2435 break;
2436
2437 case TYPE_OFFSET: {
2438 if (F.LocalNumTypes != 0) {
2439 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002440 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002441 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002442 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 F.LocalNumTypes = Record[0];
2444 unsigned LocalBaseTypeIndex = Record[1];
2445 F.BaseTypeIndex = getTotalNumTypes();
2446
2447 if (F.LocalNumTypes > 0) {
2448 // Introduce the global -> local mapping for types within this module.
2449 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2450
2451 // Introduce the local -> global mapping for types within this module.
2452 F.TypeRemap.insertOrReplace(
2453 std::make_pair(LocalBaseTypeIndex,
2454 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002455
2456 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 }
2458 break;
2459 }
2460
2461 case DECL_OFFSET: {
2462 if (F.LocalNumDecls != 0) {
2463 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002464 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002466 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 F.LocalNumDecls = Record[0];
2468 unsigned LocalBaseDeclID = Record[1];
2469 F.BaseDeclID = getTotalNumDecls();
2470
2471 if (F.LocalNumDecls > 0) {
2472 // Introduce the global -> local mapping for declarations within this
2473 // module.
2474 GlobalDeclMap.insert(
2475 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2476
2477 // Introduce the local -> global mapping for declarations within this
2478 // module.
2479 F.DeclRemap.insertOrReplace(
2480 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2481
2482 // Introduce the global -> local mapping for declarations within this
2483 // module.
2484 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002485
Ben Langmuir52ca6782014-10-20 16:27:32 +00002486 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2487 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 break;
2489 }
2490
2491 case TU_UPDATE_LEXICAL: {
2492 DeclContext *TU = Context.getTranslationUnitDecl();
2493 DeclContextInfo &Info = F.DeclContextInfos[TU];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002494 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 Info.NumLexicalDecls
Chris Lattner0e6c9402013-01-20 02:38:54 +00002496 = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 TU->setHasExternalLexicalStorage(true);
2498 break;
2499 }
2500
2501 case UPDATE_VISIBLE: {
2502 unsigned Idx = 0;
2503 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2504 ASTDeclContextNameLookupTable *Table =
Justin Bognerda4e6502014-04-14 16:34:29 +00002505 ASTDeclContextNameLookupTable::Create(
2506 (const unsigned char *)Blob.data() + Record[Idx++],
2507 (const unsigned char *)Blob.data() + sizeof(uint32_t),
2508 (const unsigned char *)Blob.data(),
2509 ASTDeclContextNameLookupTrait(*this, F));
Richard Smithcd45dbc2014-04-19 03:48:30 +00002510 if (Decl *D = GetExistingDecl(ID)) {
Richard Smithd9174792014-03-11 03:10:46 +00002511 auto *DC = cast<DeclContext>(D);
2512 DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
Richard Smith52e3fba2014-03-11 07:17:35 +00002513 auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2514 delete LookupTable;
2515 LookupTable = Table;
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 } else
2517 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2518 break;
2519 }
2520
2521 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002522 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002524 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2525 (const unsigned char *)F.IdentifierTableData + Record[0],
2526 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2527 (const unsigned char *)F.IdentifierTableData,
2528 ASTIdentifierLookupTrait(*this, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002529
2530 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2531 }
2532 break;
2533
2534 case IDENTIFIER_OFFSET: {
2535 if (F.LocalNumIdentifiers != 0) {
2536 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002537 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002539 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002540 F.LocalNumIdentifiers = Record[0];
2541 unsigned LocalBaseIdentifierID = Record[1];
2542 F.BaseIdentifierID = getTotalNumIdentifiers();
2543
2544 if (F.LocalNumIdentifiers > 0) {
2545 // Introduce the global -> local mapping for identifiers within this
2546 // module.
2547 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2548 &F));
2549
2550 // Introduce the local -> global mapping for identifiers within this
2551 // module.
2552 F.IdentifierRemap.insertOrReplace(
2553 std::make_pair(LocalBaseIdentifierID,
2554 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002555
Ben Langmuir52ca6782014-10-20 16:27:32 +00002556 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2557 + F.LocalNumIdentifiers);
2558 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 break;
2560 }
2561
Ben Langmuir332aafe2014-01-31 01:06:56 +00002562 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002563 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2564 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002566 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002567 break;
2568
2569 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002570 if (SpecialTypes.empty()) {
2571 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2572 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2573 break;
2574 }
2575
2576 if (SpecialTypes.size() != Record.size()) {
2577 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002578 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002579 }
2580
2581 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2582 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2583 if (!SpecialTypes[I])
2584 SpecialTypes[I] = ID;
2585 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2586 // merge step?
2587 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 break;
2589
2590 case STATISTICS:
2591 TotalNumStatements += Record[0];
2592 TotalNumMacros += Record[1];
2593 TotalLexicalDeclContexts += Record[2];
2594 TotalVisibleDeclContexts += Record[3];
2595 break;
2596
2597 case UNUSED_FILESCOPED_DECLS:
2598 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2599 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2600 break;
2601
2602 case DELEGATING_CTORS:
2603 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2604 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2605 break;
2606
2607 case WEAK_UNDECLARED_IDENTIFIERS:
2608 if (Record.size() % 4 != 0) {
2609 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 }
2612
2613 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2614 // files. This isn't the way to do it :)
2615 WeakUndeclaredIdentifiers.clear();
2616
2617 // Translate the weak, undeclared identifiers into global IDs.
2618 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2619 WeakUndeclaredIdentifiers.push_back(
2620 getGlobalIdentifierID(F, Record[I++]));
2621 WeakUndeclaredIdentifiers.push_back(
2622 getGlobalIdentifierID(F, Record[I++]));
2623 WeakUndeclaredIdentifiers.push_back(
2624 ReadSourceLocation(F, Record, I).getRawEncoding());
2625 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2626 }
2627 break;
2628
Guy Benyei11169dd2012-12-18 14:30:41 +00002629 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002630 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002631 F.LocalNumSelectors = Record[0];
2632 unsigned LocalBaseSelectorID = Record[1];
2633 F.BaseSelectorID = getTotalNumSelectors();
2634
2635 if (F.LocalNumSelectors > 0) {
2636 // Introduce the global -> local mapping for selectors within this
2637 // module.
2638 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2639
2640 // Introduce the local -> global mapping for selectors within this
2641 // module.
2642 F.SelectorRemap.insertOrReplace(
2643 std::make_pair(LocalBaseSelectorID,
2644 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002645
2646 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 }
2648 break;
2649 }
2650
2651 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002652 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 if (Record[0])
2654 F.SelectorLookupTable
2655 = ASTSelectorLookupTable::Create(
2656 F.SelectorLookupTableData + Record[0],
2657 F.SelectorLookupTableData,
2658 ASTSelectorLookupTrait(*this, F));
2659 TotalNumMethodPoolEntries += Record[1];
2660 break;
2661
2662 case REFERENCED_SELECTOR_POOL:
2663 if (!Record.empty()) {
2664 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2665 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2666 Record[Idx++]));
2667 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2668 getRawEncoding());
2669 }
2670 }
2671 break;
2672
2673 case PP_COUNTER_VALUE:
2674 if (!Record.empty() && Listener)
2675 Listener->ReadCounter(F, Record[0]);
2676 break;
2677
2678 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002679 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 F.NumFileSortedDecls = Record[0];
2681 break;
2682
2683 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002684 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 F.LocalNumSLocEntries = Record[0];
2686 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002687 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002688 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 SLocSpaceSize);
2690 // Make our entry in the range map. BaseID is negative and growing, so
2691 // we invert it. Because we invert it, though, we need the other end of
2692 // the range.
2693 unsigned RangeStart =
2694 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2695 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2696 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2697
2698 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2699 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2700 GlobalSLocOffsetMap.insert(
2701 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2702 - SLocSpaceSize,&F));
2703
2704 // Initialize the remapping table.
2705 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002706 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002708 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 static_cast<int>(F.SLocEntryBaseOffset - 2)));
2710
2711 TotalNumSLocEntries += F.LocalNumSLocEntries;
2712 break;
2713 }
2714
2715 case MODULE_OFFSET_MAP: {
2716 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002717 const unsigned char *Data = (const unsigned char*)Blob.data();
2718 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002719
2720 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2721 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2722 F.SLocRemap.insert(std::make_pair(0U, 0));
2723 F.SLocRemap.insert(std::make_pair(2U, 1));
2724 }
2725
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002727 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2728 RemapBuilder;
2729 RemapBuilder SLocRemap(F.SLocRemap);
2730 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2731 RemapBuilder MacroRemap(F.MacroRemap);
2732 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2733 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2734 RemapBuilder SelectorRemap(F.SelectorRemap);
2735 RemapBuilder DeclRemap(F.DeclRemap);
2736 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002737
2738 while(Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002739 using namespace llvm::support;
2740 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 StringRef Name = StringRef((const char*)Data, Len);
2742 Data += Len;
2743 ModuleFile *OM = ModuleMgr.lookup(Name);
2744 if (!OM) {
2745 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002746 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 }
2748
Justin Bogner57ba0b22014-03-28 22:03:24 +00002749 uint32_t SLocOffset =
2750 endian::readNext<uint32_t, little, unaligned>(Data);
2751 uint32_t IdentifierIDOffset =
2752 endian::readNext<uint32_t, little, unaligned>(Data);
2753 uint32_t MacroIDOffset =
2754 endian::readNext<uint32_t, little, unaligned>(Data);
2755 uint32_t PreprocessedEntityIDOffset =
2756 endian::readNext<uint32_t, little, unaligned>(Data);
2757 uint32_t SubmoduleIDOffset =
2758 endian::readNext<uint32_t, little, unaligned>(Data);
2759 uint32_t SelectorIDOffset =
2760 endian::readNext<uint32_t, little, unaligned>(Data);
2761 uint32_t DeclIDOffset =
2762 endian::readNext<uint32_t, little, unaligned>(Data);
2763 uint32_t TypeIndexOffset =
2764 endian::readNext<uint32_t, little, unaligned>(Data);
2765
Ben Langmuir785180e2014-10-20 16:27:30 +00002766 uint32_t None = std::numeric_limits<uint32_t>::max();
2767
2768 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2769 RemapBuilder &Remap) {
2770 if (Offset != None)
2771 Remap.insert(std::make_pair(Offset,
2772 static_cast<int>(BaseOffset - Offset)));
2773 };
2774 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2775 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2776 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2777 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2778 PreprocessedEntityRemap);
2779 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2780 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2781 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2782 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002783
2784 // Global -> local mappings.
2785 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2786 }
2787 break;
2788 }
2789
2790 case SOURCE_MANAGER_LINE_TABLE:
2791 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002792 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 break;
2794
2795 case SOURCE_LOCATION_PRELOADS: {
2796 // Need to transform from the local view (1-based IDs) to the global view,
2797 // which is based off F.SLocEntryBaseID.
2798 if (!F.PreloadSLocEntries.empty()) {
2799 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002800 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002801 }
2802
2803 F.PreloadSLocEntries.swap(Record);
2804 break;
2805 }
2806
2807 case EXT_VECTOR_DECLS:
2808 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2809 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2810 break;
2811
2812 case VTABLE_USES:
2813 if (Record.size() % 3 != 0) {
2814 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002815 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002816 }
2817
2818 // Later tables overwrite earlier ones.
2819 // FIXME: Modules will have some trouble with this. This is clearly not
2820 // the right way to do this.
2821 VTableUses.clear();
2822
2823 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2824 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2825 VTableUses.push_back(
2826 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2827 VTableUses.push_back(Record[Idx++]);
2828 }
2829 break;
2830
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 case PENDING_IMPLICIT_INSTANTIATIONS:
2832 if (PendingInstantiations.size() % 2 != 0) {
2833 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002834 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 }
2836
2837 if (Record.size() % 2 != 0) {
2838 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002839 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002840 }
2841
2842 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2843 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2844 PendingInstantiations.push_back(
2845 ReadSourceLocation(F, Record, I).getRawEncoding());
2846 }
2847 break;
2848
2849 case SEMA_DECL_REFS:
Richard Smith3d8e97e2013-10-18 06:54:39 +00002850 if (Record.size() != 2) {
2851 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002852 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00002853 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2855 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2856 break;
2857
2858 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002859 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2860 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2861 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00002862
2863 unsigned LocalBasePreprocessedEntityID = Record[0];
2864
2865 unsigned StartingID;
2866 if (!PP.getPreprocessingRecord())
2867 PP.createPreprocessingRecord();
2868 if (!PP.getPreprocessingRecord()->getExternalSource())
2869 PP.getPreprocessingRecord()->SetExternalSource(*this);
2870 StartingID
2871 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00002872 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00002873 F.BasePreprocessedEntityID = StartingID;
2874
2875 if (F.NumPreprocessedEntities > 0) {
2876 // Introduce the global -> local mapping for preprocessed entities in
2877 // this module.
2878 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2879
2880 // Introduce the local -> global mapping for preprocessed entities in
2881 // this module.
2882 F.PreprocessedEntityRemap.insertOrReplace(
2883 std::make_pair(LocalBasePreprocessedEntityID,
2884 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2885 }
2886
2887 break;
2888 }
2889
2890 case DECL_UPDATE_OFFSETS: {
2891 if (Record.size() % 2 != 0) {
2892 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002893 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002894 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00002895 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2896 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2897 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2898
2899 // If we've already loaded the decl, perform the updates when we finish
2900 // loading this block.
2901 if (Decl *D = GetExistingDecl(ID))
2902 PendingUpdateRecords.push_back(std::make_pair(ID, D));
2903 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 break;
2905 }
2906
2907 case DECL_REPLACEMENTS: {
2908 if (Record.size() % 3 != 0) {
2909 Error("invalid DECL_REPLACEMENTS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002910 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 }
2912 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2913 ReplacedDecls[getGlobalDeclID(F, Record[I])]
2914 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2915 break;
2916 }
2917
2918 case OBJC_CATEGORIES_MAP: {
2919 if (F.LocalNumObjCCategoriesInMap != 0) {
2920 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002921 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 }
2923
2924 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002925 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002926 break;
2927 }
2928
2929 case OBJC_CATEGORIES:
2930 F.ObjCCategories.swap(Record);
2931 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00002932
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 case CXX_BASE_SPECIFIER_OFFSETS: {
2934 if (F.LocalNumCXXBaseSpecifiers != 0) {
2935 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002936 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 }
Richard Smithc2bb8182015-03-24 06:36:48 +00002938
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 F.LocalNumCXXBaseSpecifiers = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00002940 F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
Richard Smithc2bb8182015-03-24 06:36:48 +00002941 break;
2942 }
2943
2944 case CXX_CTOR_INITIALIZERS_OFFSETS: {
2945 if (F.LocalNumCXXCtorInitializers != 0) {
2946 Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2947 return Failure;
2948 }
2949
2950 F.LocalNumCXXCtorInitializers = Record[0];
2951 F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 break;
2953 }
2954
2955 case DIAG_PRAGMA_MAPPINGS:
2956 if (F.PragmaDiagMappings.empty())
2957 F.PragmaDiagMappings.swap(Record);
2958 else
2959 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2960 Record.begin(), Record.end());
2961 break;
2962
2963 case CUDA_SPECIAL_DECL_REFS:
2964 // Later tables overwrite earlier ones.
2965 // FIXME: Modules will have trouble with this.
2966 CUDASpecialDeclRefs.clear();
2967 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2968 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2969 break;
2970
2971 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002972 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 if (Record[0]) {
2975 F.HeaderFileInfoTable
2976 = HeaderFileInfoLookupTable::Create(
2977 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2978 (const unsigned char *)F.HeaderFileInfoTableData,
2979 HeaderFileInfoTrait(*this, F,
2980 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00002981 Blob.data() + Record[2]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002982
2983 PP.getHeaderSearchInfo().SetExternalSource(this);
2984 if (!PP.getHeaderSearchInfo().getExternalLookup())
2985 PP.getHeaderSearchInfo().SetExternalLookup(this);
2986 }
2987 break;
2988 }
2989
2990 case FP_PRAGMA_OPTIONS:
2991 // Later tables overwrite earlier ones.
2992 FPPragmaOptions.swap(Record);
2993 break;
2994
2995 case OPENCL_EXTENSIONS:
2996 // Later tables overwrite earlier ones.
2997 OpenCLExtensions.swap(Record);
2998 break;
2999
3000 case TENTATIVE_DEFINITIONS:
3001 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3002 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3003 break;
3004
3005 case KNOWN_NAMESPACES:
3006 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3007 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3008 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003009
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003010 case UNDEFINED_BUT_USED:
3011 if (UndefinedButUsed.size() % 2 != 0) {
3012 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003013 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003014 }
3015
3016 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003017 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003018 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003019 }
3020 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003021 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3022 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003023 ReadSourceLocation(F, Record, I).getRawEncoding());
3024 }
3025 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003026 case DELETE_EXPRS_TO_ANALYZE:
3027 for (unsigned I = 0, N = Record.size(); I != N;) {
3028 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3029 const uint64_t Count = Record[I++];
3030 DelayedDeleteExprs.push_back(Count);
3031 for (uint64_t C = 0; C < Count; ++C) {
3032 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3033 bool IsArrayForm = Record[I++] == 1;
3034 DelayedDeleteExprs.push_back(IsArrayForm);
3035 }
3036 }
3037 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003038
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 case IMPORTED_MODULES: {
Richard Smithe842a472014-10-22 02:05:46 +00003040 if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 // If we aren't loading a module (which has its own exports), make
3042 // all of the imported modules visible.
3043 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003044 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3045 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3046 SourceLocation Loc = ReadSourceLocation(F, Record, I);
3047 if (GlobalID)
Aaron Ballman4f45b712014-03-21 15:22:56 +00003048 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 }
3050 }
3051 break;
3052 }
3053
3054 case LOCAL_REDECLARATIONS: {
3055 F.RedeclarationChains.swap(Record);
3056 break;
3057 }
3058
3059 case LOCAL_REDECLARATIONS_MAP: {
3060 if (F.LocalNumRedeclarationsInMap != 0) {
3061 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003062 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 }
3064
3065 F.LocalNumRedeclarationsInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003066 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 break;
3068 }
3069
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 case MACRO_OFFSET: {
3071 if (F.LocalNumMacros != 0) {
3072 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003073 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003075 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 F.LocalNumMacros = Record[0];
3077 unsigned LocalBaseMacroID = Record[1];
3078 F.BaseMacroID = getTotalNumMacros();
3079
3080 if (F.LocalNumMacros > 0) {
3081 // Introduce the global -> local mapping for macros within this module.
3082 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3083
3084 // Introduce the local -> global mapping for macros within this module.
3085 F.MacroRemap.insertOrReplace(
3086 std::make_pair(LocalBaseMacroID,
3087 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003088
3089 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 }
3091 break;
3092 }
3093
Richard Smithe40f2ba2013-08-07 21:41:30 +00003094 case LATE_PARSED_TEMPLATE: {
3095 LateParsedTemplates.append(Record.begin(), Record.end());
3096 break;
3097 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003098
3099 case OPTIMIZE_PRAGMA_OPTIONS:
3100 if (Record.size() != 1) {
3101 Error("invalid pragma optimize record");
3102 return Failure;
3103 }
3104 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3105 break;
Nico Weber72889432014-09-06 01:25:55 +00003106
3107 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3108 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3109 UnusedLocalTypedefNameCandidates.push_back(
3110 getGlobalDeclID(F, Record[I]));
3111 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 }
3113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003114}
3115
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003116ASTReader::ASTReadResult
3117ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3118 const ModuleFile *ImportedBy,
3119 unsigned ClientLoadCapabilities) {
3120 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003121 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003122
Richard Smithe842a472014-10-22 02:05:46 +00003123 if (F.Kind == MK_ExplicitModule) {
3124 // For an explicitly-loaded module, we don't care whether the original
3125 // module map file exists or matches.
3126 return Success;
3127 }
3128
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003129 // Try to resolve ModuleName in the current header search context and
3130 // verify that it is found in the same module map file as we saved. If the
3131 // top-level AST file is a main file, skip this check because there is no
3132 // usable header search context.
3133 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003134 "MODULE_NAME should come before MODULE_MAP_FILE");
3135 if (F.Kind == MK_ImplicitModule &&
3136 (*ModuleMgr.begin())->Kind != MK_MainFile) {
3137 // An implicitly-loaded module file should have its module listed in some
3138 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003139 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003140 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3141 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3142 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003143 assert(ImportedBy && "top-level import should be verified");
3144 if ((ClientLoadCapabilities & ARR_Missing) == 0)
Richard Smithe842a472014-10-22 02:05:46 +00003145 Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3146 << ImportedBy->FileName
3147 << F.ModuleMapPath;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003148 return Missing;
3149 }
3150
Richard Smithe842a472014-10-22 02:05:46 +00003151 assert(M->Name == F.ModuleName && "found module with different name");
3152
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003153 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003154 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003155 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3156 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003157 assert(ImportedBy && "top-level import should be verified");
3158 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3159 Diag(diag::err_imported_module_modmap_changed)
3160 << F.ModuleName << ImportedBy->FileName
3161 << ModMap->getName() << F.ModuleMapPath;
3162 return OutOfDate;
3163 }
3164
3165 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3166 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3167 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003168 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003169 const FileEntry *F =
3170 FileMgr.getFile(Filename, false, false);
3171 if (F == nullptr) {
3172 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3173 Error("could not find file '" + Filename +"' referenced by AST file");
3174 return OutOfDate;
3175 }
3176 AdditionalStoredMaps.insert(F);
3177 }
3178
3179 // Check any additional module map files (e.g. module.private.modulemap)
3180 // that are not in the pcm.
3181 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3182 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3183 // Remove files that match
3184 // Note: SmallPtrSet::erase is really remove
3185 if (!AdditionalStoredMaps.erase(ModMap)) {
3186 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3187 Diag(diag::err_module_different_modmap)
3188 << F.ModuleName << /*new*/0 << ModMap->getName();
3189 return OutOfDate;
3190 }
3191 }
3192 }
3193
3194 // Check any additional module map files that are in the pcm, but not
3195 // found in header search. Cases that match are already removed.
3196 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3197 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3198 Diag(diag::err_module_different_modmap)
3199 << F.ModuleName << /*not new*/1 << ModMap->getName();
3200 return OutOfDate;
3201 }
3202 }
3203
3204 if (Listener)
3205 Listener->ReadModuleMapFile(F.ModuleMapPath);
3206 return Success;
3207}
3208
3209
Douglas Gregorc1489562013-02-12 23:36:21 +00003210/// \brief Move the given method to the back of the global list of methods.
3211static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3212 // Find the entry for this selector in the method pool.
3213 Sema::GlobalMethodPool::iterator Known
3214 = S.MethodPool.find(Method->getSelector());
3215 if (Known == S.MethodPool.end())
3216 return;
3217
3218 // Retrieve the appropriate method list.
3219 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3220 : Known->second.second;
3221 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003222 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003223 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003224 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003225 Found = true;
3226 } else {
3227 // Keep searching.
3228 continue;
3229 }
3230 }
3231
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003232 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003233 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003234 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003235 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003236 }
3237}
3238
Richard Smithde711422015-04-23 21:20:19 +00003239void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003240 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003241 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003242 bool wasHidden = D->Hidden;
3243 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003244
Richard Smith49f906a2014-03-01 00:08:04 +00003245 if (wasHidden && SemaObj) {
3246 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3247 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003248 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 }
3250 }
3251}
3252
Richard Smith49f906a2014-03-01 00:08:04 +00003253void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003254 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003255 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003257 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003258 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003260 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003261
3262 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003263 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003264 // there is nothing more to do.
3265 continue;
3266 }
Richard Smith49f906a2014-03-01 00:08:04 +00003267
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 if (!Mod->isAvailable()) {
3269 // Modules that aren't available cannot be made visible.
3270 continue;
3271 }
3272
3273 // Update the module's name visibility.
3274 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003275
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 // If we've already deserialized any names from this module,
3277 // mark them as visible.
3278 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3279 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003280 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003282 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003283 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3284 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003286
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003288 SmallVector<Module *, 16> Exports;
3289 Mod->getExportedModules(Exports);
3290 for (SmallVectorImpl<Module *>::iterator
3291 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3292 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003293 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003294 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 }
3296 }
3297}
3298
Douglas Gregore060e572013-01-25 01:03:03 +00003299bool ASTReader::loadGlobalIndex() {
3300 if (GlobalIndex)
3301 return false;
3302
3303 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3304 !Context.getLangOpts().Modules)
3305 return true;
3306
3307 // Try to load the global index.
3308 TriedLoadingGlobalIndex = true;
3309 StringRef ModuleCachePath
3310 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3311 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003312 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003313 if (!Result.first)
3314 return true;
3315
3316 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003317 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003318 return false;
3319}
3320
3321bool ASTReader::isGlobalIndexUnavailable() const {
3322 return Context.getLangOpts().Modules && UseGlobalIndex &&
3323 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3324}
3325
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003326static void updateModuleTimestamp(ModuleFile &MF) {
3327 // Overwrite the timestamp file contents so that file's mtime changes.
3328 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003329 std::error_code EC;
3330 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3331 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003332 return;
3333 OS << "Timestamp file\n";
3334}
3335
Guy Benyei11169dd2012-12-18 14:30:41 +00003336ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3337 ModuleKind Type,
3338 SourceLocation ImportLoc,
3339 unsigned ClientLoadCapabilities) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003340 llvm::SaveAndRestore<SourceLocation>
3341 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3342
Richard Smithd1c46742014-04-30 02:24:17 +00003343 // Defer any pending actions until we get to the end of reading the AST file.
3344 Deserializing AnASTFile(this);
3345
Guy Benyei11169dd2012-12-18 14:30:41 +00003346 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003347 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003348
3349 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003350 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003351 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003352 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003353 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003354 ClientLoadCapabilities)) {
3355 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003356 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 case OutOfDate:
3358 case VersionMismatch:
3359 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003360 case HadErrors: {
3361 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3362 for (const ImportedModule &IM : Loaded)
3363 LoadedSet.insert(IM.Mod);
3364
Douglas Gregor7029ce12013-03-19 00:28:20 +00003365 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
Ben Langmuir9801b252014-06-20 00:24:56 +00003366 LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003367 Context.getLangOpts().Modules
3368 ? &PP.getHeaderSearchInfo().getModuleMap()
Craig Toppera13603a2014-05-22 05:54:18 +00003369 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003370
3371 // If we find that any modules are unusable, the global index is going
3372 // to be out-of-date. Just remove it.
3373 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003374 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003376 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 case Success:
3378 break;
3379 }
3380
3381 // Here comes stuff that we only do once the entire chain is loaded.
3382
3383 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003384 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3385 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003386 M != MEnd; ++M) {
3387 ModuleFile &F = *M->Mod;
3388
3389 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003390 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3391 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003392
3393 // Once read, set the ModuleFile bit base offset and update the size in
3394 // bits of all files we've seen.
3395 F.GlobalBitOffset = TotalModulesSizeInBits;
3396 TotalModulesSizeInBits += F.SizeInBits;
3397 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3398
3399 // Preload SLocEntries.
3400 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3401 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3402 // Load it through the SourceManager and don't call ReadSLocEntry()
3403 // directly because the entry may have already been loaded in which case
3404 // calling ReadSLocEntry() directly would trigger an assertion in
3405 // SourceManager.
3406 SourceMgr.getLoadedSLocEntryByID(Index);
3407 }
3408 }
3409
Douglas Gregor603cd862013-03-22 18:50:14 +00003410 // Setup the import locations and notify the module manager that we've
3411 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003412 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3413 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003414 M != MEnd; ++M) {
3415 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003416
3417 ModuleMgr.moduleFileAccepted(&F);
3418
3419 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003420 F.DirectImportLoc = ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 if (!M->ImportedBy)
3422 F.ImportLoc = M->ImportLoc;
3423 else
3424 F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3425 M->ImportLoc.getRawEncoding());
3426 }
3427
3428 // Mark all of the identifiers in the identifier table as being out of date,
3429 // so that various accessors know to check the loaded modules when the
3430 // identifier is used.
3431 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3432 IdEnd = PP.getIdentifierTable().end();
3433 Id != IdEnd; ++Id)
3434 Id->second->setOutOfDate(true);
3435
3436 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003437 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3438 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3440 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003441
3442 switch (Unresolved.Kind) {
3443 case UnresolvedModuleRef::Conflict:
3444 if (ResolvedMod) {
3445 Module::Conflict Conflict;
3446 Conflict.Other = ResolvedMod;
3447 Conflict.Message = Unresolved.String.str();
3448 Unresolved.Mod->Conflicts.push_back(Conflict);
3449 }
3450 continue;
3451
3452 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003453 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003454 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003455 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003456
Douglas Gregorfb912652013-03-20 21:10:35 +00003457 case UnresolvedModuleRef::Export:
3458 if (ResolvedMod || Unresolved.IsWildcard)
3459 Unresolved.Mod->Exports.push_back(
3460 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3461 continue;
3462 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003463 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003464 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003465
3466 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3467 // Might be unnecessary as use declarations are only used to build the
3468 // module itself.
Guy Benyei11169dd2012-12-18 14:30:41 +00003469
3470 InitializeContext();
3471
Richard Smith3d8e97e2013-10-18 06:54:39 +00003472 if (SemaObj)
3473 UpdateSema();
3474
Guy Benyei11169dd2012-12-18 14:30:41 +00003475 if (DeserializationListener)
3476 DeserializationListener->ReaderInitialized(this);
3477
3478 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3479 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3480 PrimaryModule.OriginalSourceFileID
3481 = FileID::get(PrimaryModule.SLocEntryBaseID
3482 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3483
3484 // If this AST file is a precompiled preamble, then set the
3485 // preamble file ID of the source manager to the file source file
3486 // from which the preamble was built.
3487 if (Type == MK_Preamble) {
3488 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3489 } else if (Type == MK_MainFile) {
3490 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3491 }
3492 }
3493
3494 // For any Objective-C class definitions we have already loaded, make sure
3495 // that we load any additional categories.
3496 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3497 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3498 ObjCClassesLoaded[I],
3499 PreviousGeneration);
3500 }
Douglas Gregore060e572013-01-25 01:03:03 +00003501
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003502 if (PP.getHeaderSearchInfo()
3503 .getHeaderSearchOpts()
3504 .ModulesValidateOncePerBuildSession) {
3505 // Now we are certain that the module and all modules it depends on are
3506 // up to date. Create or update timestamp files for modules that are
3507 // located in the module cache (not for PCH files that could be anywhere
3508 // in the filesystem).
3509 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3510 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003511 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003512 updateModuleTimestamp(*M.Mod);
3513 }
3514 }
3515 }
3516
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 return Success;
3518}
3519
Ben Langmuir487ea142014-10-23 18:05:36 +00003520static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3521
Ben Langmuir70a1b812015-03-24 04:43:52 +00003522/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3523static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3524 return Stream.Read(8) == 'C' &&
3525 Stream.Read(8) == 'P' &&
3526 Stream.Read(8) == 'C' &&
3527 Stream.Read(8) == 'H';
3528}
3529
Guy Benyei11169dd2012-12-18 14:30:41 +00003530ASTReader::ASTReadResult
3531ASTReader::ReadASTCore(StringRef FileName,
3532 ModuleKind Type,
3533 SourceLocation ImportLoc,
3534 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003535 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003536 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003537 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 unsigned ClientLoadCapabilities) {
3539 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003540 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003541 ModuleManager::AddModuleResult AddResult
3542 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003543 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003544 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003545 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003546
Douglas Gregor7029ce12013-03-19 00:28:20 +00003547 switch (AddResult) {
3548 case ModuleManager::AlreadyLoaded:
3549 return Success;
3550
3551 case ModuleManager::NewlyLoaded:
3552 // Load module file below.
3553 break;
3554
3555 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003556 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003557 // it.
3558 if (ClientLoadCapabilities & ARR_Missing)
3559 return Missing;
3560
3561 // Otherwise, return an error.
3562 {
3563 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3564 + ErrorStr;
3565 Error(Msg);
3566 }
3567 return Failure;
3568
3569 case ModuleManager::OutOfDate:
3570 // We couldn't load the module file because it is out-of-date. If the
3571 // client can handle out-of-date, return it.
3572 if (ClientLoadCapabilities & ARR_OutOfDate)
3573 return OutOfDate;
3574
3575 // Otherwise, return an error.
3576 {
3577 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3578 + ErrorStr;
3579 Error(Msg);
3580 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 return Failure;
3582 }
3583
Douglas Gregor7029ce12013-03-19 00:28:20 +00003584 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003585
3586 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3587 // module?
3588 if (FileName != "-") {
3589 CurrentDir = llvm::sys::path::parent_path(FileName);
3590 if (CurrentDir.empty()) CurrentDir = ".";
3591 }
3592
3593 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003594 BitstreamCursor &Stream = F.Stream;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003595 PCHContainerOps.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
Rafael Espindolafd832392014-11-12 14:48:44 +00003596 Stream.init(&F.StreamFile);
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003597 F.SizeInBits = F.Buffer->getBufferSize() * 8;
3598
Guy Benyei11169dd2012-12-18 14:30:41 +00003599 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003600 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003601 Diag(diag::err_not_a_pch_file) << FileName;
3602 return Failure;
3603 }
3604
3605 // This is used for compatibility with older PCH formats.
3606 bool HaveReadControlBlock = false;
3607
Chris Lattnerefa77172013-01-20 00:00:22 +00003608 while (1) {
3609 llvm::BitstreamEntry Entry = Stream.advance();
3610
3611 switch (Entry.Kind) {
3612 case llvm::BitstreamEntry::Error:
3613 case llvm::BitstreamEntry::EndBlock:
3614 case llvm::BitstreamEntry::Record:
Guy Benyei11169dd2012-12-18 14:30:41 +00003615 Error("invalid record at top-level of AST file");
3616 return Failure;
Chris Lattnerefa77172013-01-20 00:00:22 +00003617
3618 case llvm::BitstreamEntry::SubBlock:
3619 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 }
3621
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 // We only know the control subblock ID.
Chris Lattnerefa77172013-01-20 00:00:22 +00003623 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003624 case llvm::bitc::BLOCKINFO_BLOCK_ID:
3625 if (Stream.ReadBlockInfoBlock()) {
3626 Error("malformed BlockInfoBlock in AST file");
3627 return Failure;
3628 }
3629 break;
3630 case CONTROL_BLOCK_ID:
3631 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003632 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003633 case Success:
3634 break;
3635
3636 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003637 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003638 case OutOfDate: return OutOfDate;
3639 case VersionMismatch: return VersionMismatch;
3640 case ConfigurationMismatch: return ConfigurationMismatch;
3641 case HadErrors: return HadErrors;
3642 }
3643 break;
3644 case AST_BLOCK_ID:
3645 if (!HaveReadControlBlock) {
3646 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003647 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 return VersionMismatch;
3649 }
3650
3651 // Record that we've loaded this module.
3652 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3653 return Success;
3654
3655 default:
3656 if (Stream.SkipBlock()) {
3657 Error("malformed block record in AST file");
3658 return Failure;
3659 }
3660 break;
3661 }
3662 }
3663
3664 return Success;
3665}
3666
Richard Smitha7e2cc62015-05-01 01:53:09 +00003667void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 // If there's a listener, notify them that we "read" the translation unit.
3669 if (DeserializationListener)
3670 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3671 Context.getTranslationUnitDecl());
3672
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 // FIXME: Find a better way to deal with collisions between these
3674 // built-in types. Right now, we just ignore the problem.
3675
3676 // Load the special types.
3677 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3678 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3679 if (!Context.CFConstantStringTypeDecl)
3680 Context.setCFConstantStringType(GetType(String));
3681 }
3682
3683 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3684 QualType FileType = GetType(File);
3685 if (FileType.isNull()) {
3686 Error("FILE type is NULL");
3687 return;
3688 }
3689
3690 if (!Context.FILEDecl) {
3691 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3692 Context.setFILEDecl(Typedef->getDecl());
3693 else {
3694 const TagType *Tag = FileType->getAs<TagType>();
3695 if (!Tag) {
3696 Error("Invalid FILE type in AST file");
3697 return;
3698 }
3699 Context.setFILEDecl(Tag->getDecl());
3700 }
3701 }
3702 }
3703
3704 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3705 QualType Jmp_bufType = GetType(Jmp_buf);
3706 if (Jmp_bufType.isNull()) {
3707 Error("jmp_buf type is NULL");
3708 return;
3709 }
3710
3711 if (!Context.jmp_bufDecl) {
3712 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3713 Context.setjmp_bufDecl(Typedef->getDecl());
3714 else {
3715 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3716 if (!Tag) {
3717 Error("Invalid jmp_buf type in AST file");
3718 return;
3719 }
3720 Context.setjmp_bufDecl(Tag->getDecl());
3721 }
3722 }
3723 }
3724
3725 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3726 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3727 if (Sigjmp_bufType.isNull()) {
3728 Error("sigjmp_buf type is NULL");
3729 return;
3730 }
3731
3732 if (!Context.sigjmp_bufDecl) {
3733 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3734 Context.setsigjmp_bufDecl(Typedef->getDecl());
3735 else {
3736 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3737 assert(Tag && "Invalid sigjmp_buf type in AST file");
3738 Context.setsigjmp_bufDecl(Tag->getDecl());
3739 }
3740 }
3741 }
3742
3743 if (unsigned ObjCIdRedef
3744 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3745 if (Context.ObjCIdRedefinitionType.isNull())
3746 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3747 }
3748
3749 if (unsigned ObjCClassRedef
3750 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3751 if (Context.ObjCClassRedefinitionType.isNull())
3752 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3753 }
3754
3755 if (unsigned ObjCSelRedef
3756 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3757 if (Context.ObjCSelRedefinitionType.isNull())
3758 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3759 }
3760
3761 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3762 QualType Ucontext_tType = GetType(Ucontext_t);
3763 if (Ucontext_tType.isNull()) {
3764 Error("ucontext_t type is NULL");
3765 return;
3766 }
3767
3768 if (!Context.ucontext_tDecl) {
3769 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3770 Context.setucontext_tDecl(Typedef->getDecl());
3771 else {
3772 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3773 assert(Tag && "Invalid ucontext_t type in AST file");
3774 Context.setucontext_tDecl(Tag->getDecl());
3775 }
3776 }
3777 }
3778 }
3779
3780 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3781
3782 // If there were any CUDA special declarations, deserialize them.
3783 if (!CUDASpecialDeclRefs.empty()) {
3784 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3785 Context.setcudaConfigureCallDecl(
3786 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3787 }
Richard Smith56be7542014-03-21 00:33:59 +00003788
Guy Benyei11169dd2012-12-18 14:30:41 +00003789 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00003790 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00003791 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00003792 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003793 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003794 /*ImportLoc=*/Import.ImportLoc);
3795 PP.makeModuleVisible(Imported, Import.ImportLoc);
3796 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003797 }
3798 ImportedModules.clear();
3799}
3800
3801void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00003802 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00003803}
3804
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003805/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3806/// cursor into the start of the given block ID, returning false on success and
3807/// true on failure.
3808static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003809 while (1) {
3810 llvm::BitstreamEntry Entry = Cursor.advance();
3811 switch (Entry.Kind) {
3812 case llvm::BitstreamEntry::Error:
3813 case llvm::BitstreamEntry::EndBlock:
3814 return true;
3815
3816 case llvm::BitstreamEntry::Record:
3817 // Ignore top-level records.
3818 Cursor.skipRecord(Entry.ID);
3819 break;
3820
3821 case llvm::BitstreamEntry::SubBlock:
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003822 if (Entry.ID == BlockID) {
3823 if (Cursor.EnterSubBlock(BlockID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003824 return true;
3825 // Found it!
3826 return false;
3827 }
3828
3829 if (Cursor.SkipBlock())
3830 return true;
3831 }
3832 }
3833}
3834
Ben Langmuir70a1b812015-03-24 04:43:52 +00003835/// \brief Reads and return the signature record from \p StreamFile's control
3836/// block, or else returns 0.
Ben Langmuir487ea142014-10-23 18:05:36 +00003837static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3838 BitstreamCursor Stream(StreamFile);
Ben Langmuir70a1b812015-03-24 04:43:52 +00003839 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00003840 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00003841
3842 // Scan for the CONTROL_BLOCK_ID block.
3843 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3844 return 0;
3845
3846 // Scan for SIGNATURE inside the control block.
3847 ASTReader::RecordData Record;
3848 while (1) {
3849 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3850 if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3851 Entry.Kind != llvm::BitstreamEntry::Record)
3852 return 0;
3853
3854 Record.clear();
3855 StringRef Blob;
3856 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3857 return Record[0];
3858 }
3859}
3860
Guy Benyei11169dd2012-12-18 14:30:41 +00003861/// \brief Retrieve the name of the original source file name
3862/// directly from the AST file, without actually loading the AST
3863/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003864std::string ASTReader::getOriginalSourceFile(
3865 const std::string &ASTFileName, FileManager &FileMgr,
3866 const PCHContainerOperations &PCHContainerOps, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003867 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00003868 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00003870 Diags.Report(diag::err_fe_unable_to_read_pch_file)
3871 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00003872 return std::string();
3873 }
3874
3875 // Initialize the stream
3876 llvm::BitstreamReader StreamFile;
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003877 PCHContainerOps.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
Rafael Espindolaaf0e40a2014-11-12 14:42:25 +00003878 BitstreamCursor Stream(StreamFile);
Guy Benyei11169dd2012-12-18 14:30:41 +00003879
3880 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003881 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3883 return std::string();
3884 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003885
Chris Lattnere7b154b2013-01-19 21:39:22 +00003886 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003887 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003888 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3889 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003890 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003891
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003892 // Scan for ORIGINAL_FILE inside the control block.
3893 RecordData Record;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003894 while (1) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003895 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00003896 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3897 return std::string();
3898
3899 if (Entry.Kind != llvm::BitstreamEntry::Record) {
3900 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3901 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00003902 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00003903
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003905 StringRef Blob;
3906 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3907 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003909}
3910
3911namespace {
3912 class SimplePCHValidator : public ASTReaderListener {
3913 const LangOptions &ExistingLangOpts;
3914 const TargetOptions &ExistingTargetOpts;
3915 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003916 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00003917 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003918
Guy Benyei11169dd2012-12-18 14:30:41 +00003919 public:
3920 SimplePCHValidator(const LangOptions &ExistingLangOpts,
3921 const TargetOptions &ExistingTargetOpts,
3922 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003923 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 FileManager &FileMgr)
3925 : ExistingLangOpts(ExistingLangOpts),
3926 ExistingTargetOpts(ExistingTargetOpts),
3927 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003928 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 FileMgr(FileMgr)
3930 {
3931 }
3932
Richard Smith1e2cf0d2014-10-31 02:28:58 +00003933 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3934 bool AllowCompatibleDifferences) override {
3935 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3936 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 }
Chandler Carruth0d745bc2015-03-14 04:47:43 +00003938 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3939 bool AllowCompatibleDifferences) override {
3940 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3941 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00003942 }
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00003943 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3944 StringRef SpecificModuleCachePath,
3945 bool Complain) override {
3946 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3947 ExistingModuleCachePath,
3948 nullptr, ExistingLangOpts);
3949 }
Craig Topper3e89dfe2014-03-13 02:13:41 +00003950 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3951 bool Complain,
3952 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00003953 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00003954 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00003955 }
3956 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003957}
Guy Benyei11169dd2012-12-18 14:30:41 +00003958
Adrian Prantlbb165fb2015-06-20 18:53:08 +00003959bool ASTReader::readASTFileControlBlock(
3960 StringRef Filename, FileManager &FileMgr,
3961 const PCHContainerOperations &PCHContainerOps,
3962 ASTReaderListener &Listener) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00003964 // FIXME: This allows use of the VFS; we do not allow use of the
3965 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00003966 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 if (!Buffer) {
3968 return true;
3969 }
3970
3971 // Initialize the stream
3972 llvm::BitstreamReader StreamFile;
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003973 StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
3974 (const unsigned char *)(*Buffer)->getBufferEnd());
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 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00003980
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003981 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003982 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003983 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003984
3985 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00003986 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00003987 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00003988 BitstreamCursor InputFilesCursor;
3989 if (NeedsInputFiles) {
3990 InputFilesCursor = Stream;
3991 if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3992 return true;
3993
3994 // Read the abbreviations
3995 while (true) {
3996 uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3997 unsigned Code = InputFilesCursor.ReadCode();
3998
3999 // We expect all abbrevs to be at the start of the block.
4000 if (Code != llvm::bitc::DEFINE_ABBREV) {
4001 InputFilesCursor.JumpToBit(Offset);
4002 break;
4003 }
4004 InputFilesCursor.ReadAbbrevRecord();
4005 }
4006 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004007
4008 // Scan for ORIGINAL_FILE inside the control block.
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004010 std::string ModuleDir;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004011 while (1) {
4012 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4013 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4014 return false;
4015
4016 if (Entry.Kind != llvm::BitstreamEntry::Record)
4017 return true;
4018
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004020 StringRef Blob;
4021 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004022 switch ((ControlRecordTypes)RecCode) {
4023 case METADATA: {
4024 if (Record[0] != VERSION_MAJOR)
4025 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004026
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004027 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004028 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004029
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004030 break;
4031 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004032 case MODULE_NAME:
4033 Listener.ReadModuleName(Blob);
4034 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004035 case MODULE_DIRECTORY:
4036 ModuleDir = Blob;
4037 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004038 case MODULE_MAP_FILE: {
4039 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004040 auto Path = ReadString(Record, Idx);
4041 ResolveImportedPath(Path, ModuleDir);
4042 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004043 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004044 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004045 case LANGUAGE_OPTIONS:
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004046 if (ParseLanguageOptions(Record, false, Listener,
4047 /*AllowCompatibleConfigurationMismatch*/false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004048 return true;
4049 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004050
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004051 case TARGET_OPTIONS:
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004052 if (ParseTargetOptions(Record, false, Listener,
4053 /*AllowCompatibleConfigurationMismatch*/ false))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004054 return true;
4055 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004056
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004057 case DIAGNOSTIC_OPTIONS:
4058 if (ParseDiagnosticOptions(Record, false, Listener))
4059 return true;
4060 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004061
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004062 case FILE_SYSTEM_OPTIONS:
4063 if (ParseFileSystemOptions(Record, false, Listener))
4064 return true;
4065 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004066
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004067 case HEADER_SEARCH_OPTIONS:
4068 if (ParseHeaderSearchOptions(Record, false, Listener))
4069 return true;
4070 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004071
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004072 case PREPROCESSOR_OPTIONS: {
4073 std::string IgnoredSuggestedPredefines;
4074 if (ParsePreprocessorOptions(Record, false, Listener,
4075 IgnoredSuggestedPredefines))
4076 return true;
4077 break;
4078 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004079
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004080 case INPUT_FILE_OFFSETS: {
4081 if (!NeedsInputFiles)
4082 break;
4083
4084 unsigned NumInputFiles = Record[0];
4085 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004086 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004087 for (unsigned I = 0; I != NumInputFiles; ++I) {
4088 // Go find this input file.
4089 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004090
4091 if (isSystemFile && !NeedsSystemInputFiles)
4092 break; // the rest are system input files
4093
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004094 BitstreamCursor &Cursor = InputFilesCursor;
4095 SavedStreamPosition SavedPosition(Cursor);
4096 Cursor.JumpToBit(InputFileOffs[I]);
4097
4098 unsigned Code = Cursor.ReadCode();
4099 RecordData Record;
4100 StringRef Blob;
4101 bool shouldContinue = false;
4102 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4103 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004104 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004105 std::string Filename = Blob;
4106 ResolveImportedPath(Filename, ModuleDir);
4107 shouldContinue =
4108 Listener.visitInputFile(Filename, isSystemFile, Overridden);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004109 break;
4110 }
4111 if (!shouldContinue)
4112 break;
4113 }
4114 break;
4115 }
4116
Richard Smithd4b230b2014-10-27 23:01:16 +00004117 case IMPORTS: {
4118 if (!NeedsImports)
4119 break;
4120
4121 unsigned Idx = 0, N = Record.size();
4122 while (Idx < N) {
4123 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004124 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004125 std::string Filename = ReadString(Record, Idx);
4126 ResolveImportedPath(Filename, ModuleDir);
4127 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004128 }
4129 break;
4130 }
4131
Richard Smith7f330cd2015-03-18 01:42:29 +00004132 case KNOWN_MODULE_FILES: {
4133 // Known-but-not-technically-used module files are treated as imports.
4134 if (!NeedsImports)
4135 break;
4136
4137 unsigned Idx = 0, N = Record.size();
4138 while (Idx < N) {
4139 std::string Filename = ReadString(Record, Idx);
4140 ResolveImportedPath(Filename, ModuleDir);
4141 Listener.visitImport(Filename);
4142 }
4143 break;
4144 }
4145
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004146 default:
4147 // No other validation to perform.
4148 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 }
4150 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004151}
4152
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004153bool ASTReader::isAcceptableASTFile(
4154 StringRef Filename, FileManager &FileMgr,
4155 const PCHContainerOperations &PCHContainerOps, const LangOptions &LangOpts,
4156 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4157 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004158 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4159 ExistingModuleCachePath, FileMgr);
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004160 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerOps,
4161 validator);
Guy Benyei11169dd2012-12-18 14:30:41 +00004162}
4163
Ben Langmuir2c9af442014-04-10 17:57:43 +00004164ASTReader::ASTReadResult
4165ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004166 // Enter the submodule block.
4167 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4168 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004169 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004170 }
4171
4172 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4173 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004174 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004175 RecordData Record;
4176 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004177 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4178
4179 switch (Entry.Kind) {
4180 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4181 case llvm::BitstreamEntry::Error:
4182 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004183 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004184 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004185 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004186 case llvm::BitstreamEntry::Record:
4187 // The interesting case.
4188 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004190
Guy Benyei11169dd2012-12-18 14:30:41 +00004191 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004192 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004194 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4195
4196 if ((Kind == SUBMODULE_METADATA) != First) {
4197 Error("submodule metadata record should be at beginning of block");
4198 return Failure;
4199 }
4200 First = false;
4201
4202 // Submodule information is only valid if we have a current module.
4203 // FIXME: Should we error on these cases?
4204 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4205 Kind != SUBMODULE_DEFINITION)
4206 continue;
4207
4208 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 default: // Default behavior: ignore.
4210 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004211
Richard Smith03478d92014-10-23 22:12:14 +00004212 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004213 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004215 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004216 }
Richard Smith03478d92014-10-23 22:12:14 +00004217
Chris Lattner0e6c9402013-01-20 02:38:54 +00004218 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004219 unsigned Idx = 0;
4220 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4221 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4222 bool IsFramework = Record[Idx++];
4223 bool IsExplicit = Record[Idx++];
4224 bool IsSystem = Record[Idx++];
4225 bool IsExternC = Record[Idx++];
4226 bool InferSubmodules = Record[Idx++];
4227 bool InferExplicitSubmodules = Record[Idx++];
4228 bool InferExportWildcard = Record[Idx++];
4229 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004230
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004231 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004232 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004233 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004234
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 // Retrieve this (sub)module from the module map, creating it if
4236 // necessary.
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004237 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
Guy Benyei11169dd2012-12-18 14:30:41 +00004238 IsExplicit).first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004239
4240 // FIXME: set the definition loc for CurrentModule, or call
4241 // ModMap.setInferredModuleAllowedBy()
4242
Guy Benyei11169dd2012-12-18 14:30:41 +00004243 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4244 if (GlobalIndex >= SubmodulesLoaded.size() ||
4245 SubmodulesLoaded[GlobalIndex]) {
4246 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004247 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004248 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004249
Douglas Gregor7029ce12013-03-19 00:28:20 +00004250 if (!ParentModule) {
4251 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4252 if (CurFile != F.File) {
4253 if (!Diags.isDiagnosticInFlight()) {
4254 Diag(diag::err_module_file_conflict)
4255 << CurrentModule->getTopLevelModuleName()
4256 << CurFile->getName()
4257 << F.File->getName();
4258 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004259 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004260 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004261 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004262
4263 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004264 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004265
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 CurrentModule->IsFromModuleFile = true;
4267 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004268 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 CurrentModule->InferSubmodules = InferSubmodules;
4270 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4271 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004272 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 if (DeserializationListener)
4274 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4275
4276 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004277
Douglas Gregorfb912652013-03-20 21:10:35 +00004278 // Clear out data that will be replaced by what is the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004279 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004280 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004281 CurrentModule->UnresolvedConflicts.clear();
4282 CurrentModule->Conflicts.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 break;
4284 }
4285
4286 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004287 std::string Filename = Blob;
4288 ResolveImportedPath(F, Filename);
4289 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004290 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004291 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4292 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004293 // This can be a spurious difference caused by changing the VFS to
4294 // point to a different copy of the file, and it is too late to
4295 // to rebuild safely.
4296 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4297 // after input file validation only real problems would remain and we
4298 // could just error. For now, assume it's okay.
4299 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004300 }
4301 }
4302 break;
4303 }
4304
Richard Smith202210b2014-10-24 20:23:01 +00004305 case SUBMODULE_HEADER:
4306 case SUBMODULE_EXCLUDED_HEADER:
4307 case SUBMODULE_PRIVATE_HEADER:
4308 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004309 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4310 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004311 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004312
Richard Smith202210b2014-10-24 20:23:01 +00004313 case SUBMODULE_TEXTUAL_HEADER:
4314 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4315 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4316 // them here.
4317 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004318
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004320 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 break;
4322 }
4323
4324 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004325 std::string Dirname = Blob;
4326 ResolveImportedPath(F, Dirname);
4327 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004329 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4330 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004331 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4332 Error("mismatched umbrella directories in submodule");
4333 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004334 }
4335 }
4336 break;
4337 }
4338
4339 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004340 F.BaseSubmoduleID = getTotalNumSubmodules();
4341 F.LocalNumSubmodules = Record[0];
4342 unsigned LocalBaseSubmoduleID = Record[1];
4343 if (F.LocalNumSubmodules > 0) {
4344 // Introduce the global -> local mapping for submodules within this
4345 // module.
4346 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4347
4348 // Introduce the local -> global mapping for submodules within this
4349 // module.
4350 F.SubmoduleRemap.insertOrReplace(
4351 std::make_pair(LocalBaseSubmoduleID,
4352 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004353
Ben Langmuir52ca6782014-10-20 16:27:32 +00004354 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4355 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004356 break;
4357 }
4358
4359 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004361 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004362 Unresolved.File = &F;
4363 Unresolved.Mod = CurrentModule;
4364 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004365 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004367 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004368 }
4369 break;
4370 }
4371
4372 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004374 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004375 Unresolved.File = &F;
4376 Unresolved.Mod = CurrentModule;
4377 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004378 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004379 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004380 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 }
4382
4383 // Once we've loaded the set of exports, there's no reason to keep
4384 // the parsed, unresolved exports around.
4385 CurrentModule->UnresolvedExports.clear();
4386 break;
4387 }
4388 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004389 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 Context.getTargetInfo());
4391 break;
4392 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004393
4394 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004395 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004396 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004397 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004398
4399 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004400 CurrentModule->ConfigMacros.push_back(Blob.str());
4401 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004402
4403 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004404 UnresolvedModuleRef Unresolved;
4405 Unresolved.File = &F;
4406 Unresolved.Mod = CurrentModule;
4407 Unresolved.ID = Record[0];
4408 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4409 Unresolved.IsWildcard = false;
4410 Unresolved.String = Blob;
4411 UnresolvedModuleRefs.push_back(Unresolved);
4412 break;
4413 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004414 }
4415 }
4416}
4417
4418/// \brief Parse the record that corresponds to a LangOptions data
4419/// structure.
4420///
4421/// This routine parses the language options from the AST file and then gives
4422/// them to the AST listener if one is set.
4423///
4424/// \returns true if the listener deems the file unacceptable, false otherwise.
4425bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4426 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004427 ASTReaderListener &Listener,
4428 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 LangOptions LangOpts;
4430 unsigned Idx = 0;
4431#define LANGOPT(Name, Bits, Default, Description) \
4432 LangOpts.Name = Record[Idx++];
4433#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4434 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4435#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004436#define SANITIZER(NAME, ID) \
4437 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004438#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004439
4440 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4441 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4442 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4443
4444 unsigned Length = Record[Idx++];
4445 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4446 Record.begin() + Idx + Length);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004447
4448 Idx += Length;
4449
4450 // Comment options.
4451 for (unsigned N = Record[Idx++]; N; --N) {
4452 LangOpts.CommentOpts.BlockCommandNames.push_back(
4453 ReadString(Record, Idx));
4454 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004455 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004456
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004457 return Listener.ReadLanguageOptions(LangOpts, Complain,
4458 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004459}
4460
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004461bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4462 ASTReaderListener &Listener,
4463 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 unsigned Idx = 0;
4465 TargetOptions TargetOpts;
4466 TargetOpts.Triple = ReadString(Record, Idx);
4467 TargetOpts.CPU = ReadString(Record, Idx);
4468 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 for (unsigned N = Record[Idx++]; N; --N) {
4470 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4471 }
4472 for (unsigned N = Record[Idx++]; N; --N) {
4473 TargetOpts.Features.push_back(ReadString(Record, Idx));
4474 }
4475
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004476 return Listener.ReadTargetOptions(TargetOpts, Complain,
4477 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004478}
4479
4480bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4481 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004482 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004484#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004485#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004486 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004487#include "clang/Basic/DiagnosticOptions.def"
4488
Richard Smith3be1cb22014-08-07 00:24:21 +00004489 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004490 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004491 for (unsigned N = Record[Idx++]; N; --N)
4492 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004493
4494 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4495}
4496
4497bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4498 ASTReaderListener &Listener) {
4499 FileSystemOptions FSOpts;
4500 unsigned Idx = 0;
4501 FSOpts.WorkingDir = ReadString(Record, Idx);
4502 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4503}
4504
4505bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4506 bool Complain,
4507 ASTReaderListener &Listener) {
4508 HeaderSearchOptions HSOpts;
4509 unsigned Idx = 0;
4510 HSOpts.Sysroot = ReadString(Record, Idx);
4511
4512 // Include entries.
4513 for (unsigned N = Record[Idx++]; N; --N) {
4514 std::string Path = ReadString(Record, Idx);
4515 frontend::IncludeDirGroup Group
4516 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 bool IsFramework = Record[Idx++];
4518 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004519 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4520 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004521 }
4522
4523 // System header prefixes.
4524 for (unsigned N = Record[Idx++]; N; --N) {
4525 std::string Prefix = ReadString(Record, Idx);
4526 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004527 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004528 }
4529
4530 HSOpts.ResourceDir = ReadString(Record, Idx);
4531 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004532 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 HSOpts.DisableModuleHash = Record[Idx++];
4534 HSOpts.UseBuiltinIncludes = Record[Idx++];
4535 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4536 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4537 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004538 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004539
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004540 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4541 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004542}
4543
4544bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4545 bool Complain,
4546 ASTReaderListener &Listener,
4547 std::string &SuggestedPredefines) {
4548 PreprocessorOptions PPOpts;
4549 unsigned Idx = 0;
4550
4551 // Macro definitions/undefs
4552 for (unsigned N = Record[Idx++]; N; --N) {
4553 std::string Macro = ReadString(Record, Idx);
4554 bool IsUndef = Record[Idx++];
4555 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4556 }
4557
4558 // Includes
4559 for (unsigned N = Record[Idx++]; N; --N) {
4560 PPOpts.Includes.push_back(ReadString(Record, Idx));
4561 }
4562
4563 // Macro Includes
4564 for (unsigned N = Record[Idx++]; N; --N) {
4565 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4566 }
4567
4568 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004569 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4571 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4572 PPOpts.ObjCXXARCStandardLibrary =
4573 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4574 SuggestedPredefines.clear();
4575 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4576 SuggestedPredefines);
4577}
4578
4579std::pair<ModuleFile *, unsigned>
4580ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4581 GlobalPreprocessedEntityMapType::iterator
4582 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4583 assert(I != GlobalPreprocessedEntityMap.end() &&
4584 "Corrupted global preprocessed entity map");
4585 ModuleFile *M = I->second;
4586 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4587 return std::make_pair(M, LocalIndex);
4588}
4589
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004590llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004591ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4592 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4593 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4594 Mod.NumPreprocessedEntities);
4595
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004596 return llvm::make_range(PreprocessingRecord::iterator(),
4597 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00004598}
4599
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004600llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00004601ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004602 return llvm::make_range(
4603 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4604 ModuleDeclIterator(this, &Mod,
4605 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00004606}
4607
4608PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4609 PreprocessedEntityID PPID = Index+1;
4610 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4611 ModuleFile &M = *PPInfo.first;
4612 unsigned LocalIndex = PPInfo.second;
4613 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4614
Guy Benyei11169dd2012-12-18 14:30:41 +00004615 if (!PP.getPreprocessingRecord()) {
4616 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00004617 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004618 }
4619
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004620 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4621 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4622
4623 llvm::BitstreamEntry Entry =
4624 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4625 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00004626 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004627
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 // Read the record.
4629 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4630 ReadSourceLocation(M, PPOffs.End));
4631 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004632 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004633 RecordData Record;
4634 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00004635 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4636 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 switch (RecType) {
4638 case PPD_MACRO_EXPANSION: {
4639 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00004640 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00004641 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004642 if (isBuiltin)
4643 Name = getLocalIdentifier(M, Record[1]);
4644 else {
Richard Smith66a81862015-05-04 02:25:31 +00004645 PreprocessedEntityID GlobalID =
4646 getGlobalPreprocessedEntityID(M, Record[1]);
4647 Def = cast<MacroDefinitionRecord>(
4648 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 }
4650
4651 MacroExpansion *ME;
4652 if (isBuiltin)
4653 ME = new (PPRec) MacroExpansion(Name, Range);
4654 else
4655 ME = new (PPRec) MacroExpansion(Def, Range);
4656
4657 return ME;
4658 }
4659
4660 case PPD_MACRO_DEFINITION: {
4661 // Decode the identifier info and then check again; if the macro is
4662 // still defined and associated with the identifier,
4663 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00004664 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00004665
4666 if (DeserializationListener)
4667 DeserializationListener->MacroDefinitionRead(PPID, MD);
4668
4669 return MD;
4670 }
4671
4672 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00004673 const char *FullFileNameStart = Blob.data() + Record[0];
4674 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00004675 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 if (!FullFileName.empty())
4677 File = PP.getFileManager().getFile(FullFileName);
4678
4679 // FIXME: Stable encoding
4680 InclusionDirective::InclusionKind Kind
4681 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4682 InclusionDirective *ID
4683 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00004684 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 Record[1], Record[3],
4686 File,
4687 Range);
4688 return ID;
4689 }
4690 }
4691
4692 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4693}
4694
4695/// \brief \arg SLocMapI points at a chunk of a module that contains no
4696/// preprocessed entities or the entities it contains are not the ones we are
4697/// looking for. Find the next module that contains entities and return the ID
4698/// of the first entry.
4699PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4700 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4701 ++SLocMapI;
4702 for (GlobalSLocOffsetMapType::const_iterator
4703 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4704 ModuleFile &M = *SLocMapI->second;
4705 if (M.NumPreprocessedEntities)
4706 return M.BasePreprocessedEntityID;
4707 }
4708
4709 return getTotalNumPreprocessedEntities();
4710}
4711
4712namespace {
4713
4714template <unsigned PPEntityOffset::*PPLoc>
4715struct PPEntityComp {
4716 const ASTReader &Reader;
4717 ModuleFile &M;
4718
4719 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4720
4721 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4722 SourceLocation LHS = getLoc(L);
4723 SourceLocation RHS = getLoc(R);
4724 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4725 }
4726
4727 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4728 SourceLocation LHS = getLoc(L);
4729 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4730 }
4731
4732 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4733 SourceLocation RHS = getLoc(R);
4734 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4735 }
4736
4737 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4738 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4739 }
4740};
4741
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004742}
Guy Benyei11169dd2012-12-18 14:30:41 +00004743
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004744PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4745 bool EndsAfter) const {
4746 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 return getTotalNumPreprocessedEntities();
4748
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004749 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4750 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004751 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4752 "Corrupted global sloc offset map");
4753
4754 if (SLocMapI->second->NumPreprocessedEntities == 0)
4755 return findNextPreprocessedEntity(SLocMapI);
4756
4757 ModuleFile &M = *SLocMapI->second;
4758 typedef const PPEntityOffset *pp_iterator;
4759 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4760 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4761
4762 size_t Count = M.NumPreprocessedEntities;
4763 size_t Half;
4764 pp_iterator First = pp_begin;
4765 pp_iterator PPI;
4766
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004767 if (EndsAfter) {
4768 PPI = std::upper_bound(pp_begin, pp_end, Loc,
4769 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4770 } else {
4771 // Do a binary search manually instead of using std::lower_bound because
4772 // The end locations of entities may be unordered (when a macro expansion
4773 // is inside another macro argument), but for this case it is not important
4774 // whether we get the first macro expansion or its containing macro.
4775 while (Count > 0) {
4776 Half = Count / 2;
4777 PPI = First;
4778 std::advance(PPI, Half);
4779 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4780 Loc)) {
4781 First = PPI;
4782 ++First;
4783 Count = Count - Half - 1;
4784 } else
4785 Count = Half;
4786 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004787 }
4788
4789 if (PPI == pp_end)
4790 return findNextPreprocessedEntity(SLocMapI);
4791
4792 return M.BasePreprocessedEntityID + (PPI - pp_begin);
4793}
4794
Guy Benyei11169dd2012-12-18 14:30:41 +00004795/// \brief Returns a pair of [Begin, End) indices of preallocated
4796/// preprocessed entities that \arg Range encompasses.
4797std::pair<unsigned, unsigned>
4798 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4799 if (Range.isInvalid())
4800 return std::make_pair(0,0);
4801 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4802
Alp Toker2e9ce4c2014-05-16 18:59:21 +00004803 PreprocessedEntityID BeginID =
4804 findPreprocessedEntity(Range.getBegin(), false);
4805 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 return std::make_pair(BeginID, EndID);
4807}
4808
4809/// \brief Optionally returns true or false if the preallocated preprocessed
4810/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00004811Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00004812 FileID FID) {
4813 if (FID.isInvalid())
4814 return false;
4815
4816 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4817 ModuleFile &M = *PPInfo.first;
4818 unsigned LocalIndex = PPInfo.second;
4819 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4820
4821 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4822 if (Loc.isInvalid())
4823 return false;
4824
4825 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4826 return true;
4827 else
4828 return false;
4829}
4830
4831namespace {
4832 /// \brief Visitor used to search for information about a header file.
4833 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 const FileEntry *FE;
4835
David Blaikie05785d12013-02-20 22:23:23 +00004836 Optional<HeaderFileInfo> HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004837
4838 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004839 explicit HeaderFileInfoVisitor(const FileEntry *FE)
4840 : FE(FE) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00004841
4842 static bool visit(ModuleFile &M, void *UserData) {
4843 HeaderFileInfoVisitor *This
4844 = static_cast<HeaderFileInfoVisitor *>(UserData);
4845
Guy Benyei11169dd2012-12-18 14:30:41 +00004846 HeaderFileInfoLookupTable *Table
4847 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4848 if (!Table)
4849 return false;
4850
4851 // Look in the on-disk hash table for an entry for this file name.
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00004852 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 if (Pos == Table->end())
4854 return false;
4855
4856 This->HFI = *Pos;
4857 return true;
4858 }
4859
David Blaikie05785d12013-02-20 22:23:23 +00004860 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004862}
Guy Benyei11169dd2012-12-18 14:30:41 +00004863
4864HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00004865 HeaderFileInfoVisitor Visitor(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004866 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00004867 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 return *HFI;
Guy Benyei11169dd2012-12-18 14:30:41 +00004869
4870 return HeaderFileInfo();
4871}
4872
4873void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4874 // FIXME: Make it work properly with modules.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004875 SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4877 ModuleFile &F = *(*I);
4878 unsigned Idx = 0;
4879 DiagStates.clear();
4880 assert(!Diag.DiagStates.empty());
4881 DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4882 while (Idx < F.PragmaDiagMappings.size()) {
4883 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4884 unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4885 if (DiagStateID != 0) {
4886 Diag.DiagStatePoints.push_back(
4887 DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4888 FullSourceLoc(Loc, SourceMgr)));
4889 continue;
4890 }
4891
4892 assert(DiagStateID == 0);
4893 // A new DiagState was created here.
4894 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4895 DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4896 DiagStates.push_back(NewState);
4897 Diag.DiagStatePoints.push_back(
4898 DiagnosticsEngine::DiagStatePoint(NewState,
4899 FullSourceLoc(Loc, SourceMgr)));
4900 while (1) {
4901 assert(Idx < F.PragmaDiagMappings.size() &&
4902 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4903 if (Idx >= F.PragmaDiagMappings.size()) {
4904 break; // Something is messed up but at least avoid infinite loop in
4905 // release build.
4906 }
4907 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4908 if (DiagID == (unsigned)-1) {
4909 break; // no more diag/map pairs for this location.
4910 }
Alp Tokerc726c362014-06-10 09:31:37 +00004911 diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
4912 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4913 Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
Guy Benyei11169dd2012-12-18 14:30:41 +00004914 }
4915 }
4916 }
4917}
4918
4919/// \brief Get the correct cursor and offset for loading a type.
4920ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4921 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4922 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4923 ModuleFile *M = I->second;
4924 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4925}
4926
4927/// \brief Read and return the type with the given index..
4928///
4929/// The index is the type ID, shifted and minus the number of predefs. This
4930/// routine actually reads the record corresponding to the type at the given
4931/// location. It is a helper routine for GetType, which deals with reading type
4932/// IDs.
4933QualType ASTReader::readTypeRecord(unsigned Index) {
4934 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004935 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00004936
4937 // Keep track of where we are in the stream, then jump back there
4938 // after reading this type.
4939 SavedStreamPosition SavedPosition(DeclsCursor);
4940
4941 ReadingKindTracker ReadingKind(Read_Type, *this);
4942
4943 // Note that we are loading a type record.
4944 Deserializing AType(this);
4945
4946 unsigned Idx = 0;
4947 DeclsCursor.JumpToBit(Loc.Offset);
4948 RecordData Record;
4949 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004950 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 case TYPE_EXT_QUAL: {
4952 if (Record.size() != 2) {
4953 Error("Incorrect encoding of extended qualifier type");
4954 return QualType();
4955 }
4956 QualType Base = readType(*Loc.F, Record, Idx);
4957 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4958 return Context.getQualifiedType(Base, Quals);
4959 }
4960
4961 case TYPE_COMPLEX: {
4962 if (Record.size() != 1) {
4963 Error("Incorrect encoding of complex type");
4964 return QualType();
4965 }
4966 QualType ElemType = readType(*Loc.F, Record, Idx);
4967 return Context.getComplexType(ElemType);
4968 }
4969
4970 case TYPE_POINTER: {
4971 if (Record.size() != 1) {
4972 Error("Incorrect encoding of pointer type");
4973 return QualType();
4974 }
4975 QualType PointeeType = readType(*Loc.F, Record, Idx);
4976 return Context.getPointerType(PointeeType);
4977 }
4978
Reid Kleckner8a365022013-06-24 17:51:48 +00004979 case TYPE_DECAYED: {
4980 if (Record.size() != 1) {
4981 Error("Incorrect encoding of decayed type");
4982 return QualType();
4983 }
4984 QualType OriginalType = readType(*Loc.F, Record, Idx);
4985 QualType DT = Context.getAdjustedParameterType(OriginalType);
4986 if (!isa<DecayedType>(DT))
4987 Error("Decayed type does not decay");
4988 return DT;
4989 }
4990
Reid Kleckner0503a872013-12-05 01:23:43 +00004991 case TYPE_ADJUSTED: {
4992 if (Record.size() != 2) {
4993 Error("Incorrect encoding of adjusted type");
4994 return QualType();
4995 }
4996 QualType OriginalTy = readType(*Loc.F, Record, Idx);
4997 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4998 return Context.getAdjustedType(OriginalTy, AdjustedTy);
4999 }
5000
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 case TYPE_BLOCK_POINTER: {
5002 if (Record.size() != 1) {
5003 Error("Incorrect encoding of block pointer type");
5004 return QualType();
5005 }
5006 QualType PointeeType = readType(*Loc.F, Record, Idx);
5007 return Context.getBlockPointerType(PointeeType);
5008 }
5009
5010 case TYPE_LVALUE_REFERENCE: {
5011 if (Record.size() != 2) {
5012 Error("Incorrect encoding of lvalue reference type");
5013 return QualType();
5014 }
5015 QualType PointeeType = readType(*Loc.F, Record, Idx);
5016 return Context.getLValueReferenceType(PointeeType, Record[1]);
5017 }
5018
5019 case TYPE_RVALUE_REFERENCE: {
5020 if (Record.size() != 1) {
5021 Error("Incorrect encoding of rvalue reference type");
5022 return QualType();
5023 }
5024 QualType PointeeType = readType(*Loc.F, Record, Idx);
5025 return Context.getRValueReferenceType(PointeeType);
5026 }
5027
5028 case TYPE_MEMBER_POINTER: {
5029 if (Record.size() != 2) {
5030 Error("Incorrect encoding of member pointer type");
5031 return QualType();
5032 }
5033 QualType PointeeType = readType(*Loc.F, Record, Idx);
5034 QualType ClassType = readType(*Loc.F, Record, Idx);
5035 if (PointeeType.isNull() || ClassType.isNull())
5036 return QualType();
5037
5038 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5039 }
5040
5041 case TYPE_CONSTANT_ARRAY: {
5042 QualType ElementType = readType(*Loc.F, Record, Idx);
5043 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5044 unsigned IndexTypeQuals = Record[2];
5045 unsigned Idx = 3;
5046 llvm::APInt Size = ReadAPInt(Record, Idx);
5047 return Context.getConstantArrayType(ElementType, Size,
5048 ASM, IndexTypeQuals);
5049 }
5050
5051 case TYPE_INCOMPLETE_ARRAY: {
5052 QualType ElementType = readType(*Loc.F, Record, Idx);
5053 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5054 unsigned IndexTypeQuals = Record[2];
5055 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5056 }
5057
5058 case TYPE_VARIABLE_ARRAY: {
5059 QualType ElementType = readType(*Loc.F, Record, Idx);
5060 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5061 unsigned IndexTypeQuals = Record[2];
5062 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5063 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5064 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5065 ASM, IndexTypeQuals,
5066 SourceRange(LBLoc, RBLoc));
5067 }
5068
5069 case TYPE_VECTOR: {
5070 if (Record.size() != 3) {
5071 Error("incorrect encoding of vector type in AST file");
5072 return QualType();
5073 }
5074
5075 QualType ElementType = readType(*Loc.F, Record, Idx);
5076 unsigned NumElements = Record[1];
5077 unsigned VecKind = Record[2];
5078 return Context.getVectorType(ElementType, NumElements,
5079 (VectorType::VectorKind)VecKind);
5080 }
5081
5082 case TYPE_EXT_VECTOR: {
5083 if (Record.size() != 3) {
5084 Error("incorrect encoding of extended vector type in AST file");
5085 return QualType();
5086 }
5087
5088 QualType ElementType = readType(*Loc.F, Record, Idx);
5089 unsigned NumElements = Record[1];
5090 return Context.getExtVectorType(ElementType, NumElements);
5091 }
5092
5093 case TYPE_FUNCTION_NO_PROTO: {
5094 if (Record.size() != 6) {
5095 Error("incorrect encoding of no-proto function type");
5096 return QualType();
5097 }
5098 QualType ResultType = readType(*Loc.F, Record, Idx);
5099 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5100 (CallingConv)Record[4], Record[5]);
5101 return Context.getFunctionNoProtoType(ResultType, Info);
5102 }
5103
5104 case TYPE_FUNCTION_PROTO: {
5105 QualType ResultType = readType(*Loc.F, Record, Idx);
5106
5107 FunctionProtoType::ExtProtoInfo EPI;
5108 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5109 /*hasregparm*/ Record[2],
5110 /*regparm*/ Record[3],
5111 static_cast<CallingConv>(Record[4]),
5112 /*produces*/ Record[5]);
5113
5114 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005115
5116 EPI.Variadic = Record[Idx++];
5117 EPI.HasTrailingReturn = Record[Idx++];
5118 EPI.TypeQuals = Record[Idx++];
5119 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005120 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005121 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005122
5123 unsigned NumParams = Record[Idx++];
5124 SmallVector<QualType, 16> ParamTypes;
5125 for (unsigned I = 0; I != NumParams; ++I)
5126 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5127
Jordan Rose5c382722013-03-08 21:51:21 +00005128 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005129 }
5130
5131 case TYPE_UNRESOLVED_USING: {
5132 unsigned Idx = 0;
5133 return Context.getTypeDeclType(
5134 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5135 }
5136
5137 case TYPE_TYPEDEF: {
5138 if (Record.size() != 2) {
5139 Error("incorrect encoding of typedef type");
5140 return QualType();
5141 }
5142 unsigned Idx = 0;
5143 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5144 QualType Canonical = readType(*Loc.F, Record, Idx);
5145 if (!Canonical.isNull())
5146 Canonical = Context.getCanonicalType(Canonical);
5147 return Context.getTypedefType(Decl, Canonical);
5148 }
5149
5150 case TYPE_TYPEOF_EXPR:
5151 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5152
5153 case TYPE_TYPEOF: {
5154 if (Record.size() != 1) {
5155 Error("incorrect encoding of typeof(type) in AST file");
5156 return QualType();
5157 }
5158 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5159 return Context.getTypeOfType(UnderlyingType);
5160 }
5161
5162 case TYPE_DECLTYPE: {
5163 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5164 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5165 }
5166
5167 case TYPE_UNARY_TRANSFORM: {
5168 QualType BaseType = readType(*Loc.F, Record, Idx);
5169 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5170 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5171 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5172 }
5173
Richard Smith74aeef52013-04-26 16:15:35 +00005174 case TYPE_AUTO: {
5175 QualType Deduced = readType(*Loc.F, Record, Idx);
5176 bool IsDecltypeAuto = Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005177 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005178 return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005179 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005180
5181 case TYPE_RECORD: {
5182 if (Record.size() != 2) {
5183 Error("incorrect encoding of record type");
5184 return QualType();
5185 }
5186 unsigned Idx = 0;
5187 bool IsDependent = Record[Idx++];
5188 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5189 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5190 QualType T = Context.getRecordType(RD);
5191 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5192 return T;
5193 }
5194
5195 case TYPE_ENUM: {
5196 if (Record.size() != 2) {
5197 Error("incorrect encoding of enum type");
5198 return QualType();
5199 }
5200 unsigned Idx = 0;
5201 bool IsDependent = Record[Idx++];
5202 QualType T
5203 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5204 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5205 return T;
5206 }
5207
5208 case TYPE_ATTRIBUTED: {
5209 if (Record.size() != 3) {
5210 Error("incorrect encoding of attributed type");
5211 return QualType();
5212 }
5213 QualType modifiedType = readType(*Loc.F, Record, Idx);
5214 QualType equivalentType = readType(*Loc.F, Record, Idx);
5215 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5216 return Context.getAttributedType(kind, modifiedType, equivalentType);
5217 }
5218
5219 case TYPE_PAREN: {
5220 if (Record.size() != 1) {
5221 Error("incorrect encoding of paren type");
5222 return QualType();
5223 }
5224 QualType InnerType = readType(*Loc.F, Record, Idx);
5225 return Context.getParenType(InnerType);
5226 }
5227
5228 case TYPE_PACK_EXPANSION: {
5229 if (Record.size() != 2) {
5230 Error("incorrect encoding of pack expansion type");
5231 return QualType();
5232 }
5233 QualType Pattern = readType(*Loc.F, Record, Idx);
5234 if (Pattern.isNull())
5235 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005236 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005237 if (Record[1])
5238 NumExpansions = Record[1] - 1;
5239 return Context.getPackExpansionType(Pattern, NumExpansions);
5240 }
5241
5242 case TYPE_ELABORATED: {
5243 unsigned Idx = 0;
5244 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5245 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5246 QualType NamedType = readType(*Loc.F, Record, Idx);
5247 return Context.getElaboratedType(Keyword, NNS, NamedType);
5248 }
5249
5250 case TYPE_OBJC_INTERFACE: {
5251 unsigned Idx = 0;
5252 ObjCInterfaceDecl *ItfD
5253 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5254 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5255 }
5256
5257 case TYPE_OBJC_OBJECT: {
5258 unsigned Idx = 0;
5259 QualType Base = readType(*Loc.F, Record, Idx);
5260 unsigned NumProtos = Record[Idx++];
5261 SmallVector<ObjCProtocolDecl*, 4> Protos;
5262 for (unsigned I = 0; I != NumProtos; ++I)
5263 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5264 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5265 }
5266
5267 case TYPE_OBJC_OBJECT_POINTER: {
5268 unsigned Idx = 0;
5269 QualType Pointee = readType(*Loc.F, Record, Idx);
5270 return Context.getObjCObjectPointerType(Pointee);
5271 }
5272
5273 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5274 unsigned Idx = 0;
5275 QualType Parm = readType(*Loc.F, Record, Idx);
5276 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005277 return Context.getSubstTemplateTypeParmType(
5278 cast<TemplateTypeParmType>(Parm),
5279 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 }
5281
5282 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5283 unsigned Idx = 0;
5284 QualType Parm = readType(*Loc.F, Record, Idx);
5285 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5286 return Context.getSubstTemplateTypeParmPackType(
5287 cast<TemplateTypeParmType>(Parm),
5288 ArgPack);
5289 }
5290
5291 case TYPE_INJECTED_CLASS_NAME: {
5292 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5293 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5294 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5295 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005296 const Type *T = nullptr;
5297 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5298 if (const Type *Existing = DI->getTypeForDecl()) {
5299 T = Existing;
5300 break;
5301 }
5302 }
5303 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005304 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005305 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5306 DI->setTypeForDecl(T);
5307 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005308 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005309 }
5310
5311 case TYPE_TEMPLATE_TYPE_PARM: {
5312 unsigned Idx = 0;
5313 unsigned Depth = Record[Idx++];
5314 unsigned Index = Record[Idx++];
5315 bool Pack = Record[Idx++];
5316 TemplateTypeParmDecl *D
5317 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5318 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5319 }
5320
5321 case TYPE_DEPENDENT_NAME: {
5322 unsigned Idx = 0;
5323 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5324 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5325 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5326 QualType Canon = readType(*Loc.F, Record, Idx);
5327 if (!Canon.isNull())
5328 Canon = Context.getCanonicalType(Canon);
5329 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5330 }
5331
5332 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5333 unsigned Idx = 0;
5334 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5335 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5336 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5337 unsigned NumArgs = Record[Idx++];
5338 SmallVector<TemplateArgument, 8> Args;
5339 Args.reserve(NumArgs);
5340 while (NumArgs--)
5341 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5342 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5343 Args.size(), Args.data());
5344 }
5345
5346 case TYPE_DEPENDENT_SIZED_ARRAY: {
5347 unsigned Idx = 0;
5348
5349 // ArrayType
5350 QualType ElementType = readType(*Loc.F, Record, Idx);
5351 ArrayType::ArraySizeModifier ASM
5352 = (ArrayType::ArraySizeModifier)Record[Idx++];
5353 unsigned IndexTypeQuals = Record[Idx++];
5354
5355 // DependentSizedArrayType
5356 Expr *NumElts = ReadExpr(*Loc.F);
5357 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5358
5359 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5360 IndexTypeQuals, Brackets);
5361 }
5362
5363 case TYPE_TEMPLATE_SPECIALIZATION: {
5364 unsigned Idx = 0;
5365 bool IsDependent = Record[Idx++];
5366 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5367 SmallVector<TemplateArgument, 8> Args;
5368 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5369 QualType Underlying = readType(*Loc.F, Record, Idx);
5370 QualType T;
5371 if (Underlying.isNull())
5372 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5373 Args.size());
5374 else
5375 T = Context.getTemplateSpecializationType(Name, Args.data(),
5376 Args.size(), Underlying);
5377 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5378 return T;
5379 }
5380
5381 case TYPE_ATOMIC: {
5382 if (Record.size() != 1) {
5383 Error("Incorrect encoding of atomic type");
5384 return QualType();
5385 }
5386 QualType ValueType = readType(*Loc.F, Record, Idx);
5387 return Context.getAtomicType(ValueType);
5388 }
5389 }
5390 llvm_unreachable("Invalid TypeCode!");
5391}
5392
Richard Smith564417a2014-03-20 21:47:22 +00005393void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5394 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005395 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005396 const RecordData &Record, unsigned &Idx) {
5397 ExceptionSpecificationType EST =
5398 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005399 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005400 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005401 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005402 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005403 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005404 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005405 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005406 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005407 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5408 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005409 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005410 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005411 }
5412}
5413
Guy Benyei11169dd2012-12-18 14:30:41 +00005414class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5415 ASTReader &Reader;
5416 ModuleFile &F;
5417 const ASTReader::RecordData &Record;
5418 unsigned &Idx;
5419
5420 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5421 unsigned &I) {
5422 return Reader.ReadSourceLocation(F, R, I);
5423 }
5424
5425 template<typename T>
5426 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5427 return Reader.ReadDeclAs<T>(F, Record, Idx);
5428 }
5429
5430public:
5431 TypeLocReader(ASTReader &Reader, ModuleFile &F,
5432 const ASTReader::RecordData &Record, unsigned &Idx)
5433 : Reader(Reader), F(F), Record(Record), Idx(Idx)
5434 { }
5435
5436 // We want compile-time assurance that we've enumerated all of
5437 // these, so unfortunately we have to declare them first, then
5438 // define them out-of-line.
5439#define ABSTRACT_TYPELOC(CLASS, PARENT)
5440#define TYPELOC(CLASS, PARENT) \
5441 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5442#include "clang/AST/TypeLocNodes.def"
5443
5444 void VisitFunctionTypeLoc(FunctionTypeLoc);
5445 void VisitArrayTypeLoc(ArrayTypeLoc);
5446};
5447
5448void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5449 // nothing to do
5450}
5451void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5452 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5453 if (TL.needsExtraLocalData()) {
5454 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5455 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5456 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5457 TL.setModeAttr(Record[Idx++]);
5458 }
5459}
5460void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5461 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5462}
5463void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5464 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5465}
Reid Kleckner8a365022013-06-24 17:51:48 +00005466void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5467 // nothing to do
5468}
Reid Kleckner0503a872013-12-05 01:23:43 +00005469void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5470 // nothing to do
5471}
Guy Benyei11169dd2012-12-18 14:30:41 +00005472void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5473 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5474}
5475void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5476 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5477}
5478void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5479 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5480}
5481void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5482 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5483 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5484}
5485void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5486 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5487 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5488 if (Record[Idx++])
5489 TL.setSizeExpr(Reader.ReadExpr(F));
5490 else
Craig Toppera13603a2014-05-22 05:54:18 +00005491 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005492}
5493void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5494 VisitArrayTypeLoc(TL);
5495}
5496void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5497 VisitArrayTypeLoc(TL);
5498}
5499void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5500 VisitArrayTypeLoc(TL);
5501}
5502void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5503 DependentSizedArrayTypeLoc TL) {
5504 VisitArrayTypeLoc(TL);
5505}
5506void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5507 DependentSizedExtVectorTypeLoc TL) {
5508 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5509}
5510void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5511 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5512}
5513void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5514 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5515}
5516void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5517 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5518 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5519 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5520 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005521 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5522 TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005523 }
5524}
5525void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5526 VisitFunctionTypeLoc(TL);
5527}
5528void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5529 VisitFunctionTypeLoc(TL);
5530}
5531void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5532 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5533}
5534void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5535 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5536}
5537void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5538 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5539 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5540 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5541}
5542void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5543 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5544 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5545 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5546 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5547}
5548void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5549 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5550}
5551void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5552 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5553 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5554 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5555 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5556}
5557void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5558 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5559}
5560void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5561 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5562}
5563void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5564 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5565}
5566void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5567 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5568 if (TL.hasAttrOperand()) {
5569 SourceRange range;
5570 range.setBegin(ReadSourceLocation(Record, Idx));
5571 range.setEnd(ReadSourceLocation(Record, Idx));
5572 TL.setAttrOperandParensRange(range);
5573 }
5574 if (TL.hasAttrExprOperand()) {
5575 if (Record[Idx++])
5576 TL.setAttrExprOperand(Reader.ReadExpr(F));
5577 else
Craig Toppera13603a2014-05-22 05:54:18 +00005578 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00005579 } else if (TL.hasAttrEnumOperand())
5580 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5581}
5582void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5583 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5584}
5585void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5586 SubstTemplateTypeParmTypeLoc TL) {
5587 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5588}
5589void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5590 SubstTemplateTypeParmPackTypeLoc TL) {
5591 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5592}
5593void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5594 TemplateSpecializationTypeLoc TL) {
5595 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5596 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5597 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5598 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5599 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5600 TL.setArgLocInfo(i,
5601 Reader.GetTemplateArgumentLocInfo(F,
5602 TL.getTypePtr()->getArg(i).getKind(),
5603 Record, Idx));
5604}
5605void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5606 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5607 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5608}
5609void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5610 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5611 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5612}
5613void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5614 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5615}
5616void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5617 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5618 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5619 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5620}
5621void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5622 DependentTemplateSpecializationTypeLoc TL) {
5623 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5624 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5625 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5626 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5627 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5628 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5629 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5630 TL.setArgLocInfo(I,
5631 Reader.GetTemplateArgumentLocInfo(F,
5632 TL.getTypePtr()->getArg(I).getKind(),
5633 Record, Idx));
5634}
5635void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5636 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5637}
5638void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5639 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5640}
5641void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5642 TL.setHasBaseTypeAsWritten(Record[Idx++]);
5643 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5644 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5645 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5646 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5647}
5648void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5649 TL.setStarLoc(ReadSourceLocation(Record, Idx));
5650}
5651void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5652 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5653 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5654 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5655}
5656
5657TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5658 const RecordData &Record,
5659 unsigned &Idx) {
5660 QualType InfoTy = readType(F, Record, Idx);
5661 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00005662 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005663
5664 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5665 TypeLocReader TLR(*this, F, Record, Idx);
5666 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5667 TLR.Visit(TL);
5668 return TInfo;
5669}
5670
5671QualType ASTReader::GetType(TypeID ID) {
5672 unsigned FastQuals = ID & Qualifiers::FastMask;
5673 unsigned Index = ID >> Qualifiers::FastWidth;
5674
5675 if (Index < NUM_PREDEF_TYPE_IDS) {
5676 QualType T;
5677 switch ((PredefinedTypeIDs)Index) {
5678 case PREDEF_TYPE_NULL_ID: return QualType();
5679 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5680 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5681
5682 case PREDEF_TYPE_CHAR_U_ID:
5683 case PREDEF_TYPE_CHAR_S_ID:
5684 // FIXME: Check that the signedness of CharTy is correct!
5685 T = Context.CharTy;
5686 break;
5687
5688 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5689 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5690 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5691 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5692 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5693 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5694 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5695 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5696 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5697 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5698 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5699 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5700 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5701 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5702 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5703 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5704 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5705 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5706 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
5707 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
5708 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5709 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5710 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5711 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5712 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5713 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5714 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5715 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00005716 case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5717 case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5718 case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5719 case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5720 case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5721 case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
Guy Benyei61054192013-02-07 10:55:47 +00005722 case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005723 case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005724 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
5725
5726 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5727 T = Context.getAutoRRefDeductType();
5728 break;
5729
5730 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5731 T = Context.ARCUnbridgedCastTy;
5732 break;
5733
5734 case PREDEF_TYPE_VA_LIST_TAG:
5735 T = Context.getVaListTagType();
5736 break;
5737
5738 case PREDEF_TYPE_BUILTIN_FN:
5739 T = Context.BuiltinFnTy;
5740 break;
5741 }
5742
5743 assert(!T.isNull() && "Unknown predefined type");
5744 return T.withFastQualifiers(FastQuals);
5745 }
5746
5747 Index -= NUM_PREDEF_TYPE_IDS;
5748 assert(Index < TypesLoaded.size() && "Type index out-of-range");
5749 if (TypesLoaded[Index].isNull()) {
5750 TypesLoaded[Index] = readTypeRecord(Index);
5751 if (TypesLoaded[Index].isNull())
5752 return QualType();
5753
5754 TypesLoaded[Index]->setFromAST();
5755 if (DeserializationListener)
5756 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5757 TypesLoaded[Index]);
5758 }
5759
5760 return TypesLoaded[Index].withFastQualifiers(FastQuals);
5761}
5762
5763QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5764 return GetType(getGlobalTypeID(F, LocalID));
5765}
5766
5767serialization::TypeID
5768ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5769 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5770 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5771
5772 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5773 return LocalID;
5774
5775 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5776 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5777 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5778
5779 unsigned GlobalIndex = LocalIndex + I->second;
5780 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5781}
5782
5783TemplateArgumentLocInfo
5784ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5785 TemplateArgument::ArgKind Kind,
5786 const RecordData &Record,
5787 unsigned &Index) {
5788 switch (Kind) {
5789 case TemplateArgument::Expression:
5790 return ReadExpr(F);
5791 case TemplateArgument::Type:
5792 return GetTypeSourceInfo(F, Record, Index);
5793 case TemplateArgument::Template: {
5794 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5795 Index);
5796 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5797 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5798 SourceLocation());
5799 }
5800 case TemplateArgument::TemplateExpansion: {
5801 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5802 Index);
5803 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5804 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5805 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5806 EllipsisLoc);
5807 }
5808 case TemplateArgument::Null:
5809 case TemplateArgument::Integral:
5810 case TemplateArgument::Declaration:
5811 case TemplateArgument::NullPtr:
5812 case TemplateArgument::Pack:
5813 // FIXME: Is this right?
5814 return TemplateArgumentLocInfo();
5815 }
5816 llvm_unreachable("unexpected template argument loc");
5817}
5818
5819TemplateArgumentLoc
5820ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5821 const RecordData &Record, unsigned &Index) {
5822 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5823
5824 if (Arg.getKind() == TemplateArgument::Expression) {
5825 if (Record[Index++]) // bool InfoHasSameExpr.
5826 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5827 }
5828 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5829 Record, Index));
5830}
5831
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005832const ASTTemplateArgumentListInfo*
5833ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5834 const RecordData &Record,
5835 unsigned &Index) {
5836 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5837 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5838 unsigned NumArgsAsWritten = Record[Index++];
5839 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5840 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5841 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5842 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5843}
5844
Guy Benyei11169dd2012-12-18 14:30:41 +00005845Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5846 return GetDecl(ID);
5847}
5848
Richard Smith50895422015-01-31 03:04:55 +00005849template<typename TemplateSpecializationDecl>
5850static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5851 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5852 TSD->getSpecializedTemplate()->LoadLazySpecializations();
5853}
5854
Richard Smith053f6c62014-05-16 23:01:30 +00005855void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00005856 if (NumCurrentElementsDeserializing) {
5857 // We arrange to not care about the complete redeclaration chain while we're
5858 // deserializing. Just remember that the AST has marked this one as complete
5859 // but that it's not actually complete yet, so we know we still need to
5860 // complete it later.
5861 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5862 return;
5863 }
5864
Richard Smith053f6c62014-05-16 23:01:30 +00005865 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5866
Richard Smith053f6c62014-05-16 23:01:30 +00005867 // If this is a named declaration, complete it by looking it up
5868 // within its context.
5869 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00005870 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00005871 // all mergeable entities within it.
5872 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5873 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5874 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5875 auto *II = Name.getAsIdentifierInfo();
5876 if (isa<TranslationUnitDecl>(DC) && II) {
5877 // Outside of C++, we don't have a lookup table for the TU, so update
5878 // the identifier instead. In C++, either way should work fine.
5879 if (II->isOutOfDate())
5880 updateOutOfDateIdentifier(*II);
5881 } else
5882 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00005883 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5884 // FIXME: It'd be nice to do something a bit more targeted here.
5885 D->getDeclContext()->decls_begin();
Richard Smith053f6c62014-05-16 23:01:30 +00005886 }
5887 }
Richard Smith50895422015-01-31 03:04:55 +00005888
5889 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5890 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5891 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5892 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5893 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5894 if (auto *Template = FD->getPrimaryTemplate())
5895 Template->LoadLazySpecializations();
5896 }
Richard Smith053f6c62014-05-16 23:01:30 +00005897}
5898
Richard Smithc2bb8182015-03-24 06:36:48 +00005899uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5900 const RecordData &Record,
5901 unsigned &Idx) {
5902 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5903 Error("malformed AST file: missing C++ ctor initializers");
5904 return 0;
5905 }
5906
5907 unsigned LocalID = Record[Idx++];
5908 return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5909}
5910
5911CXXCtorInitializer **
5912ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
5913 RecordLocation Loc = getLocalBitOffset(Offset);
5914 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5915 SavedStreamPosition SavedPosition(Cursor);
5916 Cursor.JumpToBit(Loc.Offset);
5917 ReadingKindTracker ReadingKind(Read_Decl, *this);
5918
5919 RecordData Record;
5920 unsigned Code = Cursor.ReadCode();
5921 unsigned RecCode = Cursor.readRecord(Code, Record);
5922 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5923 Error("malformed AST file: missing C++ ctor initializers");
5924 return nullptr;
5925 }
5926
5927 unsigned Idx = 0;
5928 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5929}
5930
Richard Smithcd45dbc2014-04-19 03:48:30 +00005931uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5932 const RecordData &Record,
5933 unsigned &Idx) {
5934 if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5935 Error("malformed AST file: missing C++ base specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00005936 return 0;
Richard Smithcd45dbc2014-04-19 03:48:30 +00005937 }
5938
Guy Benyei11169dd2012-12-18 14:30:41 +00005939 unsigned LocalID = Record[Idx++];
5940 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5941}
5942
5943CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5944 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005945 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005946 SavedStreamPosition SavedPosition(Cursor);
5947 Cursor.JumpToBit(Loc.Offset);
5948 ReadingKindTracker ReadingKind(Read_Decl, *this);
5949 RecordData Record;
5950 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005951 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00005952 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005953 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00005954 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005955 }
5956
5957 unsigned Idx = 0;
5958 unsigned NumBases = Record[Idx++];
5959 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5960 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5961 for (unsigned I = 0; I != NumBases; ++I)
5962 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5963 return Bases;
5964}
5965
5966serialization::DeclID
5967ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5968 if (LocalID < NUM_PREDEF_DECL_IDS)
5969 return LocalID;
5970
5971 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5972 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5973 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5974
5975 return LocalID + I->second;
5976}
5977
5978bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5979 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00005980 // Predefined decls aren't from any module.
5981 if (ID < NUM_PREDEF_DECL_IDS)
5982 return false;
5983
Guy Benyei11169dd2012-12-18 14:30:41 +00005984 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5985 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5986 return &M == I->second;
5987}
5988
Douglas Gregor9f782892013-01-21 15:25:38 +00005989ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005990 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00005991 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005992 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5993 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5994 return I->second;
5995}
5996
5997SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5998 if (ID < NUM_PREDEF_DECL_IDS)
5999 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006000
Guy Benyei11169dd2012-12-18 14:30:41 +00006001 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6002
6003 if (Index > DeclsLoaded.size()) {
6004 Error("declaration ID out-of-range for AST file");
6005 return SourceLocation();
6006 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006007
Guy Benyei11169dd2012-12-18 14:30:41 +00006008 if (Decl *D = DeclsLoaded[Index])
6009 return D->getLocation();
6010
6011 unsigned RawLocation = 0;
6012 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6013 return ReadSourceLocation(*Rec.F, RawLocation);
6014}
6015
Richard Smithfe620d22015-03-05 23:24:12 +00006016static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6017 switch (ID) {
6018 case PREDEF_DECL_NULL_ID:
6019 return nullptr;
6020
6021 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6022 return Context.getTranslationUnitDecl();
6023
6024 case PREDEF_DECL_OBJC_ID_ID:
6025 return Context.getObjCIdDecl();
6026
6027 case PREDEF_DECL_OBJC_SEL_ID:
6028 return Context.getObjCSelDecl();
6029
6030 case PREDEF_DECL_OBJC_CLASS_ID:
6031 return Context.getObjCClassDecl();
6032
6033 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6034 return Context.getObjCProtocolDecl();
6035
6036 case PREDEF_DECL_INT_128_ID:
6037 return Context.getInt128Decl();
6038
6039 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6040 return Context.getUInt128Decl();
6041
6042 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6043 return Context.getObjCInstanceTypeDecl();
6044
6045 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6046 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006047
6048 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6049 return Context.getExternCContextDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006050 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006051 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006052}
6053
Richard Smithcd45dbc2014-04-19 03:48:30 +00006054Decl *ASTReader::GetExistingDecl(DeclID ID) {
6055 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006056 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6057 if (D) {
6058 // Track that we have merged the declaration with ID \p ID into the
6059 // pre-existing predefined declaration \p D.
6060 auto &Merged = MergedDecls[D->getCanonicalDecl()];
6061 if (Merged.empty())
6062 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 }
Richard Smithfe620d22015-03-05 23:24:12 +00006064 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006065 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006066
Guy Benyei11169dd2012-12-18 14:30:41 +00006067 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6068
6069 if (Index >= DeclsLoaded.size()) {
6070 assert(0 && "declaration ID out-of-range for AST file");
6071 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006072 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006073 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006074
6075 return DeclsLoaded[Index];
6076}
6077
6078Decl *ASTReader::GetDecl(DeclID ID) {
6079 if (ID < NUM_PREDEF_DECL_IDS)
6080 return GetExistingDecl(ID);
6081
6082 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6083
6084 if (Index >= DeclsLoaded.size()) {
6085 assert(0 && "declaration ID out-of-range for AST file");
6086 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006087 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006088 }
6089
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 if (!DeclsLoaded[Index]) {
6091 ReadDeclRecord(ID);
6092 if (DeserializationListener)
6093 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6094 }
6095
6096 return DeclsLoaded[Index];
6097}
6098
6099DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6100 DeclID GlobalID) {
6101 if (GlobalID < NUM_PREDEF_DECL_IDS)
6102 return GlobalID;
6103
6104 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6105 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6106 ModuleFile *Owner = I->second;
6107
6108 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6109 = M.GlobalToLocalDeclIDs.find(Owner);
6110 if (Pos == M.GlobalToLocalDeclIDs.end())
6111 return 0;
6112
6113 return GlobalID - Owner->BaseDeclID + Pos->second;
6114}
6115
6116serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6117 const RecordData &Record,
6118 unsigned &Idx) {
6119 if (Idx >= Record.size()) {
6120 Error("Corrupted AST file");
6121 return 0;
6122 }
6123
6124 return getGlobalDeclID(F, Record[Idx++]);
6125}
6126
6127/// \brief Resolve the offset of a statement into a statement.
6128///
6129/// This operation will read a new statement from the external
6130/// source each time it is called, and is meant to be used via a
6131/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6132Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6133 // Switch case IDs are per Decl.
6134 ClearSwitchCaseIDs();
6135
6136 // Offset here is a global offset across the entire chain.
6137 RecordLocation Loc = getLocalBitOffset(Offset);
6138 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6139 return ReadStmtFromStream(*Loc.F);
6140}
6141
6142namespace {
6143 class FindExternalLexicalDeclsVisitor {
6144 ASTReader &Reader;
6145 const DeclContext *DC;
6146 bool (*isKindWeWant)(Decl::Kind);
6147
6148 SmallVectorImpl<Decl*> &Decls;
6149 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6150
6151 public:
6152 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6153 bool (*isKindWeWant)(Decl::Kind),
6154 SmallVectorImpl<Decl*> &Decls)
6155 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6156 {
6157 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6158 PredefsVisited[I] = false;
6159 }
6160
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006161 static bool visitPostorder(ModuleFile &M, void *UserData) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006162 FindExternalLexicalDeclsVisitor *This
6163 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6164
6165 ModuleFile::DeclContextInfosMap::iterator Info
6166 = M.DeclContextInfos.find(This->DC);
6167 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6168 return false;
6169
6170 // Load all of the declaration IDs
6171 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6172 *IDE = ID + Info->second.NumLexicalDecls;
6173 ID != IDE; ++ID) {
6174 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6175 continue;
6176
6177 // Don't add predefined declarations to the lexical context more
6178 // than once.
6179 if (ID->second < NUM_PREDEF_DECL_IDS) {
6180 if (This->PredefsVisited[ID->second])
6181 continue;
6182
6183 This->PredefsVisited[ID->second] = true;
6184 }
6185
6186 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6187 if (!This->DC->isDeclInLexicalTraversal(D))
6188 This->Decls.push_back(D);
6189 }
6190 }
6191
6192 return false;
6193 }
6194 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006195}
Guy Benyei11169dd2012-12-18 14:30:41 +00006196
6197ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
6198 bool (*isKindWeWant)(Decl::Kind),
6199 SmallVectorImpl<Decl*> &Decls) {
6200 // There might be lexical decls in multiple modules, for the TU at
6201 // least. Walk all of the modules in the order they were loaded.
6202 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
Manuel Klimek9eff8b12015-05-20 10:29:23 +00006203 ModuleMgr.visitDepthFirst(
6204 nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
Guy Benyei11169dd2012-12-18 14:30:41 +00006205 ++NumLexicalDeclContextsRead;
6206 return ELR_Success;
6207}
6208
6209namespace {
6210
6211class DeclIDComp {
6212 ASTReader &Reader;
6213 ModuleFile &Mod;
6214
6215public:
6216 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6217
6218 bool operator()(LocalDeclID L, LocalDeclID R) const {
6219 SourceLocation LHS = getLocation(L);
6220 SourceLocation RHS = getLocation(R);
6221 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6222 }
6223
6224 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6225 SourceLocation RHS = getLocation(R);
6226 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6227 }
6228
6229 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6230 SourceLocation LHS = getLocation(L);
6231 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6232 }
6233
6234 SourceLocation getLocation(LocalDeclID ID) const {
6235 return Reader.getSourceManager().getFileLoc(
6236 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6237 }
6238};
6239
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006240}
Guy Benyei11169dd2012-12-18 14:30:41 +00006241
6242void ASTReader::FindFileRegionDecls(FileID File,
6243 unsigned Offset, unsigned Length,
6244 SmallVectorImpl<Decl *> &Decls) {
6245 SourceManager &SM = getSourceManager();
6246
6247 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6248 if (I == FileDeclIDs.end())
6249 return;
6250
6251 FileDeclsInfo &DInfo = I->second;
6252 if (DInfo.Decls.empty())
6253 return;
6254
6255 SourceLocation
6256 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6257 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6258
6259 DeclIDComp DIDComp(*this, *DInfo.Mod);
6260 ArrayRef<serialization::LocalDeclID>::iterator
6261 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6262 BeginLoc, DIDComp);
6263 if (BeginIt != DInfo.Decls.begin())
6264 --BeginIt;
6265
6266 // If we are pointing at a top-level decl inside an objc container, we need
6267 // to backtrack until we find it otherwise we will fail to report that the
6268 // region overlaps with an objc container.
6269 while (BeginIt != DInfo.Decls.begin() &&
6270 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6271 ->isTopLevelDeclInObjCContainer())
6272 --BeginIt;
6273
6274 ArrayRef<serialization::LocalDeclID>::iterator
6275 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6276 EndLoc, DIDComp);
6277 if (EndIt != DInfo.Decls.end())
6278 ++EndIt;
6279
6280 for (ArrayRef<serialization::LocalDeclID>::iterator
6281 DIt = BeginIt; DIt != EndIt; ++DIt)
6282 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6283}
6284
6285namespace {
6286 /// \brief ModuleFile visitor used to perform name lookup into a
6287 /// declaration context.
6288 class DeclContextNameLookupVisitor {
6289 ASTReader &Reader;
Richard Smith8c913ec2014-08-14 02:21:01 +00006290 ArrayRef<const DeclContext *> Contexts;
Guy Benyei11169dd2012-12-18 14:30:41 +00006291 DeclarationName Name;
6292 SmallVectorImpl<NamedDecl *> &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006293 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
Guy Benyei11169dd2012-12-18 14:30:41 +00006294
6295 public:
Richard Smith8c913ec2014-08-14 02:21:01 +00006296 DeclContextNameLookupVisitor(ASTReader &Reader,
6297 ArrayRef<const DeclContext *> Contexts,
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 DeclarationName Name,
Richard Smith52874ec2015-02-13 20:17:14 +00006299 SmallVectorImpl<NamedDecl *> &Decls,
6300 llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6301 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls),
6302 DeclSet(DeclSet) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006303
6304 static bool visit(ModuleFile &M, void *UserData) {
6305 DeclContextNameLookupVisitor *This
6306 = static_cast<DeclContextNameLookupVisitor *>(UserData);
6307
6308 // Check whether we have any visible declaration information for
6309 // this context in this module.
6310 ModuleFile::DeclContextInfosMap::iterator Info;
6311 bool FoundInfo = false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006312 for (auto *DC : This->Contexts) {
6313 Info = M.DeclContextInfos.find(DC);
6314 if (Info != M.DeclContextInfos.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006315 Info->second.NameLookupTableData) {
6316 FoundInfo = true;
6317 break;
6318 }
6319 }
6320
6321 if (!FoundInfo)
6322 return false;
Richard Smith8c913ec2014-08-14 02:21:01 +00006323
Guy Benyei11169dd2012-12-18 14:30:41 +00006324 // Look for this name within this module.
Richard Smith52e3fba2014-03-11 07:17:35 +00006325 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 Info->second.NameLookupTableData;
6327 ASTDeclContextNameLookupTable::iterator Pos
6328 = LookupTable->find(This->Name);
6329 if (Pos == LookupTable->end())
6330 return false;
6331
6332 bool FoundAnything = false;
6333 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6334 for (; Data.first != Data.second; ++Data.first) {
6335 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6336 if (!ND)
6337 continue;
6338
6339 if (ND->getDeclName() != This->Name) {
6340 // A name might be null because the decl's redeclarable part is
6341 // currently read before reading its name. The lookup is triggered by
6342 // building that decl (likely indirectly), and so it is later in the
6343 // sense of "already existing" and can be ignored here.
Richard Smith8c913ec2014-08-14 02:21:01 +00006344 // FIXME: This should not happen; deserializing declarations should
6345 // not perform lookups since that can lead to deserialization cycles.
Guy Benyei11169dd2012-12-18 14:30:41 +00006346 continue;
6347 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006348
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 // Record this declaration.
6350 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006351 if (This->DeclSet.insert(ND).second)
6352 This->Decls.push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006353 }
6354
6355 return FoundAnything;
6356 }
6357 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006358}
Guy Benyei11169dd2012-12-18 14:30:41 +00006359
Douglas Gregor9f782892013-01-21 15:25:38 +00006360/// \brief Retrieve the "definitive" module file for the definition of the
6361/// given declaration context, if there is one.
6362///
6363/// The "definitive" module file is the only place where we need to look to
6364/// find information about the declarations within the given declaration
6365/// context. For example, C++ and Objective-C classes, C structs/unions, and
6366/// Objective-C protocols, categories, and extensions are all defined in a
6367/// single place in the source code, so they have definitive module files
6368/// associated with them. C++ namespaces, on the other hand, can have
6369/// definitions in multiple different module files.
6370///
6371/// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6372/// NDEBUG checking.
6373static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6374 ASTReader &Reader) {
Douglas Gregor7a6e2002013-01-22 17:08:30 +00006375 if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6376 return Reader.getOwningModuleFile(cast<Decl>(DefDC));
Douglas Gregor9f782892013-01-21 15:25:38 +00006377
Craig Toppera13603a2014-05-22 05:54:18 +00006378 return nullptr;
Douglas Gregor9f782892013-01-21 15:25:38 +00006379}
6380
Richard Smith9ce12e32013-02-07 03:30:24 +00006381bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006382ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6383 DeclarationName Name) {
6384 assert(DC->hasExternalVisibleStorage() &&
6385 "DeclContext has no visible decls in storage");
6386 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006387 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006388
Richard Smith8c913ec2014-08-14 02:21:01 +00006389 Deserializing LookupResults(this);
6390
Guy Benyei11169dd2012-12-18 14:30:41 +00006391 SmallVector<NamedDecl *, 64> Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006392 llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
Richard Smith8c913ec2014-08-14 02:21:01 +00006393
Guy Benyei11169dd2012-12-18 14:30:41 +00006394 // Compute the declaration contexts we need to look into. Multiple such
6395 // declaration contexts occur when two declaration contexts from disjoint
6396 // modules get merged, e.g., when two namespaces with the same name are
6397 // independently defined in separate modules.
6398 SmallVector<const DeclContext *, 2> Contexts;
6399 Contexts.push_back(DC);
Richard Smith8c913ec2014-08-14 02:21:01 +00006400
Guy Benyei11169dd2012-12-18 14:30:41 +00006401 if (DC->isNamespace()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006402 auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 if (Merged != MergedDecls.end()) {
6404 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6405 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6406 }
6407 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006408
6409 auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
Richard Smith52874ec2015-02-13 20:17:14 +00006410 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls, DeclSet);
Richard Smith8c913ec2014-08-14 02:21:01 +00006411
6412 // If we can definitively determine which module file to look into,
6413 // only look there. Otherwise, look in all module files.
6414 ModuleFile *Definitive;
6415 if (Contexts.size() == 1 &&
6416 (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
6417 DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6418 } else {
6419 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6420 }
6421 };
6422
6423 LookUpInContexts(Contexts);
6424
6425 // If this might be an implicit special member function, then also search
6426 // all merged definitions of the surrounding class. We need to search them
6427 // individually, because finding an entity in one of them doesn't imply that
6428 // we can't find a different entity in another one.
Richard Smithcd45dbc2014-04-19 03:48:30 +00006429 if (isa<CXXRecordDecl>(DC)) {
Richard Smith02793752015-03-27 21:16:39 +00006430 auto Merged = MergedLookups.find(DC);
6431 if (Merged != MergedLookups.end()) {
6432 for (unsigned I = 0; I != Merged->second.size(); ++I) {
6433 const DeclContext *Context = Merged->second[I];
6434 LookUpInContexts(Context);
6435 // We might have just added some more merged lookups. If so, our
6436 // iterator is now invalid, so grab a fresh one before continuing.
6437 Merged = MergedLookups.find(DC);
Richard Smithe0612472014-11-21 05:16:13 +00006438 }
Richard Smith8c913ec2014-08-14 02:21:01 +00006439 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006440 }
6441
Guy Benyei11169dd2012-12-18 14:30:41 +00006442 ++NumVisibleDeclContextsRead;
6443 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006444 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006445}
6446
6447namespace {
6448 /// \brief ModuleFile visitor used to retrieve all visible names in a
6449 /// declaration context.
6450 class DeclContextAllNamesVisitor {
6451 ASTReader &Reader;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006452 SmallVectorImpl<const DeclContext *> &Contexts;
Craig Topper3598eb72013-07-05 04:43:31 +00006453 DeclsMap &Decls;
Richard Smith52874ec2015-02-13 20:17:14 +00006454 llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006455 bool VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006456
6457 public:
6458 DeclContextAllNamesVisitor(ASTReader &Reader,
6459 SmallVectorImpl<const DeclContext *> &Contexts,
Craig Topper3598eb72013-07-05 04:43:31 +00006460 DeclsMap &Decls, bool VisitAll)
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006461 : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
Guy Benyei11169dd2012-12-18 14:30:41 +00006462
6463 static bool visit(ModuleFile &M, void *UserData) {
6464 DeclContextAllNamesVisitor *This
6465 = static_cast<DeclContextAllNamesVisitor *>(UserData);
6466
6467 // Check whether we have any visible declaration information for
6468 // this context in this module.
6469 ModuleFile::DeclContextInfosMap::iterator Info;
6470 bool FoundInfo = false;
6471 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6472 Info = M.DeclContextInfos.find(This->Contexts[I]);
6473 if (Info != M.DeclContextInfos.end() &&
6474 Info->second.NameLookupTableData) {
6475 FoundInfo = true;
6476 break;
6477 }
6478 }
6479
6480 if (!FoundInfo)
6481 return false;
6482
Richard Smith52e3fba2014-03-11 07:17:35 +00006483 ASTDeclContextNameLookupTable *LookupTable =
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 Info->second.NameLookupTableData;
6485 bool FoundAnything = false;
6486 for (ASTDeclContextNameLookupTable::data_iterator
Douglas Gregor5e306b12013-01-23 22:38:11 +00006487 I = LookupTable->data_begin(), E = LookupTable->data_end();
6488 I != E;
6489 ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006490 ASTDeclContextNameLookupTrait::data_type Data = *I;
6491 for (; Data.first != Data.second; ++Data.first) {
6492 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6493 *Data.first);
6494 if (!ND)
6495 continue;
6496
6497 // Record this declaration.
6498 FoundAnything = true;
Richard Smith52874ec2015-02-13 20:17:14 +00006499 if (This->DeclSet.insert(ND).second)
6500 This->Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006501 }
6502 }
6503
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006504 return FoundAnything && !This->VisitAll;
Guy Benyei11169dd2012-12-18 14:30:41 +00006505 }
6506 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006507}
Guy Benyei11169dd2012-12-18 14:30:41 +00006508
6509void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6510 if (!DC->hasExternalVisibleStorage())
6511 return;
Craig Topper79be4cd2013-07-05 04:33:53 +00006512 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006513
6514 // Compute the declaration contexts we need to look into. Multiple such
6515 // declaration contexts occur when two declaration contexts from disjoint
6516 // modules get merged, e.g., when two namespaces with the same name are
6517 // independently defined in separate modules.
6518 SmallVector<const DeclContext *, 2> Contexts;
6519 Contexts.push_back(DC);
6520
6521 if (DC->isNamespace()) {
6522 MergedDeclsMap::iterator Merged
6523 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6524 if (Merged != MergedDecls.end()) {
6525 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6526 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6527 }
6528 }
6529
Argyrios Kyrtzidis2810e9d2012-12-19 22:21:18 +00006530 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6531 /*VisitAll=*/DC->isFileContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6533 ++NumVisibleDeclContextsRead;
6534
Craig Topper79be4cd2013-07-05 04:33:53 +00006535 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006536 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6537 }
6538 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6539}
6540
6541/// \brief Under non-PCH compilation the consumer receives the objc methods
6542/// before receiving the implementation, and codegen depends on this.
6543/// We simulate this by deserializing and passing to consumer the methods of the
6544/// implementation before passing the deserialized implementation decl.
6545static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6546 ASTConsumer *Consumer) {
6547 assert(ImplD && Consumer);
6548
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006549 for (auto *I : ImplD->methods())
6550 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006551
6552 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6553}
6554
6555void ASTReader::PassInterestingDeclsToConsumer() {
6556 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006557
6558 if (PassingDeclsToConsumer)
6559 return;
6560
6561 // Guard variable to avoid recursively redoing the process of passing
6562 // decls to consumer.
6563 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6564 true);
6565
Richard Smith9e2341d2015-03-23 03:25:59 +00006566 // Ensure that we've loaded all potentially-interesting declarations
6567 // that need to be eagerly loaded.
6568 for (auto ID : EagerlyDeserializedDecls)
6569 GetDecl(ID);
6570 EagerlyDeserializedDecls.clear();
6571
Guy Benyei11169dd2012-12-18 14:30:41 +00006572 while (!InterestingDecls.empty()) {
6573 Decl *D = InterestingDecls.front();
6574 InterestingDecls.pop_front();
6575
6576 PassInterestingDeclToConsumer(D);
6577 }
6578}
6579
6580void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6581 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6582 PassObjCImplDeclToConsumer(ImplD, Consumer);
6583 else
6584 Consumer->HandleInterestingDecl(DeclGroupRef(D));
6585}
6586
6587void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6588 this->Consumer = Consumer;
6589
Richard Smith9e2341d2015-03-23 03:25:59 +00006590 if (Consumer)
6591 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00006592
6593 if (DeserializationListener)
6594 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00006595}
6596
6597void ASTReader::PrintStats() {
6598 std::fprintf(stderr, "*** AST File Statistics:\n");
6599
6600 unsigned NumTypesLoaded
6601 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6602 QualType());
6603 unsigned NumDeclsLoaded
6604 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006605 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006606 unsigned NumIdentifiersLoaded
6607 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6608 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006609 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 unsigned NumMacrosLoaded
6611 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6612 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00006613 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 unsigned NumSelectorsLoaded
6615 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6616 SelectorsLoaded.end(),
6617 Selector());
6618
6619 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6620 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6621 NumSLocEntriesRead, TotalNumSLocEntries,
6622 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6623 if (!TypesLoaded.empty())
6624 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6625 NumTypesLoaded, (unsigned)TypesLoaded.size(),
6626 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6627 if (!DeclsLoaded.empty())
6628 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6629 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6630 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6631 if (!IdentifiersLoaded.empty())
6632 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6633 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6634 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6635 if (!MacrosLoaded.empty())
6636 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6637 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6638 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6639 if (!SelectorsLoaded.empty())
6640 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6641 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6642 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6643 if (TotalNumStatements)
6644 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6645 NumStatementsRead, TotalNumStatements,
6646 ((float)NumStatementsRead/TotalNumStatements * 100));
6647 if (TotalNumMacros)
6648 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6649 NumMacrosRead, TotalNumMacros,
6650 ((float)NumMacrosRead/TotalNumMacros * 100));
6651 if (TotalLexicalDeclContexts)
6652 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6653 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6654 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6655 * 100));
6656 if (TotalVisibleDeclContexts)
6657 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6658 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6659 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6660 * 100));
6661 if (TotalNumMethodPoolEntries) {
6662 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6663 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6664 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6665 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00006666 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006667 if (NumMethodPoolLookups) {
6668 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6669 NumMethodPoolHits, NumMethodPoolLookups,
6670 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6671 }
6672 if (NumMethodPoolTableLookups) {
6673 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6674 NumMethodPoolTableHits, NumMethodPoolTableLookups,
6675 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6676 * 100.0));
6677 }
6678
Douglas Gregor00a50f72013-01-25 00:38:33 +00006679 if (NumIdentifierLookupHits) {
6680 std::fprintf(stderr,
6681 " %u / %u identifier table lookups succeeded (%f%%)\n",
6682 NumIdentifierLookupHits, NumIdentifierLookups,
6683 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6684 }
6685
Douglas Gregore060e572013-01-25 01:03:03 +00006686 if (GlobalIndex) {
6687 std::fprintf(stderr, "\n");
6688 GlobalIndex->printStats();
6689 }
6690
Guy Benyei11169dd2012-12-18 14:30:41 +00006691 std::fprintf(stderr, "\n");
6692 dump();
6693 std::fprintf(stderr, "\n");
6694}
6695
6696template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6697static void
6698dumpModuleIDMap(StringRef Name,
6699 const ContinuousRangeMap<Key, ModuleFile *,
6700 InitialCapacity> &Map) {
6701 if (Map.begin() == Map.end())
6702 return;
6703
6704 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6705 llvm::errs() << Name << ":\n";
6706 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6707 I != IEnd; ++I) {
6708 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6709 << "\n";
6710 }
6711}
6712
6713void ASTReader::dump() {
6714 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6715 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6716 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6717 dumpModuleIDMap("Global type map", GlobalTypeMap);
6718 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6719 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6720 dumpModuleIDMap("Global macro map", GlobalMacroMap);
6721 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6722 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6723 dumpModuleIDMap("Global preprocessed entity map",
6724 GlobalPreprocessedEntityMap);
6725
6726 llvm::errs() << "\n*** PCH/Modules Loaded:";
6727 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6728 MEnd = ModuleMgr.end();
6729 M != MEnd; ++M)
6730 (*M)->dump();
6731}
6732
6733/// Return the amount of memory used by memory buffers, breaking down
6734/// by heap-backed versus mmap'ed memory.
6735void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6736 for (ModuleConstIterator I = ModuleMgr.begin(),
6737 E = ModuleMgr.end(); I != E; ++I) {
6738 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6739 size_t bytes = buf->getBufferSize();
6740 switch (buf->getBufferKind()) {
6741 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6742 sizes.malloc_bytes += bytes;
6743 break;
6744 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6745 sizes.mmap_bytes += bytes;
6746 break;
6747 }
6748 }
6749 }
6750}
6751
6752void ASTReader::InitializeSema(Sema &S) {
6753 SemaObj = &S;
6754 S.addExternalSource(this);
6755
6756 // Makes sure any declarations that were deserialized "too early"
6757 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00006758 for (uint64_t ID : PreloadedDeclIDs) {
6759 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6760 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00006761 }
Ben Langmuir5418f402014-09-10 21:29:41 +00006762 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006763
Richard Smith3d8e97e2013-10-18 06:54:39 +00006764 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 if (!FPPragmaOptions.empty()) {
6766 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6767 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6768 }
6769
Richard Smith3d8e97e2013-10-18 06:54:39 +00006770 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00006771 if (!OpenCLExtensions.empty()) {
6772 unsigned I = 0;
6773#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6774#include "clang/Basic/OpenCLExtensions.def"
6775
6776 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6777 }
Richard Smith3d8e97e2013-10-18 06:54:39 +00006778
6779 UpdateSema();
6780}
6781
6782void ASTReader::UpdateSema() {
6783 assert(SemaObj && "no Sema to update");
6784
6785 // Load the offsets of the declarations that Sema references.
6786 // They will be lazily deserialized when needed.
6787 if (!SemaDeclRefs.empty()) {
6788 assert(SemaDeclRefs.size() % 2 == 0);
6789 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6790 if (!SemaObj->StdNamespace)
6791 SemaObj->StdNamespace = SemaDeclRefs[I];
6792 if (!SemaObj->StdBadAlloc)
6793 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6794 }
6795 SemaDeclRefs.clear();
6796 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00006797
6798 // Update the state of 'pragma clang optimize'. Use the same API as if we had
6799 // encountered the pragma in the source.
6800 if(OptimizeOffPragmaLocation.isValid())
6801 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Guy Benyei11169dd2012-12-18 14:30:41 +00006802}
6803
6804IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6805 // Note that we are loading an identifier.
6806 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00006807 StringRef Name(NameStart, NameEnd - NameStart);
6808
6809 // If there is a global index, look there first to determine which modules
6810 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00006811 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00006812 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00006813 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00006814 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6815 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00006816 }
6817 }
Douglas Gregor7211ac12013-01-25 23:32:03 +00006818 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00006819 NumIdentifierLookups,
6820 NumIdentifierLookupHits);
Douglas Gregor7211ac12013-01-25 23:32:03 +00006821 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006822 IdentifierInfo *II = Visitor.getIdentifierInfo();
6823 markIdentifierUpToDate(II);
6824 return II;
6825}
6826
6827namespace clang {
6828 /// \brief An identifier-lookup iterator that enumerates all of the
6829 /// identifiers stored within a set of AST files.
6830 class ASTIdentifierIterator : public IdentifierIterator {
6831 /// \brief The AST reader whose identifiers are being enumerated.
6832 const ASTReader &Reader;
6833
6834 /// \brief The current index into the chain of AST files stored in
6835 /// the AST reader.
6836 unsigned Index;
6837
6838 /// \brief The current position within the identifier lookup table
6839 /// of the current AST file.
6840 ASTIdentifierLookupTable::key_iterator Current;
6841
6842 /// \brief The end position within the identifier lookup table of
6843 /// the current AST file.
6844 ASTIdentifierLookupTable::key_iterator End;
6845
6846 public:
6847 explicit ASTIdentifierIterator(const ASTReader &Reader);
6848
Craig Topper3e89dfe2014-03-13 02:13:41 +00006849 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00006850 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006851}
Guy Benyei11169dd2012-12-18 14:30:41 +00006852
6853ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6854 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6855 ASTIdentifierLookupTable *IdTable
6856 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6857 Current = IdTable->key_begin();
6858 End = IdTable->key_end();
6859}
6860
6861StringRef ASTIdentifierIterator::Next() {
6862 while (Current == End) {
6863 // If we have exhausted all of our AST files, we're done.
6864 if (Index == 0)
6865 return StringRef();
6866
6867 --Index;
6868 ASTIdentifierLookupTable *IdTable
6869 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6870 IdentifierLookupTable;
6871 Current = IdTable->key_begin();
6872 End = IdTable->key_end();
6873 }
6874
6875 // We have any identifiers remaining in the current AST file; return
6876 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006877 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00006878 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00006879 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00006880}
6881
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00006882IdentifierIterator *ASTReader::getIdentifiers() {
6883 if (!loadGlobalIndex())
6884 return GlobalIndex->createIdentifierIterator();
6885
Guy Benyei11169dd2012-12-18 14:30:41 +00006886 return new ASTIdentifierIterator(*this);
6887}
6888
6889namespace clang { namespace serialization {
6890 class ReadMethodPoolVisitor {
6891 ASTReader &Reader;
6892 Selector Sel;
6893 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006894 unsigned InstanceBits;
6895 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006896 bool InstanceHasMoreThanOneDecl;
6897 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006898 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6899 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00006900
6901 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00006902 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00006903 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00006904 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00006905 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6906 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00006907
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 static bool visit(ModuleFile &M, void *UserData) {
6909 ReadMethodPoolVisitor *This
6910 = static_cast<ReadMethodPoolVisitor *>(UserData);
6911
6912 if (!M.SelectorLookupTable)
6913 return false;
6914
6915 // If we've already searched this module file, skip it now.
6916 if (M.Generation <= This->PriorGeneration)
6917 return true;
6918
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006919 ++This->Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006920 ASTSelectorLookupTable *PoolTable
6921 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6922 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6923 if (Pos == PoolTable->end())
6924 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006925
6926 ++This->Reader.NumMethodPoolTableHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 ++This->Reader.NumSelectorsRead;
6928 // FIXME: Not quite happy with the statistics here. We probably should
6929 // disable this tracking when called via LoadSelector.
6930 // Also, should entries without methods count as misses?
6931 ++This->Reader.NumMethodPoolEntriesRead;
6932 ASTSelectorLookupTrait::data_type Data = *Pos;
6933 if (This->Reader.DeserializationListener)
6934 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6935 This->Sel);
6936
6937 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6938 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006939 This->InstanceBits = Data.InstanceBits;
6940 This->FactoryBits = Data.FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00006941 This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6942 This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 return true;
6944 }
6945
6946 /// \brief Retrieve the instance methods found by this visitor.
6947 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6948 return InstanceMethods;
6949 }
6950
6951 /// \brief Retrieve the instance methods found by this visitor.
6952 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6953 return FactoryMethods;
6954 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006955
6956 unsigned getInstanceBits() const { return InstanceBits; }
6957 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00006958 bool instanceHasMoreThanOneDecl() const {
6959 return InstanceHasMoreThanOneDecl;
6960 }
6961 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006962 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006963} } // end namespace clang::serialization
Guy Benyei11169dd2012-12-18 14:30:41 +00006964
6965/// \brief Add the given set of methods to the method list.
6966static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6967 ObjCMethodList &List) {
6968 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6969 S.addMethodToGlobalList(&List, Methods[I]);
6970 }
6971}
6972
6973void ASTReader::ReadMethodPool(Selector Sel) {
6974 // Get the selector generation and update it to the current generation.
6975 unsigned &Generation = SelectorGeneration[Sel];
6976 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00006977 Generation = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00006978
6979 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006980 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6982 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6983
6984 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006985 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00006987
6988 ++NumMethodPoolHits;
6989
Guy Benyei11169dd2012-12-18 14:30:41 +00006990 if (!getSema())
6991 return;
6992
6993 Sema &S = *getSema();
6994 Sema::GlobalMethodPool::iterator Pos
6995 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00006996
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006997 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00006998 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00006999 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007000 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007001
7002 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7003 // when building a module we keep every method individually and may need to
7004 // update hasMoreThanOneDecl as we add the methods.
7005 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7006 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007007}
7008
7009void ASTReader::ReadKnownNamespaces(
7010 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7011 Namespaces.clear();
7012
7013 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7014 if (NamespaceDecl *Namespace
7015 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7016 Namespaces.push_back(Namespace);
7017 }
7018}
7019
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007020void ASTReader::ReadUndefinedButUsed(
Nick Lewyckyf0f56162013-01-31 03:23:57 +00007021 llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007022 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7023 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007024 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007025 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007026 Undefined.insert(std::make_pair(D, Loc));
7027 }
7028}
Nick Lewycky8334af82013-01-26 00:35:08 +00007029
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007030void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7031 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7032 Exprs) {
7033 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7034 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7035 uint64_t Count = DelayedDeleteExprs[Idx++];
7036 for (uint64_t C = 0; C < Count; ++C) {
7037 SourceLocation DeleteLoc =
7038 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7039 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7040 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7041 }
7042 }
7043}
7044
Guy Benyei11169dd2012-12-18 14:30:41 +00007045void ASTReader::ReadTentativeDefinitions(
7046 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7047 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7048 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7049 if (Var)
7050 TentativeDefs.push_back(Var);
7051 }
7052 TentativeDefinitions.clear();
7053}
7054
7055void ASTReader::ReadUnusedFileScopedDecls(
7056 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7057 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7058 DeclaratorDecl *D
7059 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7060 if (D)
7061 Decls.push_back(D);
7062 }
7063 UnusedFileScopedDecls.clear();
7064}
7065
7066void ASTReader::ReadDelegatingConstructors(
7067 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7068 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7069 CXXConstructorDecl *D
7070 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7071 if (D)
7072 Decls.push_back(D);
7073 }
7074 DelegatingCtorDecls.clear();
7075}
7076
7077void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7078 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7079 TypedefNameDecl *D
7080 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7081 if (D)
7082 Decls.push_back(D);
7083 }
7084 ExtVectorDecls.clear();
7085}
7086
Nico Weber72889432014-09-06 01:25:55 +00007087void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7088 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7089 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7090 ++I) {
7091 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7092 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7093 if (D)
7094 Decls.insert(D);
7095 }
7096 UnusedLocalTypedefNameCandidates.clear();
7097}
7098
Guy Benyei11169dd2012-12-18 14:30:41 +00007099void ASTReader::ReadReferencedSelectors(
7100 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7101 if (ReferencedSelectorsData.empty())
7102 return;
7103
7104 // If there are @selector references added them to its pool. This is for
7105 // implementation of -Wselector.
7106 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7107 unsigned I = 0;
7108 while (I < DataSize) {
7109 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7110 SourceLocation SelLoc
7111 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7112 Sels.push_back(std::make_pair(Sel, SelLoc));
7113 }
7114 ReferencedSelectorsData.clear();
7115}
7116
7117void ASTReader::ReadWeakUndeclaredIdentifiers(
7118 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7119 if (WeakUndeclaredIdentifiers.empty())
7120 return;
7121
7122 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7123 IdentifierInfo *WeakId
7124 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7125 IdentifierInfo *AliasId
7126 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7127 SourceLocation Loc
7128 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7129 bool Used = WeakUndeclaredIdentifiers[I++];
7130 WeakInfo WI(AliasId, Loc);
7131 WI.setUsed(Used);
7132 WeakIDs.push_back(std::make_pair(WeakId, WI));
7133 }
7134 WeakUndeclaredIdentifiers.clear();
7135}
7136
7137void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7138 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7139 ExternalVTableUse VT;
7140 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7141 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7142 VT.DefinitionRequired = VTableUses[Idx++];
7143 VTables.push_back(VT);
7144 }
7145
7146 VTableUses.clear();
7147}
7148
7149void ASTReader::ReadPendingInstantiations(
7150 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7151 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7152 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7153 SourceLocation Loc
7154 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7155
7156 Pending.push_back(std::make_pair(D, Loc));
7157 }
7158 PendingInstantiations.clear();
7159}
7160
Richard Smithe40f2ba2013-08-07 21:41:30 +00007161void ASTReader::ReadLateParsedTemplates(
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007162 llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007163 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7164 /* In loop */) {
7165 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7166
7167 LateParsedTemplate *LT = new LateParsedTemplate;
7168 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7169
7170 ModuleFile *F = getOwningModuleFile(LT->D);
7171 assert(F && "No module");
7172
7173 unsigned TokN = LateParsedTemplates[Idx++];
7174 LT->Toks.reserve(TokN);
7175 for (unsigned T = 0; T < TokN; ++T)
7176 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7177
Chandler Carruth52cee4d2015-03-26 09:08:15 +00007178 LPTMap.insert(std::make_pair(FD, LT));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007179 }
7180
7181 LateParsedTemplates.clear();
7182}
7183
Guy Benyei11169dd2012-12-18 14:30:41 +00007184void ASTReader::LoadSelector(Selector Sel) {
7185 // It would be complicated to avoid reading the methods anyway. So don't.
7186 ReadMethodPool(Sel);
7187}
7188
7189void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7190 assert(ID && "Non-zero identifier ID required");
7191 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7192 IdentifiersLoaded[ID - 1] = II;
7193 if (DeserializationListener)
7194 DeserializationListener->IdentifierRead(ID, II);
7195}
7196
7197/// \brief Set the globally-visible declarations associated with the given
7198/// identifier.
7199///
7200/// If the AST reader is currently in a state where the given declaration IDs
7201/// cannot safely be resolved, they are queued until it is safe to resolve
7202/// them.
7203///
7204/// \param II an IdentifierInfo that refers to one or more globally-visible
7205/// declarations.
7206///
7207/// \param DeclIDs the set of declaration IDs with the name @p II that are
7208/// visible at global scope.
7209///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007210/// \param Decls if non-null, this vector will be populated with the set of
7211/// deserialized declarations. These declarations will not be pushed into
7212/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007213void
7214ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7215 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007216 SmallVectorImpl<Decl *> *Decls) {
7217 if (NumCurrentElementsDeserializing && !Decls) {
7218 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007219 return;
7220 }
7221
7222 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007223 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007224 // Queue this declaration so that it will be added to the
7225 // translation unit scope and identifier's declaration chain
7226 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007227 PreloadedDeclIDs.push_back(DeclIDs[I]);
7228 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007229 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007230
7231 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7232
7233 // If we're simply supposed to record the declarations, do so now.
7234 if (Decls) {
7235 Decls->push_back(D);
7236 continue;
7237 }
7238
7239 // Introduce this declaration into the translation-unit scope
7240 // and add it to the declaration chain for this identifier, so
7241 // that (unqualified) name lookup will find it.
7242 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007243 }
7244}
7245
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007246IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007248 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007249
7250 if (IdentifiersLoaded.empty()) {
7251 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007252 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007253 }
7254
7255 ID -= 1;
7256 if (!IdentifiersLoaded[ID]) {
7257 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7258 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7259 ModuleFile *M = I->second;
7260 unsigned Index = ID - M->BaseIdentifierID;
7261 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7262
7263 // All of the strings in the AST file are preceded by a 16-bit length.
7264 // Extract that 16-bit length to avoid having to execute strlen().
7265 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7266 // unsigned integers. This is important to avoid integer overflow when
7267 // we cast them to 'unsigned'.
7268 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7269 unsigned StrLen = (((unsigned) StrLenPtr[0])
7270 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007271 IdentifiersLoaded[ID]
7272 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Guy Benyei11169dd2012-12-18 14:30:41 +00007273 if (DeserializationListener)
7274 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7275 }
7276
7277 return IdentifiersLoaded[ID];
7278}
7279
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007280IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7281 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007282}
7283
7284IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7285 if (LocalID < NUM_PREDEF_IDENT_IDS)
7286 return LocalID;
7287
7288 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7289 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7290 assert(I != M.IdentifierRemap.end()
7291 && "Invalid index into identifier index remap");
7292
7293 return LocalID + I->second;
7294}
7295
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007296MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007297 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007298 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007299
7300 if (MacrosLoaded.empty()) {
7301 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007302 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007303 }
7304
7305 ID -= NUM_PREDEF_MACRO_IDS;
7306 if (!MacrosLoaded[ID]) {
7307 GlobalMacroMapType::iterator I
7308 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7309 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7310 ModuleFile *M = I->second;
7311 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007312 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7313
7314 if (DeserializationListener)
7315 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7316 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007317 }
7318
7319 return MacrosLoaded[ID];
7320}
7321
7322MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7323 if (LocalID < NUM_PREDEF_MACRO_IDS)
7324 return LocalID;
7325
7326 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7327 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7328 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7329
7330 return LocalID + I->second;
7331}
7332
7333serialization::SubmoduleID
7334ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7335 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7336 return LocalID;
7337
7338 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7339 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7340 assert(I != M.SubmoduleRemap.end()
7341 && "Invalid index into submodule index remap");
7342
7343 return LocalID + I->second;
7344}
7345
7346Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7347 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7348 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007349 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007350 }
7351
7352 if (GlobalID > SubmodulesLoaded.size()) {
7353 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007354 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007355 }
7356
7357 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7358}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007359
7360Module *ASTReader::getModule(unsigned ID) {
7361 return getSubmodule(ID);
7362}
7363
Guy Benyei11169dd2012-12-18 14:30:41 +00007364Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7365 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7366}
7367
7368Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7369 if (ID == 0)
7370 return Selector();
7371
7372 if (ID > SelectorsLoaded.size()) {
7373 Error("selector ID out of range in AST file");
7374 return Selector();
7375 }
7376
Craig Toppera13603a2014-05-22 05:54:18 +00007377 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007378 // Load this selector from the selector table.
7379 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7380 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7381 ModuleFile &M = *I->second;
7382 ASTSelectorLookupTrait Trait(*this, M);
7383 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7384 SelectorsLoaded[ID - 1] =
7385 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7386 if (DeserializationListener)
7387 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7388 }
7389
7390 return SelectorsLoaded[ID - 1];
7391}
7392
7393Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7394 return DecodeSelector(ID);
7395}
7396
7397uint32_t ASTReader::GetNumExternalSelectors() {
7398 // ID 0 (the null selector) is considered an external selector.
7399 return getTotalNumSelectors() + 1;
7400}
7401
7402serialization::SelectorID
7403ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7404 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7405 return LocalID;
7406
7407 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7408 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7409 assert(I != M.SelectorRemap.end()
7410 && "Invalid index into selector index remap");
7411
7412 return LocalID + I->second;
7413}
7414
7415DeclarationName
7416ASTReader::ReadDeclarationName(ModuleFile &F,
7417 const RecordData &Record, unsigned &Idx) {
7418 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7419 switch (Kind) {
7420 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007421 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007422
7423 case DeclarationName::ObjCZeroArgSelector:
7424 case DeclarationName::ObjCOneArgSelector:
7425 case DeclarationName::ObjCMultiArgSelector:
7426 return DeclarationName(ReadSelector(F, Record, Idx));
7427
7428 case DeclarationName::CXXConstructorName:
7429 return Context.DeclarationNames.getCXXConstructorName(
7430 Context.getCanonicalType(readType(F, Record, Idx)));
7431
7432 case DeclarationName::CXXDestructorName:
7433 return Context.DeclarationNames.getCXXDestructorName(
7434 Context.getCanonicalType(readType(F, Record, Idx)));
7435
7436 case DeclarationName::CXXConversionFunctionName:
7437 return Context.DeclarationNames.getCXXConversionFunctionName(
7438 Context.getCanonicalType(readType(F, Record, Idx)));
7439
7440 case DeclarationName::CXXOperatorName:
7441 return Context.DeclarationNames.getCXXOperatorName(
7442 (OverloadedOperatorKind)Record[Idx++]);
7443
7444 case DeclarationName::CXXLiteralOperatorName:
7445 return Context.DeclarationNames.getCXXLiteralOperatorName(
7446 GetIdentifierInfo(F, Record, Idx));
7447
7448 case DeclarationName::CXXUsingDirective:
7449 return DeclarationName::getUsingDirectiveName();
7450 }
7451
7452 llvm_unreachable("Invalid NameKind!");
7453}
7454
7455void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7456 DeclarationNameLoc &DNLoc,
7457 DeclarationName Name,
7458 const RecordData &Record, unsigned &Idx) {
7459 switch (Name.getNameKind()) {
7460 case DeclarationName::CXXConstructorName:
7461 case DeclarationName::CXXDestructorName:
7462 case DeclarationName::CXXConversionFunctionName:
7463 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7464 break;
7465
7466 case DeclarationName::CXXOperatorName:
7467 DNLoc.CXXOperatorName.BeginOpNameLoc
7468 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7469 DNLoc.CXXOperatorName.EndOpNameLoc
7470 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7471 break;
7472
7473 case DeclarationName::CXXLiteralOperatorName:
7474 DNLoc.CXXLiteralOperatorName.OpNameLoc
7475 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7476 break;
7477
7478 case DeclarationName::Identifier:
7479 case DeclarationName::ObjCZeroArgSelector:
7480 case DeclarationName::ObjCOneArgSelector:
7481 case DeclarationName::ObjCMultiArgSelector:
7482 case DeclarationName::CXXUsingDirective:
7483 break;
7484 }
7485}
7486
7487void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7488 DeclarationNameInfo &NameInfo,
7489 const RecordData &Record, unsigned &Idx) {
7490 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7491 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7492 DeclarationNameLoc DNLoc;
7493 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7494 NameInfo.setInfo(DNLoc);
7495}
7496
7497void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7498 const RecordData &Record, unsigned &Idx) {
7499 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7500 unsigned NumTPLists = Record[Idx++];
7501 Info.NumTemplParamLists = NumTPLists;
7502 if (NumTPLists) {
7503 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7504 for (unsigned i=0; i != NumTPLists; ++i)
7505 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7506 }
7507}
7508
7509TemplateName
7510ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7511 unsigned &Idx) {
7512 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7513 switch (Kind) {
7514 case TemplateName::Template:
7515 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7516
7517 case TemplateName::OverloadedTemplate: {
7518 unsigned size = Record[Idx++];
7519 UnresolvedSet<8> Decls;
7520 while (size--)
7521 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7522
7523 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7524 }
7525
7526 case TemplateName::QualifiedTemplate: {
7527 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7528 bool hasTemplKeyword = Record[Idx++];
7529 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7530 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7531 }
7532
7533 case TemplateName::DependentTemplate: {
7534 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7535 if (Record[Idx++]) // isIdentifier
7536 return Context.getDependentTemplateName(NNS,
7537 GetIdentifierInfo(F, Record,
7538 Idx));
7539 return Context.getDependentTemplateName(NNS,
7540 (OverloadedOperatorKind)Record[Idx++]);
7541 }
7542
7543 case TemplateName::SubstTemplateTemplateParm: {
7544 TemplateTemplateParmDecl *param
7545 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7546 if (!param) return TemplateName();
7547 TemplateName replacement = ReadTemplateName(F, Record, Idx);
7548 return Context.getSubstTemplateTemplateParm(param, replacement);
7549 }
7550
7551 case TemplateName::SubstTemplateTemplateParmPack: {
7552 TemplateTemplateParmDecl *Param
7553 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7554 if (!Param)
7555 return TemplateName();
7556
7557 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7558 if (ArgPack.getKind() != TemplateArgument::Pack)
7559 return TemplateName();
7560
7561 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7562 }
7563 }
7564
7565 llvm_unreachable("Unhandled template name kind!");
7566}
7567
7568TemplateArgument
7569ASTReader::ReadTemplateArgument(ModuleFile &F,
7570 const RecordData &Record, unsigned &Idx) {
7571 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7572 switch (Kind) {
7573 case TemplateArgument::Null:
7574 return TemplateArgument();
7575 case TemplateArgument::Type:
7576 return TemplateArgument(readType(F, Record, Idx));
7577 case TemplateArgument::Declaration: {
7578 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00007579 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007580 }
7581 case TemplateArgument::NullPtr:
7582 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7583 case TemplateArgument::Integral: {
7584 llvm::APSInt Value = ReadAPSInt(Record, Idx);
7585 QualType T = readType(F, Record, Idx);
7586 return TemplateArgument(Context, Value, T);
7587 }
7588 case TemplateArgument::Template:
7589 return TemplateArgument(ReadTemplateName(F, Record, Idx));
7590 case TemplateArgument::TemplateExpansion: {
7591 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00007592 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00007593 if (unsigned NumExpansions = Record[Idx++])
7594 NumTemplateExpansions = NumExpansions - 1;
7595 return TemplateArgument(Name, NumTemplateExpansions);
7596 }
7597 case TemplateArgument::Expression:
7598 return TemplateArgument(ReadExpr(F));
7599 case TemplateArgument::Pack: {
7600 unsigned NumArgs = Record[Idx++];
7601 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7602 for (unsigned I = 0; I != NumArgs; ++I)
7603 Args[I] = ReadTemplateArgument(F, Record, Idx);
7604 return TemplateArgument(Args, NumArgs);
7605 }
7606 }
7607
7608 llvm_unreachable("Unhandled template argument kind!");
7609}
7610
7611TemplateParameterList *
7612ASTReader::ReadTemplateParameterList(ModuleFile &F,
7613 const RecordData &Record, unsigned &Idx) {
7614 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7615 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7616 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7617
7618 unsigned NumParams = Record[Idx++];
7619 SmallVector<NamedDecl *, 16> Params;
7620 Params.reserve(NumParams);
7621 while (NumParams--)
7622 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7623
7624 TemplateParameterList* TemplateParams =
7625 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7626 Params.data(), Params.size(), RAngleLoc);
7627 return TemplateParams;
7628}
7629
7630void
7631ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00007632ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00007633 ModuleFile &F, const RecordData &Record,
7634 unsigned &Idx) {
7635 unsigned NumTemplateArgs = Record[Idx++];
7636 TemplArgs.reserve(NumTemplateArgs);
7637 while (NumTemplateArgs--)
7638 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7639}
7640
7641/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00007642void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 const RecordData &Record, unsigned &Idx) {
7644 unsigned NumDecls = Record[Idx++];
7645 Set.reserve(Context, NumDecls);
7646 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00007647 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00007649 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00007650 }
7651}
7652
7653CXXBaseSpecifier
7654ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7655 const RecordData &Record, unsigned &Idx) {
7656 bool isVirtual = static_cast<bool>(Record[Idx++]);
7657 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7658 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7659 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7660 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7661 SourceRange Range = ReadSourceRange(F, Record, Idx);
7662 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7663 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7664 EllipsisLoc);
7665 Result.setInheritConstructors(inheritConstructors);
7666 return Result;
7667}
7668
Richard Smithc2bb8182015-03-24 06:36:48 +00007669CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00007670ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7671 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00007673 assert(NumInitializers && "wrote ctor initializers but have no inits");
7674 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7675 for (unsigned i = 0; i != NumInitializers; ++i) {
7676 TypeSourceInfo *TInfo = nullptr;
7677 bool IsBaseVirtual = false;
7678 FieldDecl *Member = nullptr;
7679 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007680
Richard Smithc2bb8182015-03-24 06:36:48 +00007681 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7682 switch (Type) {
7683 case CTOR_INITIALIZER_BASE:
7684 TInfo = GetTypeSourceInfo(F, Record, Idx);
7685 IsBaseVirtual = Record[Idx++];
7686 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007687
Richard Smithc2bb8182015-03-24 06:36:48 +00007688 case CTOR_INITIALIZER_DELEGATING:
7689 TInfo = GetTypeSourceInfo(F, Record, Idx);
7690 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007691
Richard Smithc2bb8182015-03-24 06:36:48 +00007692 case CTOR_INITIALIZER_MEMBER:
7693 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7694 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007695
Richard Smithc2bb8182015-03-24 06:36:48 +00007696 case CTOR_INITIALIZER_INDIRECT_MEMBER:
7697 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7698 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007699 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007700
7701 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7702 Expr *Init = ReadExpr(F);
7703 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7704 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7705 bool IsWritten = Record[Idx++];
7706 unsigned SourceOrderOrNumArrayIndices;
7707 SmallVector<VarDecl *, 8> Indices;
7708 if (IsWritten) {
7709 SourceOrderOrNumArrayIndices = Record[Idx++];
7710 } else {
7711 SourceOrderOrNumArrayIndices = Record[Idx++];
7712 Indices.reserve(SourceOrderOrNumArrayIndices);
7713 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7714 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7715 }
7716
7717 CXXCtorInitializer *BOMInit;
7718 if (Type == CTOR_INITIALIZER_BASE) {
7719 BOMInit = new (Context)
7720 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7721 RParenLoc, MemberOrEllipsisLoc);
7722 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7723 BOMInit = new (Context)
7724 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7725 } else if (IsWritten) {
7726 if (Member)
7727 BOMInit = new (Context) CXXCtorInitializer(
7728 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7729 else
7730 BOMInit = new (Context)
7731 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7732 LParenLoc, Init, RParenLoc);
7733 } else {
7734 if (IndirectMember) {
7735 assert(Indices.empty() && "Indirect field improperly initialized");
7736 BOMInit = new (Context)
7737 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7738 LParenLoc, Init, RParenLoc);
7739 } else {
7740 BOMInit = CXXCtorInitializer::Create(
7741 Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7742 Indices.data(), Indices.size());
7743 }
7744 }
7745
7746 if (IsWritten)
7747 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7748 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00007749 }
7750
Richard Smithc2bb8182015-03-24 06:36:48 +00007751 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00007752}
7753
7754NestedNameSpecifier *
7755ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7756 const RecordData &Record, unsigned &Idx) {
7757 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00007758 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007759 for (unsigned I = 0; I != N; ++I) {
7760 NestedNameSpecifier::SpecifierKind Kind
7761 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7762 switch (Kind) {
7763 case NestedNameSpecifier::Identifier: {
7764 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7765 NNS = NestedNameSpecifier::Create(Context, Prev, II);
7766 break;
7767 }
7768
7769 case NestedNameSpecifier::Namespace: {
7770 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7771 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7772 break;
7773 }
7774
7775 case NestedNameSpecifier::NamespaceAlias: {
7776 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7777 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7778 break;
7779 }
7780
7781 case NestedNameSpecifier::TypeSpec:
7782 case NestedNameSpecifier::TypeSpecWithTemplate: {
7783 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7784 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00007785 return nullptr;
7786
Guy Benyei11169dd2012-12-18 14:30:41 +00007787 bool Template = Record[Idx++];
7788 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7789 break;
7790 }
7791
7792 case NestedNameSpecifier::Global: {
7793 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7794 // No associated value, and there can't be a prefix.
7795 break;
7796 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007797
7798 case NestedNameSpecifier::Super: {
7799 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7800 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7801 break;
7802 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007803 }
7804 Prev = NNS;
7805 }
7806 return NNS;
7807}
7808
7809NestedNameSpecifierLoc
7810ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7811 unsigned &Idx) {
7812 unsigned N = Record[Idx++];
7813 NestedNameSpecifierLocBuilder Builder;
7814 for (unsigned I = 0; I != N; ++I) {
7815 NestedNameSpecifier::SpecifierKind Kind
7816 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7817 switch (Kind) {
7818 case NestedNameSpecifier::Identifier: {
7819 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7820 SourceRange Range = ReadSourceRange(F, Record, Idx);
7821 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7822 break;
7823 }
7824
7825 case NestedNameSpecifier::Namespace: {
7826 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7827 SourceRange Range = ReadSourceRange(F, Record, Idx);
7828 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7829 break;
7830 }
7831
7832 case NestedNameSpecifier::NamespaceAlias: {
7833 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7834 SourceRange Range = ReadSourceRange(F, Record, Idx);
7835 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7836 break;
7837 }
7838
7839 case NestedNameSpecifier::TypeSpec:
7840 case NestedNameSpecifier::TypeSpecWithTemplate: {
7841 bool Template = Record[Idx++];
7842 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7843 if (!T)
7844 return NestedNameSpecifierLoc();
7845 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7846
7847 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7848 Builder.Extend(Context,
7849 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7850 T->getTypeLoc(), ColonColonLoc);
7851 break;
7852 }
7853
7854 case NestedNameSpecifier::Global: {
7855 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7856 Builder.MakeGlobal(Context, ColonColonLoc);
7857 break;
7858 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007859
7860 case NestedNameSpecifier::Super: {
7861 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7862 SourceRange Range = ReadSourceRange(F, Record, Idx);
7863 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7864 break;
7865 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007866 }
7867 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00007868
Guy Benyei11169dd2012-12-18 14:30:41 +00007869 return Builder.getWithLocInContext(Context);
7870}
7871
7872SourceRange
7873ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7874 unsigned &Idx) {
7875 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7876 SourceLocation end = ReadSourceLocation(F, Record, Idx);
7877 return SourceRange(beg, end);
7878}
7879
7880/// \brief Read an integral value
7881llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7882 unsigned BitWidth = Record[Idx++];
7883 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7884 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7885 Idx += NumWords;
7886 return Result;
7887}
7888
7889/// \brief Read a signed integral value
7890llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7891 bool isUnsigned = Record[Idx++];
7892 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7893}
7894
7895/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00007896llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7897 const llvm::fltSemantics &Sem,
7898 unsigned &Idx) {
7899 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007900}
7901
7902// \brief Read a string
7903std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7904 unsigned Len = Record[Idx++];
7905 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7906 Idx += Len;
7907 return Result;
7908}
7909
Richard Smith7ed1bc92014-12-05 22:42:13 +00007910std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7911 unsigned &Idx) {
7912 std::string Filename = ReadString(Record, Idx);
7913 ResolveImportedPath(F, Filename);
7914 return Filename;
7915}
7916
Guy Benyei11169dd2012-12-18 14:30:41 +00007917VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7918 unsigned &Idx) {
7919 unsigned Major = Record[Idx++];
7920 unsigned Minor = Record[Idx++];
7921 unsigned Subminor = Record[Idx++];
7922 if (Minor == 0)
7923 return VersionTuple(Major);
7924 if (Subminor == 0)
7925 return VersionTuple(Major, Minor - 1);
7926 return VersionTuple(Major, Minor - 1, Subminor - 1);
7927}
7928
7929CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7930 const RecordData &Record,
7931 unsigned &Idx) {
7932 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7933 return CXXTemporary::Create(Context, Decl);
7934}
7935
7936DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00007937 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007938}
7939
7940DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7941 return Diags.Report(Loc, DiagID);
7942}
7943
7944/// \brief Retrieve the identifier table associated with the
7945/// preprocessor.
7946IdentifierTable &ASTReader::getIdentifierTable() {
7947 return PP.getIdentifierTable();
7948}
7949
7950/// \brief Record that the given ID maps to the given switch-case
7951/// statement.
7952void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007953 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007954 "Already have a SwitchCase with this ID");
7955 (*CurrSwitchCaseStmts)[ID] = SC;
7956}
7957
7958/// \brief Retrieve the switch-case statement with the given ID.
7959SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00007960 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00007961 return (*CurrSwitchCaseStmts)[ID];
7962}
7963
7964void ASTReader::ClearSwitchCaseIDs() {
7965 CurrSwitchCaseStmts->clear();
7966}
7967
7968void ASTReader::ReadComments() {
7969 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007970 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00007971 serialization::ModuleFile *> >::iterator
7972 I = CommentsCursors.begin(),
7973 E = CommentsCursors.end();
7974 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007975 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007976 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00007977 serialization::ModuleFile &F = *I->second;
7978 SavedStreamPosition SavedPosition(Cursor);
7979
7980 RecordData Record;
7981 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007982 llvm::BitstreamEntry Entry =
7983 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00007984
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007985 switch (Entry.Kind) {
7986 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7987 case llvm::BitstreamEntry::Error:
7988 Error("malformed block record in AST file");
7989 return;
7990 case llvm::BitstreamEntry::EndBlock:
7991 goto NextCursor;
7992 case llvm::BitstreamEntry::Record:
7993 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00007994 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007995 }
7996
7997 // Read a record.
7998 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007999 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008000 case COMMENTS_RAW_COMMENT: {
8001 unsigned Idx = 0;
8002 SourceRange SR = ReadSourceRange(F, Record, Idx);
8003 RawComment::CommentKind Kind =
8004 (RawComment::CommentKind) Record[Idx++];
8005 bool IsTrailingComment = Record[Idx++];
8006 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008007 Comments.push_back(new (Context) RawComment(
8008 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8009 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008010 break;
8011 }
8012 }
8013 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008014 NextCursor:
8015 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008016 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008017}
8018
Argyrios Kyrtzidis1bde1172014-11-18 05:24:18 +00008019void ASTReader::getInputFiles(ModuleFile &F,
8020 SmallVectorImpl<serialization::InputFile> &Files) {
8021 for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8022 unsigned ID = I+1;
8023 Files.push_back(getInputFile(F, ID));
8024 }
8025}
8026
Richard Smithcd45dbc2014-04-19 03:48:30 +00008027std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8028 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008029 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008030 return M->getFullModuleName();
8031
8032 // Otherwise, use the name of the top-level module the decl is within.
8033 if (ModuleFile *M = getOwningModuleFile(D))
8034 return M->ModuleName;
8035
8036 // Not from a module.
8037 return "";
8038}
8039
Guy Benyei11169dd2012-12-18 14:30:41 +00008040void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008041 while (!PendingIdentifierInfos.empty() ||
8042 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008043 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008044 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008045 // If any identifiers with corresponding top-level declarations have
8046 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008047 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8048 TopLevelDeclsMap;
8049 TopLevelDeclsMap TopLevelDecls;
8050
Guy Benyei11169dd2012-12-18 14:30:41 +00008051 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008052 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008053 SmallVector<uint32_t, 4> DeclIDs =
8054 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008055 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008056
8057 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008058 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008059
Richard Smith851072e2014-05-19 20:59:20 +00008060 // For each decl chain that we wanted to complete while deserializing, mark
8061 // it as "still needs to be completed".
8062 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8063 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8064 }
8065 PendingIncompleteDeclChains.clear();
8066
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 // Load pending declaration chains.
Richard Smithfe620d22015-03-05 23:24:12 +00008068 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
Richard Smithfe620d22015-03-05 23:24:12 +00008069 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Richard Smithe687bf82015-03-16 20:54:07 +00008070 loadPendingDeclChain(PendingDeclChains[I]);
Richard Smithfe620d22015-03-05 23:24:12 +00008071 }
8072 assert(PendingDeclChainsKnown.empty());
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 PendingDeclChains.clear();
8074
Douglas Gregor6168bd22013-02-18 15:53:43 +00008075 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008076 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8077 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008078 IdentifierInfo *II = TLD->first;
8079 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008080 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008081 }
8082 }
8083
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 // Load any pending macro definitions.
8085 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008086 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8087 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8088 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8089 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008090 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008091 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008092 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008093 if (Info.M->Kind != MK_ImplicitModule &&
8094 Info.M->Kind != MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008095 resolvePendingMacro(II, Info);
8096 }
8097 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008098 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008099 ++IDIdx) {
8100 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Richard Smithe842a472014-10-22 02:05:46 +00008101 if (Info.M->Kind == MK_ImplicitModule ||
8102 Info.M->Kind == MK_ExplicitModule)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008103 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 }
8105 }
8106 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008107
8108 // Wire up the DeclContexts for Decls that we delayed setting until
8109 // recursive loading is completed.
8110 while (!PendingDeclContextInfos.empty()) {
8111 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8112 PendingDeclContextInfos.pop_front();
8113 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8114 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8115 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8116 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008117
Richard Smithd1c46742014-04-30 02:24:17 +00008118 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008119 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008120 auto Update = PendingUpdateRecords.pop_back_val();
8121 ReadingKindTracker ReadingKind(Read_Decl, *this);
8122 loadDeclUpdateRecords(Update.first, Update.second);
8123 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 }
Richard Smith8a639892015-01-24 01:07:20 +00008125
8126 // At this point, all update records for loaded decls are in place, so any
8127 // fake class definitions should have become real.
8128 assert(PendingFakeDefinitionData.empty() &&
8129 "faked up a class definition but never saw the real one");
8130
Guy Benyei11169dd2012-12-18 14:30:41 +00008131 // If we deserialized any C++ or Objective-C class definitions, any
8132 // Objective-C protocol definitions, or any redeclarable templates, make sure
8133 // that all redeclarations point to the definitions. Note that this can only
8134 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008135 for (Decl *D : PendingDefinitions) {
8136 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008137 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008138 // Make sure that the TagType points at the definition.
8139 const_cast<TagType*>(TagT)->decl = TD;
8140 }
Richard Smith8ce51082015-03-11 01:44:51 +00008141
Craig Topperc6914d02014-08-25 04:15:02 +00008142 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008143 for (auto *R = getMostRecentExistingDecl(RD); R;
8144 R = R->getPreviousDecl()) {
8145 assert((R == D) ==
8146 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008147 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008148 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008149 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 }
8151
8152 continue;
8153 }
Richard Smith8ce51082015-03-11 01:44:51 +00008154
Craig Topperc6914d02014-08-25 04:15:02 +00008155 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008156 // Make sure that the ObjCInterfaceType points at the definition.
8157 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8158 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008159
8160 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8161 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8162
Guy Benyei11169dd2012-12-18 14:30:41 +00008163 continue;
8164 }
Richard Smith8ce51082015-03-11 01:44:51 +00008165
Craig Topperc6914d02014-08-25 04:15:02 +00008166 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008167 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8168 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8169
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 continue;
8171 }
Richard Smith8ce51082015-03-11 01:44:51 +00008172
Craig Topperc6914d02014-08-25 04:15:02 +00008173 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008174 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8175 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008176 }
8177 PendingDefinitions.clear();
8178
8179 // Load the bodies of any functions or methods we've encountered. We do
8180 // this now (delayed) so that we can be sure that the declaration chains
8181 // have been fully wired up.
Richard Smith8ce51082015-03-11 01:44:51 +00008182 // FIXME: There seems to be no point in delaying this, it does not depend
8183 // on the redecl chains having been wired up.
Guy Benyei11169dd2012-12-18 14:30:41 +00008184 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8185 PBEnd = PendingBodies.end();
8186 PB != PBEnd; ++PB) {
8187 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8188 // FIXME: Check for =delete/=default?
8189 // FIXME: Complain about ODR violations here?
8190 if (!getContext().getLangOpts().Modules || !FD->hasBody())
8191 FD->setLazyBody(PB->second);
8192 continue;
8193 }
8194
8195 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8196 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8197 MD->setLazyBody(PB->second);
8198 }
8199 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008200
8201 // Do some cleanup.
8202 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8203 getContext().deduplicateMergedDefinitonsFor(ND);
8204 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008205}
8206
8207void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008208 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8209 return;
8210
Richard Smitha0ce9c42014-07-29 23:23:27 +00008211 // Trigger the import of the full definition of each class that had any
8212 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008213 // These updates may in turn find and diagnose some ODR failures, so take
8214 // ownership of the set first.
8215 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8216 PendingOdrMergeFailures.clear();
8217 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008218 Merge.first->buildLookup();
8219 Merge.first->decls_begin();
8220 Merge.first->bases_begin();
8221 Merge.first->vbases_begin();
8222 for (auto *RD : Merge.second) {
8223 RD->decls_begin();
8224 RD->bases_begin();
8225 RD->vbases_begin();
8226 }
8227 }
8228
8229 // For each declaration from a merged context, check that the canonical
8230 // definition of that context also contains a declaration of the same
8231 // entity.
8232 //
8233 // Caution: this loop does things that might invalidate iterators into
8234 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8235 while (!PendingOdrMergeChecks.empty()) {
8236 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8237
8238 // FIXME: Skip over implicit declarations for now. This matters for things
8239 // like implicitly-declared special member functions. This isn't entirely
8240 // correct; we can end up with multiple unmerged declarations of the same
8241 // implicit entity.
8242 if (D->isImplicit())
8243 continue;
8244
8245 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008246
8247 bool Found = false;
8248 const Decl *DCanon = D->getCanonicalDecl();
8249
Richard Smith01bdb7a2014-08-28 05:44:07 +00008250 for (auto RI : D->redecls()) {
8251 if (RI->getLexicalDeclContext() == CanonDef) {
8252 Found = true;
8253 break;
8254 }
8255 }
8256 if (Found)
8257 continue;
8258
Richard Smitha0ce9c42014-07-29 23:23:27 +00008259 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith01bdb7a2014-08-28 05:44:07 +00008260 DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
Richard Smitha0ce9c42014-07-29 23:23:27 +00008261 for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8262 !Found && I != E; ++I) {
8263 for (auto RI : (*I)->redecls()) {
8264 if (RI->getLexicalDeclContext() == CanonDef) {
8265 // This declaration is present in the canonical definition. If it's
8266 // in the same redecl chain, it's the one we're looking for.
8267 if (RI->getCanonicalDecl() == DCanon)
8268 Found = true;
8269 else
8270 Candidates.push_back(cast<NamedDecl>(RI));
8271 break;
8272 }
8273 }
8274 }
8275
8276 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008277 // The AST doesn't like TagDecls becoming invalid after they've been
8278 // completed. We only really need to mark FieldDecls as invalid here.
8279 if (!isa<TagDecl>(D))
8280 D->setInvalidDecl();
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008281
8282 // Ensure we don't accidentally recursively enter deserialization while
8283 // we're producing our diagnostic.
8284 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008285
8286 std::string CanonDefModule =
8287 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8288 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8289 << D << getOwningModuleNameForDiagnostic(D)
8290 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8291
8292 if (Candidates.empty())
8293 Diag(cast<Decl>(CanonDef)->getLocation(),
8294 diag::note_module_odr_violation_no_possible_decls) << D;
8295 else {
8296 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8297 Diag(Candidates[I]->getLocation(),
8298 diag::note_module_odr_violation_possible_decl)
8299 << Candidates[I];
8300 }
8301
8302 DiagnosedOdrMergeFailures.insert(CanonDef);
8303 }
8304 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008305
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008306 if (OdrMergeFailures.empty())
8307 return;
8308
8309 // Ensure we don't accidentally recursively enter deserialization while
8310 // we're producing our diagnostics.
8311 Deserializing RecursionGuard(this);
8312
Richard Smithcd45dbc2014-04-19 03:48:30 +00008313 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008314 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008315 // If we've already pointed out a specific problem with this class, don't
8316 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008317 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008318 continue;
8319
8320 bool Diagnosed = false;
8321 for (auto *RD : Merge.second) {
8322 // Multiple different declarations got merged together; tell the user
8323 // where they came from.
8324 if (Merge.first != RD) {
8325 // FIXME: Walk the definition, figure out what's different,
8326 // and diagnose that.
8327 if (!Diagnosed) {
8328 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8329 Diag(Merge.first->getLocation(),
8330 diag::err_module_odr_violation_different_definitions)
8331 << Merge.first << Module.empty() << Module;
8332 Diagnosed = true;
8333 }
8334
8335 Diag(RD->getLocation(),
8336 diag::note_module_odr_violation_different_definitions)
8337 << getOwningModuleNameForDiagnostic(RD);
8338 }
8339 }
8340
8341 if (!Diagnosed) {
8342 // All definitions are updates to the same declaration. This happens if a
8343 // module instantiates the declaration of a class template specialization
8344 // and two or more other modules instantiate its definition.
8345 //
8346 // FIXME: Indicate which modules had instantiations of this definition.
8347 // FIXME: How can this even happen?
8348 Diag(Merge.first->getLocation(),
8349 diag::err_module_odr_violation_different_instantiations)
8350 << Merge.first;
8351 }
8352 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008353}
8354
8355void ASTReader::FinishedDeserializing() {
8356 assert(NumCurrentElementsDeserializing &&
8357 "FinishedDeserializing not paired with StartedDeserializing");
8358 if (NumCurrentElementsDeserializing == 1) {
8359 // We decrease NumCurrentElementsDeserializing only after pending actions
8360 // are finished, to avoid recursively re-calling finishPendingActions().
8361 finishPendingActions();
8362 }
8363 --NumCurrentElementsDeserializing;
8364
Richard Smitha0ce9c42014-07-29 23:23:27 +00008365 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008366 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008367 while (!PendingExceptionSpecUpdates.empty()) {
8368 auto Updates = std::move(PendingExceptionSpecUpdates);
8369 PendingExceptionSpecUpdates.clear();
8370 for (auto Update : Updates) {
8371 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8372 SemaObj->UpdateExceptionSpec(Update.second,
8373 FPT->getExtProtoInfo().ExceptionSpec);
8374 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008375 }
8376
Richard Smitha0ce9c42014-07-29 23:23:27 +00008377 diagnoseOdrViolations();
8378
Richard Smith04d05b52014-03-23 00:27:18 +00008379 // We are not in recursive loading, so it's safe to pass the "interesting"
8380 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008381 if (Consumer)
8382 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008383 }
8384}
8385
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008386void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008387 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8388 // Remove any fake results before adding any real ones.
8389 auto It = PendingFakeLookupResults.find(II);
8390 if (It != PendingFakeLookupResults.end()) {
8391 for (auto *ND : PendingFakeLookupResults[II])
8392 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008393 // FIXME: this works around module+PCH performance issue.
8394 // Rather than erase the result from the map, which is O(n), just clear
8395 // the vector of NamedDecls.
8396 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008397 }
8398 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008399
8400 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8401 SemaObj->TUScope->AddDecl(D);
8402 } else if (SemaObj->TUScope) {
8403 // Adding the decl to IdResolver may have failed because it was already in
8404 // (even though it was not added in scope). If it is already in, make sure
8405 // it gets in the scope as well.
8406 if (std::find(SemaObj->IdResolver.begin(Name),
8407 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8408 SemaObj->TUScope->AddDecl(D);
8409 }
8410}
8411
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008412ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8413 const PCHContainerOperations &PCHContainerOps,
8414 StringRef isysroot, bool DisableValidation,
8415 bool AllowASTWithCompilerErrors,
Nico Weber824285e2014-05-08 04:26:47 +00008416 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Ben Langmuir2cb4a782014-02-05 22:21:15 +00008417 bool UseGlobalIndex)
Craig Toppera13603a2014-05-22 05:54:18 +00008418 : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
Nico Weber824285e2014-05-08 04:26:47 +00008419 OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008420 FileMgr(PP.getFileManager()), PCHContainerOps(PCHContainerOps),
8421 Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8422 Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerOps),
8423 isysroot(isysroot), DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00008424 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8425 AllowConfigurationMismatch(AllowConfigurationMismatch),
8426 ValidateSystemInputs(ValidateSystemInputs),
8427 UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
Adrian Prantlbb165fb2015-06-20 18:53:08 +00008428 CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8429 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8430 NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8431 NumIdentifierLookupHits(0), NumSelectorsRead(0),
Nico Weber824285e2014-05-08 04:26:47 +00008432 NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8433 NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8434 NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8435 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8436 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8437 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00008438 PassingDeclsToConsumer(false), ReadingKind(Read_None) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008439 SourceMgr.setExternalSLocEntrySource(this);
8440}
8441
8442ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00008443 if (OwnsDeserializationListener)
8444 delete DeserializationListener;
8445
Guy Benyei11169dd2012-12-18 14:30:41 +00008446 for (DeclContextVisibleUpdatesPending::iterator
8447 I = PendingVisibleUpdates.begin(),
8448 E = PendingVisibleUpdates.end();
8449 I != E; ++I) {
8450 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8451 F = I->second.end();
8452 J != F; ++J)
8453 delete J->first;
8454 }
8455}