blob: 4d0ad9147771e82228b9260b56dc566699b34ea8 [file] [log] [blame]
Sebastian Redl904c9c82010-08-18 23:57:11 +00001//===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
Douglas Gregor2cf26342009-04-09 22:27:44 +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//
Sebastian Redlc43b54c2010-08-18 23:56:43 +000010// This file defines the ASTReader class, which reads AST files.
Douglas Gregor2cf26342009-04-09 22:27:44 +000011//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000014#include "clang/Serialization/ASTReader.h"
15#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregor98339b92011-08-25 20:47:51 +000016#include "clang/Serialization/ModuleManager.h"
Chandler Carrutha2398d72011-12-09 00:02:23 +000017#include "clang/Serialization/SerializationDiagnostic.h"
Argyrios Kyrtzidis0eca89e2010-08-20 16:03:52 +000018#include "ASTCommon.h"
Douglas Gregor98339b92011-08-25 20:47:51 +000019#include "ASTReaderInternals.h"
Douglas Gregore737f502010-08-12 20:07:10 +000020#include "clang/Sema/Sema.h"
John McCall5f1e0942010-08-24 08:50:51 +000021#include "clang/Sema/Scope.h"
Douglas Gregorfdd01722009-04-14 00:24:19 +000022#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000023#include "clang/AST/ASTContext.h"
John McCall2a7fb272010-08-25 05:32:35 +000024#include "clang/AST/DeclTemplate.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000025#include "clang/AST/Expr.h"
John McCall7a1fad32010-08-24 07:32:53 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregor5f791bb2011-02-28 23:58:31 +000027#include "clang/AST/NestedNameSpecifier.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000028#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000029#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000030#include "clang/Lex/MacroInfo.h"
Douglas Gregor6a5a23f2010-03-19 21:51:54 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora71a7d82012-10-24 20:05:57 +000033#include "clang/Lex/PreprocessorOptions.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000034#include "clang/Lex/HeaderSearch.h"
Douglas Gregorbbf38312012-10-24 16:50:34 +000035#include "clang/Lex/HeaderSearchOptions.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000036#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000037#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000038#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000039#include "clang/Basic/FileManager.h"
Chris Lattner10e286a2010-11-23 19:19:34 +000040#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000041#include "clang/Basic/TargetInfo.h"
Douglas Gregor57016dd2012-10-16 23:40:58 +000042#include "clang/Basic/TargetOptions.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000043#include "clang/Basic/Version.h"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000044#include "clang/Basic/VersionTuple.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000045#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000046#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000047#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000048#include "llvm/Support/ErrorHandling.h"
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000049#include "llvm/Support/FileSystem.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000050#include "llvm/Support/Path.h"
Nick Lewyckyb346d2f2012-04-16 02:51:46 +000051#include "llvm/Support/SaveAndRestore.h"
Michael J. Spencer3a321e22010-12-09 17:36:38 +000052#include "llvm/Support/system_error.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000053#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000054#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000055#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000056#include <sys/stat.h>
Douglas Gregorcfbf1c72011-02-10 17:09:37 +000057
Douglas Gregor2cf26342009-04-09 22:27:44 +000058using namespace clang;
Sebastian Redl8538e8d2010-08-18 23:57:32 +000059using namespace clang::serialization;
Douglas Gregor98339b92011-08-25 20:47:51 +000060using namespace clang::serialization::reader;
Douglas Gregor2cf26342009-04-09 22:27:44 +000061
62//===----------------------------------------------------------------------===//
Sebastian Redl3c7f4132010-08-18 23:57:06 +000063// PCH validator implementation
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000064//===----------------------------------------------------------------------===//
65
Sebastian Redl571db7f2010-08-18 23:56:56 +000066ASTReaderListener::~ASTReaderListener() {}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000067
Douglas Gregor27ffa6c2012-10-23 06:18:24 +000068/// \brief Compare the given set of language options against an existing set of
69/// language options.
70///
71/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
72///
73/// \returns true if the languagae options mis-match, false otherwise.
74static bool checkLanguageOptions(const LangOptions &LangOpts,
75 const LangOptions &ExistingLangOpts,
76 DiagnosticsEngine *Diags) {
77#define LANGOPT(Name, Bits, Default, Description) \
78 if (ExistingLangOpts.Name != LangOpts.Name) { \
79 if (Diags) \
80 Diags->Report(diag::err_pch_langopt_mismatch) \
81 << Description << LangOpts.Name << ExistingLangOpts.Name; \
82 return true; \
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000083 }
84
Douglas Gregor27ffa6c2012-10-23 06:18:24 +000085#define VALUE_LANGOPT(Name, Bits, Default, Description) \
86 if (ExistingLangOpts.Name != LangOpts.Name) { \
87 if (Diags) \
88 Diags->Report(diag::err_pch_langopt_value_mismatch) \
89 << Description; \
90 return true; \
Douglas Gregor38295be2012-10-22 23:51:00 +000091 }
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000092
Douglas Gregor27ffa6c2012-10-23 06:18:24 +000093#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
94 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
95 if (Diags) \
96 Diags->Report(diag::err_pch_langopt_value_mismatch) \
97 << Description; \
98 return true; \
Douglas Gregor7d5e81b2011-09-13 18:26:39 +000099 }
100
101#define BENIGN_LANGOPT(Name, Bits, Default, Description)
102#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
103#include "clang/Basic/LangOptions.def"
John McCall260611a2012-06-20 06:18:46 +0000104
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000105 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
106 if (Diags)
107 Diags->Report(diag::err_pch_langopt_value_mismatch)
108 << "target Objective-C runtime";
John McCall260611a2012-06-20 06:18:46 +0000109 return true;
110 }
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000111
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000112 return false;
113}
114
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000115/// \brief Compare the given set of target options against an existing set of
116/// target options.
117///
118/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
119///
120/// \returns true if the target options mis-match, false otherwise.
121static bool checkTargetOptions(const TargetOptions &TargetOpts,
122 const TargetOptions &ExistingTargetOpts,
123 DiagnosticsEngine *Diags) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000124#define CHECK_TARGET_OPT(Field, Name) \
125 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000126 if (Diags) \
127 Diags->Report(diag::err_pch_targetopt_mismatch) \
Douglas Gregor38295be2012-10-22 23:51:00 +0000128 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
129 return true; \
Douglas Gregor57016dd2012-10-16 23:40:58 +0000130 }
131
132 CHECK_TARGET_OPT(Triple, "target");
133 CHECK_TARGET_OPT(CPU, "target CPU");
134 CHECK_TARGET_OPT(ABI, "target ABI");
135 CHECK_TARGET_OPT(CXXABI, "target C++ ABI");
136 CHECK_TARGET_OPT(LinkerVersion, "target linker version");
137#undef CHECK_TARGET_OPT
138
139 // Compare feature sets.
140 SmallVector<StringRef, 4> ExistingFeatures(
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000141 ExistingTargetOpts.FeaturesAsWritten.begin(),
142 ExistingTargetOpts.FeaturesAsWritten.end());
Douglas Gregor57016dd2012-10-16 23:40:58 +0000143 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
144 TargetOpts.FeaturesAsWritten.end());
145 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
146 std::sort(ReadFeatures.begin(), ReadFeatures.end());
147
148 unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
149 unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
150 while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
151 if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
152 ++ExistingIdx;
153 ++ReadIdx;
154 continue;
155 }
156
157 if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000158 if (Diags)
159 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Douglas Gregor38295be2012-10-22 23:51:00 +0000160 << false << ReadFeatures[ReadIdx];
Douglas Gregor57016dd2012-10-16 23:40:58 +0000161 return true;
162 }
163
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000164 if (Diags)
165 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Douglas Gregor38295be2012-10-22 23:51:00 +0000166 << true << ExistingFeatures[ExistingIdx];
Douglas Gregor57016dd2012-10-16 23:40:58 +0000167 return true;
168 }
169
170 if (ExistingIdx < ExistingN) {
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000171 if (Diags)
172 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Douglas Gregor38295be2012-10-22 23:51:00 +0000173 << true << ExistingFeatures[ExistingIdx];
Douglas Gregor57016dd2012-10-16 23:40:58 +0000174 return true;
175 }
176
177 if (ReadIdx < ReadN) {
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000178 if (Diags)
179 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Douglas Gregor38295be2012-10-22 23:51:00 +0000180 << false << ReadFeatures[ReadIdx];
Douglas Gregor57016dd2012-10-16 23:40:58 +0000181 return true;
182 }
183
184 return false;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000185}
186
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000187bool
188PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
189 bool Complain) {
Douglas Gregor4c0c7e82012-10-24 23:41:50 +0000190 const LangOptions &ExistingLangOpts = PP.getLangOpts();
191 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000192 Complain? &Reader.Diags : 0);
193}
194
195bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
196 bool Complain) {
197 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
198 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
199 Complain? &Reader.Diags : 0);
200}
201
Benjamin Kramer54353f42010-11-25 18:29:30 +0000202namespace {
Douglas Gregor4c0c7e82012-10-24 23:41:50 +0000203 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
204 MacroDefinitionsMap;
205}
206
207/// \brief Collect the macro definitions provided by the given preprocessor
208/// options.
209static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
210 MacroDefinitionsMap &Macros,
211 SmallVectorImpl<StringRef> *MacroNames = 0){
212 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
213 StringRef Macro = PPOpts.Macros[I].first;
214 bool IsUndef = PPOpts.Macros[I].second;
215
216 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
217 StringRef MacroName = MacroPair.first;
218 StringRef MacroBody = MacroPair.second;
219
220 // For an #undef'd macro, we only care about the name.
221 if (IsUndef) {
222 if (MacroNames && !Macros.count(MacroName))
223 MacroNames->push_back(MacroName);
224
225 Macros[MacroName] = std::make_pair("", true);
226 continue;
227 }
228
229 // For a #define'd macro, figure out the actual definition.
230 if (MacroName.size() == Macro.size())
231 MacroBody = "1";
232 else {
233 // Note: GCC drops anything following an end-of-line character.
234 StringRef::size_type End = MacroBody.find_first_of("\n\r");
235 MacroBody = MacroBody.substr(0, End);
236 }
237
238 if (MacroNames && !Macros.count(MacroName))
239 MacroNames->push_back(MacroName);
240 Macros[MacroName] = std::make_pair(MacroBody, false);
241 }
242}
243
244/// \brief Check the preprocessor options deserialized from the control block
245/// against the preprocessor options in an existing preprocessor.
246///
247/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
248static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
249 const PreprocessorOptions &ExistingPPOpts,
250 DiagnosticsEngine *Diags) {
251 // Check macro definitions.
252 MacroDefinitionsMap ASTFileMacros;
253 collectMacroDefinitions(PPOpts, ASTFileMacros);
254 MacroDefinitionsMap ExistingMacros;
255 SmallVector<StringRef, 4> ExistingMacroNames;
256 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
257
258 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
259 // Dig out the macro definition in the existing preprocessor options.
260 StringRef MacroName = ExistingMacroNames[I];
261 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
262
263 // Check whether we know anything about this macro name or not.
264 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
265 = ASTFileMacros.find(MacroName);
266 if (Known == ASTFileMacros.end()) {
267 // FIXME: Check whether this identifier was referenced anywhere in the
268 // AST file. If so, we should reject the AST file. Unfortunately, this
269 // information isn't in the control block. What shall we do about it?
270 continue;
271 }
272
273 // If the macro was defined in one but undef'd in the other, we have a
274 // conflict.
275 if (Existing.second != Known->second.second) {
276 if (Diags) {
277 Diags->Report(diag::err_pch_macro_def_undef)
278 << MacroName << Known->second.second;
279 }
280 return true;
281 }
282
283 // If the macro was #undef'd in both, or if the macro bodies are identical,
284 // it's fine.
285 if (Existing.second || Existing.first == Known->second.first)
286 continue;
287
288 // The macro bodies differ; complain.
289 if (Diags) {
290 Diags->Report(diag::err_pch_macro_def_conflict)
291 << MacroName << Known->second.first << Existing.first;
292 }
293 return true;
294 }
295
296 // Check whether we're using predefines.
297 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
298 if (Diags) {
299 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
300 }
301 return true;
302 }
303
304 return false;
305}
306
307bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
308 bool Complain) {
309 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
310
311 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
312 Complain? &Reader.Diags : 0);
313}
314
315namespace {
Benjamin Kramer54353f42010-11-25 18:29:30 +0000316 struct EmptyStringRef {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000317 bool operator ()(StringRef r) const { return r.empty(); }
Benjamin Kramer54353f42010-11-25 18:29:30 +0000318 };
319 struct EmptyBlock {
320 bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
321 };
322}
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000323
Chris Lattner5f9e2722011-07-23 10:55:15 +0000324static bool EqualConcatenations(SmallVector<StringRef, 2> L,
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000325 PCHPredefinesBlocks R) {
326 // First, sum up the lengths.
327 unsigned LL = 0, RL = 0;
328 for (unsigned I = 0, N = L.size(); I != N; ++I) {
329 LL += L[I].size();
330 }
331 for (unsigned I = 0, N = R.size(); I != N; ++I) {
332 RL += R[I].Data.size();
333 }
334 if (LL != RL)
335 return false;
336 if (LL == 0 && RL == 0)
337 return true;
338
339 // Kick out empty parts, they confuse the algorithm below.
340 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
341 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
342
343 // Do it the hard way. At this point, both vectors must be non-empty.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000344 StringRef LR = L[0], RR = R[0].Data;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000345 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
Daniel Dunbarc76c9e02010-07-16 00:00:11 +0000346 (void) RN;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000347 for (;;) {
348 // Compare the current pieces.
349 if (LR.size() == RR.size()) {
350 // If they're the same length, it's pretty easy.
351 if (LR != RR)
352 return false;
353 // Both pieces are done, advance.
354 ++LI;
355 ++RI;
356 // If either string is done, they're both done, since they're the same
357 // length.
358 if (LI == LN) {
359 assert(RI == RN && "Strings not the same length after all?");
360 return true;
361 }
362 LR = L[LI];
363 RR = R[RI].Data;
364 } else if (LR.size() < RR.size()) {
365 // Right piece is longer.
366 if (!RR.startswith(LR))
367 return false;
368 ++LI;
369 assert(LI != LN && "Strings not the same length after all?");
370 RR = RR.substr(LR.size());
371 LR = L[LI];
372 } else {
373 // Left piece is longer.
374 if (!LR.startswith(RR))
375 return false;
376 ++RI;
377 assert(RI != RN && "Strings not the same length after all?");
378 LR = LR.substr(RR.size());
379 RR = R[RI].Data;
380 }
381 }
382}
383
Chris Lattner5f9e2722011-07-23 10:55:15 +0000384static std::pair<FileID, StringRef::size_type>
385FindMacro(const PCHPredefinesBlocks &Buffers, StringRef MacroDef) {
386 std::pair<FileID, StringRef::size_type> Res;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000387 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
388 Res.second = Buffers[I].Data.find(MacroDef);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000389 if (Res.second != StringRef::npos) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000390 Res.first = Buffers[I].BufferID;
391 break;
392 }
393 }
394 return Res;
395}
396
397bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000398 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000399 std::string &SuggestedPredefines,
Douglas Gregor38295be2012-10-22 23:51:00 +0000400 FileManager &FileMgr,
401 bool Complain) {
Daniel Dunbarc7162932009-11-11 23:58:53 +0000402 // We are in the context of an implicit include, so the predefines buffer will
403 // have a #include entry for the PCH file itself (as normalized by the
404 // preprocessor initialization). Find it and skip over it in the checking
405 // below.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000406 SmallString<256> PCHInclude;
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000407 PCHInclude += "#include \"";
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000408 PCHInclude += HeaderSearch::NormalizeDashIncludePath(OriginalFileName,
409 FileMgr);
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000410 PCHInclude += "\"\n";
Chris Lattner5f9e2722011-07-23 10:55:15 +0000411 std::pair<StringRef,StringRef> Split =
412 StringRef(PP.getPredefines()).split(PCHInclude.str());
413 StringRef Left = Split.first, Right = Split.second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000414 if (Left == PP.getPredefines()) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000415 if (Complain)
416 Error("Missing PCH include entry!");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000417 return true;
418 }
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000419
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000420 // If the concatenation of all the PCH buffers is equal to the adjusted
421 // command line, we're done.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000422 SmallVector<StringRef, 2> CommandLine;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000423 CommandLine.push_back(Left);
424 CommandLine.push_back(Right);
425 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000426 return false;
427
428 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000430 // The predefines buffers are different. Determine what the differences are,
431 // and whether they require us to reject the PCH file.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000432 SmallVector<StringRef, 8> PCHLines;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000433 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
434 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbare6750492009-11-13 16:46:11 +0000435
Chris Lattner5f9e2722011-07-23 10:55:15 +0000436 SmallVector<StringRef, 8> CmdLineLines;
Daniel Dunbare6750492009-11-13 16:46:11 +0000437 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis297c7062010-09-30 16:53:50 +0000438
439 // Pick out implicit #includes after the PCH and don't consider them for
440 // validation; we will insert them into SuggestedPredefines so that the
441 // preprocessor includes them.
442 std::string IncludesAfterPCH;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000443 SmallVector<StringRef, 8> AfterPCHLines;
Argyrios Kyrtzidis297c7062010-09-30 16:53:50 +0000444 Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
445 for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
446 if (AfterPCHLines[i].startswith("#include ")) {
447 IncludesAfterPCH += AfterPCHLines[i];
448 IncludesAfterPCH += '\n';
449 } else {
450 CmdLineLines.push_back(AfterPCHLines[i]);
451 }
452 }
453
454 // Make sure we add the includes last into SuggestedPredefines before we
455 // exit this function.
456 struct AddIncludesRAII {
457 std::string &SuggestedPredefines;
458 std::string &IncludesAfterPCH;
459
460 AddIncludesRAII(std::string &SuggestedPredefines,
461 std::string &IncludesAfterPCH)
462 : SuggestedPredefines(SuggestedPredefines),
463 IncludesAfterPCH(IncludesAfterPCH) { }
464 ~AddIncludesRAII() {
465 SuggestedPredefines += IncludesAfterPCH;
466 }
467 } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000468
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000469 // Sort both sets of predefined buffer lines, since we allow some extra
470 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000471 std::sort(CmdLineLines.begin(), CmdLineLines.end());
472 std::sort(PCHLines.begin(), PCHLines.end());
473
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000474 // Determine which predefines that were used to build the PCH file are missing
475 // from the command line.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000476 std::vector<StringRef> MissingPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000477 std::set_difference(PCHLines.begin(), PCHLines.end(),
478 CmdLineLines.begin(), CmdLineLines.end(),
479 std::back_inserter(MissingPredefines));
480
481 bool MissingDefines = false;
482 bool ConflictingDefines = false;
483 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000484 StringRef Missing = MissingPredefines[I];
Argyrios Kyrtzidis297c7062010-09-30 16:53:50 +0000485 if (Missing.startswith("#include ")) {
486 // An -include was specified when generating the PCH; it is included in
487 // the PCH, just ignore it.
488 continue;
489 }
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000490 if (!Missing.startswith("#define ")) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000491 if (Complain)
492 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000493 return true;
494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000496 // This is a macro definition. Determine the name of the macro we're
497 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000498 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000499 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000500 = Missing.find_first_of("( \n\r", StartOfMacroName);
501 assert(EndOfMacroName != std::string::npos &&
502 "Couldn't find the end of the macro name");
Chris Lattner5f9e2722011-07-23 10:55:15 +0000503 StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000504
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000505 // Determine whether this macro was given a different definition on the
506 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000507 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000508 std::string::size_type MacroDefLen = MacroDefStart.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000509 SmallVector<StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000510 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
511 MacroDefStart);
512 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000513 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000514 // Different macro; we're done.
515 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000516 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
519 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000520 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000521 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000522 (*ConflictPos)[MacroDefLen] != '(')
523 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000525 // We found a conflicting macro definition.
526 break;
527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000529 if (ConflictPos != CmdLineLines.end()) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000530 if (!Complain)
531 return true;
532
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000533 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
534 << MacroName;
535
536 // Show the definition of this macro within the PCH file.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000537 std::pair<FileID, StringRef::size_type> MacroLoc =
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000538 FindMacro(Buffers, Missing);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000539 assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000540 SourceLocation PCHMissingLoc =
541 SourceMgr.getLocForStartOfFile(MacroLoc.first)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000542 .getLocWithOffset(MacroLoc.second);
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000543 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000544
545 ConflictingDefines = true;
546 continue;
547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000549 // If the macro doesn't conflict, then we'll just pick up the macro
550 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000551 if (ConflictingDefines)
552 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000554 if (!MissingDefines) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000555 if (!Complain)
556 return true;
557
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000558 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
559 MissingDefines = true;
560 }
561
Douglas Gregor38295be2012-10-22 23:51:00 +0000562 if (!Complain)
563 return true;
564
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000565 // Show the definition of this macro within the PCH file.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000566 std::pair<FileID, StringRef::size_type> MacroLoc =
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000567 FindMacro(Buffers, Missing);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000568 assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000569 SourceLocation PCHMissingLoc =
570 SourceMgr.getLocForStartOfFile(MacroLoc.first)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000571 .getLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000572 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
573 }
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000575 if (ConflictingDefines)
576 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000578 // Determine what predefines were introduced based on command-line
579 // parameters that were not present when building the PCH
580 // file. Extra #defines are okay, so long as the identifiers being
581 // defined were not used within the precompiled header.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000582 std::vector<StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000583 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
584 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000585 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000586 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000587 StringRef &Extra = ExtraPredefines[I];
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000588 if (!Extra.startswith("#define ")) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000589 if (Complain)
590 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000591 return true;
592 }
593
594 // This is an extra macro definition. Determine the name of the
595 // macro we're defining.
596 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000597 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000598 = Extra.find_first_of("( \n\r", StartOfMacroName);
599 assert(EndOfMacroName != std::string::npos &&
600 "Couldn't find the end of the macro name");
Chris Lattner5f9e2722011-07-23 10:55:15 +0000601 StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000602
603 // Check whether this name was used somewhere in the PCH file. If
604 // so, defining it as a macro could change behavior, so we reject
605 // the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000606 if (IdentifierInfo *II = Reader.get(MacroName)) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000607 if (Complain)
608 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000609 return true;
610 }
611
612 // Add this definition to the suggested predefines buffer.
613 SuggestedPredefines += Extra;
614 SuggestedPredefines += '\n';
615 }
616
617 // If we get here, it's because the predefines buffer had compatible
618 // contents. Accept the PCH file.
619 return false;
620}
621
Douglas Gregor12fab312010-03-16 16:35:32 +0000622void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
623 unsigned ID) {
624 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
625 ++NumHeaderInfos;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000626}
627
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000628void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000629 PP.setCounterValue(Value);
630}
631
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000632//===----------------------------------------------------------------------===//
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000633// AST reader implementation
Douglas Gregor668c1a42009-04-21 22:25:48 +0000634//===----------------------------------------------------------------------===//
635
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000636void
Sebastian Redl571db7f2010-08-18 23:56:56 +0000637ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000638 DeserializationListener = Listener;
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000639}
640
Chris Lattner4c6f9522009-04-27 05:14:47 +0000641
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000642
Douglas Gregor98339b92011-08-25 20:47:51 +0000643unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
644 return serialization::ComputeHash(Sel);
645}
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000646
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Douglas Gregor98339b92011-08-25 20:47:51 +0000648std::pair<unsigned, unsigned>
649ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
650 using namespace clang::io;
651 unsigned KeyLen = ReadUnalignedLE16(d);
652 unsigned DataLen = ReadUnalignedLE16(d);
653 return std::make_pair(KeyLen, DataLen);
654}
655
656ASTSelectorLookupTrait::internal_key_type
657ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
658 using namespace clang::io;
Douglas Gregor35942772011-09-09 21:34:22 +0000659 SelectorTable &SelTable = Reader.getContext().Selectors;
Douglas Gregor98339b92011-08-25 20:47:51 +0000660 unsigned N = ReadUnalignedLE16(d);
661 IdentifierInfo *FirstII
662 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
663 if (N == 0)
664 return SelTable.getNullarySelector(FirstII);
665 else if (N == 1)
666 return SelTable.getUnarySelector(FirstII);
667
668 SmallVector<IdentifierInfo *, 16> Args;
669 Args.push_back(FirstII);
670 for (unsigned I = 1; I != N; ++I)
671 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
672
673 return SelTable.getSelector(N, Args.data());
674}
675
676ASTSelectorLookupTrait::data_type
677ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
678 unsigned DataLen) {
679 using namespace clang::io;
680
681 data_type Result;
682
683 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
684 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
685 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
686
687 // Load instance methods
Douglas Gregor98339b92011-08-25 20:47:51 +0000688 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
689 if (ObjCMethodDecl *Method
690 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
691 Result.Instance.push_back(Method);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000692 }
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Douglas Gregor98339b92011-08-25 20:47:51 +0000694 // Load factory methods
Douglas Gregor98339b92011-08-25 20:47:51 +0000695 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
696 if (ObjCMethodDecl *Method
697 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
698 Result.Factory.push_back(Method);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000699 }
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Douglas Gregor98339b92011-08-25 20:47:51 +0000701 return Result;
702}
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Douglas Gregor98339b92011-08-25 20:47:51 +0000704unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
705 return llvm::HashString(StringRef(a.first, a.second));
706}
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Douglas Gregor98339b92011-08-25 20:47:51 +0000708std::pair<unsigned, unsigned>
709ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
710 using namespace clang::io;
711 unsigned DataLen = ReadUnalignedLE16(d);
712 unsigned KeyLen = ReadUnalignedLE16(d);
713 return std::make_pair(KeyLen, DataLen);
714}
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000715
Douglas Gregor98339b92011-08-25 20:47:51 +0000716std::pair<const char*, unsigned>
717ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
718 assert(n >= 2 && d[n-1] == '\0');
719 return std::make_pair((const char*) d, n-1);
720}
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000721
Douglas Gregor98339b92011-08-25 20:47:51 +0000722IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
723 const unsigned char* d,
724 unsigned DataLen) {
725 using namespace clang::io;
726 unsigned RawID = ReadUnalignedLE32(d);
727 bool IsInteresting = RawID & 0x01;
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Douglas Gregor98339b92011-08-25 20:47:51 +0000729 // Wipe out the "is interesting" bit.
730 RawID = RawID >> 1;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000731
Douglas Gregor98339b92011-08-25 20:47:51 +0000732 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
733 if (!IsInteresting) {
734 // For uninteresting identifiers, just build the IdentifierInfo
735 // and associate it with the persistent ID.
Douglas Gregor668c1a42009-04-21 22:25:48 +0000736 IdentifierInfo *II = KnownII;
Douglas Gregor5d5051f2012-01-24 15:24:38 +0000737 if (!II) {
Douglas Gregor6ec60e02011-08-03 21:49:18 +0000738 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
Douglas Gregor5d5051f2012-01-24 15:24:38 +0000739 KnownII = II;
740 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000741 Reader.SetIdentifierInfo(ID, II);
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000742 II->setIsFromAST();
Douglas Gregor057df202012-01-18 20:56:22 +0000743 Reader.markIdentifierUpToDate(II);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000744 return II;
745 }
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +0000747 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
Douglas Gregor98339b92011-08-25 20:47:51 +0000748 unsigned Bits = ReadUnalignedLE16(d);
749 bool CPlusPlusOperatorKeyword = Bits & 0x01;
750 Bits >>= 1;
751 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
752 Bits >>= 1;
753 bool Poisoned = Bits & 0x01;
754 Bits >>= 1;
755 bool ExtensionToken = Bits & 0x01;
756 Bits >>= 1;
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +0000757 bool hadMacroDefinition = Bits & 0x01;
758 Bits >>= 1;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000759
Douglas Gregor98339b92011-08-25 20:47:51 +0000760 assert(Bits == 0 && "Extra bits in the identifier?");
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +0000761 DataLen -= 8;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000762
Douglas Gregor98339b92011-08-25 20:47:51 +0000763 // Build the IdentifierInfo itself and link the identifier ID with
764 // the new IdentifierInfo.
765 IdentifierInfo *II = KnownII;
Douglas Gregor5d5051f2012-01-24 15:24:38 +0000766 if (!II) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000767 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
Douglas Gregor5d5051f2012-01-24 15:24:38 +0000768 KnownII = II;
769 }
Douglas Gregor057df202012-01-18 20:56:22 +0000770 Reader.markIdentifierUpToDate(II);
Douglas Gregoreee242f2011-10-27 09:33:13 +0000771 II->setIsFromAST();
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000772
Douglas Gregor98339b92011-08-25 20:47:51 +0000773 // Set or check the various bits in the IdentifierInfo structure.
774 // Token IDs are read-only.
775 if (HasRevertedTokenIDToIdentifier)
776 II->RevertTokenIDToIdentifier();
777 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
778 assert(II->isExtensionToken() == ExtensionToken &&
779 "Incorrect extension token flag");
780 (void)ExtensionToken;
781 if (Poisoned)
782 II->setIsPoisoned(true);
783 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
784 "Incorrect C++ operator keyword flag");
785 (void)CPlusPlusOperatorKeyword;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000786
Douglas Gregor98339b92011-08-25 20:47:51 +0000787 // If this identifier is a macro, deserialize the macro
788 // definition.
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +0000789 if (hadMacroDefinition) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000790 SmallVector<MacroID, 4> MacroIDs;
791 while (uint32_t LocalID = ReadUnalignedLE32(d)) {
792 MacroIDs.push_back(Reader.getGlobalMacroID(F, LocalID));
793 DataLen -= 4;
Douglas Gregor13292642011-12-02 15:45:10 +0000794 }
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000795 DataLen -= 4;
796 Reader.setIdentifierIsMacro(II, MacroIDs);
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000797 }
798
Douglas Gregoreee242f2011-10-27 09:33:13 +0000799 Reader.SetIdentifierInfo(ID, II);
800
Douglas Gregor98339b92011-08-25 20:47:51 +0000801 // Read all of the declarations visible at global scope with this
802 // name.
Douglas Gregor98339b92011-08-25 20:47:51 +0000803 if (DataLen > 0) {
804 SmallVector<uint32_t, 4> DeclIDs;
805 for (; DataLen > 0; DataLen -= 4)
806 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
807 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000808 }
809
Douglas Gregor98339b92011-08-25 20:47:51 +0000810 return II;
811}
Michael J. Spencer20249a12010-10-21 03:16:25 +0000812
Douglas Gregor98339b92011-08-25 20:47:51 +0000813unsigned
814ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
815 llvm::FoldingSetNodeID ID;
816 ID.AddInteger(Key.Kind);
817
818 switch (Key.Kind) {
819 case DeclarationName::Identifier:
820 case DeclarationName::CXXLiteralOperatorName:
821 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
822 break;
823 case DeclarationName::ObjCZeroArgSelector:
824 case DeclarationName::ObjCOneArgSelector:
825 case DeclarationName::ObjCMultiArgSelector:
826 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
827 break;
828 case DeclarationName::CXXOperatorName:
829 ID.AddInteger((OverloadedOperatorKind)Key.Data);
830 break;
831 case DeclarationName::CXXConstructorName:
832 case DeclarationName::CXXDestructorName:
833 case DeclarationName::CXXConversionFunctionName:
834 case DeclarationName::CXXUsingDirective:
835 break;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000836 }
837
Douglas Gregor98339b92011-08-25 20:47:51 +0000838 return ID.ComputeHash();
839}
Argyrios Kyrtzidisa60786b2010-08-20 23:35:55 +0000840
Douglas Gregor98339b92011-08-25 20:47:51 +0000841ASTDeclContextNameLookupTrait::internal_key_type
842ASTDeclContextNameLookupTrait::GetInternalKey(
843 const external_key_type& Name) const {
844 DeclNameKey Key;
845 Key.Kind = Name.getNameKind();
846 switch (Name.getNameKind()) {
847 case DeclarationName::Identifier:
848 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
849 break;
850 case DeclarationName::ObjCZeroArgSelector:
851 case DeclarationName::ObjCOneArgSelector:
852 case DeclarationName::ObjCMultiArgSelector:
853 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
854 break;
855 case DeclarationName::CXXOperatorName:
856 Key.Data = Name.getCXXOverloadedOperator();
857 break;
858 case DeclarationName::CXXLiteralOperatorName:
859 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
860 break;
861 case DeclarationName::CXXConstructorName:
862 case DeclarationName::CXXDestructorName:
863 case DeclarationName::CXXConversionFunctionName:
864 case DeclarationName::CXXUsingDirective:
865 Key.Data = 0;
866 break;
Argyrios Kyrtzidisa60786b2010-08-20 23:35:55 +0000867 }
868
Douglas Gregor98339b92011-08-25 20:47:51 +0000869 return Key;
870}
871
Douglas Gregor98339b92011-08-25 20:47:51 +0000872std::pair<unsigned, unsigned>
873ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
874 using namespace clang::io;
875 unsigned KeyLen = ReadUnalignedLE16(d);
876 unsigned DataLen = ReadUnalignedLE16(d);
877 return std::make_pair(KeyLen, DataLen);
878}
Michael J. Spencer20249a12010-10-21 03:16:25 +0000879
Douglas Gregor98339b92011-08-25 20:47:51 +0000880ASTDeclContextNameLookupTrait::internal_key_type
881ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
882 using namespace clang::io;
883
884 DeclNameKey Key;
885 Key.Kind = (DeclarationName::NameKind)*d++;
886 switch (Key.Kind) {
887 case DeclarationName::Identifier:
888 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
889 break;
890 case DeclarationName::ObjCZeroArgSelector:
891 case DeclarationName::ObjCOneArgSelector:
892 case DeclarationName::ObjCMultiArgSelector:
893 Key.Data =
894 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
895 .getAsOpaquePtr();
896 break;
897 case DeclarationName::CXXOperatorName:
898 Key.Data = *d++; // OverloadedOperatorKind
899 break;
900 case DeclarationName::CXXLiteralOperatorName:
901 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
902 break;
903 case DeclarationName::CXXConstructorName:
904 case DeclarationName::CXXDestructorName:
905 case DeclarationName::CXXConversionFunctionName:
906 case DeclarationName::CXXUsingDirective:
907 Key.Data = 0;
908 break;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000909 }
910
Douglas Gregor98339b92011-08-25 20:47:51 +0000911 return Key;
912}
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000913
Douglas Gregor98339b92011-08-25 20:47:51 +0000914ASTDeclContextNameLookupTrait::data_type
915ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
916 const unsigned char* d,
Nick Lewyckyb346d2f2012-04-16 02:51:46 +0000917 unsigned DataLen) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000918 using namespace clang::io;
919 unsigned NumDecls = ReadUnalignedLE16(d);
Douglas Gregor9b8b20f2012-01-06 16:09:53 +0000920 LE32DeclID *Start = (LE32DeclID *)d;
Douglas Gregor98339b92011-08-25 20:47:51 +0000921 return std::make_pair(Start, Start + NumDecls);
922}
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000923
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000924bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Douglas Gregor0d95f772011-08-24 19:03:07 +0000925 llvm::BitstreamCursor &Cursor,
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +0000926 const std::pair<uint64_t, uint64_t> &Offsets,
927 DeclContextInfo &Info) {
928 SavedStreamPosition SavedPosition(Cursor);
929 // First the lexical decls.
930 if (Offsets.first != 0) {
931 Cursor.JumpToBit(Offsets.first);
932
933 RecordData Record;
934 const char *Blob;
935 unsigned BlobLen;
936 unsigned Code = Cursor.ReadCode();
937 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
938 if (RecCode != DECL_CONTEXT_LEXICAL) {
939 Error("Expected lexical block");
940 return true;
941 }
942
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000943 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
944 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +0000945 }
946
947 // Now the lookup table.
948 if (Offsets.second != 0) {
949 Cursor.JumpToBit(Offsets.second);
950
951 RecordData Record;
952 const char *Blob;
953 unsigned BlobLen;
954 unsigned Code = Cursor.ReadCode();
955 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
956 if (RecCode != DECL_CONTEXT_VISIBLE) {
957 Error("Expected visible lookup table block");
958 return true;
959 }
960 Info.NameLookupTableData
961 = ASTDeclContextNameLookupTable::Create(
962 (const unsigned char *)Blob + Record[0],
963 (const unsigned char *)Blob,
Douglas Gregor0d95f772011-08-24 19:03:07 +0000964 ASTDeclContextNameLookupTrait(*this, M));
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +0000965 }
966
967 return false;
968}
969
Chris Lattner5f9e2722011-07-23 10:55:15 +0000970void ASTReader::Error(StringRef Msg) {
Argyrios Kyrtzidis8d8f2c22011-04-25 22:23:56 +0000971 Error(diag::err_fe_pch_malformed, Msg);
972}
973
974void ASTReader::Error(unsigned DiagID,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000975 StringRef Arg1, StringRef Arg2) {
Argyrios Kyrtzidis8d8f2c22011-04-25 22:23:56 +0000976 if (Diags.isDiagnosticInFlight())
977 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
978 else
979 Diag(DiagID) << Arg1 << Arg2;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000980}
981
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000982/// \brief Tell the AST listener about the predefines buffers in the chain.
Douglas Gregor38295be2012-10-22 23:51:00 +0000983bool ASTReader::CheckPredefinesBuffers(bool Complain) {
Douglas Gregor11407b82012-10-18 21:18:25 +0000984 if (Listener) {
985 // We only care about the primary module.
986 ModuleFile &M = ModuleMgr.getPrimaryModule();
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000987 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Douglas Gregor11407b82012-10-18 21:18:25 +0000988 M.ActualOriginalSourceFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000989 SuggestedPredefines,
Douglas Gregor38295be2012-10-22 23:51:00 +0000990 FileMgr,
991 Complain);
Douglas Gregor11407b82012-10-18 21:18:25 +0000992 }
Douglas Gregore721f952009-04-28 18:58:38 +0000993 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000994}
995
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000996//===----------------------------------------------------------------------===//
997// Source Manager Deserialization
998//===----------------------------------------------------------------------===//
999
Douglas Gregorbd945002009-04-13 16:31:14 +00001000/// \brief Read the line table in the source manager block.
Sebastian Redlc3632732010-10-05 15:59:54 +00001001/// \returns true if there was an error.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001002bool ASTReader::ParseLineTable(ModuleFile &F,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001003 SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +00001004 unsigned Idx = 0;
1005 LineTableInfo &LineTable = SourceMgr.getLineTable();
1006
1007 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +00001008 std::map<int, int> FileIDs;
1009 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +00001010 // Extract the file name
1011 unsigned FilenameLen = Record[Idx++];
1012 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1013 Idx += FilenameLen;
Douglas Gregorcaed0602012-10-18 21:31:35 +00001014 MaybeAddSystemRootToFilename(F, Filename);
Jay Foad65aa6882011-06-21 15:13:30 +00001015 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
Douglas Gregorbd945002009-04-13 16:31:14 +00001016 }
1017
1018 // Parse the line entries
1019 std::vector<LineEntry> Entries;
1020 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +00001021 int FID = Record[Idx++];
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001022 assert(FID >= 0 && "Serialized line entries for non-local file.");
1023 // Remap FileID from 1-based old view.
1024 FID += F.SLocEntryBaseID - 1;
Douglas Gregorbd945002009-04-13 16:31:14 +00001025
1026 // Extract the line entries
1027 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +00001028 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +00001029 Entries.clear();
1030 Entries.reserve(NumEntries);
1031 for (unsigned I = 0; I != NumEntries; ++I) {
1032 unsigned FileOffset = Record[Idx++];
1033 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +00001034 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +00001035 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +00001036 = (SrcMgr::CharacteristicKind)Record[Idx++];
1037 unsigned IncludeOffset = Record[Idx++];
1038 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1039 FileKind, IncludeOffset));
1040 }
Douglas Gregor47d9de62012-06-08 16:40:28 +00001041 LineTable.AddEntry(FileID::get(FID), Entries);
Douglas Gregorbd945002009-04-13 16:31:14 +00001042 }
1043
1044 return false;
1045}
1046
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001047namespace {
1048
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001049class ASTStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001050public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001051 const ino_t ino;
1052 const dev_t dev;
1053 const mode_t mode;
1054 const time_t mtime;
1055 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001057 ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Chris Lattner74e976b2010-11-23 19:28:12 +00001058 : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001059};
1060
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001061class ASTStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001062 public:
1063 typedef const char *external_key_type;
1064 typedef const char *internal_key_type;
1065
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001066 typedef ASTStatData data_type;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001067
1068 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +00001069 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001070 }
1071
1072 static internal_key_type GetInternalKey(const char *path) { return path; }
1073
1074 static bool EqualKey(internal_key_type a, internal_key_type b) {
1075 return strcmp(a, b) == 0;
1076 }
1077
1078 static std::pair<unsigned, unsigned>
1079 ReadKeyDataLength(const unsigned char*& d) {
1080 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1081 unsigned DataLen = (unsigned) *d++;
1082 return std::make_pair(KeyLen + 1, DataLen);
1083 }
1084
1085 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1086 return (const char *)d;
1087 }
1088
1089 static data_type ReadData(const internal_key_type, const unsigned char *d,
1090 unsigned /*DataLen*/) {
1091 using namespace clang::io;
1092
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001093 ino_t ino = (ino_t) ReadUnalignedLE32(d);
1094 dev_t dev = (dev_t) ReadUnalignedLE32(d);
1095 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +00001096 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001097 off_t size = (off_t) ReadUnalignedLE64(d);
1098 return data_type(ino, dev, mode, mtime, size);
1099 }
1100};
1101
1102/// \brief stat() cache for precompiled headers.
1103///
1104/// This cache is very similar to the stat cache used by pretokenized
1105/// headers.
Chris Lattner10e286a2010-11-23 19:19:34 +00001106class ASTStatCache : public FileSystemStatCache {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001107 typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001108 CacheTy *Cache;
1109
1110 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +00001111public:
Chris Lattner74e976b2010-11-23 19:28:12 +00001112 ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
1113 unsigned &NumStatHits, unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001114 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
1115 Cache = CacheTy::Create(Buckets, Base);
1116 }
1117
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001118 ~ASTStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Chris Lattner898a0612010-11-23 21:17:56 +00001120 LookupResult getStat(const char *Path, struct stat &StatBuf,
1121 int *FileDescriptor) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001122 // Do the lookup for the file's data in the AST file.
Chris Lattner10e286a2010-11-23 19:19:34 +00001123 CacheTy::iterator I = Cache->find(Path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001124
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001125 // If we don't get a hit in the AST file just forward to 'stat'.
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001126 if (I == Cache->end()) {
1127 ++NumStatMisses;
Chris Lattner898a0612010-11-23 21:17:56 +00001128 return statChained(Path, StatBuf, FileDescriptor);
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001129 }
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001131 ++NumStatHits;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001132 ASTStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Chris Lattner10e286a2010-11-23 19:19:34 +00001134 StatBuf.st_ino = Data.ino;
1135 StatBuf.st_dev = Data.dev;
1136 StatBuf.st_mtime = Data.mtime;
1137 StatBuf.st_mode = Data.mode;
1138 StatBuf.st_size = Data.size;
Chris Lattnerd6f61112010-11-23 20:05:15 +00001139 return CacheExists;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001140 }
1141};
1142} // end anonymous namespace
1143
1144
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001145/// \brief Read a source manager block
Douglas Gregor4825fd72012-10-22 22:50:17 +00001146bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
Douglas Gregor14f79002009-04-10 03:52:48 +00001147 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001148
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001149 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001150
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001151 // Set the source-location entry cursor to the current position in
1152 // the stream. This cursor will be used to read the contents of the
1153 // source manager block initially, and then lazily read
1154 // source-location entries as needed.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001155 SLocEntryCursor = F.Stream;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001156
1157 // The stream itself is going to skip over the source manager block.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001158 if (F.Stream.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001159 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001160 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001161 }
1162
1163 // Enter the source manager block.
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001164 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001165 Error("malformed source manager block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001166 return true;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001167 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001168
Douglas Gregor14f79002009-04-10 03:52:48 +00001169 RecordData Record;
1170 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001171 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +00001172 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001173 if (SLocEntryCursor.ReadBlockEnd()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001174 Error("error at end of Source Manager block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001175 return true;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001176 }
Douglas Gregor4825fd72012-10-22 22:50:17 +00001177 return false;
Douglas Gregor14f79002009-04-10 03:52:48 +00001178 }
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Douglas Gregor14f79002009-04-10 03:52:48 +00001180 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1181 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001182 SLocEntryCursor.ReadSubBlockID();
1183 if (SLocEntryCursor.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001184 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001185 return true;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001186 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001187 continue;
1188 }
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Douglas Gregor14f79002009-04-10 03:52:48 +00001190 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001191 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +00001192 continue;
1193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Douglas Gregor14f79002009-04-10 03:52:48 +00001195 // Read a record.
1196 const char *BlobStart;
1197 unsigned BlobLen;
1198 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001199 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +00001200 default: // Default behavior: ignore.
1201 break;
1202
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001203 case SM_SLOC_FILE_ENTRY:
1204 case SM_SLOC_BUFFER_ENTRY:
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001205 case SM_SLOC_EXPANSION_ENTRY:
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001206 // Once we hit one of the source location entries, we're done.
Douglas Gregor4825fd72012-10-22 22:50:17 +00001207 return false;
Douglas Gregor14f79002009-04-10 03:52:48 +00001208 }
1209 }
1210}
1211
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001212/// \brief If a header file is not found at the path that we expect it to be
1213/// and the PCH file was moved from its original location, try to resolve the
1214/// file by assuming that header+PCH were moved together and the header is in
1215/// the same place relative to the PCH.
1216static std::string
1217resolveFileRelativeToOriginalDir(const std::string &Filename,
1218 const std::string &OriginalDir,
1219 const std::string &CurrDir) {
1220 assert(OriginalDir != CurrDir &&
1221 "No point trying to resolve the file if the PCH dir didn't change");
1222 using namespace llvm::sys;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001223 SmallString<128> filePath(Filename);
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001224 fs::make_absolute(filePath);
1225 assert(path::is_absolute(OriginalDir));
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001226 SmallString<128> currPCHPath(CurrDir);
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001227
1228 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1229 fileDirE = path::end(path::parent_path(filePath));
1230 path::const_iterator origDirI = path::begin(OriginalDir),
1231 origDirE = path::end(OriginalDir);
1232 // Skip the common path components from filePath and OriginalDir.
1233 while (fileDirI != fileDirE && origDirI != origDirE &&
1234 *fileDirI == *origDirI) {
1235 ++fileDirI;
1236 ++origDirI;
1237 }
1238 for (; origDirI != origDirE; ++origDirI)
1239 path::append(currPCHPath, "..");
1240 path::append(currPCHPath, fileDirI, fileDirE);
1241 path::append(currPCHPath, path::filename(Filename));
1242 return currPCHPath.str();
1243}
1244
Douglas Gregor8b53d142012-10-22 22:53:10 +00001245bool ASTReader::ReadSLocEntry(int ID) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001246 if (ID == 0)
Douglas Gregor4825fd72012-10-22 22:50:17 +00001247 return false;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001248
Douglas Gregor0cdd7982011-07-21 18:46:38 +00001249 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001250 Error("source location entry ID out-of-range for AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001251 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001252 }
1253
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001254 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001255 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Sebastian Redlc3632732010-10-05 15:59:54 +00001256 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001257 unsigned BaseOffset = F->SLocEntryBaseOffset;
Sebastian Redl9137a522010-07-16 17:50:48 +00001258
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001259 ++NumSLocEntriesRead;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001260 unsigned Code = SLocEntryCursor.ReadCode();
1261 if (Code == llvm::bitc::END_BLOCK ||
1262 Code == llvm::bitc::ENTER_SUBBLOCK ||
1263 Code == llvm::bitc::DEFINE_ABBREV) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001264 Error("incorrectly-formatted source location entry in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001265 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001266 }
1267
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001268 RecordData Record;
1269 const char *BlobStart;
1270 unsigned BlobLen;
1271 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1272 default:
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001273 Error("incorrectly-formatted source location entry in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001274 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001275
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001276 case SM_SLOC_FILE_ENTRY: {
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +00001277 // We will detect whether a file changed and return 'Failure' for it, but
1278 // we will also try to fail gracefully by setting up the SLocEntry.
Douglas Gregora930dc92012-10-22 18:42:04 +00001279 unsigned InputID = Record[4];
1280 InputFile IF = getInputFile(*F, InputID);
1281 const FileEntry *File = IF.getPointer();
1282 bool OverriddenBuffer = IF.getInt();
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +00001283
Douglas Gregora930dc92012-10-22 18:42:04 +00001284 if (!IF.getPointer())
Douglas Gregor4825fd72012-10-22 22:50:17 +00001285 return true;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001286
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001287 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Douglas Gregor72a9ae12011-07-22 16:00:58 +00001288 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001289 // This is the module's main file.
1290 IncludeLoc = getImportLocation(F);
1291 }
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001292 SrcMgr::CharacteristicKind
1293 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1294 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001295 ID, BaseOffset + Record[0]);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001296 SrcMgr::FileInfo &FileInfo =
1297 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Douglas Gregora930dc92012-10-22 18:42:04 +00001298 FileInfo.NumCreatedFIDs = Record[5];
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001299 if (Record[3])
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001300 FileInfo.setHasLineDirectives();
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001301
Douglas Gregora930dc92012-10-22 18:42:04 +00001302 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1303 unsigned NumFileDecls = Record[7];
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001304 if (NumFileDecls) {
1305 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
Argyrios Kyrtzidis9d128d02011-10-31 07:20:08 +00001306 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1307 NumFileDecls));
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001308 }
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001309
Douglas Gregor35f9ae62011-11-17 01:44:33 +00001310 const SrcMgr::ContentCache *ContentCache
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001311 = SourceMgr.getOrCreateContentCache(File,
1312 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
Douglas Gregor35f9ae62011-11-17 01:44:33 +00001313 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1314 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
Douglas Gregora081da52011-11-16 20:05:18 +00001315 unsigned Code = SLocEntryCursor.ReadCode();
1316 Record.clear();
1317 unsigned RecCode
1318 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1319
1320 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1321 Error("AST record has invalid code");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001322 return true;
Douglas Gregora081da52011-11-16 20:05:18 +00001323 }
1324
1325 llvm::MemoryBuffer *Buffer
1326 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
Douglas Gregora930dc92012-10-22 18:42:04 +00001327 File->getName());
Douglas Gregora081da52011-11-16 20:05:18 +00001328 SourceMgr.overrideFileContents(File, Buffer);
1329 }
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +00001330
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001331 break;
1332 }
1333
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001334 case SM_SLOC_BUFFER_ENTRY: {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001335 const char *Name = BlobStart;
1336 unsigned Offset = Record[0];
1337 unsigned Code = SLocEntryCursor.ReadCode();
1338 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001339 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001340 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001341
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001342 if (RecCode != SM_SLOC_BUFFER_BLOB) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001343 Error("AST record has invalid code");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001344 return true;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001345 }
1346
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001347 llvm::MemoryBuffer *Buffer
Douglas Gregora081da52011-11-16 20:05:18 +00001348 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
1349 Name);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001350 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID,
1351 BaseOffset + Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Douglas Gregor6236a292011-12-02 21:56:05 +00001353 if (strcmp(Name, "<built-in>") == 0 && F->Kind == MK_PCH) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001354 PCHPredefinesBlock Block = {
1355 BufferID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001356 StringRef(BlobStart, BlobLen - 1)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001357 };
1358 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001359 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001360
1361 break;
1362 }
1363
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001364 case SM_SLOC_EXPANSION_ENTRY: {
Sebastian Redlc3632732010-10-05 15:59:54 +00001365 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
Chandler Carruthbf340e42011-07-26 03:03:05 +00001366 SourceMgr.createExpansionLoc(SpellingLoc,
Sebastian Redlc3632732010-10-05 15:59:54 +00001367 ReadSourceLocation(*F, Record[2]),
1368 ReadSourceLocation(*F, Record[3]),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001369 Record[4],
1370 ID,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001371 BaseOffset + Record[0]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001372 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001373 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001374 }
1375
Douglas Gregor4825fd72012-10-22 22:50:17 +00001376 return false;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001377}
1378
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001379/// \brief Find the location where the module F is imported.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001380SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001381 if (F->ImportLoc.isValid())
1382 return F->ImportLoc;
Jonathan D. Turner2e091632011-07-29 18:09:09 +00001383
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001384 // Otherwise we have a PCH. It's considered to be "imported" at the first
1385 // location of its includer.
Jonathan D. Turner2e091632011-07-29 18:09:09 +00001386 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001387 // Main file is the importer. We assume that it is the first entry in the
1388 // entry table. We can't ask the manager, because at the time of PCH loading
1389 // the main file entry doesn't exist yet.
1390 // The very first entry is the invalid instantiation loc, which takes up
1391 // offsets 0 and 1.
1392 return SourceLocation::getFromRawEncoding(2U);
1393 }
Jonathan D. Turner2e091632011-07-29 18:09:09 +00001394 //return F->Loaders[0]->FirstLoc;
1395 return F->ImportedBy[0]->FirstLoc;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001396}
1397
Chris Lattner6367f6d2009-04-27 01:05:14 +00001398/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1399/// specified cursor. Read the abbreviations that are at the top of the block
1400/// and then leave the cursor pointing into the block.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00001401bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
Chris Lattner6367f6d2009-04-27 01:05:14 +00001402 unsigned BlockID) {
1403 if (Cursor.EnterSubBlock(BlockID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001404 Error("malformed block record in AST file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001405 return Failure;
1406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Chris Lattner6367f6d2009-04-27 01:05:14 +00001408 while (true) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001409 uint64_t Offset = Cursor.GetCurrentBitNo();
Chris Lattner6367f6d2009-04-27 01:05:14 +00001410 unsigned Code = Cursor.ReadCode();
Michael J. Spencer20249a12010-10-21 03:16:25 +00001411
Chris Lattner6367f6d2009-04-27 01:05:14 +00001412 // We expect all abbrevs to be at the start of the block.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001413 if (Code != llvm::bitc::DEFINE_ABBREV) {
1414 Cursor.JumpToBit(Offset);
Chris Lattner6367f6d2009-04-27 01:05:14 +00001415 return false;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001416 }
Chris Lattner6367f6d2009-04-27 01:05:14 +00001417 Cursor.ReadAbbrevRecord();
1418 }
1419}
1420
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00001421void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset,
1422 MacroInfo *Hint) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001423 llvm::BitstreamCursor &Stream = F.MacroCursor;
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Douglas Gregor37e26842009-04-21 23:56:24 +00001425 // Keep track of where we are in the stream, then jump back there
1426 // after reading this macro.
1427 SavedStreamPosition SavedPosition(Stream);
1428
1429 Stream.JumpToBit(Offset);
1430 RecordData Record;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001431 SmallVector<IdentifierInfo*, 16> MacroArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001432 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Douglas Gregore8219a62012-10-11 21:07:39 +00001434 // RAII object to add the loaded macro information once we're done
1435 // adding tokens.
1436 struct AddLoadedMacroInfoRAII {
1437 Preprocessor &PP;
1438 MacroInfo *Hint;
1439 MacroInfo *MI;
1440 IdentifierInfo *II;
1441
1442 AddLoadedMacroInfoRAII(Preprocessor &PP, MacroInfo *Hint)
1443 : PP(PP), Hint(Hint), MI(), II() { }
1444 ~AddLoadedMacroInfoRAII( ) {
1445 if (MI) {
1446 // Finally, install the macro.
1447 PP.addLoadedMacroInfo(II, MI, Hint);
1448 }
1449 }
1450 } AddLoadedMacroInfo(PP, Hint);
1451
Douglas Gregor37e26842009-04-21 23:56:24 +00001452 while (true) {
1453 unsigned Code = Stream.ReadCode();
1454 switch (Code) {
1455 case llvm::bitc::END_BLOCK:
Douglas Gregor3b2257c2011-08-04 18:09:14 +00001456 return;
Douglas Gregor37e26842009-04-21 23:56:24 +00001457
1458 case llvm::bitc::ENTER_SUBBLOCK:
1459 // No known subblocks, always skip them.
1460 Stream.ReadSubBlockID();
1461 if (Stream.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001462 Error("malformed block record in AST file");
Douglas Gregor3b2257c2011-08-04 18:09:14 +00001463 return;
Douglas Gregor37e26842009-04-21 23:56:24 +00001464 }
1465 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Douglas Gregor37e26842009-04-21 23:56:24 +00001467 case llvm::bitc::DEFINE_ABBREV:
1468 Stream.ReadAbbrevRecord();
1469 continue;
1470 default: break;
1471 }
1472
1473 // Read a record.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001474 const char *BlobStart = 0;
1475 unsigned BlobLen = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001476 Record.clear();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001477 PreprocessorRecordTypes RecType =
Michael J. Spencer20249a12010-10-21 03:16:25 +00001478 (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
Douglas Gregorecdcb882010-10-20 22:00:55 +00001479 BlobLen);
Douglas Gregor37e26842009-04-21 23:56:24 +00001480 switch (RecType) {
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001481 case PP_MACRO_OBJECT_LIKE:
1482 case PP_MACRO_FUNCTION_LIKE: {
Douglas Gregor37e26842009-04-21 23:56:24 +00001483 // If we already have a macro, that means that we've hit the end
1484 // of the definition of the macro we were looking for. We're
1485 // done.
1486 if (Macro)
Douglas Gregor3b2257c2011-08-04 18:09:14 +00001487 return;
Douglas Gregor37e26842009-04-21 23:56:24 +00001488
Douglas Gregor95eab172011-07-28 20:55:49 +00001489 IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
Douglas Gregor37e26842009-04-21 23:56:24 +00001490 if (II == 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001491 Error("macro must have a name in AST file");
Douglas Gregor3b2257c2011-08-04 18:09:14 +00001492 return;
Douglas Gregor37e26842009-04-21 23:56:24 +00001493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Douglas Gregora8235d62012-10-09 23:05:51 +00001495 unsigned GlobalID = getGlobalMacroID(F, Record[1]);
1496
1497 // If this macro has already been loaded, don't do so again.
1498 if (MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS])
1499 return;
1500
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001501 SubmoduleID GlobalSubmoduleID = getGlobalSubmoduleID(F, Record[2]);
1502 unsigned NextIndex = 3;
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001503 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Douglas Gregor712f2fc2011-09-09 22:02:16 +00001504 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001505
Douglas Gregora8235d62012-10-09 23:05:51 +00001506 // Record this macro.
1507 MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS] = MI;
1508
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001509 SourceLocation UndefLoc = ReadSourceLocation(F, Record, NextIndex);
1510 if (UndefLoc.isValid())
1511 MI->setUndefLoc(UndefLoc);
1512
1513 MI->setIsUsed(Record[NextIndex++]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001514 MI->setIsFromAST();
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001516 bool IsPublic = Record[NextIndex++];
Douglas Gregoraa93a872011-10-17 15:32:29 +00001517 MI->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001518
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001519 if (RecType == PP_MACRO_FUNCTION_LIKE) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001520 // Decode function-like macro info.
Douglas Gregor7143aab2011-09-01 17:04:32 +00001521 bool isC99VarArgs = Record[NextIndex++];
1522 bool isGNUVarArgs = Record[NextIndex++];
Douglas Gregor37e26842009-04-21 23:56:24 +00001523 MacroArgs.clear();
Douglas Gregor7143aab2011-09-01 17:04:32 +00001524 unsigned NumArgs = Record[NextIndex++];
Douglas Gregor37e26842009-04-21 23:56:24 +00001525 for (unsigned i = 0; i != NumArgs; ++i)
Douglas Gregor7143aab2011-09-01 17:04:32 +00001526 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Douglas Gregor37e26842009-04-21 23:56:24 +00001527
1528 // Install function-like macro info.
1529 MI->setIsFunctionLike();
1530 if (isC99VarArgs) MI->setIsC99Varargs();
1531 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001532 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Douglas Gregor712f2fc2011-09-09 22:02:16 +00001533 PP.getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001534 }
1535
Douglas Gregora8235d62012-10-09 23:05:51 +00001536 if (DeserializationListener)
1537 DeserializationListener->MacroRead(GlobalID, MI);
1538
1539 // If an update record marked this as undefined, do so now.
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001540 // FIXME: Only if the submodule this update came from is visible?
Douglas Gregora8235d62012-10-09 23:05:51 +00001541 MacroUpdatesMap::iterator Update = MacroUpdates.find(GlobalID);
1542 if (Update != MacroUpdates.end()) {
1543 if (MI->getUndefLoc().isInvalid()) {
Douglas Gregor54c8a402012-10-12 00:16:50 +00001544 for (unsigned I = 0, N = Update->second.size(); I != N; ++I) {
1545 bool Hidden = false;
1546 if (unsigned SubmoduleID = Update->second[I].first) {
1547 if (Module *Owner = getSubmodule(SubmoduleID)) {
1548 if (Owner->NameVisibility == Module::Hidden) {
1549 // Note that this #undef is hidden.
1550 Hidden = true;
1551
1552 // Record this hiding for later.
1553 HiddenNamesMap[Owner].push_back(
1554 HiddenName(II, MI, Update->second[I].second.UndefLoc));
1555 }
1556 }
1557 }
1558
1559 if (!Hidden) {
1560 MI->setUndefLoc(Update->second[I].second.UndefLoc);
1561 if (PPMutationListener *Listener = PP.getPPMutationListener())
1562 Listener->UndefinedMacro(MI);
1563 break;
1564 }
1565 }
Douglas Gregora8235d62012-10-09 23:05:51 +00001566 }
1567 MacroUpdates.erase(Update);
1568 }
1569
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001570 // Determine whether this macro definition is visible.
1571 bool Hidden = !MI->isPublic();
1572 if (!Hidden && GlobalSubmoduleID) {
1573 if (Module *Owner = getSubmodule(GlobalSubmoduleID)) {
1574 if (Owner->NameVisibility == Module::Hidden) {
1575 // The owning module is not visible, and this macro definition
1576 // should not be, either.
1577 Hidden = true;
1578
1579 // Note that this macro definition was hidden because its owning
1580 // module is not yet visible.
1581 HiddenNamesMap[Owner].push_back(HiddenName(II, MI));
1582 }
1583 }
1584 }
1585 MI->setHidden(Hidden);
1586
Douglas Gregore8219a62012-10-11 21:07:39 +00001587 // Make sure we install the macro once we're done.
1588 AddLoadedMacroInfo.MI = MI;
1589 AddLoadedMacroInfo.II = II;
Douglas Gregor37e26842009-04-21 23:56:24 +00001590
1591 // Remember that we saw this macro last so that we add the tokens that
1592 // form its body to it.
1593 Macro = MI;
Michael J. Spencer20249a12010-10-21 03:16:25 +00001594
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00001595 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1596 Record[NextIndex]) {
1597 // We have a macro definition. Register the association
1598 PreprocessedEntityID
1599 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1600 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1601 PPRec.RegisterMacroDefinition(Macro,
1602 PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true));
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001603 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00001604
Douglas Gregor37e26842009-04-21 23:56:24 +00001605 ++NumMacrosRead;
1606 break;
1607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001609 case PP_TOKEN: {
Douglas Gregor37e26842009-04-21 23:56:24 +00001610 // If we see a TOKEN before a PP_MACRO_*, then the file is
1611 // erroneous, just pretend we didn't see this.
1612 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Douglas Gregor37e26842009-04-21 23:56:24 +00001614 Token Tok;
1615 Tok.startToken();
Sebastian Redlc3632732010-10-05 15:59:54 +00001616 Tok.setLocation(ReadSourceLocation(F, Record[0]));
Douglas Gregor37e26842009-04-21 23:56:24 +00001617 Tok.setLength(Record[1]);
Douglas Gregor95eab172011-07-28 20:55:49 +00001618 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
Douglas Gregor37e26842009-04-21 23:56:24 +00001619 Tok.setIdentifierInfo(II);
1620 Tok.setKind((tok::TokenKind)Record[3]);
1621 Tok.setFlag((Token::TokenFlags)Record[4]);
1622 Macro->AddTokenToBody(Tok);
1623 break;
1624 }
David Blaikie7530c032012-01-17 06:56:22 +00001625 }
Douglas Gregor4800a5c2011-02-08 21:58:10 +00001626 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001627}
1628
Douglas Gregor86c67d82011-07-28 22:39:26 +00001629PreprocessedEntityID
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001630ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
Argyrios Kyrtzidis1f6d2252011-09-19 20:40:02 +00001631 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Douglas Gregor272b6bc2011-08-04 18:56:47 +00001632 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1633 assert(I != M.PreprocessedEntityRemap.end()
1634 && "Invalid index into preprocessed entity index remap");
1635
1636 return LocalID + I->second;
Douglas Gregor86c67d82011-07-28 22:39:26 +00001637}
1638
Douglas Gregor98339b92011-08-25 20:47:51 +00001639unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1640 return llvm::HashString(llvm::sys::path::filename(path));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001641}
Douglas Gregor98339b92011-08-25 20:47:51 +00001642
1643HeaderFileInfoTrait::internal_key_type
1644HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1645
1646bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1647 if (strcmp(a, b) == 0)
1648 return true;
1649
1650 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1651 return false;
Douglas Gregor99a922b2011-12-09 16:22:07 +00001652
1653 // Determine whether the actual files are equivalent.
1654 bool Result = false;
1655 if (llvm::sys::fs::equivalent(a, b, Result))
Douglas Gregor98339b92011-08-25 20:47:51 +00001656 return false;
1657
Douglas Gregor99a922b2011-12-09 16:22:07 +00001658 return Result;
Douglas Gregor98339b92011-08-25 20:47:51 +00001659}
1660
1661std::pair<unsigned, unsigned>
1662HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1663 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1664 unsigned DataLen = (unsigned) *d++;
1665 return std::make_pair(KeyLen + 1, DataLen);
1666}
1667
1668HeaderFileInfoTrait::data_type
1669HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1670 unsigned DataLen) {
1671 const unsigned char *End = d + DataLen;
1672 using namespace clang::io;
1673 HeaderFileInfo HFI;
1674 unsigned Flags = *d++;
1675 HFI.isImport = (Flags >> 5) & 0x01;
1676 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1677 HFI.DirInfo = (Flags >> 2) & 0x03;
1678 HFI.Resolved = (Flags >> 1) & 0x01;
1679 HFI.IndexHeaderMapHeader = Flags & 0x01;
1680 HFI.NumIncludes = ReadUnalignedLE16(d);
Douglas Gregor541ba162011-10-17 18:53:12 +00001681 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1682 ReadUnalignedLE32(d));
Douglas Gregor98339b92011-08-25 20:47:51 +00001683 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1684 // The framework offset is 1 greater than the actual offset,
1685 // since 0 is used as an indicator for "no framework name".
1686 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1687 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1688 }
1689
1690 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1691 (void)End;
1692
1693 // This HeaderFileInfo was externally loaded.
1694 HFI.External = true;
1695 return HFI;
1696}
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001697
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001698void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ArrayRef<MacroID> IDs){
1699 II->setHadMacroDefinition(true);
1700 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1701 PendingMacroIDs[II].append(IDs.begin(), IDs.end());
Douglas Gregor295a2a62010-10-30 00:23:06 +00001702}
1703
Sebastian Redlc43b54c2010-08-18 23:56:43 +00001704void ASTReader::ReadDefinedMacros() {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001705 // Note that we are loading defined macros.
1706 Deserializing Macros(this);
1707
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00001708 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1709 E = ModuleMgr.rend(); I != E; ++I) {
1710 llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001711
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001712 // If there was no preprocessor block, skip this file.
1713 if (!MacroCursor.getBitStreamReader())
1714 continue;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001715
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001716 llvm::BitstreamCursor Cursor = MacroCursor;
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00001717 Cursor.JumpToBit((*I)->MacroStartOffset);
Michael J. Spencer20249a12010-10-21 03:16:25 +00001718
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001719 RecordData Record;
1720 while (true) {
1721 unsigned Code = Cursor.ReadCode();
Douglas Gregorecdcb882010-10-20 22:00:55 +00001722 if (Code == llvm::bitc::END_BLOCK)
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001723 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001724
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001725 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1726 // No known subblocks, always skip them.
1727 Cursor.ReadSubBlockID();
1728 if (Cursor.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001729 Error("malformed block record in AST file");
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001730 return;
1731 }
1732 continue;
1733 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001734
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001735 if (Code == llvm::bitc::DEFINE_ABBREV) {
1736 Cursor.ReadAbbrevRecord();
1737 continue;
1738 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001739
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001740 // Read a record.
1741 const char *BlobStart;
1742 unsigned BlobLen;
1743 Record.clear();
1744 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1745 default: // Default behavior: ignore.
1746 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001747
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001748 case PP_MACRO_OBJECT_LIKE:
1749 case PP_MACRO_FUNCTION_LIKE:
Douglas Gregor95eab172011-07-28 20:55:49 +00001750 getLocalIdentifier(**I, Record[0]);
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001751 break;
1752
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001753 case PP_TOKEN:
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001754 // Ignore tokens.
1755 break;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001756 }
Douglas Gregor88a35862010-01-04 19:18:44 +00001757 }
1758 }
Douglas Gregor295a2a62010-10-30 00:23:06 +00001759}
1760
Douglas Gregoreee242f2011-10-27 09:33:13 +00001761namespace {
1762 /// \brief Visitor class used to look up identifirs in an AST file.
1763 class IdentifierLookupVisitor {
1764 StringRef Name;
Douglas Gregor057df202012-01-18 20:56:22 +00001765 unsigned PriorGeneration;
Douglas Gregoreee242f2011-10-27 09:33:13 +00001766 IdentifierInfo *Found;
1767 public:
Douglas Gregor057df202012-01-18 20:56:22 +00001768 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration)
1769 : Name(Name), PriorGeneration(PriorGeneration), Found() { }
Douglas Gregoreee242f2011-10-27 09:33:13 +00001770
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001771 static bool visit(ModuleFile &M, void *UserData) {
Douglas Gregoreee242f2011-10-27 09:33:13 +00001772 IdentifierLookupVisitor *This
1773 = static_cast<IdentifierLookupVisitor *>(UserData);
1774
Douglas Gregor057df202012-01-18 20:56:22 +00001775 // If we've already searched this module file, skip it now.
1776 if (M.Generation <= This->PriorGeneration)
1777 return true;
1778
Douglas Gregoreee242f2011-10-27 09:33:13 +00001779 ASTIdentifierLookupTable *IdTable
1780 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1781 if (!IdTable)
1782 return false;
1783
Douglas Gregor5d5051f2012-01-24 15:24:38 +00001784 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1785 M, This->Found);
1786
Douglas Gregoreee242f2011-10-27 09:33:13 +00001787 std::pair<const char*, unsigned> Key(This->Name.begin(),
1788 This->Name.size());
Douglas Gregor5d5051f2012-01-24 15:24:38 +00001789 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Trait);
Douglas Gregoreee242f2011-10-27 09:33:13 +00001790 if (Pos == IdTable->end())
1791 return false;
1792
1793 // Dereferencing the iterator has the effect of building the
1794 // IdentifierInfo node and populating it with the various
1795 // declarations it needs.
1796 This->Found = *Pos;
1797 return true;
1798 }
1799
1800 // \brief Retrieve the identifier info found within the module
1801 // files.
1802 IdentifierInfo *getIdentifierInfo() const { return Found; }
1803 };
1804}
1805
1806void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001807 // Note that we are loading an identifier.
1808 Deserializing AnIdentifier(this);
1809
Douglas Gregor057df202012-01-18 20:56:22 +00001810 unsigned PriorGeneration = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00001811 if (getContext().getLangOpts().Modules)
Douglas Gregor057df202012-01-18 20:56:22 +00001812 PriorGeneration = IdentifierGeneration[&II];
1813
1814 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration);
1815 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
1816 markIdentifierUpToDate(&II);
1817}
1818
1819void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1820 if (!II)
1821 return;
1822
1823 II->setOutOfDate(false);
1824
1825 // Update the generation for this identifier.
David Blaikie4e4d0842012-03-11 07:00:24 +00001826 if (getContext().getLangOpts().Modules)
Douglas Gregor057df202012-01-18 20:56:22 +00001827 IdentifierGeneration[II] = CurrentGeneration;
Douglas Gregoreee242f2011-10-27 09:33:13 +00001828}
1829
Douglas Gregora930dc92012-10-22 18:42:04 +00001830llvm::PointerIntPair<const FileEntry *, 1, bool>
Douglas Gregor38295be2012-10-22 23:51:00 +00001831ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Douglas Gregora930dc92012-10-22 18:42:04 +00001832 // If this ID is bogus, just return an empty input file.
1833 if (ID == 0 || ID > F.InputFilesLoaded.size())
1834 return InputFile();
1835
1836 // If we've already loaded this input file, return it.
1837 if (F.InputFilesLoaded[ID-1].getPointer())
1838 return F.InputFilesLoaded[ID-1];
1839
1840 // Go find this input file.
1841 llvm::BitstreamCursor &Cursor = F.InputFilesCursor;
1842 SavedStreamPosition SavedPosition(Cursor);
1843 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1844
1845 unsigned Code = Cursor.ReadCode();
1846 RecordData Record;
1847 const char *BlobStart = 0;
1848 unsigned BlobLen = 0;
1849 switch ((InputFileRecordTypes)Cursor.ReadRecord(Code, Record,
1850 &BlobStart, &BlobLen)) {
1851 case INPUT_FILE: {
1852 unsigned StoredID = Record[0];
1853 assert(ID == StoredID && "Bogus stored ID or offset");
NAKAMURA Takumi6b8194e2012-10-22 21:50:39 +00001854 (void)StoredID;
Douglas Gregora930dc92012-10-22 18:42:04 +00001855 off_t StoredSize = (off_t)Record[1];
1856 time_t StoredTime = (time_t)Record[2];
1857 bool Overridden = (bool)Record[3];
1858
1859 // Get the file entry for this input file.
1860 StringRef OrigFilename(BlobStart, BlobLen);
1861 std::string Filename = OrigFilename;
1862 MaybeAddSystemRootToFilename(F, Filename);
1863 const FileEntry *File
1864 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1865 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1866
1867 // If we didn't find the file, resolve it relative to the
1868 // original directory from which this AST file was created.
1869 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1870 F.OriginalDir != CurrentDir) {
1871 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1872 F.OriginalDir,
1873 CurrentDir);
1874 if (!Resolved.empty())
1875 File = FileMgr.getFile(Resolved);
1876 }
1877
1878 // For an overridden file, create a virtual file with the stored
1879 // size/timestamp.
1880 if (Overridden && File == 0) {
1881 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1882 }
1883
1884 if (File == 0) {
Douglas Gregor38295be2012-10-22 23:51:00 +00001885 if (Complain) {
1886 std::string ErrorStr = "could not find file '";
1887 ErrorStr += Filename;
1888 ErrorStr += "' referenced by AST file";
1889 Error(ErrorStr.c_str());
1890 }
Douglas Gregora930dc92012-10-22 18:42:04 +00001891 return InputFile();
1892 }
1893
1894 // Note that we've loaded this input file.
1895 F.InputFilesLoaded[ID-1] = InputFile(File, Overridden);
1896
1897 // Check if there was a request to override the contents of the file
1898 // that was part of the precompiled header. Overridding such a file
1899 // can lead to problems when lexing using the source locations from the
1900 // PCH.
1901 SourceManager &SM = getSourceManager();
1902 if (!Overridden && SM.isFileOverridden(File)) {
1903 Error(diag::err_fe_pch_file_overridden, Filename);
1904 // After emitting the diagnostic, recover by disabling the override so
1905 // that the original file will be used.
1906 SM.disableFileContentsOverride(File);
1907 // The FileEntry is a virtual file entry with the size of the contents
1908 // that would override the original contents. Set it to the original's
1909 // size/time.
1910 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1911 StoredSize, StoredTime);
1912 }
1913
1914 // For an overridden file, there is nothing to validate.
1915 if (Overridden)
1916 return InputFile(File, Overridden);
1917
1918 // The stat info from the FileEntry came from the cached stat
1919 // info of the PCH, so we cannot trust it.
1920 struct stat StatBuf;
1921 if (::stat(File->getName(), &StatBuf) != 0) {
1922 StatBuf.st_size = File->getSize();
1923 StatBuf.st_mtime = File->getModificationTime();
1924 }
1925
1926 if ((StoredSize != StatBuf.st_size
1927#if !defined(LLVM_ON_WIN32)
1928 // In our regression testing, the Windows file system seems to
1929 // have inconsistent modification times that sometimes
1930 // erroneously trigger this error-handling path.
1931 || StoredTime != StatBuf.st_mtime
1932#endif
1933 )) {
Douglas Gregor38295be2012-10-22 23:51:00 +00001934 if (Complain)
1935 Error(diag::err_fe_pch_file_modified, Filename);
1936
Douglas Gregora930dc92012-10-22 18:42:04 +00001937 return InputFile();
1938 }
1939
1940 return InputFile(File, Overridden);
1941 }
1942 }
1943
1944 return InputFile();
1945}
1946
Chris Lattner5f9e2722011-07-23 10:55:15 +00001947const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
Douglas Gregor69e16082012-10-18 21:47:16 +00001948 ModuleFile &M = ModuleMgr.getPrimaryModule();
Argyrios Kyrtzidisb68ffb12011-06-01 05:43:53 +00001949 std::string Filename = filenameStrRef;
Douglas Gregor69e16082012-10-18 21:47:16 +00001950 MaybeAddSystemRootToFilename(M, Filename);
Argyrios Kyrtzidisb68ffb12011-06-01 05:43:53 +00001951 const FileEntry *File = FileMgr.getFile(Filename);
Douglas Gregor69e16082012-10-18 21:47:16 +00001952 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1953 M.OriginalDir != CurrentDir) {
Argyrios Kyrtzidisb68ffb12011-06-01 05:43:53 +00001954 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
Douglas Gregor69e16082012-10-18 21:47:16 +00001955 M.OriginalDir,
Argyrios Kyrtzidisb68ffb12011-06-01 05:43:53 +00001956 CurrentDir);
1957 if (!resolved.empty())
1958 File = FileMgr.getFile(resolved);
1959 }
1960
1961 return File;
1962}
1963
Douglas Gregore650c8c2009-07-07 00:12:59 +00001964/// \brief If we are loading a relocatable PCH file, and the filename is
1965/// not an absolute path, add the system root to the beginning of the file
1966/// name.
Douglas Gregora930dc92012-10-22 18:42:04 +00001967StringRef ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
1968 std::string &Filename) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001969 // If this is not a relocatable PCH file, there's nothing to do.
Douglas Gregorcaed0602012-10-18 21:31:35 +00001970 if (!M.RelocatablePCH)
Douglas Gregora930dc92012-10-22 18:42:04 +00001971 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Michael J. Spencer256053b2010-12-17 21:22:22 +00001973 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
Douglas Gregora930dc92012-10-22 18:42:04 +00001974 return Filename;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001975
Douglas Gregor832d6202011-07-22 16:35:34 +00001976 if (isysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001977 // If no system root was given, default to '/'
1978 Filename.insert(Filename.begin(), '/');
Douglas Gregora930dc92012-10-22 18:42:04 +00001979 return Filename;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001980 }
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Douglas Gregor832d6202011-07-22 16:35:34 +00001982 unsigned Length = isysroot.size();
Douglas Gregore650c8c2009-07-07 00:12:59 +00001983 if (isysroot[Length - 1] != '/')
1984 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Douglas Gregor832d6202011-07-22 16:35:34 +00001986 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
Douglas Gregora930dc92012-10-22 18:42:04 +00001987 return Filename;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001988}
1989
Douglas Gregor38295be2012-10-22 23:51:00 +00001990ASTReader::ASTReadResult
1991ASTReader::ReadControlBlock(ModuleFile &F,
1992 llvm::SmallVectorImpl<ModuleFile *> &Loaded,
1993 unsigned ClientLoadCapabilities) {
Douglas Gregor1d9d9892012-10-18 05:31:06 +00001994 llvm::BitstreamCursor &Stream = F.Stream;
1995
1996 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
1997 Error("malformed block record in AST file");
1998 return Failure;
1999 }
2000
2001 // Read all of the records and blocks in the control block.
2002 RecordData Record;
2003 while (!Stream.AtEndOfStream()) {
2004 unsigned Code = Stream.ReadCode();
2005 if (Code == llvm::bitc::END_BLOCK) {
2006 if (Stream.ReadBlockEnd()) {
2007 Error("error at end of control block in AST file");
2008 return Failure;
2009 }
2010
Douglas Gregora930dc92012-10-22 18:42:04 +00002011 // Validate all of the input files.
2012 if (!DisableValidation) {
Douglas Gregor38295be2012-10-22 23:51:00 +00002013 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Douglas Gregora930dc92012-10-22 18:42:04 +00002014 for (unsigned I = 0, N = Record[0]; I < N; ++I)
Douglas Gregor38295be2012-10-22 23:51:00 +00002015 if (!getInputFile(F, I+1, Complain).getPointer())
Douglas Gregor4825fd72012-10-22 22:50:17 +00002016 return OutOfDate;
Douglas Gregora930dc92012-10-22 18:42:04 +00002017 }
2018
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002019 return Success;
2020 }
2021
2022 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor745e6f12012-10-19 00:38:02 +00002023 switch (Stream.ReadSubBlockID()) {
2024 case INPUT_FILES_BLOCK_ID:
Douglas Gregora930dc92012-10-22 18:42:04 +00002025 F.InputFilesCursor = Stream;
2026 if (Stream.SkipBlock() || // Skip with the main cursor
2027 // Read the abbreviations
2028 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2029 Error("malformed block record in AST file");
Douglas Gregor745e6f12012-10-19 00:38:02 +00002030 return Failure;
Douglas Gregor745e6f12012-10-19 00:38:02 +00002031 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002032 continue;
Douglas Gregor745e6f12012-10-19 00:38:02 +00002033
2034 default:
2035 if (!Stream.SkipBlock())
2036 continue;
2037 break;
2038 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002039
2040 Error("malformed block record in AST file");
2041 return Failure;
2042 }
2043
2044 if (Code == llvm::bitc::DEFINE_ABBREV) {
2045 Stream.ReadAbbrevRecord();
2046 continue;
2047 }
2048
2049 // Read and process a record.
2050 Record.clear();
2051 const char *BlobStart = 0;
2052 unsigned BlobLen = 0;
2053 switch ((ControlRecordTypes)Stream.ReadRecord(Code, Record,
2054 &BlobStart, &BlobLen)) {
2055 case METADATA: {
2056 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
Douglas Gregor38295be2012-10-22 23:51:00 +00002057 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2058 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
2059 : diag::warn_pch_version_too_new);
Douglas Gregor4825fd72012-10-22 22:50:17 +00002060 return VersionMismatch;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002061 }
2062
2063 bool hasErrors = Record[5];
2064 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2065 Diag(diag::err_pch_with_compiler_errors);
Douglas Gregor4825fd72012-10-22 22:50:17 +00002066 return HadErrors;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002067 }
2068
Douglas Gregorcaed0602012-10-18 21:31:35 +00002069 F.RelocatablePCH = Record[4];
Douglas Gregor7ae467f2012-10-18 18:27:37 +00002070
2071 const std::string &CurBranch = getClangFullRepositoryVersion();
2072 StringRef ASTBranch(BlobStart, BlobLen);
2073 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
Douglas Gregor38295be2012-10-22 23:51:00 +00002074 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2075 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
Douglas Gregor4825fd72012-10-22 22:50:17 +00002076 return VersionMismatch;
Douglas Gregor7ae467f2012-10-18 18:27:37 +00002077 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002078 break;
2079 }
2080
2081 case IMPORTS: {
2082 // Load each of the imported PCH files.
2083 unsigned Idx = 0, N = Record.size();
2084 while (Idx < N) {
2085 // Read information about the AST file.
2086 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2087 unsigned Length = Record[Idx++];
2088 SmallString<128> ImportedFile(Record.begin() + Idx,
2089 Record.begin() + Idx + Length);
2090 Idx += Length;
2091
2092 // Load the AST file.
Douglas Gregor38295be2012-10-22 23:51:00 +00002093 switch(ReadASTCore(ImportedFile, ImportedKind, &F, Loaded,
2094 ClientLoadCapabilities)) {
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002095 case Failure: return Failure;
2096 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor4825fd72012-10-22 22:50:17 +00002097 case OutOfDate: return OutOfDate;
2098 case VersionMismatch: return VersionMismatch;
2099 case ConfigurationMismatch: return ConfigurationMismatch;
2100 case HadErrors: return HadErrors;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002101 case Success: break;
2102 }
2103 }
2104 break;
2105 }
2106
Douglas Gregor38295be2012-10-22 23:51:00 +00002107 case LANGUAGE_OPTIONS: {
2108 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2109 if (Listener && &F == *ModuleMgr.begin() &&
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00002110 ParseLanguageOptions(Record, Complain, *Listener) &&
2111 !DisableValidation)
Douglas Gregor4825fd72012-10-22 22:50:17 +00002112 return ConfigurationMismatch;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002113 break;
Douglas Gregor38295be2012-10-22 23:51:00 +00002114 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002115
Douglas Gregoree097c12012-10-18 17:58:09 +00002116 case TARGET_OPTIONS: {
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00002117 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2118 if (Listener && &F == *ModuleMgr.begin() &&
2119 ParseTargetOptions(Record, Complain, *Listener) &&
2120 !DisableValidation)
2121 return ConfigurationMismatch;
Douglas Gregoree097c12012-10-18 17:58:09 +00002122 break;
2123 }
2124
Douglas Gregor5f3d8222012-10-24 15:17:15 +00002125 case DIAGNOSTIC_OPTIONS: {
2126 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2127 if (Listener && &F == *ModuleMgr.begin() &&
2128 ParseDiagnosticOptions(Record, Complain, *Listener) &&
2129 !DisableValidation)
2130 return ConfigurationMismatch;
2131 break;
2132 }
Douglas Gregor1b2c3c02012-10-24 15:49:58 +00002133
2134 case FILE_SYSTEM_OPTIONS: {
2135 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2136 if (Listener && &F == *ModuleMgr.begin() &&
2137 ParseFileSystemOptions(Record, Complain, *Listener) &&
2138 !DisableValidation)
2139 return ConfigurationMismatch;
2140 break;
2141 }
2142
Douglas Gregorbbf38312012-10-24 16:50:34 +00002143 case HEADER_SEARCH_OPTIONS: {
2144 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2145 if (Listener && &F == *ModuleMgr.begin() &&
2146 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
2147 !DisableValidation)
2148 return ConfigurationMismatch;
2149 break;
2150 }
2151
Douglas Gregora71a7d82012-10-24 20:05:57 +00002152 case PREPROCESSOR_OPTIONS: {
2153 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2154 if (Listener && &F == *ModuleMgr.begin() &&
2155 ParsePreprocessorOptions(Record, Complain, *Listener) &&
2156 !DisableValidation)
2157 return ConfigurationMismatch;
2158 break;
2159 }
2160
Douglas Gregor39c497b2012-10-18 18:36:53 +00002161 case ORIGINAL_FILE:
Douglas Gregor69e16082012-10-18 21:47:16 +00002162 F.OriginalSourceFileID = FileID::get(Record[0]);
2163 F.ActualOriginalSourceFileName.assign(BlobStart, BlobLen);
2164 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2165 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002166 break;
2167
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002168 case ORIGINAL_PCH_DIR:
Douglas Gregor69e16082012-10-18 21:47:16 +00002169 F.OriginalDir.assign(BlobStart, BlobLen);
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002170 break;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002171
Douglas Gregora930dc92012-10-22 18:42:04 +00002172 case INPUT_FILE_OFFSETS:
2173 F.InputFileOffsets = (const uint32_t *)BlobStart;
2174 F.InputFilesLoaded.resize(Record[0]);
Douglas Gregor745e6f12012-10-19 00:38:02 +00002175 break;
2176 }
Douglas Gregor745e6f12012-10-19 00:38:02 +00002177 }
2178
2179 Error("premature end of bitstream in AST file");
2180 return Failure;
2181}
2182
Douglas Gregor4825fd72012-10-22 22:50:17 +00002183bool ASTReader::ReadASTBlock(ModuleFile &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00002184 llvm::BitstreamCursor &Stream = F.Stream;
2185
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002186 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002187 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002188 return true;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002189 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002190
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002191 // Read all of the records and blocks for the AST file.
Douglas Gregor8038d512009-04-10 17:25:41 +00002192 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002193 while (!Stream.AtEndOfStream()) {
2194 unsigned Code = Stream.ReadCode();
2195 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002196 if (Stream.ReadBlockEnd()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002197 Error("error at end of module block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002198 return true;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002199 }
Chris Lattner7356a312009-04-11 21:15:38 +00002200
Argyrios Kyrtzidis1f941242012-09-21 01:30:00 +00002201 DeclContext *DC = Context.getTranslationUnitDecl();
2202 if (!DC->hasExternalVisibleStorage() && DC->hasExternalLexicalStorage())
2203 DC->setMustBuildLookupTable();
2204
Douglas Gregor4825fd72012-10-22 22:50:17 +00002205 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002206 }
2207
2208 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2209 switch (Stream.ReadSubBlockID()) {
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002210 case DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00002211 // We lazily load the decls block, but we want to set up the
2212 // DeclsCursor cursor to point into it. Clone our current bitcode
2213 // cursor to it, enter the block and read the abbrevs in that block.
2214 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00002215 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00002216 if (Stream.SkipBlock() || // Skip with the main cursor.
2217 // Read the abbrevs.
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002218 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002219 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002220 return true;
Chris Lattner6367f6d2009-04-27 01:05:14 +00002221 }
2222 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002224 case DECL_UPDATES_BLOCK_ID:
2225 if (Stream.SkipBlock()) {
2226 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002227 return true;
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002228 }
2229 break;
2230
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002231 case PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00002232 F.MacroCursor = Stream;
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002233 if (!PP.getExternalSource())
2234 PP.setExternalSource(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00002235
Douglas Gregorecdcb882010-10-20 22:00:55 +00002236 if (Stream.SkipBlock() ||
2237 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002238 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002239 return true;
Chris Lattner7356a312009-04-11 21:15:38 +00002240 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00002241 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
Chris Lattner7356a312009-04-11 21:15:38 +00002242 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002243
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002244 case PREPROCESSOR_DETAIL_BLOCK_ID:
2245 F.PreprocessorDetailCursor = Stream;
2246 if (Stream.SkipBlock() ||
2247 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2248 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2249 Error("malformed preprocessor detail record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002250 return true;
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002251 }
2252 F.PreprocessorDetailStartOffset
2253 = F.PreprocessorDetailCursor.GetCurrentBitNo();
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002254
2255 if (!PP.getPreprocessingRecord())
Argyrios Kyrtzidisc6c54522012-03-05 05:48:17 +00002256 PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002257 if (!PP.getPreprocessingRecord()->getExternalSource())
2258 PP.getPreprocessingRecord()->SetExternalSource(*this);
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002259 break;
2260
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002261 case SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor4825fd72012-10-22 22:50:17 +00002262 if (ReadSourceManagerBlock(F))
2263 return true;
Douglas Gregor14f79002009-04-10 03:52:48 +00002264 break;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002265
2266 case SUBMODULE_BLOCK_ID:
Douglas Gregor4825fd72012-10-22 22:50:17 +00002267 if (ReadSubmoduleBlock(F))
2268 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002269 break;
2270
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002271 case COMMENTS_BLOCK_ID: {
2272 llvm::BitstreamCursor C = Stream;
2273 if (Stream.SkipBlock() ||
2274 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2275 Error("malformed comments block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002276 return true;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002277 }
2278 CommentsCursors.push_back(std::make_pair(C, &F));
2279 break;
2280 }
2281
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002282 default:
2283 if (!Stream.SkipBlock())
2284 break;
2285 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002286 return true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002287 }
Douglas Gregor8038d512009-04-10 17:25:41 +00002288 continue;
2289 }
2290
2291 if (Code == llvm::bitc::DEFINE_ABBREV) {
2292 Stream.ReadAbbrevRecord();
2293 continue;
2294 }
2295
2296 // Read and process a record.
2297 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00002298 const char *BlobStart = 0;
2299 unsigned BlobLen = 0;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002300 switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
Sebastian Redlc3632732010-10-05 15:59:54 +00002301 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00002302 default: // Default behavior: ignore.
2303 break;
2304
Douglas Gregora119da02011-08-02 16:26:37 +00002305 case TYPE_OFFSET: {
Sebastian Redl12d6da02010-07-19 22:06:55 +00002306 if (F.LocalNumTypes != 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002307 Error("duplicate TYPE_OFFSET record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002308 return true;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002309 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00002310 F.TypeOffsets = (const uint32_t *)BlobStart;
2311 F.LocalNumTypes = Record[0];
Douglas Gregore3605012011-08-02 18:32:54 +00002312 unsigned LocalBaseTypeIndex = Record[1];
2313 F.BaseTypeIndex = getTotalNumTypes();
Douglas Gregor1e849b62011-07-29 00:21:44 +00002314
Douglas Gregora119da02011-08-02 16:26:37 +00002315 if (F.LocalNumTypes > 0) {
2316 // Introduce the global -> local mapping for types within this module.
2317 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2318
2319 // Introduce the local -> global mapping for types within this module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002320 F.TypeRemap.insertOrReplace(
2321 std::make_pair(LocalBaseTypeIndex,
2322 F.BaseTypeIndex - LocalBaseTypeIndex));
Douglas Gregora119da02011-08-02 16:26:37 +00002323
2324 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2325 }
Douglas Gregor8038d512009-04-10 17:25:41 +00002326 break;
Douglas Gregora119da02011-08-02 16:26:37 +00002327 }
2328
Douglas Gregor496c7092011-08-03 15:48:04 +00002329 case DECL_OFFSET: {
Sebastian Redl12d6da02010-07-19 22:06:55 +00002330 if (F.LocalNumDecls != 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002331 Error("duplicate DECL_OFFSET record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002332 return true;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002333 }
Argyrios Kyrtzidis9d31fa72011-10-27 18:47:35 +00002334 F.DeclOffsets = (const DeclOffset *)BlobStart;
Sebastian Redl12d6da02010-07-19 22:06:55 +00002335 F.LocalNumDecls = Record[0];
Douglas Gregor496c7092011-08-03 15:48:04 +00002336 unsigned LocalBaseDeclID = Record[1];
Douglas Gregor9827a802011-07-29 00:56:45 +00002337 F.BaseDeclID = getTotalNumDecls();
Douglas Gregor96e973f2011-07-20 00:27:43 +00002338
Douglas Gregor496c7092011-08-03 15:48:04 +00002339 if (F.LocalNumDecls > 0) {
2340 // Introduce the global -> local mapping for declarations within this
2341 // module.
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00002342 GlobalDeclMap.insert(
2343 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
Douglas Gregor496c7092011-08-03 15:48:04 +00002344
2345 // Introduce the local -> global mapping for declarations within this
2346 // module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002347 F.DeclRemap.insertOrReplace(
2348 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
Douglas Gregor496c7092011-08-03 15:48:04 +00002349
Douglas Gregora1be2782011-12-17 23:38:30 +00002350 // Introduce the global -> local mapping for declarations within this
2351 // module.
2352 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2353
Douglas Gregor496c7092011-08-03 15:48:04 +00002354 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2355 }
Douglas Gregor8038d512009-04-10 17:25:41 +00002356 break;
Douglas Gregor496c7092011-08-03 15:48:04 +00002357 }
2358
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002359 case TU_UPDATE_LEXICAL: {
Douglas Gregor35942772011-09-09 21:34:22 +00002360 DeclContext *TU = Context.getTranslationUnitDecl();
Douglas Gregor0d95f772011-08-24 19:03:07 +00002361 DeclContextInfo &Info = F.DeclContextInfos[TU];
2362 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
2363 Info.NumLexicalDecls
2364 = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
Douglas Gregor35942772011-09-09 21:34:22 +00002365 TU->setHasExternalLexicalStorage(true);
Sebastian Redld692af72010-07-27 18:24:41 +00002366 break;
2367 }
2368
Sebastian Redle1dde812010-08-24 00:50:04 +00002369 case UPDATE_VISIBLE: {
Douglas Gregor496c7092011-08-03 15:48:04 +00002370 unsigned Idx = 0;
2371 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Benjamin Kramerb1758c62012-04-15 12:36:49 +00002372 ASTDeclContextNameLookupTable *Table =
2373 ASTDeclContextNameLookupTable::Create(
Douglas Gregor496c7092011-08-03 15:48:04 +00002374 (const unsigned char *)BlobStart + Record[Idx++],
Sebastian Redle1dde812010-08-24 00:50:04 +00002375 (const unsigned char *)BlobStart,
Douglas Gregor393f2492011-07-22 00:38:23 +00002376 ASTDeclContextNameLookupTrait(*this, F));
Douglas Gregor35942772011-09-09 21:34:22 +00002377 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2378 DeclContext *TU = Context.getTranslationUnitDecl();
Douglas Gregor0d95f772011-08-24 19:03:07 +00002379 F.DeclContextInfos[TU].NameLookupTableData = Table;
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00002380 TU->setHasExternalVisibleStorage(true);
Sebastian Redle1dde812010-08-24 00:50:04 +00002381 } else
Douglas Gregor496c7092011-08-03 15:48:04 +00002382 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
Sebastian Redle1dde812010-08-24 00:50:04 +00002383 break;
2384 }
2385
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002386 case IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00002387 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002388 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00002389 F.IdentifierLookupTable
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002390 = ASTIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00002391 (const unsigned char *)F.IdentifierTableData + Record[0],
2392 (const unsigned char *)F.IdentifierTableData,
Sebastian Redlc3632732010-10-05 15:59:54 +00002393 ASTIdentifierLookupTrait(*this, F));
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002394
2395 PP.getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002396 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00002397 break;
2398
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002399 case IDENTIFIER_OFFSET: {
Sebastian Redl2da08f92010-07-19 22:28:42 +00002400 if (F.LocalNumIdentifiers != 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002401 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002402 return true;
Douglas Gregorafaf3082009-04-11 00:14:32 +00002403 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00002404 F.IdentifierOffsets = (const uint32_t *)BlobStart;
2405 F.LocalNumIdentifiers = Record[0];
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002406 unsigned LocalBaseIdentifierID = Record[1];
Douglas Gregor9827a802011-07-29 00:56:45 +00002407 F.BaseIdentifierID = getTotalNumIdentifiers();
Douglas Gregor67268d02011-07-20 00:59:32 +00002408
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002409 if (F.LocalNumIdentifiers > 0) {
2410 // Introduce the global -> local mapping for identifiers within this
2411 // module.
2412 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2413 &F));
2414
2415 // Introduce the local -> global mapping for identifiers within this
2416 // module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002417 F.IdentifierRemap.insertOrReplace(
2418 std::make_pair(LocalBaseIdentifierID,
2419 F.BaseIdentifierID - LocalBaseIdentifierID));
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002420
2421 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2422 + F.LocalNumIdentifiers);
2423 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00002424 break;
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002425 }
Douglas Gregora8235d62012-10-09 23:05:51 +00002426
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002427 case EXTERNAL_DEFINITIONS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002428 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2429 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregorfdd01722009-04-14 00:24:19 +00002430 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00002431
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002432 case SPECIAL_TYPES:
Douglas Gregor393f2492011-07-22 00:38:23 +00002433 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2434 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
Douglas Gregorad1de002009-04-18 05:55:16 +00002435 break;
2436
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002437 case STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00002438 TotalNumStatements += Record[0];
2439 TotalNumMacros += Record[1];
2440 TotalLexicalDeclContexts += Record[2];
2441 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00002442 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002443
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002444 case UNUSED_FILESCOPED_DECLS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002445 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2446 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
Tanya Lattnere6bbc012010-02-12 00:07:30 +00002447 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00002448
Sean Huntebcbe1d2011-05-04 23:29:54 +00002449 case DELEGATING_CTORS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002450 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2451 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
Sean Huntebcbe1d2011-05-04 23:29:54 +00002452 break;
2453
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002454 case WEAK_UNDECLARED_IDENTIFIERS:
Douglas Gregor31e37b22011-07-28 18:09:57 +00002455 if (Record.size() % 4 != 0) {
2456 Error("invalid weak identifiers record");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002457 return true;
Douglas Gregor31e37b22011-07-28 18:09:57 +00002458 }
2459
2460 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2461 // files. This isn't the way to do it :)
2462 WeakUndeclaredIdentifiers.clear();
2463
2464 // Translate the weak, undeclared identifiers into global IDs.
2465 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2466 WeakUndeclaredIdentifiers.push_back(
2467 getGlobalIdentifierID(F, Record[I++]));
2468 WeakUndeclaredIdentifiers.push_back(
2469 getGlobalIdentifierID(F, Record[I++]));
2470 WeakUndeclaredIdentifiers.push_back(
2471 ReadSourceLocation(F, Record, I).getRawEncoding());
2472 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2473 }
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00002474 break;
2475
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002476 case LOCALLY_SCOPED_EXTERNAL_DECLS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002477 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2478 LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregor14c22f22009-04-22 22:18:58 +00002479 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002480
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002481 case SELECTOR_OFFSETS: {
Sebastian Redl059612d2010-08-03 21:58:15 +00002482 F.SelectorOffsets = (const uint32_t *)BlobStart;
Sebastian Redl725cd962010-08-04 20:40:17 +00002483 F.LocalNumSelectors = Record[0];
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002484 unsigned LocalBaseSelectorID = Record[1];
Douglas Gregor9827a802011-07-29 00:56:45 +00002485 F.BaseSelectorID = getTotalNumSelectors();
Douglas Gregor96958cb2011-07-20 01:10:58 +00002486
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002487 if (F.LocalNumSelectors > 0) {
2488 // Introduce the global -> local mapping for selectors within this
2489 // module.
2490 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2491
2492 // Introduce the local -> global mapping for selectors within this
2493 // module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002494 F.SelectorRemap.insertOrReplace(
2495 std::make_pair(LocalBaseSelectorID,
2496 F.BaseSelectorID - LocalBaseSelectorID));
Douglas Gregor83941df2009-04-25 17:48:32 +00002497
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002498 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2499 }
2500 break;
2501 }
2502
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002503 case METHOD_POOL:
Sebastian Redl725cd962010-08-04 20:40:17 +00002504 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
Douglas Gregor83941df2009-04-25 17:48:32 +00002505 if (Record[0])
Sebastian Redl725cd962010-08-04 20:40:17 +00002506 F.SelectorLookupTable
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002507 = ASTSelectorLookupTable::Create(
Sebastian Redl725cd962010-08-04 20:40:17 +00002508 F.SelectorLookupTableData + Record[0],
2509 F.SelectorLookupTableData,
Douglas Gregor409448c2011-07-21 22:35:25 +00002510 ASTSelectorLookupTrait(*this, F));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00002511 TotalNumMethodPoolEntries += Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002512 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00002513
Sebastian Redl4ee5a6f2010-09-22 00:42:30 +00002514 case REFERENCED_SELECTOR_POOL:
Douglas Gregor8451ec72011-07-28 14:41:43 +00002515 if (!Record.empty()) {
2516 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2517 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2518 Record[Idx++]));
2519 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2520 getRawEncoding());
2521 }
2522 }
Fariborz Jahanian32019832010-07-23 19:11:11 +00002523 break;
2524
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002525 case PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002526 if (!Record.empty() && Listener)
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002527 Listener->ReadCounter(F, Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00002528 break;
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00002529
2530 case FILE_SORTED_DECLS:
2531 F.FileSortedDecls = (const DeclID *)BlobStart;
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002532 F.NumFileSortedDecls = Record[0];
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00002533 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002534
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002535 case SOURCE_LOCATION_OFFSETS: {
2536 F.SLocEntryOffsets = (const uint32_t *)BlobStart;
Sebastian Redl518d8cb2010-07-20 21:20:32 +00002537 F.LocalNumSLocEntries = Record[0];
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002538 unsigned SLocSpaceSize = Record[1];
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002539 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002540 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2541 SLocSpaceSize);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002542 // Make our entry in the range map. BaseID is negative and growing, so
2543 // we invert it. Because we invert it, though, we need the other end of
2544 // the range.
2545 unsigned RangeStart =
2546 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2547 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2548 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2549
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002550 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2551 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2552 GlobalSLocOffsetMap.insert(
2553 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2554 - SLocSpaceSize,&F));
2555
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002556 // Initialize the remapping table.
2557 // Invalid stays invalid.
2558 F.SLocRemap.insert(std::make_pair(0U, 0));
2559 // This module. Base was 2 when being compiled.
2560 F.SLocRemap.insert(std::make_pair(2U,
2561 static_cast<int>(F.SLocEntryBaseOffset - 2)));
Douglas Gregor0cdd7982011-07-21 18:46:38 +00002562
2563 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002564 break;
2565 }
2566
Douglas Gregor5d51a1d2011-08-01 16:01:55 +00002567 case MODULE_OFFSET_MAP: {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002568 // Additional remapping information.
2569 const unsigned char *Data = (const unsigned char*)BlobStart;
2570 const unsigned char *DataEnd = Data + BlobLen;
Douglas Gregorf33740e2011-08-02 10:56:51 +00002571
2572 // Continuous range maps we may be updating in our module.
2573 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002574 ContinuousRangeMap<uint32_t, int, 2>::Builder
2575 IdentifierRemap(F.IdentifierRemap);
Douglas Gregora8235d62012-10-09 23:05:51 +00002576 ContinuousRangeMap<uint32_t, int, 2>::Builder
2577 MacroRemap(F.MacroRemap);
2578 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002579 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2580 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregor26ced122011-12-01 00:59:36 +00002581 SubmoduleRemap(F.SubmoduleRemap);
2582 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002583 SelectorRemap(F.SelectorRemap);
Douglas Gregor496c7092011-08-03 15:48:04 +00002584 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
Douglas Gregora119da02011-08-02 16:26:37 +00002585 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2586
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002587 while(Data < DataEnd) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002588 uint16_t Len = io::ReadUnalignedLE16(Data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002589 StringRef Name = StringRef((const char*)Data, Len);
Douglas Gregorf33740e2011-08-02 10:56:51 +00002590 Data += Len;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002591 ModuleFile *OM = ModuleMgr.lookup(Name);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002592 if (!OM) {
2593 Error("SourceLocation remap refers to unknown module");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002594 return true;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002595 }
Douglas Gregorf33740e2011-08-02 10:56:51 +00002596
2597 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2598 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregora8235d62012-10-09 23:05:51 +00002599 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregorf33740e2011-08-02 10:56:51 +00002600 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregor26ced122011-12-01 00:59:36 +00002601 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregorf33740e2011-08-02 10:56:51 +00002602 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2603 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregora119da02011-08-02 16:26:37 +00002604 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
Douglas Gregorf33740e2011-08-02 10:56:51 +00002605
2606 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2607 SLocRemap.insert(std::make_pair(SLocOffset,
2608 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002609 IdentifierRemap.insert(
2610 std::make_pair(IdentifierIDOffset,
2611 OM->BaseIdentifierID - IdentifierIDOffset));
Douglas Gregora8235d62012-10-09 23:05:51 +00002612 MacroRemap.insert(std::make_pair(MacroIDOffset,
2613 OM->BaseMacroID - MacroIDOffset));
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002614 PreprocessedEntityRemap.insert(
2615 std::make_pair(PreprocessedEntityIDOffset,
2616 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
Douglas Gregor26ced122011-12-01 00:59:36 +00002617 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2618 OM->BaseSubmoduleID - SubmoduleIDOffset));
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002619 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2620 OM->BaseSelectorID - SelectorIDOffset));
Douglas Gregor496c7092011-08-03 15:48:04 +00002621 DeclRemap.insert(std::make_pair(DeclIDOffset,
2622 OM->BaseDeclID - DeclIDOffset));
2623
Douglas Gregora119da02011-08-02 16:26:37 +00002624 TypeRemap.insert(std::make_pair(TypeIndexOffset,
Douglas Gregore3605012011-08-02 18:32:54 +00002625 OM->BaseTypeIndex - TypeIndexOffset));
Douglas Gregora1be2782011-12-17 23:38:30 +00002626
2627 // Global -> local mappings.
2628 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002629 }
2630 break;
2631 }
2632
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002633 case SOURCE_MANAGER_LINE_TABLE:
2634 if (ParseLineTable(F, Record))
Douglas Gregor4825fd72012-10-22 22:50:17 +00002635 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002636 break;
2637
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002638 case SOURCE_LOCATION_PRELOADS: {
2639 // Need to transform from the local view (1-based IDs) to the global view,
2640 // which is based off F.SLocEntryBaseID.
Douglas Gregorf249bf32011-08-25 21:09:44 +00002641 if (!F.PreloadSLocEntries.empty()) {
2642 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002643 return true;
Douglas Gregorf249bf32011-08-25 21:09:44 +00002644 }
2645
2646 F.PreloadSLocEntries.swap(Record);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002647 break;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002648 }
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002649
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002650 case STAT_CACHE: {
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002651 if (!DisableStatCache) {
2652 ASTStatCache *MyStatCache =
2653 new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2654 (const unsigned char *)BlobStart,
2655 NumStatHits, NumStatMisses);
2656 FileMgr.addStatCache(MyStatCache);
2657 F.StatCache = MyStatCache;
2658 }
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002659 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00002660 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00002661
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002662 case EXT_VECTOR_DECLS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002663 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2664 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregorb81c1702009-04-27 20:06:05 +00002665 break;
2666
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002667 case VTABLE_USES:
Douglas Gregordfe65432011-07-28 19:11:31 +00002668 if (Record.size() % 3 != 0) {
2669 Error("Invalid VTABLE_USES record");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002670 return true;
Douglas Gregordfe65432011-07-28 19:11:31 +00002671 }
2672
Sebastian Redl40566802010-08-05 18:21:25 +00002673 // Later tables overwrite earlier ones.
Douglas Gregordfe65432011-07-28 19:11:31 +00002674 // FIXME: Modules will have some trouble with this. This is clearly not
2675 // the right way to do this.
Douglas Gregor409448c2011-07-21 22:35:25 +00002676 VTableUses.clear();
Douglas Gregordfe65432011-07-28 19:11:31 +00002677
2678 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2679 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2680 VTableUses.push_back(
2681 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2682 VTableUses.push_back(Record[Idx++]);
2683 }
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00002684 break;
2685
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002686 case DYNAMIC_CLASSES:
Douglas Gregor409448c2011-07-21 22:35:25 +00002687 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2688 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00002689 break;
2690
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002691 case PENDING_IMPLICIT_INSTANTIATIONS:
Douglas Gregorf2abb522011-07-28 19:26:52 +00002692 if (PendingInstantiations.size() % 2 != 0) {
Axel Naumann39d26c32012-10-02 09:09:43 +00002693 Error("Invalid existing PendingInstantiations");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002694 return true;
Axel Naumann39d26c32012-10-02 09:09:43 +00002695 }
2696
2697 if (Record.size() % 2 != 0) {
Douglas Gregorf2abb522011-07-28 19:26:52 +00002698 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002699 return true;
Douglas Gregorf2abb522011-07-28 19:26:52 +00002700 }
Axel Naumann39d26c32012-10-02 09:09:43 +00002701
Douglas Gregorf2abb522011-07-28 19:26:52 +00002702 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2703 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2704 PendingInstantiations.push_back(
2705 ReadSourceLocation(F, Record, I).getRawEncoding());
2706 }
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00002707 break;
2708
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002709 case SEMA_DECL_REFS:
Sebastian Redl40566802010-08-05 18:21:25 +00002710 // Later tables overwrite earlier ones.
Douglas Gregor409448c2011-07-21 22:35:25 +00002711 // FIXME: Modules will have some trouble with this.
2712 SemaDeclRefs.clear();
2713 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2714 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00002715 break;
2716
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002717 case PPD_ENTITIES_OFFSETS: {
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002718 F.PreprocessedEntityOffsets = (const PPEntityOffset *)BlobStart;
2719 assert(BlobLen % sizeof(PPEntityOffset) == 0);
2720 F.NumPreprocessedEntities = BlobLen / sizeof(PPEntityOffset);
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002721
2722 unsigned LocalBasePreprocessedEntityID = Record[0];
Douglas Gregorfb2d9e02011-08-04 16:36:56 +00002723
Douglas Gregor4c30bb12011-07-21 00:47:40 +00002724 unsigned StartingID;
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002725 if (!PP.getPreprocessingRecord())
Argyrios Kyrtzidisc6c54522012-03-05 05:48:17 +00002726 PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002727 if (!PP.getPreprocessingRecord()->getExternalSource())
2728 PP.getPreprocessingRecord()->SetExternalSource(*this);
2729 StartingID
2730 = PP.getPreprocessingRecord()
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002731 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Douglas Gregor9827a802011-07-29 00:56:45 +00002732 F.BasePreprocessedEntityID = StartingID;
Douglas Gregor4c30bb12011-07-21 00:47:40 +00002733
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002734 if (F.NumPreprocessedEntities > 0) {
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002735 // Introduce the global -> local mapping for preprocessed entities in
2736 // this module.
2737 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2738
2739 // Introduce the local -> global mapping for preprocessed entities in
2740 // this module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002741 F.PreprocessedEntityRemap.insertOrReplace(
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002742 std::make_pair(LocalBasePreprocessedEntityID,
2743 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2744 }
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002745
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002746 break;
Douglas Gregor4c30bb12011-07-21 00:47:40 +00002747 }
2748
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002749 case DECL_UPDATE_OFFSETS: {
2750 if (Record.size() % 2 != 0) {
2751 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002752 return true;
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002753 }
2754 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
Douglas Gregor496c7092011-08-03 15:48:04 +00002755 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2756 .push_back(std::make_pair(&F, Record[I+1]));
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002757 break;
2758 }
2759
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002760 case DECL_REPLACEMENTS: {
Argyrios Kyrtzidisef23b602011-10-31 07:20:15 +00002761 if (Record.size() % 3 != 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002762 Error("invalid DECL_REPLACEMENTS block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002763 return true;
Sebastian Redl0b17c612010-08-13 00:28:03 +00002764 }
Argyrios Kyrtzidisef23b602011-10-31 07:20:15 +00002765 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
Douglas Gregor496c7092011-08-03 15:48:04 +00002766 ReplacedDecls[getGlobalDeclID(F, Record[I])]
Argyrios Kyrtzidisef23b602011-10-31 07:20:15 +00002767 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
Sebastian Redl0b17c612010-08-13 00:28:03 +00002768 break;
2769 }
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00002770
Douglas Gregorcff9f262012-01-27 01:47:08 +00002771 case OBJC_CATEGORIES_MAP: {
2772 if (F.LocalNumObjCCategoriesInMap != 0) {
2773 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002774 return true;
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00002775 }
Douglas Gregorcff9f262012-01-27 01:47:08 +00002776
2777 F.LocalNumObjCCategoriesInMap = Record[0];
2778 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)BlobStart;
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00002779 break;
2780 }
Douglas Gregor7c789c12010-10-29 22:39:52 +00002781
Douglas Gregorcff9f262012-01-27 01:47:08 +00002782 case OBJC_CATEGORIES:
2783 F.ObjCCategories.swap(Record);
2784 break;
2785
Douglas Gregor7c789c12010-10-29 22:39:52 +00002786 case CXX_BASE_SPECIFIER_OFFSETS: {
2787 if (F.LocalNumCXXBaseSpecifiers != 0) {
2788 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002789 return true;
Douglas Gregor7c789c12010-10-29 22:39:52 +00002790 }
2791
2792 F.LocalNumCXXBaseSpecifiers = Record[0];
2793 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
Jonathan D. Turner1da90142011-07-21 21:15:19 +00002794 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
Douglas Gregor7c789c12010-10-29 22:39:52 +00002795 break;
2796 }
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002797
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +00002798 case DIAG_PRAGMA_MAPPINGS:
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002799 if (Record.size() % 2 != 0) {
2800 Error("invalid DIAG_USER_MAPPINGS block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002801 return true;
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002802 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002803
2804 if (F.PragmaDiagMappings.empty())
2805 F.PragmaDiagMappings.swap(Record);
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002806 else
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002807 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2808 Record.begin(), Record.end());
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002809 break;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002810
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00002811 case CUDA_SPECIAL_DECL_REFS:
2812 // Later tables overwrite earlier ones.
Douglas Gregor409448c2011-07-21 22:35:25 +00002813 // FIXME: Modules will have trouble with this.
2814 CUDASpecialDeclRefs.clear();
2815 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2816 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00002817 break;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002818
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002819 case HEADER_SEARCH_TABLE: {
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002820 F.HeaderFileInfoTableData = BlobStart;
2821 F.LocalNumHeaderFileInfos = Record[1];
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002822 F.HeaderFileFrameworkStrings = BlobStart + Record[2];
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002823 if (Record[0]) {
2824 F.HeaderFileInfoTable
2825 = HeaderFileInfoLookupTable::Create(
2826 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002827 (const unsigned char *)F.HeaderFileInfoTableData,
Douglas Gregor95eab172011-07-28 20:55:49 +00002828 HeaderFileInfoTrait(*this, F,
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002829 &PP.getHeaderSearchInfo(),
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002830 BlobStart + Record[2]));
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002831
2832 PP.getHeaderSearchInfo().SetExternalSource(this);
2833 if (!PP.getHeaderSearchInfo().getExternalLookup())
2834 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002835 }
2836 break;
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002837 }
2838
Peter Collingbourne84bccea2011-02-15 19:46:30 +00002839 case FP_PRAGMA_OPTIONS:
2840 // Later tables overwrite earlier ones.
2841 FPPragmaOptions.swap(Record);
2842 break;
2843
2844 case OPENCL_EXTENSIONS:
2845 // Later tables overwrite earlier ones.
2846 OpenCLExtensions.swap(Record);
2847 break;
Sean Huntebcbe1d2011-05-04 23:29:54 +00002848
2849 case TENTATIVE_DEFINITIONS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002850 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2851 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
Sean Huntebcbe1d2011-05-04 23:29:54 +00002852 break;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002853
2854 case KNOWN_NAMESPACES:
Douglas Gregor409448c2011-07-21 22:35:25 +00002855 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2856 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002857 break;
Douglas Gregorf6137e42011-12-03 00:59:55 +00002858
2859 case IMPORTED_MODULES: {
2860 if (F.Kind != MK_Module) {
2861 // If we aren't loading a module (which has its own exports), make
2862 // all of the imported modules visible.
2863 // FIXME: Deal with macros-only imports.
2864 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2865 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2866 ImportedModules.push_back(GlobalID);
2867 }
2868 }
2869 break;
Douglas Gregora1be2782011-12-17 23:38:30 +00002870 }
Douglas Gregor2171bf12012-01-15 16:58:34 +00002871
Douglas Gregora1be2782011-12-17 23:38:30 +00002872 case LOCAL_REDECLARATIONS: {
Douglas Gregor2171bf12012-01-15 16:58:34 +00002873 F.RedeclarationChains.swap(Record);
2874 break;
2875 }
2876
2877 case LOCAL_REDECLARATIONS_MAP: {
2878 if (F.LocalNumRedeclarationsInMap != 0) {
2879 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002880 return true;
Douglas Gregora1be2782011-12-17 23:38:30 +00002881 }
Douglas Gregorf6137e42011-12-03 00:59:55 +00002882
Douglas Gregor2171bf12012-01-15 16:58:34 +00002883 F.LocalNumRedeclarationsInMap = Record[0];
2884 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)BlobStart;
Douglas Gregora1be2782011-12-17 23:38:30 +00002885 break;
Douglas Gregorf6137e42011-12-03 00:59:55 +00002886 }
Douglas Gregorc3cfd2a2011-12-22 21:40:42 +00002887
2888 case MERGED_DECLARATIONS: {
2889 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2890 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2891 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2892 for (unsigned N = Record[Idx++]; N > 0; --N)
2893 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2894 }
2895 break;
2896 }
Douglas Gregora8235d62012-10-09 23:05:51 +00002897
2898 case MACRO_OFFSET: {
2899 if (F.LocalNumMacros != 0) {
2900 Error("duplicate MACRO_OFFSET record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002901 return true;
Douglas Gregora8235d62012-10-09 23:05:51 +00002902 }
2903 F.MacroOffsets = (const uint32_t *)BlobStart;
2904 F.LocalNumMacros = Record[0];
2905 unsigned LocalBaseMacroID = Record[1];
2906 F.BaseMacroID = getTotalNumMacros();
2907
2908 if (F.LocalNumMacros > 0) {
2909 // Introduce the global -> local mapping for macros within this module.
2910 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2911
2912 // Introduce the local -> global mapping for macros within this module.
2913 F.MacroRemap.insertOrReplace(
2914 std::make_pair(LocalBaseMacroID,
2915 F.BaseMacroID - LocalBaseMacroID));
2916
2917 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2918 }
2919 break;
2920 }
2921
2922 case MACRO_UPDATES: {
2923 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2924 MacroID ID = getGlobalMacroID(F, Record[I++]);
2925 if (I == N)
2926 break;
2927
Douglas Gregor54c8a402012-10-12 00:16:50 +00002928 SourceLocation UndefLoc = ReadSourceLocation(F, Record, I);
2929 SubmoduleID SubmoduleID = getGlobalSubmoduleID(F, Record[I++]);;
2930 MacroUpdate Update;
2931 Update.UndefLoc = UndefLoc;
2932 MacroUpdates[ID].push_back(std::make_pair(SubmoduleID, Update));
Douglas Gregora8235d62012-10-09 23:05:51 +00002933 }
2934 break;
2935 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00002936 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002937 }
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002938 Error("premature end of bitstream in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002939 return true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002940}
2941
Douglas Gregorecc2c092011-12-01 22:20:10 +00002942void ASTReader::makeNamesVisible(const HiddenNames &Names) {
Douglas Gregor13292642011-12-02 15:45:10 +00002943 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
Douglas Gregor54c8a402012-10-12 00:16:50 +00002944 switch (Names[I].getKind()) {
2945 case HiddenName::Declaration:
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00002946 Names[I].getDecl()->Hidden = false;
Douglas Gregor54c8a402012-10-12 00:16:50 +00002947 break;
2948
2949 case HiddenName::MacroVisibility: {
2950 std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2951 Macro.second->setHidden(!Macro.second->isPublic());
2952 if (Macro.second->isDefined()) {
2953 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2954 }
2955 break;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00002956 }
2957
Douglas Gregor54c8a402012-10-12 00:16:50 +00002958 case HiddenName::MacroUndef: {
2959 std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2960 if (Macro.second->isDefined()) {
2961 Macro.second->setUndefLoc(Names[I].getMacroUndefLoc());
2962 if (PPMutationListener *Listener = PP.getPPMutationListener())
2963 Listener->UndefinedMacro(Macro.second);
2964 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2965 }
2966 break;
2967 }
Douglas Gregor1d4c1132011-12-20 22:06:13 +00002968 }
Douglas Gregor13292642011-12-02 15:45:10 +00002969 }
Douglas Gregorecc2c092011-12-01 22:20:10 +00002970}
2971
Douglas Gregor5e356932011-12-01 17:11:21 +00002972void ASTReader::makeModuleVisible(Module *Mod,
2973 Module::NameVisibilityKind NameVisibility) {
2974 llvm::SmallPtrSet<Module *, 4> Visited;
2975 llvm::SmallVector<Module *, 4> Stack;
2976 Stack.push_back(Mod);
2977 while (!Stack.empty()) {
2978 Mod = Stack.back();
2979 Stack.pop_back();
2980
2981 if (NameVisibility <= Mod->NameVisibility) {
2982 // This module already has this level of visibility (or greater), so
2983 // there is nothing more to do.
2984 continue;
2985 }
2986
Douglas Gregor51f564f2011-12-31 04:05:44 +00002987 if (!Mod->isAvailable()) {
2988 // Modules that aren't available cannot be made visible.
2989 continue;
2990 }
2991
Douglas Gregor5e356932011-12-01 17:11:21 +00002992 // Update the module's name visibility.
2993 Mod->NameVisibility = NameVisibility;
2994
Douglas Gregorecc2c092011-12-01 22:20:10 +00002995 // If we've already deserialized any names from this module,
Douglas Gregor5e356932011-12-01 17:11:21 +00002996 // mark them as visible.
Douglas Gregorecc2c092011-12-01 22:20:10 +00002997 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
2998 if (Hidden != HiddenNamesMap.end()) {
2999 makeNamesVisible(Hidden->second);
3000 HiddenNamesMap.erase(Hidden);
3001 }
Douglas Gregor5e356932011-12-01 17:11:21 +00003002
3003 // Push any non-explicit submodules onto the stack to be marked as
3004 // visible.
Douglas Gregorb7a78192012-01-04 23:32:19 +00003005 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3006 SubEnd = Mod->submodule_end();
Douglas Gregor5e356932011-12-01 17:11:21 +00003007 Sub != SubEnd; ++Sub) {
Douglas Gregorb7a78192012-01-04 23:32:19 +00003008 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
3009 Stack.push_back(*Sub);
Douglas Gregor5e356932011-12-01 17:11:21 +00003010 }
Douglas Gregor07165b92011-12-02 19:11:09 +00003011
3012 // Push any exported modules onto the stack to be marked as visible.
Douglas Gregor0adaa882011-12-05 17:28:06 +00003013 bool AnyWildcard = false;
3014 bool UnrestrictedWildcard = false;
3015 llvm::SmallVector<Module *, 4> WildcardRestrictions;
Douglas Gregor07165b92011-12-02 19:11:09 +00003016 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
3017 Module *Exported = Mod->Exports[I].getPointer();
Douglas Gregor0adaa882011-12-05 17:28:06 +00003018 if (!Mod->Exports[I].getInt()) {
3019 // Export a named module directly; no wildcards involved.
3020 if (Visited.insert(Exported))
Douglas Gregor07165b92011-12-02 19:11:09 +00003021 Stack.push_back(Exported);
Douglas Gregor0adaa882011-12-05 17:28:06 +00003022
3023 continue;
Douglas Gregor07165b92011-12-02 19:11:09 +00003024 }
Douglas Gregor0adaa882011-12-05 17:28:06 +00003025
3026 // Wildcard export: export all of the imported modules that match
3027 // the given pattern.
3028 AnyWildcard = true;
3029 if (UnrestrictedWildcard)
3030 continue;
3031
3032 if (Module *Restriction = Mod->Exports[I].getPointer())
3033 WildcardRestrictions.push_back(Restriction);
3034 else {
3035 WildcardRestrictions.clear();
3036 UnrestrictedWildcard = true;
3037 }
3038 }
3039
3040 // If there were any wildcards, push any imported modules that were
3041 // re-exported by the wildcard restriction.
3042 if (!AnyWildcard)
3043 continue;
3044
3045 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
3046 Module *Imported = Mod->Imports[I];
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00003047 if (!Visited.insert(Imported))
Douglas Gregor0adaa882011-12-05 17:28:06 +00003048 continue;
3049
3050 bool Acceptable = UnrestrictedWildcard;
3051 if (!Acceptable) {
3052 // Check whether this module meets one of the restrictions.
3053 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
3054 Module *Restriction = WildcardRestrictions[R];
3055 if (Imported == Restriction || Imported->isSubModuleOf(Restriction)) {
3056 Acceptable = true;
3057 break;
3058 }
3059 }
3060 }
3061
3062 if (!Acceptable)
3063 continue;
3064
Douglas Gregor0adaa882011-12-05 17:28:06 +00003065 Stack.push_back(Imported);
Douglas Gregor07165b92011-12-02 19:11:09 +00003066 }
Douglas Gregor5e356932011-12-01 17:11:21 +00003067 }
3068}
3069
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00003070ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
Douglas Gregor38295be2012-10-22 23:51:00 +00003071 ModuleKind Type,
3072 unsigned ClientLoadCapabilities) {
Douglas Gregor057df202012-01-18 20:56:22 +00003073 // Bump the generation number.
Douglas Gregorcff9f262012-01-27 01:47:08 +00003074 unsigned PreviousGeneration = CurrentGeneration++;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003075
3076 // Load the core of the AST files.
3077 llvm::SmallVector<ModuleFile *, 4> Loaded;
Douglas Gregor38295be2012-10-22 23:51:00 +00003078 switch(ReadASTCore(FileName, Type, /*ImportedBy=*/0, Loaded,
3079 ClientLoadCapabilities)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00003080 case Failure: return Failure;
Douglas Gregor4825fd72012-10-22 22:50:17 +00003081 case OutOfDate: return OutOfDate;
3082 case VersionMismatch: return VersionMismatch;
3083 case ConfigurationMismatch: return ConfigurationMismatch;
3084 case HadErrors: return HadErrors;
Sebastian Redlcdf3b832010-07-16 20:41:52 +00003085 case Success: break;
3086 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003087
3088 // Here comes stuff that we only do once the entire chain is loaded.
Douglas Gregor057df202012-01-18 20:56:22 +00003089
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003090 // Load the AST blocks of all of the modules that we loaded.
3091 for (llvm::SmallVectorImpl<ModuleFile *>::iterator M = Loaded.begin(),
3092 MEnd = Loaded.end();
3093 M != MEnd; ++M) {
3094 ModuleFile &F = **M;
3095
3096 // Read the AST block.
Douglas Gregor4825fd72012-10-22 22:50:17 +00003097 if (ReadASTBlock(F))
3098 return Failure;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003099
3100 // Once read, set the ModuleFile bit base offset and update the size in
3101 // bits of all files we've seen.
3102 F.GlobalBitOffset = TotalModulesSizeInBits;
3103 TotalModulesSizeInBits += F.SizeInBits;
3104 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3105
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003106 // Preload SLocEntries.
3107 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3108 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Douglas Gregor8b53d142012-10-22 22:53:10 +00003109 // Load it through the SourceManager and don't call ReadSLocEntry()
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003110 // directly because the entry may have already been loaded in which case
Douglas Gregor8b53d142012-10-22 22:53:10 +00003111 // calling ReadSLocEntry() directly would trigger an assertion in
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003112 // SourceManager.
3113 SourceMgr.getLoadedSLocEntryByID(Index);
3114 }
3115 }
3116
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003117 // Check the predefines buffers.
Douglas Gregor38295be2012-10-22 23:51:00 +00003118 bool ConfigComplain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
Douglas Gregor6236a292011-12-02 21:56:05 +00003119 if (!DisableValidation && Type == MK_PCH &&
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00003120 // FIXME: CheckPredefinesBuffers also sets the SuggestedPredefines;
3121 // if DisableValidation is true, defines that were set on command-line
3122 // but not in the PCH file will not be added to SuggestedPredefines.
Douglas Gregor38295be2012-10-22 23:51:00 +00003123 CheckPredefinesBuffers(ConfigComplain))
Douglas Gregor4825fd72012-10-22 22:50:17 +00003124 return ConfigurationMismatch;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003125
Douglas Gregoreee242f2011-10-27 09:33:13 +00003126 // Mark all of the identifiers in the identifier table as being out of date,
3127 // so that various accessors know to check the loaded modules when the
3128 // identifier is used.
Douglas Gregor712f2fc2011-09-09 22:02:16 +00003129 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3130 IdEnd = PP.getIdentifierTable().end();
3131 Id != IdEnd; ++Id)
Douglas Gregoreee242f2011-10-27 09:33:13 +00003132 Id->second->setOutOfDate(true);
Douglas Gregor057df202012-01-18 20:56:22 +00003133
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003134 // Resolve any unresolved module exports.
Douglas Gregor55988682011-12-05 16:33:54 +00003135 for (unsigned I = 0, N = UnresolvedModuleImportExports.size(); I != N; ++I) {
3136 UnresolvedModuleImportExport &Unresolved = UnresolvedModuleImportExports[I];
3137 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
Douglas Gregor0adaa882011-12-05 17:28:06 +00003138 Module *ResolvedMod = getSubmodule(GlobalID);
3139
3140 if (Unresolved.IsImport) {
3141 if (ResolvedMod)
Douglas Gregor55988682011-12-05 16:33:54 +00003142 Unresolved.Mod->Imports.push_back(ResolvedMod);
Douglas Gregor0adaa882011-12-05 17:28:06 +00003143 continue;
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003144 }
Douglas Gregor0adaa882011-12-05 17:28:06 +00003145
3146 if (ResolvedMod || Unresolved.IsWildcard)
3147 Unresolved.Mod->Exports.push_back(
3148 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003149 }
Douglas Gregor55988682011-12-05 16:33:54 +00003150 UnresolvedModuleImportExports.clear();
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003151
Douglas Gregor35942772011-09-09 21:34:22 +00003152 InitializeContext();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003153
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00003154 if (DeserializationListener)
3155 DeserializationListener->ReaderInitialized(this);
3156
Douglas Gregor11407b82012-10-18 21:18:25 +00003157 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3158 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3159 PrimaryModule.OriginalSourceFileID
3160 = FileID::get(PrimaryModule.SLocEntryBaseID
3161 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +00003162
Douglas Gregor11407b82012-10-18 21:18:25 +00003163 // If this AST file is a precompiled preamble, then set the
3164 // preamble file ID of the source manager to the file source file
3165 // from which the preamble was built.
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +00003166 if (Type == MK_Preamble) {
Douglas Gregor11407b82012-10-18 21:18:25 +00003167 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +00003168 } else if (Type == MK_MainFile) {
Douglas Gregor11407b82012-10-18 21:18:25 +00003169 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00003170 }
Douglas Gregor414cb642010-11-30 05:23:00 +00003171 }
3172
Douglas Gregorcff9f262012-01-27 01:47:08 +00003173 // For any Objective-C class definitions we have already loaded, make sure
3174 // that we load any additional categories.
3175 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3176 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3177 ObjCClassesLoaded[I],
3178 PreviousGeneration);
3179 }
3180
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003181 return Success;
3182}
3183
Douglas Gregor38295be2012-10-22 23:51:00 +00003184ASTReader::ASTReadResult
3185ASTReader::ReadASTCore(StringRef FileName,
3186 ModuleKind Type,
3187 ModuleFile *ImportedBy,
3188 llvm::SmallVectorImpl<ModuleFile *> &Loaded,
3189 unsigned ClientLoadCapabilities) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003190 ModuleFile *M;
Douglas Gregorfac4ece2011-08-19 02:29:29 +00003191 bool NewModule;
3192 std::string ErrorStr;
3193 llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
Douglas Gregor057df202012-01-18 20:56:22 +00003194 CurrentGeneration, ErrorStr);
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003195
Douglas Gregorfac4ece2011-08-19 02:29:29 +00003196 if (!M) {
3197 // We couldn't load the module.
3198 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3199 + ErrorStr;
3200 Error(Msg);
3201 return Failure;
3202 }
3203
3204 if (!NewModule) {
3205 // We've already loaded this module.
3206 return Success;
3207 }
3208
3209 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3210 // module?
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00003211 if (FileName != "-") {
3212 CurrentDir = llvm::sys::path::parent_path(FileName);
3213 if (CurrentDir.empty()) CurrentDir = ".";
3214 }
3215
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003216 ModuleFile &F = *M;
Sebastian Redl9137a522010-07-16 17:50:48 +00003217 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003218 Stream.init(F.StreamFile);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00003219 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Douglas Gregor8f1231b2011-07-22 06:10:01 +00003220
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003221 // Sniff for the signature.
3222 if (Stream.Read(8) != 'C' ||
3223 Stream.Read(8) != 'P' ||
3224 Stream.Read(8) != 'C' ||
3225 Stream.Read(8) != 'H') {
3226 Diag(diag::err_not_a_pch_file) << FileName;
3227 return Failure;
3228 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003229
Douglas Gregor2cf26342009-04-09 22:27:44 +00003230 while (!Stream.AtEndOfStream()) {
3231 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Douglas Gregore1d918e2009-04-10 23:10:45 +00003233 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003234 Error("invalid record at top-level of AST file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00003235 return Failure;
3236 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003237
3238 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003239
Douglas Gregor7ae467f2012-10-18 18:27:37 +00003240 // We only know the control subblock ID.
Douglas Gregor2cf26342009-04-09 22:27:44 +00003241 switch (BlockID) {
3242 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00003243 if (Stream.ReadBlockInfoBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003244 Error("malformed BlockInfoBlock in AST file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00003245 return Failure;
3246 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003247 break;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003248 case CONTROL_BLOCK_ID:
Douglas Gregor38295be2012-10-22 23:51:00 +00003249 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003250 case Success:
3251 break;
3252
Douglas Gregor4825fd72012-10-22 22:50:17 +00003253 case Failure: return Failure;
3254 case OutOfDate: return OutOfDate;
3255 case VersionMismatch: return VersionMismatch;
3256 case ConfigurationMismatch: return ConfigurationMismatch;
3257 case HadErrors: return HadErrors;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003258 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003259 break;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003260 case AST_BLOCK_ID:
3261 // Record that we've loaded this module.
3262 Loaded.push_back(M);
3263 return Success;
3264
Douglas Gregor2cf26342009-04-09 22:27:44 +00003265 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00003266 if (Stream.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003267 Error("malformed block record in AST file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00003268 return Failure;
3269 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003270 break;
3271 }
Mike Stump1eb44332009-09-09 15:08:12 +00003272 }
Douglas Gregor8f1231b2011-07-22 06:10:01 +00003273
Sebastian Redlcdf3b832010-07-16 20:41:52 +00003274 return Success;
3275}
3276
Douglas Gregor712f2fc2011-09-09 22:02:16 +00003277void ASTReader::InitializeContext() {
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00003278 // If there's a listener, notify them that we "read" the translation unit.
3279 if (DeserializationListener)
Douglas Gregor35942772011-09-09 21:34:22 +00003280 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3281 Context.getTranslationUnitDecl());
Douglas Gregor3747ee72010-10-01 01:18:02 +00003282
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00003283 // Make sure we load the declaration update records for the translation unit,
3284 // if there are any.
Douglas Gregor35942772011-09-09 21:34:22 +00003285 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3286 Context.getTranslationUnitDecl());
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00003287
Douglas Gregor5f957282011-08-11 22:18:49 +00003288 // FIXME: Find a better way to deal with collisions between these
3289 // built-in types. Right now, we just ignore the problem.
3290
3291 // Load the special types.
Douglas Gregora6ea10e2012-01-17 18:09:05 +00003292 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
Douglas Gregor02a5e872011-09-10 00:30:18 +00003293 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3294 if (!Context.CFConstantStringTypeDecl)
3295 Context.setCFConstantStringType(GetType(String));
3296 }
3297
3298 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3299 QualType FileType = GetType(File);
3300 if (FileType.isNull()) {
3301 Error("FILE type is NULL");
3302 return;
3303 }
3304
3305 if (!Context.FILEDecl) {
3306 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3307 Context.setFILEDecl(Typedef->getDecl());
3308 else {
3309 const TagType *Tag = FileType->getAs<TagType>();
3310 if (!Tag) {
3311 Error("Invalid FILE type in AST file");
3312 return;
3313 }
3314 Context.setFILEDecl(Tag->getDecl());
Jonathan D. Turnerde91db52011-08-05 23:07:10 +00003315 }
Jonathan D. Turnerde91db52011-08-05 23:07:10 +00003316 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003317 }
Douglas Gregor5f957282011-08-11 22:18:49 +00003318
Douglas Gregor72cd7a02011-11-11 19:13:12 +00003319 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
Douglas Gregor02a5e872011-09-10 00:30:18 +00003320 QualType Jmp_bufType = GetType(Jmp_buf);
3321 if (Jmp_bufType.isNull()) {
3322 Error("jmp_buf type is NULL");
3323 return;
3324 }
3325
3326 if (!Context.jmp_bufDecl) {
3327 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3328 Context.setjmp_bufDecl(Typedef->getDecl());
3329 else {
3330 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3331 if (!Tag) {
3332 Error("Invalid jmp_buf type in AST file");
3333 return;
3334 }
3335 Context.setjmp_bufDecl(Tag->getDecl());
Jonathan D. Turnerde91db52011-08-05 23:07:10 +00003336 }
Jonathan D. Turnerde91db52011-08-05 23:07:10 +00003337 }
Mike Stump782fa302009-07-28 02:25:19 +00003338 }
Douglas Gregor02a5e872011-09-10 00:30:18 +00003339
Douglas Gregor72cd7a02011-11-11 19:13:12 +00003340 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
Douglas Gregor02a5e872011-09-10 00:30:18 +00003341 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3342 if (Sigjmp_bufType.isNull()) {
3343 Error("sigjmp_buf type is NULL");
3344 return;
3345 }
3346
3347 if (!Context.sigjmp_bufDecl) {
3348 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3349 Context.setsigjmp_bufDecl(Typedef->getDecl());
3350 else {
3351 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3352 assert(Tag && "Invalid sigjmp_buf type in AST file");
3353 Context.setsigjmp_bufDecl(Tag->getDecl());
3354 }
3355 }
3356 }
3357
3358 if (unsigned ObjCIdRedef
3359 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3360 if (Context.ObjCIdRedefinitionType.isNull())
3361 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3362 }
3363
3364 if (unsigned ObjCClassRedef
3365 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3366 if (Context.ObjCClassRedefinitionType.isNull())
3367 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3368 }
3369
3370 if (unsigned ObjCSelRedef
3371 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3372 if (Context.ObjCSelRedefinitionType.isNull())
3373 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3374 }
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00003375
3376 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3377 QualType Ucontext_tType = GetType(Ucontext_t);
3378 if (Ucontext_tType.isNull()) {
3379 Error("ucontext_t type is NULL");
3380 return;
3381 }
3382
3383 if (!Context.ucontext_tDecl) {
3384 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3385 Context.setucontext_tDecl(Typedef->getDecl());
3386 else {
3387 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3388 assert(Tag && "Invalid ucontext_t type in AST file");
3389 Context.setucontext_tDecl(Tag->getDecl());
3390 }
3391 }
3392 }
Douglas Gregor5f957282011-08-11 22:18:49 +00003393 }
3394
Douglas Gregor35942772011-09-09 21:34:22 +00003395 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00003396
3397 // If there were any CUDA special declarations, deserialize them.
3398 if (!CUDASpecialDeclRefs.empty()) {
3399 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
Douglas Gregor35942772011-09-09 21:34:22 +00003400 Context.setcudaConfigureCallDecl(
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00003401 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3402 }
Douglas Gregorf6137e42011-12-03 00:59:55 +00003403
3404 // Re-export any modules that were imported by a non-module AST file.
3405 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3406 if (Module *Imported = getSubmodule(ImportedModules[I]))
3407 makeModuleVisible(Imported, Module::AllVisible);
3408 }
3409 ImportedModules.clear();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003410}
3411
Douglas Gregorecc2c092011-12-01 22:20:10 +00003412void ASTReader::finalizeForWriting() {
3413 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3414 HiddenEnd = HiddenNamesMap.end();
3415 Hidden != HiddenEnd; ++Hidden) {
3416 makeNamesVisible(Hidden->second);
3417 }
3418 HiddenNamesMap.clear();
3419}
3420
Douglas Gregorb64c1932009-05-12 01:31:05 +00003421/// \brief Retrieve the name of the original source file name
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003422/// directly from the AST file, without actually loading the AST
Douglas Gregorb64c1932009-05-12 01:31:05 +00003423/// file.
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003424std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00003425 FileManager &FileMgr,
David Blaikied6471f72011-09-25 23:23:43 +00003426 DiagnosticsEngine &Diags) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003427 // Open the AST file.
Douglas Gregorb64c1932009-05-12 01:31:05 +00003428 std::string ErrStr;
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003429 OwningPtr<llvm::MemoryBuffer> Buffer;
Chris Lattner39b49bc2010-11-23 08:35:12 +00003430 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
Douglas Gregorb64c1932009-05-12 01:31:05 +00003431 if (!Buffer) {
Kaelyn Uhrainda01f622012-06-20 00:36:03 +00003432 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003433 return std::string();
3434 }
3435
3436 // Initialize the stream
3437 llvm::BitstreamReader StreamFile;
3438 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00003439 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00003440 (const unsigned char *)Buffer->getBufferEnd());
3441 Stream.init(StreamFile);
3442
3443 // Sniff for the signature.
3444 if (Stream.Read(8) != 'C' ||
3445 Stream.Read(8) != 'P' ||
3446 Stream.Read(8) != 'C' ||
3447 Stream.Read(8) != 'H') {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003448 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003449 return std::string();
3450 }
3451
3452 RecordData Record;
3453 while (!Stream.AtEndOfStream()) {
3454 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00003455
Douglas Gregorb64c1932009-05-12 01:31:05 +00003456 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3457 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003459 // We only know the AST subblock ID.
Douglas Gregorb64c1932009-05-12 01:31:05 +00003460 switch (BlockID) {
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003461 case CONTROL_BLOCK_ID:
3462 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003463 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003464 return std::string();
3465 }
3466 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Douglas Gregorb64c1932009-05-12 01:31:05 +00003468 default:
3469 if (Stream.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003470 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003471 return std::string();
3472 }
3473 break;
3474 }
3475 continue;
3476 }
3477
3478 if (Code == llvm::bitc::END_BLOCK) {
3479 if (Stream.ReadBlockEnd()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003480 Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003481 return std::string();
3482 }
3483 continue;
3484 }
3485
3486 if (Code == llvm::bitc::DEFINE_ABBREV) {
3487 Stream.ReadAbbrevRecord();
3488 continue;
3489 }
3490
3491 Record.clear();
3492 const char *BlobStart = 0;
3493 unsigned BlobLen = 0;
Douglas Gregor39c497b2012-10-18 18:36:53 +00003494 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen) == ORIGINAL_FILE)
Douglas Gregorb64c1932009-05-12 01:31:05 +00003495 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00003496 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00003497
3498 return std::string();
3499}
3500
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003501namespace {
3502 class SimplePCHValidator : public ASTReaderListener {
3503 const LangOptions &ExistingLangOpts;
3504 const TargetOptions &ExistingTargetOpts;
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003505 const PreprocessorOptions &ExistingPPOpts;
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003506
3507 public:
3508 SimplePCHValidator(const LangOptions &ExistingLangOpts,
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003509 const TargetOptions &ExistingTargetOpts,
3510 const PreprocessorOptions &ExistingPPOpts)
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003511 : ExistingLangOpts(ExistingLangOpts),
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003512 ExistingTargetOpts(ExistingTargetOpts),
3513 ExistingPPOpts(ExistingPPOpts)
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003514 {
3515 }
3516
3517 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3518 bool Complain) {
3519 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3520 }
3521 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3522 bool Complain) {
3523 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3524 }
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003525 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3526 bool Complain) {
3527 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0);
3528 }
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003529 };
3530}
3531
3532bool ASTReader::isAcceptableASTFile(StringRef Filename,
3533 FileManager &FileMgr,
3534 const LangOptions &LangOpts,
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003535 const TargetOptions &TargetOpts,
3536 const PreprocessorOptions &PPOpts) {
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003537 // Open the AST file.
3538 std::string ErrStr;
3539 OwningPtr<llvm::MemoryBuffer> Buffer;
3540 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3541 if (!Buffer) {
3542 return false;
3543 }
3544
3545 // Initialize the stream
3546 llvm::BitstreamReader StreamFile;
3547 llvm::BitstreamCursor Stream;
3548 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3549 (const unsigned char *)Buffer->getBufferEnd());
3550 Stream.init(StreamFile);
3551
3552 // Sniff for the signature.
3553 if (Stream.Read(8) != 'C' ||
3554 Stream.Read(8) != 'P' ||
3555 Stream.Read(8) != 'C' ||
3556 Stream.Read(8) != 'H') {
3557 return false;
3558 }
3559
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003560 SimplePCHValidator Validator(LangOpts, TargetOpts, PPOpts);
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003561 RecordData Record;
3562 bool InControlBlock = false;
3563 while (!Stream.AtEndOfStream()) {
3564 unsigned Code = Stream.ReadCode();
3565
3566 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3567 unsigned BlockID = Stream.ReadSubBlockID();
3568
3569 // We only know the control subblock ID.
3570 switch (BlockID) {
3571 case CONTROL_BLOCK_ID:
3572 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3573 return false;
3574 } else {
3575 InControlBlock = true;
3576 }
3577 break;
3578
3579 default:
3580 if (Stream.SkipBlock())
3581 return false;
3582 break;
3583 }
3584 continue;
3585 }
3586
3587 if (Code == llvm::bitc::END_BLOCK) {
3588 if (Stream.ReadBlockEnd()) {
3589 return false;
3590 }
3591 InControlBlock = false;
3592 continue;
3593 }
3594
3595 if (Code == llvm::bitc::DEFINE_ABBREV) {
3596 Stream.ReadAbbrevRecord();
3597 continue;
3598 }
3599
3600 Record.clear();
3601 const char *BlobStart = 0;
3602 unsigned BlobLen = 0;
3603 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
3604 if (InControlBlock) {
3605 switch ((ControlRecordTypes)RecCode) {
3606 case METADATA: {
3607 if (Record[0] != VERSION_MAJOR) {
3608 return false;
3609 }
3610
3611 const std::string &CurBranch = getClangFullRepositoryVersion();
3612 StringRef ASTBranch(BlobStart, BlobLen);
3613 if (StringRef(CurBranch) != ASTBranch)
3614 return false;
3615
3616 break;
3617 }
3618 case LANGUAGE_OPTIONS:
3619 if (ParseLanguageOptions(Record, false, Validator))
3620 return false;
3621 break;
3622
3623 case TARGET_OPTIONS:
3624 if (ParseTargetOptions(Record, false, Validator))
3625 return false;
3626 break;
3627
Douglas Gregor5f3d8222012-10-24 15:17:15 +00003628 case DIAGNOSTIC_OPTIONS:
3629 if (ParseDiagnosticOptions(Record, false, Validator))
3630 return false;
3631 break;
3632
Douglas Gregorbbf38312012-10-24 16:50:34 +00003633 case FILE_SYSTEM_OPTIONS:
3634 if (ParseFileSystemOptions(Record, false, Validator))
3635 return false;
3636 break;
3637
3638 case HEADER_SEARCH_OPTIONS:
3639 if (ParseHeaderSearchOptions(Record, false, Validator))
3640 return false;
3641 break;
3642
Douglas Gregora71a7d82012-10-24 20:05:57 +00003643 case PREPROCESSOR_OPTIONS:
3644 if (ParsePreprocessorOptions(Record, false, Validator))
3645 return false;
3646 break;
3647
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003648 default:
3649 // No other validation to perform.
3650 break;
3651 }
3652 }
3653 }
3654
3655 return true;
3656}
3657
Douglas Gregor4825fd72012-10-22 22:50:17 +00003658bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003659 // Enter the submodule block.
3660 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3661 Error("malformed submodule block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003662 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003663 }
3664
3665 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
Douglas Gregor26ced122011-12-01 00:59:36 +00003666 bool First = true;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003667 Module *CurrentModule = 0;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003668 RecordData Record;
3669 while (true) {
3670 unsigned Code = F.Stream.ReadCode();
3671 if (Code == llvm::bitc::END_BLOCK) {
3672 if (F.Stream.ReadBlockEnd()) {
3673 Error("error at end of submodule block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003674 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003675 }
Douglas Gregor4825fd72012-10-22 22:50:17 +00003676 return false;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003677 }
3678
3679 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3680 // No known subblocks, always skip them.
3681 F.Stream.ReadSubBlockID();
3682 if (F.Stream.SkipBlock()) {
3683 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003684 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003685 }
3686 continue;
3687 }
3688
3689 if (Code == llvm::bitc::DEFINE_ABBREV) {
3690 F.Stream.ReadAbbrevRecord();
3691 continue;
3692 }
3693
3694 // Read a record.
3695 const char *BlobStart;
3696 unsigned BlobLen;
3697 Record.clear();
3698 switch (F.Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
3699 default: // Default behavior: ignore.
3700 break;
3701
3702 case SUBMODULE_DEFINITION: {
Douglas Gregor26ced122011-12-01 00:59:36 +00003703 if (First) {
3704 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003705 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003706 }
3707
Douglas Gregore209e502011-12-06 01:10:29 +00003708 if (Record.size() < 7) {
Douglas Gregor1e123682011-12-05 22:27:44 +00003709 Error("malformed module definition");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003710 return true;
Douglas Gregor1e123682011-12-05 22:27:44 +00003711 }
3712
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003713 StringRef Name(BlobStart, BlobLen);
Douglas Gregore209e502011-12-06 01:10:29 +00003714 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3715 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3716 bool IsFramework = Record[2];
3717 bool IsExplicit = Record[3];
Douglas Gregora1f1fad2012-01-27 19:52:33 +00003718 bool IsSystem = Record[4];
3719 bool InferSubmodules = Record[5];
3720 bool InferExplicitSubmodules = Record[6];
3721 bool InferExportWildcard = Record[7];
Douglas Gregor1e123682011-12-05 22:27:44 +00003722
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003723 Module *ParentModule = 0;
Douglas Gregor26ced122011-12-01 00:59:36 +00003724 if (Parent)
3725 ParentModule = getSubmodule(Parent);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003726
3727 // Retrieve this (sub)module from the module map, creating it if
3728 // necessary.
3729 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3730 IsFramework,
3731 IsExplicit).first;
Douglas Gregore209e502011-12-06 01:10:29 +00003732 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3733 if (GlobalIndex >= SubmodulesLoaded.size() ||
3734 SubmodulesLoaded[GlobalIndex]) {
Douglas Gregor26ced122011-12-01 00:59:36 +00003735 Error("too many submodules");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003736 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003737 }
Douglas Gregora015cab2011-12-02 17:30:13 +00003738
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +00003739 CurrentModule->setASTFile(F.File);
Douglas Gregor305dc3e2011-12-20 00:28:52 +00003740 CurrentModule->IsFromModuleFile = true;
Douglas Gregora1f1fad2012-01-27 19:52:33 +00003741 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Douglas Gregor1e123682011-12-05 22:27:44 +00003742 CurrentModule->InferSubmodules = InferSubmodules;
3743 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3744 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregora015cab2011-12-02 17:30:13 +00003745 if (DeserializationListener)
Douglas Gregore209e502011-12-06 01:10:29 +00003746 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
Douglas Gregora015cab2011-12-02 17:30:13 +00003747
Douglas Gregore209e502011-12-06 01:10:29 +00003748 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003749 break;
3750 }
3751
Douglas Gregor77d029f2011-12-08 19:11:24 +00003752 case SUBMODULE_UMBRELLA_HEADER: {
Douglas Gregor26ced122011-12-01 00:59:36 +00003753 if (First) {
3754 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003755 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003756 }
3757
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003758 if (!CurrentModule)
3759 break;
3760
3761 StringRef FileName(BlobStart, BlobLen);
3762 if (const FileEntry *Umbrella = PP.getFileManager().getFile(FileName)) {
Douglas Gregor10694ce2011-12-08 17:39:04 +00003763 if (!CurrentModule->getUmbrellaHeader())
Douglas Gregore209e502011-12-06 01:10:29 +00003764 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
Douglas Gregor10694ce2011-12-08 17:39:04 +00003765 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003766 Error("mismatched umbrella headers in submodule");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003767 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003768 }
3769 }
3770 break;
3771 }
3772
3773 case SUBMODULE_HEADER: {
Douglas Gregor26ced122011-12-01 00:59:36 +00003774 if (First) {
3775 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003776 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003777 }
3778
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003779 if (!CurrentModule)
3780 break;
3781
3782 // FIXME: Be more lazy about this!
3783 StringRef FileName(BlobStart, BlobLen);
3784 if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3785 if (std::find(CurrentModule->Headers.begin(),
3786 CurrentModule->Headers.end(),
3787 File) == CurrentModule->Headers.end())
Douglas Gregor2b49d1f2012-10-15 06:28:11 +00003788 ModMap.addHeader(CurrentModule, File, false);
3789 }
3790 break;
3791 }
3792
3793 case SUBMODULE_EXCLUDED_HEADER: {
3794 if (First) {
3795 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003796 return true;
Douglas Gregor2b49d1f2012-10-15 06:28:11 +00003797 }
3798
3799 if (!CurrentModule)
3800 break;
3801
3802 // FIXME: Be more lazy about this!
3803 StringRef FileName(BlobStart, BlobLen);
3804 if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3805 if (std::find(CurrentModule->Headers.begin(),
3806 CurrentModule->Headers.end(),
3807 File) == CurrentModule->Headers.end())
3808 ModMap.addHeader(CurrentModule, File, true);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003809 }
3810 break;
3811 }
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +00003812
3813 case SUBMODULE_TOPHEADER: {
3814 if (First) {
3815 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003816 return true;
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +00003817 }
3818
3819 if (!CurrentModule)
3820 break;
3821
3822 // FIXME: Be more lazy about this!
3823 StringRef FileName(BlobStart, BlobLen);
3824 if (const FileEntry *File = PP.getFileManager().getFile(FileName))
3825 CurrentModule->TopHeaders.insert(File);
3826 break;
3827 }
3828
Douglas Gregor77d029f2011-12-08 19:11:24 +00003829 case SUBMODULE_UMBRELLA_DIR: {
3830 if (First) {
3831 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003832 return true;
Douglas Gregor77d029f2011-12-08 19:11:24 +00003833 }
3834
3835 if (!CurrentModule)
3836 break;
3837
3838 StringRef DirName(BlobStart, BlobLen);
3839 if (const DirectoryEntry *Umbrella
3840 = PP.getFileManager().getDirectory(DirName)) {
3841 if (!CurrentModule->getUmbrellaDir())
3842 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3843 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3844 Error("mismatched umbrella directories in submodule");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003845 return true;
Douglas Gregor77d029f2011-12-08 19:11:24 +00003846 }
3847 }
3848 break;
3849 }
3850
Douglas Gregor26ced122011-12-01 00:59:36 +00003851 case SUBMODULE_METADATA: {
3852 if (!First) {
3853 Error("submodule metadata record not at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003854 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003855 }
3856 First = false;
3857
3858 F.BaseSubmoduleID = getTotalNumSubmodules();
Douglas Gregor26ced122011-12-01 00:59:36 +00003859 F.LocalNumSubmodules = Record[0];
3860 unsigned LocalBaseSubmoduleID = Record[1];
3861 if (F.LocalNumSubmodules > 0) {
3862 // Introduce the global -> local mapping for submodules within this
3863 // module.
3864 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3865
3866 // Introduce the local -> global mapping for submodules within this
3867 // module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00003868 F.SubmoduleRemap.insertOrReplace(
Douglas Gregor26ced122011-12-01 00:59:36 +00003869 std::make_pair(LocalBaseSubmoduleID,
3870 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3871
3872 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3873 }
3874 break;
3875 }
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003876
Douglas Gregor55988682011-12-05 16:33:54 +00003877 case SUBMODULE_IMPORTS: {
3878 if (First) {
3879 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003880 return true;
Douglas Gregor55988682011-12-05 16:33:54 +00003881 }
3882
3883 if (!CurrentModule)
3884 break;
3885
3886 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
3887 UnresolvedModuleImportExport Unresolved;
3888 Unresolved.File = &F;
3889 Unresolved.Mod = CurrentModule;
3890 Unresolved.ID = Record[Idx];
3891 Unresolved.IsImport = true;
3892 Unresolved.IsWildcard = false;
3893 UnresolvedModuleImportExports.push_back(Unresolved);
3894 }
3895 break;
3896 }
3897
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003898 case SUBMODULE_EXPORTS: {
3899 if (First) {
3900 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003901 return true;
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003902 }
3903
3904 if (!CurrentModule)
3905 break;
3906
3907 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor55988682011-12-05 16:33:54 +00003908 UnresolvedModuleImportExport Unresolved;
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003909 Unresolved.File = &F;
Douglas Gregor55988682011-12-05 16:33:54 +00003910 Unresolved.Mod = CurrentModule;
3911 Unresolved.ID = Record[Idx];
3912 Unresolved.IsImport = false;
3913 Unresolved.IsWildcard = Record[Idx + 1];
3914 UnresolvedModuleImportExports.push_back(Unresolved);
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003915 }
3916
3917 // Once we've loaded the set of exports, there's no reason to keep
3918 // the parsed, unresolved exports around.
3919 CurrentModule->UnresolvedExports.clear();
3920 break;
3921 }
Douglas Gregor51f564f2011-12-31 04:05:44 +00003922 case SUBMODULE_REQUIRES: {
3923 if (First) {
3924 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003925 return true;
Douglas Gregor51f564f2011-12-31 04:05:44 +00003926 }
3927
3928 if (!CurrentModule)
3929 break;
3930
3931 CurrentModule->addRequirement(StringRef(BlobStart, BlobLen),
David Blaikie4e4d0842012-03-11 07:00:24 +00003932 Context.getLangOpts(),
Douglas Gregordc58aa72012-01-30 06:01:29 +00003933 Context.getTargetInfo());
Douglas Gregor51f564f2011-12-31 04:05:44 +00003934 break;
3935 }
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003936 }
3937 }
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003938}
3939
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003940/// \brief Parse the record that corresponds to a LangOptions data
3941/// structure.
3942///
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003943/// This routine parses the language options from the AST file and then gives
3944/// them to the AST listener if one is set.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003945///
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003946/// \returns true if the listener deems the file unacceptable, false otherwise.
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003947bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3948 bool Complain,
3949 ASTReaderListener &Listener) {
3950 LangOptions LangOpts;
3951 unsigned Idx = 0;
Douglas Gregor7d5e81b2011-09-13 18:26:39 +00003952#define LANGOPT(Name, Bits, Default, Description) \
3953 LangOpts.Name = Record[Idx++];
3954#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
3955 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
3956#include "clang/Basic/LangOptions.def"
John McCall260611a2012-06-20 06:18:46 +00003957
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003958 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
3959 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
3960 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
3961
3962 unsigned Length = Record[Idx++];
3963 LangOpts.CurrentModule.assign(Record.begin() + Idx,
3964 Record.begin() + Idx + Length);
3965 return Listener.ReadLanguageOptions(LangOpts, Complain);
3966}
3967
3968bool ASTReader::ParseTargetOptions(const RecordData &Record,
3969 bool Complain,
3970 ASTReaderListener &Listener) {
3971 unsigned Idx = 0;
3972 TargetOptions TargetOpts;
3973 TargetOpts.Triple = ReadString(Record, Idx);
3974 TargetOpts.CPU = ReadString(Record, Idx);
3975 TargetOpts.ABI = ReadString(Record, Idx);
3976 TargetOpts.CXXABI = ReadString(Record, Idx);
3977 TargetOpts.LinkerVersion = ReadString(Record, Idx);
3978 for (unsigned N = Record[Idx++]; N; --N) {
3979 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
3980 }
3981 for (unsigned N = Record[Idx++]; N; --N) {
3982 TargetOpts.Features.push_back(ReadString(Record, Idx));
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003983 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003984
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003985 return Listener.ReadTargetOptions(TargetOpts, Complain);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003986}
3987
Douglas Gregor5f3d8222012-10-24 15:17:15 +00003988bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
3989 ASTReaderListener &Listener) {
3990 DiagnosticOptions DiagOpts;
3991 unsigned Idx = 0;
3992#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
3993#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
3994 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
3995#include "clang/Basic/DiagnosticOptions.def"
3996
3997 for (unsigned N = Record[Idx++]; N; --N) {
3998 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
3999 }
4000
4001 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4002}
4003
Douglas Gregor1b2c3c02012-10-24 15:49:58 +00004004bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4005 ASTReaderListener &Listener) {
4006 FileSystemOptions FSOpts;
4007 unsigned Idx = 0;
4008 FSOpts.WorkingDir = ReadString(Record, Idx);
4009 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4010}
4011
Douglas Gregorbbf38312012-10-24 16:50:34 +00004012bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4013 bool Complain,
4014 ASTReaderListener &Listener) {
4015 HeaderSearchOptions HSOpts;
4016 unsigned Idx = 0;
4017 HSOpts.Sysroot = ReadString(Record, Idx);
4018
4019 // Include entries.
4020 for (unsigned N = Record[Idx++]; N; --N) {
4021 std::string Path = ReadString(Record, Idx);
4022 frontend::IncludeDirGroup Group
4023 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4024 bool IsUserSupplied = Record[Idx++];
4025 bool IsFramework = Record[Idx++];
4026 bool IgnoreSysRoot = Record[Idx++];
4027 bool IsInternal = Record[Idx++];
4028 bool ImplicitExternC = Record[Idx++];
4029 HSOpts.UserEntries.push_back(
4030 HeaderSearchOptions::Entry(Path, Group, IsUserSupplied, IsFramework,
4031 IgnoreSysRoot, IsInternal, ImplicitExternC));
4032 }
4033
4034 // System header prefixes.
4035 for (unsigned N = Record[Idx++]; N; --N) {
4036 std::string Prefix = ReadString(Record, Idx);
4037 bool IsSystemHeader = Record[Idx++];
4038 HSOpts.SystemHeaderPrefixes.push_back(
4039 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4040 }
4041
4042 HSOpts.ResourceDir = ReadString(Record, Idx);
4043 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4044 HSOpts.DisableModuleHash = Record[Idx++];
4045 HSOpts.UseBuiltinIncludes = Record[Idx++];
4046 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4047 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4048 HSOpts.UseLibcxx = Record[Idx++];
4049
4050 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4051}
4052
Douglas Gregora71a7d82012-10-24 20:05:57 +00004053bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4054 bool Complain,
4055 ASTReaderListener &Listener) {
4056 PreprocessorOptions PPOpts;
4057 unsigned Idx = 0;
4058
4059 // Macro definitions/undefs
4060 for (unsigned N = Record[Idx++]; N; --N) {
4061 std::string Macro = ReadString(Record, Idx);
4062 bool IsUndef = Record[Idx++];
4063 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4064 }
4065
4066 // Includes
4067 for (unsigned N = Record[Idx++]; N; --N) {
4068 PPOpts.Includes.push_back(ReadString(Record, Idx));
4069 }
4070
4071 // Macro Includes
4072 for (unsigned N = Record[Idx++]; N; --N) {
4073 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4074 }
4075
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00004076 PPOpts.UsePredefines = Record[Idx++];
Douglas Gregora71a7d82012-10-24 20:05:57 +00004077 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4078 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4079 PPOpts.ObjCXXARCStandardLibrary =
4080 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4081 return Listener.ReadPreprocessorOptions(PPOpts, Complain);
4082}
4083
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004084std::pair<ModuleFile *, unsigned>
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004085ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00004086 GlobalPreprocessedEntityMapType::iterator
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004087 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00004088 assert(I != GlobalPreprocessedEntityMap.end() &&
4089 "Corrupted global preprocessed entity map");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004090 ModuleFile *M = I->second;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004091 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4092 return std::make_pair(M, LocalIndex);
4093}
4094
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00004095std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4096ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4097 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4098 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4099 Mod.NumPreprocessedEntities);
4100
4101 return std::make_pair(PreprocessingRecord::iterator(),
4102 PreprocessingRecord::iterator());
4103}
4104
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00004105std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4106ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4107 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4108 ModuleDeclIterator(this, &Mod,
4109 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4110}
4111
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004112PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4113 PreprocessedEntityID PPID = Index+1;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004114 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4115 ModuleFile &M = *PPInfo.first;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004116 unsigned LocalIndex = PPInfo.second;
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004117 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
Douglas Gregor4800a5c2011-02-08 21:58:10 +00004118
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00004119 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004120 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004121
4122 unsigned Code = M.PreprocessorDetailCursor.ReadCode();
4123 switch (Code) {
4124 case llvm::bitc::END_BLOCK:
4125 return 0;
4126
4127 case llvm::bitc::ENTER_SUBBLOCK:
4128 Error("unexpected subblock record in preprocessor detail block");
4129 return 0;
4130
4131 case llvm::bitc::DEFINE_ABBREV:
4132 Error("unexpected abbrevation record in preprocessor detail block");
4133 return 0;
4134
4135 default:
4136 break;
4137 }
4138
4139 if (!PP.getPreprocessingRecord()) {
4140 Error("no preprocessing record");
4141 return 0;
4142 }
4143
4144 // Read the record.
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004145 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4146 ReadSourceLocation(M, PPOffs.End));
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004147 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4148 const char *BlobStart = 0;
4149 unsigned BlobLen = 0;
4150 RecordData Record;
4151 PreprocessorDetailRecordTypes RecType =
4152 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.ReadRecord(
4153 Code, Record, BlobStart, BlobLen);
4154 switch (RecType) {
4155 case PPD_MACRO_EXPANSION: {
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004156 bool isBuiltin = Record[0];
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004157 IdentifierInfo *Name = 0;
4158 MacroDefinition *Def = 0;
4159 if (isBuiltin)
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004160 Name = getLocalIdentifier(M, Record[1]);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004161 else {
4162 PreprocessedEntityID
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004163 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004164 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4165 }
4166
4167 MacroExpansion *ME;
4168 if (isBuiltin)
4169 ME = new (PPRec) MacroExpansion(Name, Range);
4170 else
4171 ME = new (PPRec) MacroExpansion(Def, Range);
4172
4173 return ME;
4174 }
4175
4176 case PPD_MACRO_DEFINITION: {
4177 // Decode the identifier info and then check again; if the macro is
4178 // still defined and associated with the identifier,
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004179 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004180 MacroDefinition *MD
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004181 = new (PPRec) MacroDefinition(II, Range);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004182
4183 if (DeserializationListener)
4184 DeserializationListener->MacroDefinitionRead(PPID, MD);
4185
4186 return MD;
4187 }
4188
4189 case PPD_INCLUSION_DIRECTIVE: {
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004190 const char *FullFileNameStart = BlobStart + Record[0];
Argyrios Kyrtzidis29f98b42012-03-08 01:08:28 +00004191 StringRef FullFileName(FullFileNameStart, BlobLen - Record[0]);
4192 const FileEntry *File = 0;
4193 if (!FullFileName.empty())
4194 File = PP.getFileManager().getFile(FullFileName);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004195
4196 // FIXME: Stable encoding
4197 InclusionDirective::InclusionKind Kind
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004198 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004199 InclusionDirective *ID
4200 = new (PPRec) InclusionDirective(PPRec, Kind,
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004201 StringRef(BlobStart, Record[0]),
Argyrios Kyrtzidis8dd927c2012-10-02 16:10:46 +00004202 Record[1], Record[3],
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004203 File,
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004204 Range);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004205 return ID;
4206 }
4207 }
David Blaikie7530c032012-01-17 06:56:22 +00004208
4209 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00004210}
4211
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004212/// \brief \arg SLocMapI points at a chunk of a module that contains no
4213/// preprocessed entities or the entities it contains are not the ones we are
4214/// looking for. Find the next module that contains entities and return the ID
4215/// of the first entry.
4216PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4217 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4218 ++SLocMapI;
4219 for (GlobalSLocOffsetMapType::const_iterator
4220 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004221 ModuleFile &M = *SLocMapI->second;
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004222 if (M.NumPreprocessedEntities)
4223 return getGlobalPreprocessedEntityID(M, M.BasePreprocessedEntityID);
4224 }
4225
4226 return getTotalNumPreprocessedEntities();
4227}
4228
4229namespace {
4230
4231template <unsigned PPEntityOffset::*PPLoc>
4232struct PPEntityComp {
4233 const ASTReader &Reader;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004234 ModuleFile &M;
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004235
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004236 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004237
Benjamin Kramer88df1252011-09-21 06:42:26 +00004238 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4239 SourceLocation LHS = getLoc(L);
4240 SourceLocation RHS = getLoc(R);
4241 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4242 }
4243
4244 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004245 SourceLocation LHS = getLoc(L);
4246 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4247 }
4248
Benjamin Kramer88df1252011-09-21 06:42:26 +00004249 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004250 SourceLocation RHS = getLoc(R);
4251 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4252 }
4253
4254 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4255 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4256 }
4257};
4258
4259}
4260
4261/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4262PreprocessedEntityID
4263ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4264 if (SourceMgr.isLocalSourceLocation(BLoc))
4265 return getTotalNumPreprocessedEntities();
4266
4267 GlobalSLocOffsetMapType::const_iterator
4268 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4269 BLoc.getOffset());
4270 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4271 "Corrupted global sloc offset map");
4272
4273 if (SLocMapI->second->NumPreprocessedEntities == 0)
4274 return findNextPreprocessedEntity(SLocMapI);
4275
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004276 ModuleFile &M = *SLocMapI->second;
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004277 typedef const PPEntityOffset *pp_iterator;
4278 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4279 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
Argyrios Kyrtzidis4cd06342011-09-22 21:17:02 +00004280
4281 size_t Count = M.NumPreprocessedEntities;
4282 size_t Half;
4283 pp_iterator First = pp_begin;
4284 pp_iterator PPI;
4285
4286 // Do a binary search manually instead of using std::lower_bound because
4287 // The end locations of entities may be unordered (when a macro expansion
4288 // is inside another macro argument), but for this case it is not important
4289 // whether we get the first macro expansion or its containing macro.
4290 while (Count > 0) {
4291 Half = Count/2;
4292 PPI = First;
4293 std::advance(PPI, Half);
4294 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4295 BLoc)){
4296 First = PPI;
4297 ++First;
4298 Count = Count - Half - 1;
4299 } else
4300 Count = Half;
4301 }
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004302
4303 if (PPI == pp_end)
4304 return findNextPreprocessedEntity(SLocMapI);
4305
4306 return getGlobalPreprocessedEntityID(M,
4307 M.BasePreprocessedEntityID + (PPI - pp_begin));
4308}
4309
4310/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4311PreprocessedEntityID
4312ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4313 if (SourceMgr.isLocalSourceLocation(ELoc))
4314 return getTotalNumPreprocessedEntities();
4315
4316 GlobalSLocOffsetMapType::const_iterator
4317 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4318 ELoc.getOffset());
4319 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4320 "Corrupted global sloc offset map");
4321
4322 if (SLocMapI->second->NumPreprocessedEntities == 0)
4323 return findNextPreprocessedEntity(SLocMapI);
4324
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004325 ModuleFile &M = *SLocMapI->second;
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004326 typedef const PPEntityOffset *pp_iterator;
4327 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4328 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4329 pp_iterator PPI =
4330 std::upper_bound(pp_begin, pp_end, ELoc,
4331 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4332
4333 if (PPI == pp_end)
4334 return findNextPreprocessedEntity(SLocMapI);
4335
4336 return getGlobalPreprocessedEntityID(M,
4337 M.BasePreprocessedEntityID + (PPI - pp_begin));
4338}
4339
4340/// \brief Returns a pair of [Begin, End) indices of preallocated
4341/// preprocessed entities that \arg Range encompasses.
4342std::pair<unsigned, unsigned>
4343 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4344 if (Range.isInvalid())
4345 return std::make_pair(0,0);
4346 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4347
4348 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4349 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4350 return std::make_pair(BeginID, EndID);
4351}
4352
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004353/// \brief Optionally returns true or false if the preallocated preprocessed
4354/// entity with index \arg Index came from file \arg FID.
4355llvm::Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
4356 FileID FID) {
4357 if (FID.isInvalid())
4358 return false;
4359
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004360 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4361 ModuleFile &M = *PPInfo.first;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004362 unsigned LocalIndex = PPInfo.second;
4363 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4364
4365 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4366 if (Loc.isInvalid())
4367 return false;
4368
4369 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4370 return true;
4371 else
4372 return false;
4373}
4374
Douglas Gregord10a3812011-08-25 18:14:34 +00004375namespace {
4376 /// \brief Visitor used to search for information about a header file.
4377 class HeaderFileInfoVisitor {
4378 ASTReader &Reader;
4379 const FileEntry *FE;
4380
4381 llvm::Optional<HeaderFileInfo> HFI;
4382
4383 public:
4384 HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
4385 : Reader(Reader), FE(FE) { }
4386
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004387 static bool visit(ModuleFile &M, void *UserData) {
Douglas Gregord10a3812011-08-25 18:14:34 +00004388 HeaderFileInfoVisitor *This
4389 = static_cast<HeaderFileInfoVisitor *>(UserData);
4390
4391 HeaderFileInfoTrait Trait(This->Reader, M,
4392 &This->Reader.getPreprocessor().getHeaderSearchInfo(),
4393 M.HeaderFileFrameworkStrings,
4394 This->FE->getName());
4395
4396 HeaderFileInfoLookupTable *Table
4397 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4398 if (!Table)
4399 return false;
4400
4401 // Look in the on-disk hash table for an entry for this file name.
4402 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
4403 &Trait);
4404 if (Pos == Table->end())
4405 return false;
4406
4407 This->HFI = *Pos;
4408 return true;
4409 }
4410
4411 llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4412 };
4413}
4414
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00004415HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Douglas Gregord10a3812011-08-25 18:14:34 +00004416 HeaderFileInfoVisitor Visitor(*this, FE);
4417 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4418 if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00004419 if (Listener)
Douglas Gregord10a3812011-08-25 18:14:34 +00004420 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4421 return *HFI;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00004422 }
4423
4424 return HeaderFileInfo();
4425}
4426
David Blaikied6471f72011-09-25 23:23:43 +00004427void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00004428 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004429 ModuleFile &F = *(*I);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00004430 unsigned Idx = 0;
4431 while (Idx < F.PragmaDiagMappings.size()) {
4432 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
Argyrios Kyrtzidis87429a02011-11-09 01:24:17 +00004433 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4434 Diag.DiagStatePoints.push_back(
4435 DiagnosticsEngine::DiagStatePoint(&Diag.DiagStates.back(),
4436 FullSourceLoc(Loc, SourceMgr)));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00004437 while (1) {
4438 assert(Idx < F.PragmaDiagMappings.size() &&
4439 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4440 if (Idx >= F.PragmaDiagMappings.size()) {
4441 break; // Something is messed up but at least avoid infinite loop in
4442 // release build.
4443 }
4444 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4445 if (DiagID == (unsigned)-1) {
4446 break; // no more diag/map pairs for this location.
4447 }
4448 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
Argyrios Kyrtzidis87429a02011-11-09 01:24:17 +00004449 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4450 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00004451 }
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +00004452 }
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00004453 }
4454}
4455
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00004456/// \brief Get the correct cursor and offset for loading a type.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00004457ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
Douglas Gregora119da02011-08-02 16:26:37 +00004458 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
Jonathan D. Turnere9b76c12011-07-20 21:31:32 +00004459 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004460 ModuleFile *M = I->second;
Douglas Gregore3605012011-08-02 18:32:54 +00004461 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00004462}
4463
4464/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00004465///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00004466/// The index is the type ID, shifted and minus the number of predefs. This
4467/// routine actually reads the record corresponding to the type at the given
4468/// location. It is a helper routine for GetType, which deals with reading type
4469/// IDs.
Douglas Gregor393f2492011-07-22 00:38:23 +00004470QualType ASTReader::readTypeRecord(unsigned Index) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00004471 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redlc3632732010-10-05 15:59:54 +00004472 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00004473
Douglas Gregor0b748912009-04-14 21:18:50 +00004474 // Keep track of where we are in the stream, then jump back there
4475 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004476 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00004477
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00004478 ReadingKindTracker ReadingKind(Read_Type, *this);
Sebastian Redl27372b42010-08-11 18:52:41 +00004479
Douglas Gregord89275b2009-07-06 18:54:52 +00004480 // Note that we are loading a type record.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00004481 Deserializing AType(this);
Mike Stump1eb44332009-09-09 15:08:12 +00004482
Douglas Gregor393f2492011-07-22 00:38:23 +00004483 unsigned Idx = 0;
Sebastian Redlc3632732010-10-05 15:59:54 +00004484 DeclsCursor.JumpToBit(Loc.Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004485 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004486 unsigned Code = DeclsCursor.ReadCode();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004487 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
4488 case TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004489 if (Record.size() != 2) {
4490 Error("Incorrect encoding of extended qualifier type");
4491 return QualType();
4492 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004493 QualType Base = readType(*Loc.F, Record, Idx);
4494 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Douglas Gregor35942772011-09-09 21:34:22 +00004495 return Context.getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00004496 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004497
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004498 case TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004499 if (Record.size() != 1) {
4500 Error("Incorrect encoding of complex type");
4501 return QualType();
4502 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004503 QualType ElemType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004504 return Context.getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004505 }
4506
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004507 case TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004508 if (Record.size() != 1) {
4509 Error("Incorrect encoding of pointer type");
4510 return QualType();
4511 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004512 QualType PointeeType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004513 return Context.getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004514 }
4515
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004516 case TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004517 if (Record.size() != 1) {
4518 Error("Incorrect encoding of block pointer type");
4519 return QualType();
4520 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004521 QualType PointeeType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004522 return Context.getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004523 }
4524
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004525 case TYPE_LVALUE_REFERENCE: {
Richard Smithdf1550f2011-04-12 10:38:03 +00004526 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004527 Error("Incorrect encoding of lvalue reference type");
4528 return QualType();
4529 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004530 QualType PointeeType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004531 return Context.getLValueReferenceType(PointeeType, Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004532 }
4533
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004534 case TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004535 if (Record.size() != 1) {
4536 Error("Incorrect encoding of rvalue reference type");
4537 return QualType();
4538 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004539 QualType PointeeType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004540 return Context.getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004541 }
4542
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004543 case TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00004544 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004545 Error("Incorrect encoding of member pointer type");
4546 return QualType();
4547 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004548 QualType PointeeType = readType(*Loc.F, Record, Idx);
4549 QualType ClassType = readType(*Loc.F, Record, Idx);
Douglas Gregor1ab55e92010-12-10 17:03:06 +00004550 if (PointeeType.isNull() || ClassType.isNull())
4551 return QualType();
4552
Douglas Gregor35942772011-09-09 21:34:22 +00004553 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00004554 }
4555
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004556 case TYPE_CONSTANT_ARRAY: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004557 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004558 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4559 unsigned IndexTypeQuals = Record[2];
4560 unsigned Idx = 3;
4561 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004562 return Context.getConstantArrayType(ElementType, Size,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004563 ASM, IndexTypeQuals);
4564 }
4565
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004566 case TYPE_INCOMPLETE_ARRAY: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004567 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004568 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4569 unsigned IndexTypeQuals = Record[2];
Douglas Gregor35942772011-09-09 21:34:22 +00004570 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004571 }
4572
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004573 case TYPE_VARIABLE_ARRAY: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004574 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregor0b748912009-04-14 21:18:50 +00004575 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4576 unsigned IndexTypeQuals = Record[2];
Sebastian Redlc3632732010-10-05 15:59:54 +00004577 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4578 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
Douglas Gregor35942772011-09-09 21:34:22 +00004579 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004580 ASM, IndexTypeQuals,
4581 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004582 }
4583
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004584 case TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00004585 if (Record.size() != 3) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004586 Error("incorrect encoding of vector type in AST file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004587 return QualType();
4588 }
4589
Douglas Gregor393f2492011-07-22 00:38:23 +00004590 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004591 unsigned NumElements = Record[1];
Bob Wilsone86d78c2010-11-10 21:56:12 +00004592 unsigned VecKind = Record[2];
Douglas Gregor35942772011-09-09 21:34:22 +00004593 return Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00004594 (VectorType::VectorKind)VecKind);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004595 }
4596
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004597 case TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00004598 if (Record.size() != 3) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004599 Error("incorrect encoding of extended vector type in AST file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004600 return QualType();
4601 }
4602
Douglas Gregor393f2492011-07-22 00:38:23 +00004603 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004604 unsigned NumElements = Record[1];
Douglas Gregor35942772011-09-09 21:34:22 +00004605 return Context.getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004606 }
4607
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004608 case TYPE_FUNCTION_NO_PROTO: {
John McCallf85e1932011-06-15 23:02:42 +00004609 if (Record.size() != 6) {
Douglas Gregora02b1472009-04-28 21:53:25 +00004610 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004611 return QualType();
4612 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004613 QualType ResultType = readType(*Loc.F, Record, Idx);
John McCallf85e1932011-06-15 23:02:42 +00004614 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4615 (CallingConv)Record[4], Record[5]);
Douglas Gregor35942772011-09-09 21:34:22 +00004616 return Context.getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004617 }
4618
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004619 case TYPE_FUNCTION_PROTO: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004620 QualType ResultType = readType(*Loc.F, Record, Idx);
John McCalle23cf432010-12-14 08:05:40 +00004621
4622 FunctionProtoType::ExtProtoInfo EPI;
4623 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
Eli Friedmana49218e2011-04-09 08:18:08 +00004624 /*hasregparm*/ Record[2],
4625 /*regparm*/ Record[3],
John McCallf85e1932011-06-15 23:02:42 +00004626 static_cast<CallingConv>(Record[4]),
4627 /*produces*/ Record[5]);
John McCalle23cf432010-12-14 08:05:40 +00004628
John McCallf85e1932011-06-15 23:02:42 +00004629 unsigned Idx = 6;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004630 unsigned NumParams = Record[Idx++];
Chris Lattner5f9e2722011-07-23 10:55:15 +00004631 SmallVector<QualType, 16> ParamTypes;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004632 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor393f2492011-07-22 00:38:23 +00004633 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
John McCalle23cf432010-12-14 08:05:40 +00004634
4635 EPI.Variadic = Record[Idx++];
Richard Smitheefb3d52012-02-10 09:58:53 +00004636 EPI.HasTrailingReturn = Record[Idx++];
John McCalle23cf432010-12-14 08:05:40 +00004637 EPI.TypeQuals = Record[Idx++];
Douglas Gregorc938c162011-01-26 05:01:58 +00004638 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Sebastian Redl60618fa2011-03-12 11:50:43 +00004639 ExceptionSpecificationType EST =
4640 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4641 EPI.ExceptionSpecType = EST;
Douglas Gregorb0d06e22012-04-04 00:34:49 +00004642 SmallVector<QualType, 2> Exceptions;
Sebastian Redl60618fa2011-03-12 11:50:43 +00004643 if (EST == EST_Dynamic) {
4644 EPI.NumExceptions = Record[Idx++];
Sebastian Redl60618fa2011-03-12 11:50:43 +00004645 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
Douglas Gregor393f2492011-07-22 00:38:23 +00004646 Exceptions.push_back(readType(*Loc.F, Record, Idx));
Sebastian Redl60618fa2011-03-12 11:50:43 +00004647 EPI.Exceptions = Exceptions.data();
4648 } else if (EST == EST_ComputedNoexcept) {
4649 EPI.NoexceptExpr = ReadExpr(*Loc.F);
Richard Smith7bb698a2012-04-21 17:47:47 +00004650 } else if (EST == EST_Uninstantiated) {
4651 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4652 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
Richard Smithb9d0b762012-07-27 04:22:15 +00004653 } else if (EST == EST_Unevaluated) {
4654 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
Sebastian Redl60618fa2011-03-12 11:50:43 +00004655 }
Douglas Gregor35942772011-09-09 21:34:22 +00004656 return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
John McCalle23cf432010-12-14 08:05:40 +00004657 EPI);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004658 }
4659
Douglas Gregor409448c2011-07-21 22:35:25 +00004660 case TYPE_UNRESOLVED_USING: {
4661 unsigned Idx = 0;
Douglas Gregor35942772011-09-09 21:34:22 +00004662 return Context.getTypeDeclType(
Douglas Gregor409448c2011-07-21 22:35:25 +00004663 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4664 }
4665
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004666 case TYPE_TYPEDEF: {
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00004667 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004668 Error("incorrect encoding of typedef type");
4669 return QualType();
4670 }
Douglas Gregor409448c2011-07-21 22:35:25 +00004671 unsigned Idx = 0;
4672 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004673 QualType Canonical = readType(*Loc.F, Record, Idx);
Douglas Gregor32adc8b2010-10-26 00:51:02 +00004674 if (!Canonical.isNull())
Douglas Gregor35942772011-09-09 21:34:22 +00004675 Canonical = Context.getCanonicalType(Canonical);
4676 return Context.getTypedefType(Decl, Canonical);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00004677 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004678
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004679 case TYPE_TYPEOF_EXPR:
Douglas Gregor35942772011-09-09 21:34:22 +00004680 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004681
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004682 case TYPE_TYPEOF: {
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004683 if (Record.size() != 1) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004684 Error("incorrect encoding of typeof(type) in AST file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004685 return QualType();
4686 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004687 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004688 return Context.getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004689 }
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Douglas Gregorf8af9822012-02-12 18:42:33 +00004691 case TYPE_DECLTYPE: {
4692 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4693 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4694 }
Anders Carlsson395b4752009-06-24 19:06:50 +00004695
Sean Huntca63c202011-05-24 22:41:36 +00004696 case TYPE_UNARY_TRANSFORM: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004697 QualType BaseType = readType(*Loc.F, Record, Idx);
4698 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Sean Huntca63c202011-05-24 22:41:36 +00004699 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Douglas Gregor35942772011-09-09 21:34:22 +00004700 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
Sean Huntca63c202011-05-24 22:41:36 +00004701 }
4702
Richard Smith34b41d92011-02-20 03:19:35 +00004703 case TYPE_AUTO:
Douglas Gregor35942772011-09-09 21:34:22 +00004704 return Context.getAutoType(readType(*Loc.F, Record, Idx));
Richard Smith34b41d92011-02-20 03:19:35 +00004705
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004706 case TYPE_RECORD: {
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004707 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004708 Error("incorrect encoding of record type");
4709 return QualType();
4710 }
Douglas Gregor409448c2011-07-21 22:35:25 +00004711 unsigned Idx = 0;
4712 bool IsDependent = Record[Idx++];
Douglas Gregor56ca8a92012-01-17 19:21:53 +00004713 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4714 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4715 QualType T = Context.getRecordType(RD);
John McCallf4c73712011-01-19 06:33:43 +00004716 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004717 return T;
4718 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004719
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004720 case TYPE_ENUM: {
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004721 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004722 Error("incorrect encoding of enum type");
4723 return QualType();
4724 }
Douglas Gregor409448c2011-07-21 22:35:25 +00004725 unsigned Idx = 0;
4726 bool IsDependent = Record[Idx++];
4727 QualType T
Douglas Gregor35942772011-09-09 21:34:22 +00004728 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
John McCallf4c73712011-01-19 06:33:43 +00004729 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004730 return T;
4731 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00004732
John McCall9d156a72011-01-06 01:58:22 +00004733 case TYPE_ATTRIBUTED: {
4734 if (Record.size() != 3) {
4735 Error("incorrect encoding of attributed type");
4736 return QualType();
4737 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004738 QualType modifiedType = readType(*Loc.F, Record, Idx);
4739 QualType equivalentType = readType(*Loc.F, Record, Idx);
John McCall9d156a72011-01-06 01:58:22 +00004740 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Douglas Gregor35942772011-09-09 21:34:22 +00004741 return Context.getAttributedType(kind, modifiedType, equivalentType);
John McCall9d156a72011-01-06 01:58:22 +00004742 }
4743
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004744 case TYPE_PAREN: {
4745 if (Record.size() != 1) {
4746 Error("incorrect encoding of paren type");
4747 return QualType();
4748 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004749 QualType InnerType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004750 return Context.getParenType(InnerType);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004751 }
4752
Douglas Gregor7536dd52010-12-20 02:24:11 +00004753 case TYPE_PACK_EXPANSION: {
Douglas Gregorf9997a02011-02-01 15:24:58 +00004754 if (Record.size() != 2) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00004755 Error("incorrect encoding of pack expansion type");
4756 return QualType();
4757 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004758 QualType Pattern = readType(*Loc.F, Record, Idx);
Douglas Gregor7536dd52010-12-20 02:24:11 +00004759 if (Pattern.isNull())
4760 return QualType();
Douglas Gregorcded4f62011-01-14 17:04:44 +00004761 llvm::Optional<unsigned> NumExpansions;
4762 if (Record[1])
4763 NumExpansions = Record[1] - 1;
Douglas Gregor35942772011-09-09 21:34:22 +00004764 return Context.getPackExpansionType(Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00004765 }
4766
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004767 case TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004768 unsigned Idx = 0;
4769 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00004770 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004771 QualType NamedType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004772 return Context.getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00004773 }
4774
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004775 case TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00004776 unsigned Idx = 0;
Douglas Gregor409448c2011-07-21 22:35:25 +00004777 ObjCInterfaceDecl *ItfD
4778 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Douglas Gregor56ca8a92012-01-17 19:21:53 +00004779 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
John McCallc12c5bb2010-05-15 11:32:37 +00004780 }
4781
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004782 case TYPE_OBJC_OBJECT: {
John McCallc12c5bb2010-05-15 11:32:37 +00004783 unsigned Idx = 0;
Douglas Gregor393f2492011-07-22 00:38:23 +00004784 QualType Base = readType(*Loc.F, Record, Idx);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00004785 unsigned NumProtos = Record[Idx++];
Chris Lattner5f9e2722011-07-23 10:55:15 +00004786 SmallVector<ObjCProtocolDecl*, 4> Protos;
Chris Lattnerc6fa4452009-04-22 06:45:28 +00004787 for (unsigned I = 0; I != NumProtos; ++I)
Douglas Gregor409448c2011-07-21 22:35:25 +00004788 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregor35942772011-09-09 21:34:22 +00004789 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00004790 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004791
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004792 case TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00004793 unsigned Idx = 0;
Douglas Gregor393f2492011-07-22 00:38:23 +00004794 QualType Pointee = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004795 return Context.getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00004796 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00004797
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004798 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
John McCall49a832b2009-10-18 09:09:24 +00004799 unsigned Idx = 0;
Douglas Gregor393f2492011-07-22 00:38:23 +00004800 QualType Parm = readType(*Loc.F, Record, Idx);
4801 QualType Replacement = readType(*Loc.F, Record, Idx);
John McCall49a832b2009-10-18 09:09:24 +00004802 return
Douglas Gregor35942772011-09-09 21:34:22 +00004803 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
John McCall49a832b2009-10-18 09:09:24 +00004804 Replacement);
4805 }
John McCall3cb0ebd2010-03-10 03:28:59 +00004806
Douglas Gregorc3069d62011-01-14 02:55:32 +00004807 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4808 unsigned Idx = 0;
Douglas Gregor393f2492011-07-22 00:38:23 +00004809 QualType Parm = readType(*Loc.F, Record, Idx);
Douglas Gregorc3069d62011-01-14 02:55:32 +00004810 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004811 return Context.getSubstTemplateTypeParmPackType(
Douglas Gregorc3069d62011-01-14 02:55:32 +00004812 cast<TemplateTypeParmType>(Parm),
4813 ArgPack);
4814 }
4815
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004816 case TYPE_INJECTED_CLASS_NAME: {
Douglas Gregor409448c2011-07-21 22:35:25 +00004817 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004818 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00004819 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004820 // for AST reading, too much interdependencies.
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00004821 return
Douglas Gregor35942772011-09-09 21:34:22 +00004822 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00004823 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004824
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004825 case TYPE_TEMPLATE_TYPE_PARM: {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00004826 unsigned Idx = 0;
4827 unsigned Depth = Record[Idx++];
4828 unsigned Index = Record[Idx++];
4829 bool Pack = Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00004830 TemplateTypeParmDecl *D
4831 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004832 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00004833 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004834
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004835 case TYPE_DEPENDENT_NAME: {
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00004836 unsigned Idx = 0;
4837 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00004838 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregor95eab172011-07-28 20:55:49 +00004839 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004840 QualType Canon = readType(*Loc.F, Record, Idx);
Douglas Gregor32adc8b2010-10-26 00:51:02 +00004841 if (!Canon.isNull())
Douglas Gregor35942772011-09-09 21:34:22 +00004842 Canon = Context.getCanonicalType(Canon);
4843 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00004844 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004845
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004846 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004847 unsigned Idx = 0;
4848 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00004849 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregor95eab172011-07-28 20:55:49 +00004850 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004851 unsigned NumArgs = Record[Idx++];
Chris Lattner5f9e2722011-07-23 10:55:15 +00004852 SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004853 Args.reserve(NumArgs);
4854 while (NumArgs--)
Sebastian Redlc3632732010-10-05 15:59:54 +00004855 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
Douglas Gregor35942772011-09-09 21:34:22 +00004856 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004857 Args.size(), Args.data());
4858 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004859
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004860 case TYPE_DEPENDENT_SIZED_ARRAY: {
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00004861 unsigned Idx = 0;
4862
4863 // ArrayType
Douglas Gregor393f2492011-07-22 00:38:23 +00004864 QualType ElementType = readType(*Loc.F, Record, Idx);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00004865 ArrayType::ArraySizeModifier ASM
4866 = (ArrayType::ArraySizeModifier)Record[Idx++];
4867 unsigned IndexTypeQuals = Record[Idx++];
4868
4869 // DependentSizedArrayType
Sebastian Redlc3632732010-10-05 15:59:54 +00004870 Expr *NumElts = ReadExpr(*Loc.F);
4871 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00004872
Douglas Gregor35942772011-09-09 21:34:22 +00004873 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00004874 IndexTypeQuals, Brackets);
4875 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004876
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004877 case TYPE_TEMPLATE_SPECIALIZATION: {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00004878 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004879 bool IsDependent = Record[Idx++];
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004880 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004881 SmallVector<TemplateArgument, 8> Args;
Sebastian Redlc3632732010-10-05 15:59:54 +00004882 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004883 QualType Underlying = readType(*Loc.F, Record, Idx);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004884 QualType T;
Richard Smith3e4c6c42011-05-05 21:57:07 +00004885 if (Underlying.isNull())
Douglas Gregor35942772011-09-09 21:34:22 +00004886 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004887 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00004888 else
Douglas Gregor35942772011-09-09 21:34:22 +00004889 T = Context.getTemplateSpecializationType(Name, Args.data(),
Richard Smith3e4c6c42011-05-05 21:57:07 +00004890 Args.size(), Underlying);
John McCallf4c73712011-01-19 06:33:43 +00004891 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004892 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00004893 }
Eli Friedmanb001de72011-10-06 23:00:33 +00004894
4895 case TYPE_ATOMIC: {
4896 if (Record.size() != 1) {
4897 Error("Incorrect encoding of atomic type");
4898 return QualType();
4899 }
4900 QualType ValueType = readType(*Loc.F, Record, Idx);
4901 return Context.getAtomicType(ValueType);
4902 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00004903 }
David Blaikie7530c032012-01-17 06:56:22 +00004904 llvm_unreachable("Invalid TypeCode!");
Douglas Gregor2cf26342009-04-09 22:27:44 +00004905}
4906
Sebastian Redlc3632732010-10-05 15:59:54 +00004907class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
Sebastian Redlc43b54c2010-08-18 23:56:43 +00004908 ASTReader &Reader;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004909 ModuleFile &F;
Sebastian Redlc43b54c2010-08-18 23:56:43 +00004910 const ASTReader::RecordData &Record;
John McCalla1ee0c52009-10-16 21:56:05 +00004911 unsigned &Idx;
4912
Sebastian Redlc3632732010-10-05 15:59:54 +00004913 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4914 unsigned &I) {
4915 return Reader.ReadSourceLocation(F, R, I);
4916 }
4917
Douglas Gregor409448c2011-07-21 22:35:25 +00004918 template<typename T>
4919 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4920 return Reader.ReadDeclAs<T>(F, Record, Idx);
4921 }
4922
John McCalla1ee0c52009-10-16 21:56:05 +00004923public:
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004924 TypeLocReader(ASTReader &Reader, ModuleFile &F,
Sebastian Redlc43b54c2010-08-18 23:56:43 +00004925 const ASTReader::RecordData &Record, unsigned &Idx)
Benjamin Kramerfacde172012-06-06 17:32:50 +00004926 : Reader(Reader), F(F), Record(Record), Idx(Idx)
Sebastian Redlc3632732010-10-05 15:59:54 +00004927 { }
John McCalla1ee0c52009-10-16 21:56:05 +00004928
John McCall51bd8032009-10-18 01:05:36 +00004929 // We want compile-time assurance that we've enumerated all of
4930 // these, so unfortunately we have to declare them first, then
4931 // define them out-of-line.
4932#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00004933#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00004934 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00004935#include "clang/AST/TypeLocNodes.def"
4936
John McCall51bd8032009-10-18 01:05:36 +00004937 void VisitFunctionTypeLoc(FunctionTypeLoc);
4938 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00004939};
4940
John McCall51bd8032009-10-18 01:05:36 +00004941void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00004942 // nothing to do
4943}
John McCall51bd8032009-10-18 01:05:36 +00004944void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004945 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
Douglas Gregorddf889a2010-01-18 18:04:31 +00004946 if (TL.needsExtraLocalData()) {
4947 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4948 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4949 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4950 TL.setModeAttr(Record[Idx++]);
4951 }
John McCalla1ee0c52009-10-16 21:56:05 +00004952}
John McCall51bd8032009-10-18 01:05:36 +00004953void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004954 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00004955}
John McCall51bd8032009-10-18 01:05:36 +00004956void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004957 TL.setStarLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00004958}
John McCall51bd8032009-10-18 01:05:36 +00004959void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004960 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00004961}
John McCall51bd8032009-10-18 01:05:36 +00004962void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004963 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00004964}
John McCall51bd8032009-10-18 01:05:36 +00004965void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004966 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00004967}
John McCall51bd8032009-10-18 01:05:36 +00004968void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004969 TL.setStarLoc(ReadSourceLocation(Record, Idx));
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00004970 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00004971}
John McCall51bd8032009-10-18 01:05:36 +00004972void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004973 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
4974 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00004975 if (Record[Idx++])
Sebastian Redlc3632732010-10-05 15:59:54 +00004976 TL.setSizeExpr(Reader.ReadExpr(F));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004977 else
John McCall51bd8032009-10-18 01:05:36 +00004978 TL.setSizeExpr(0);
4979}
4980void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
4981 VisitArrayTypeLoc(TL);
4982}
4983void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
4984 VisitArrayTypeLoc(TL);
4985}
4986void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
4987 VisitArrayTypeLoc(TL);
4988}
4989void TypeLocReader::VisitDependentSizedArrayTypeLoc(
4990 DependentSizedArrayTypeLoc TL) {
4991 VisitArrayTypeLoc(TL);
4992}
4993void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
4994 DependentSizedExtVectorTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004995 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00004996}
4997void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00004998 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00004999}
5000void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005001 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005002}
5003void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00005004 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
Abramo Bagnara59c0a812012-10-04 21:42:10 +00005005 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5006 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
Abramo Bagnara796aa442011-03-12 11:17:06 +00005007 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005008 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
Douglas Gregor409448c2011-07-21 22:35:25 +00005009 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005010 }
5011}
5012void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5013 VisitFunctionTypeLoc(TL);
5014}
5015void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5016 VisitFunctionTypeLoc(TL);
5017}
John McCalled976492009-12-04 22:46:56 +00005018void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005019 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCalled976492009-12-04 22:46:56 +00005020}
John McCall51bd8032009-10-18 01:05:36 +00005021void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005022 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005023}
5024void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005025 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5026 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5027 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005028}
5029void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005030 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5031 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5032 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5033 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005034}
5035void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005036 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005037}
Sean Huntca63c202011-05-24 22:41:36 +00005038void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5039 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5040 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5041 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5042 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5043}
Richard Smith34b41d92011-02-20 03:19:35 +00005044void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5045 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5046}
John McCall51bd8032009-10-18 01:05:36 +00005047void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005048 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005049}
5050void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005051 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005052}
John McCall9d156a72011-01-06 01:58:22 +00005053void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5054 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5055 if (TL.hasAttrOperand()) {
5056 SourceRange range;
5057 range.setBegin(ReadSourceLocation(Record, Idx));
5058 range.setEnd(ReadSourceLocation(Record, Idx));
5059 TL.setAttrOperandParensRange(range);
5060 }
5061 if (TL.hasAttrExprOperand()) {
5062 if (Record[Idx++])
5063 TL.setAttrExprOperand(Reader.ReadExpr(F));
5064 else
5065 TL.setAttrExprOperand(0);
5066 } else if (TL.hasAttrEnumOperand())
5067 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5068}
John McCall51bd8032009-10-18 01:05:36 +00005069void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005070 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005071}
John McCall49a832b2009-10-18 09:09:24 +00005072void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5073 SubstTemplateTypeParmTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005074 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall49a832b2009-10-18 09:09:24 +00005075}
Douglas Gregorc3069d62011-01-14 02:55:32 +00005076void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5077 SubstTemplateTypeParmPackTypeLoc TL) {
5078 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5079}
John McCall51bd8032009-10-18 01:05:36 +00005080void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5081 TemplateSpecializationTypeLoc TL) {
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005082 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
Sebastian Redlc3632732010-10-05 15:59:54 +00005083 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5084 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5085 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCall833ca992009-10-29 08:12:44 +00005086 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5087 TL.setArgLocInfo(i,
Sebastian Redlc3632732010-10-05 15:59:54 +00005088 Reader.GetTemplateArgumentLocInfo(F,
5089 TL.getTypePtr()->getArg(i).getKind(),
5090 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005091}
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005092void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5093 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5094 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5095}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005096void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnara38a42912012-02-06 19:09:27 +00005097 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregor9e876872011-03-01 18:12:44 +00005098 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005099}
John McCall3cb0ebd2010-03-10 03:28:59 +00005100void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005101 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall3cb0ebd2010-03-10 03:28:59 +00005102}
Douglas Gregor4714c122010-03-31 17:34:00 +00005103void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara38a42912012-02-06 19:09:27 +00005104 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregor2494dd02011-03-01 01:34:45 +00005105 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
Sebastian Redlc3632732010-10-05 15:59:54 +00005106 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005107}
John McCall33500952010-06-11 00:33:02 +00005108void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5109 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005110 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregor94fdffa2011-03-01 20:11:18 +00005111 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
Abramo Bagnara66581d42012-02-06 22:45:07 +00005112 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005113 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
Sebastian Redlc3632732010-10-05 15:59:54 +00005114 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5115 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCall33500952010-06-11 00:33:02 +00005116 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5117 TL.setArgLocInfo(I,
Sebastian Redlc3632732010-10-05 15:59:54 +00005118 Reader.GetTemplateArgumentLocInfo(F,
5119 TL.getTypePtr()->getArg(I).getKind(),
5120 Record, Idx));
John McCall33500952010-06-11 00:33:02 +00005121}
Douglas Gregor7536dd52010-12-20 02:24:11 +00005122void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5123 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5124}
John McCall51bd8032009-10-18 01:05:36 +00005125void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005126 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCallc12c5bb2010-05-15 11:32:37 +00005127}
5128void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5129 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Sebastian Redlc3632732010-10-05 15:59:54 +00005130 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5131 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005132 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Sebastian Redlc3632732010-10-05 15:59:54 +00005133 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005134}
John McCall54e14c42009-10-22 22:37:11 +00005135void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005136 TL.setStarLoc(ReadSourceLocation(Record, Idx));
John McCall54e14c42009-10-22 22:37:11 +00005137}
Eli Friedmanb001de72011-10-06 23:00:33 +00005138void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5139 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5140 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5141 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5142}
John McCalla1ee0c52009-10-16 21:56:05 +00005143
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005144TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
Sebastian Redl577d4792010-07-22 22:43:28 +00005145 const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00005146 unsigned &Idx) {
Douglas Gregor393f2492011-07-22 00:38:23 +00005147 QualType InfoTy = readType(F, Record, Idx);
John McCalla1ee0c52009-10-16 21:56:05 +00005148 if (InfoTy.isNull())
5149 return 0;
5150
Douglas Gregor35942772011-09-09 21:34:22 +00005151 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Sebastian Redlc3632732010-10-05 15:59:54 +00005152 TypeLocReader TLR(*this, F, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00005153 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00005154 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00005155 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00005156}
Douglas Gregor2cf26342009-04-09 22:27:44 +00005157
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005158QualType ASTReader::GetType(TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00005159 unsigned FastQuals = ID & Qualifiers::FastMask;
5160 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005161
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005162 if (Index < NUM_PREDEF_TYPE_IDS) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00005163 QualType T;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005164 switch ((PredefinedTypeIDs)Index) {
5165 case PREDEF_TYPE_NULL_ID: return QualType();
Douglas Gregor35942772011-09-09 21:34:22 +00005166 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5167 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005168
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005169 case PREDEF_TYPE_CHAR_U_ID:
5170 case PREDEF_TYPE_CHAR_S_ID:
Douglas Gregor2cf26342009-04-09 22:27:44 +00005171 // FIXME: Check that the signedness of CharTy is correct!
Douglas Gregor35942772011-09-09 21:34:22 +00005172 T = Context.CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005173 break;
5174
Douglas Gregor35942772011-09-09 21:34:22 +00005175 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5176 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5177 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5178 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5179 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5180 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5181 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5182 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5183 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5184 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5185 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5186 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5187 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00005188 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
Douglas Gregor35942772011-09-09 21:34:22 +00005189 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5190 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5191 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5192 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5193 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
John McCall3c3b7f92011-10-25 17:37:35 +00005194 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
Douglas Gregor35942772011-09-09 21:34:22 +00005195 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5196 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5197 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5198 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5199 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5200 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5201 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5202 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
5203 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
Douglas Gregor3b8043b2011-08-09 15:13:55 +00005204
5205 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
Douglas Gregor35942772011-09-09 21:34:22 +00005206 T = Context.getAutoRRefDeductType();
Douglas Gregor3b8043b2011-08-09 15:13:55 +00005207 break;
John McCall0ddaeb92011-10-17 18:09:15 +00005208
5209 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5210 T = Context.ARCUnbridgedCastTy;
5211 break;
5212
Meador Ingefb40e3f2012-07-01 15:57:25 +00005213 case PREDEF_TYPE_VA_LIST_TAG:
5214 T = Context.getVaListTagType();
5215 break;
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005216
5217 case PREDEF_TYPE_BUILTIN_FN:
5218 T = Context.BuiltinFnTy;
5219 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005220 }
5221
5222 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00005223 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00005224 }
5225
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005226 Index -= NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00005227 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00005228 if (TypesLoaded[Index].isNull()) {
Douglas Gregor393f2492011-07-22 00:38:23 +00005229 TypesLoaded[Index] = readTypeRecord(Index);
Douglas Gregor97475832010-10-05 18:37:06 +00005230 if (TypesLoaded[Index].isNull())
5231 return QualType();
5232
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005233 TypesLoaded[Index]->setFromAST();
Sebastian Redl30c514c2010-07-14 23:45:08 +00005234 if (DeserializationListener)
Argyrios Kyrtzidisc8e5d512010-08-20 16:03:59 +00005235 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
Sebastian Redl1476ed42010-07-16 16:36:56 +00005236 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00005237 }
Mike Stump1eb44332009-09-09 15:08:12 +00005238
John McCall0953e762009-09-24 19:53:00 +00005239 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00005240}
5241
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005242QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
Douglas Gregor393f2492011-07-22 00:38:23 +00005243 return GetType(getGlobalTypeID(F, LocalID));
5244}
5245
5246serialization::TypeID
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005247ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
Douglas Gregora119da02011-08-02 16:26:37 +00005248 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5249 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5250
5251 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5252 return LocalID;
5253
5254 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5255 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5256 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5257
5258 unsigned GlobalIndex = LocalIndex + I->second;
5259 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5260}
5261
John McCall833ca992009-10-29 08:12:44 +00005262TemplateArgumentLocInfo
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005263ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
Sebastian Redlc3632732010-10-05 15:59:54 +00005264 TemplateArgument::ArgKind Kind,
John McCall833ca992009-10-29 08:12:44 +00005265 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00005266 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00005267 switch (Kind) {
5268 case TemplateArgument::Expression:
Sebastian Redlc3632732010-10-05 15:59:54 +00005269 return ReadExpr(F);
John McCall833ca992009-10-29 08:12:44 +00005270 case TemplateArgument::Type:
Sebastian Redlc3632732010-10-05 15:59:54 +00005271 return GetTypeSourceInfo(F, Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00005272 case TemplateArgument::Template: {
Douglas Gregorb6744ef2011-03-02 17:09:35 +00005273 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5274 Index);
Sebastian Redlc3632732010-10-05 15:59:54 +00005275 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregorb6744ef2011-03-02 17:09:35 +00005276 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Douglas Gregora7fc9012011-01-05 18:58:31 +00005277 SourceLocation());
5278 }
5279 case TemplateArgument::TemplateExpansion: {
Douglas Gregorb6744ef2011-03-02 17:09:35 +00005280 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5281 Index);
Douglas Gregora7fc9012011-01-05 18:58:31 +00005282 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregorba68eca2011-01-05 17:40:24 +00005283 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregorb6744ef2011-03-02 17:09:35 +00005284 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Douglas Gregorba68eca2011-01-05 17:40:24 +00005285 EllipsisLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00005286 }
John McCall833ca992009-10-29 08:12:44 +00005287 case TemplateArgument::Null:
5288 case TemplateArgument::Integral:
5289 case TemplateArgument::Declaration:
Eli Friedmand7a6b162012-09-26 02:36:12 +00005290 case TemplateArgument::NullPtr:
John McCall833ca992009-10-29 08:12:44 +00005291 case TemplateArgument::Pack:
Eli Friedmand7a6b162012-09-26 02:36:12 +00005292 // FIXME: Is this right?
John McCall833ca992009-10-29 08:12:44 +00005293 return TemplateArgumentLocInfo();
5294 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005295 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00005296}
5297
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00005298TemplateArgumentLoc
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005299ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
Sebastian Redl577d4792010-07-22 22:43:28 +00005300 const RecordData &Record, unsigned &Index) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005301 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00005302
5303 if (Arg.getKind() == TemplateArgument::Expression) {
5304 if (Record[Index++]) // bool InfoHasSameExpr.
5305 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5306 }
Sebastian Redlc3632732010-10-05 15:59:54 +00005307 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00005308 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00005309}
5310
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005311Decl *ASTReader::GetExternalDecl(uint32_t ID) {
John McCall76bd1f32010-06-01 09:23:16 +00005312 return GetDecl(ID);
5313}
5314
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005315uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
Douglas Gregore92b8a12011-08-04 00:01:48 +00005316 unsigned &Idx){
5317 if (Idx >= Record.size())
Douglas Gregor7c789c12010-10-29 22:39:52 +00005318 return 0;
Douglas Gregor7c789c12010-10-29 22:39:52 +00005319
Douglas Gregore92b8a12011-08-04 00:01:48 +00005320 unsigned LocalID = Record[Idx++];
5321 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005322}
5323
5324CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005325 RecordLocation Loc = getLocalBitOffset(Offset);
5326 llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Douglas Gregor7c789c12010-10-29 22:39:52 +00005327 SavedStreamPosition SavedPosition(Cursor);
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005328 Cursor.JumpToBit(Loc.Offset);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005329 ReadingKindTracker ReadingKind(Read_Decl, *this);
5330 RecordData Record;
5331 unsigned Code = Cursor.ReadCode();
5332 unsigned RecCode = Cursor.ReadRecord(Code, Record);
5333 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5334 Error("Malformed AST file: missing C++ base specifiers");
5335 return 0;
5336 }
5337
5338 unsigned Idx = 0;
5339 unsigned NumBases = Record[Idx++];
Douglas Gregor35942772011-09-09 21:34:22 +00005340 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005341 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5342 for (unsigned I = 0; I != NumBases; ++I)
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005343 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005344 return Bases;
5345}
5346
Douglas Gregor409448c2011-07-21 22:35:25 +00005347serialization::DeclID
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00005348ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005349 if (LocalID < NUM_PREDEF_DECL_IDS)
Douglas Gregor496c7092011-08-03 15:48:04 +00005350 return LocalID;
5351
5352 ContinuousRangeMap<uint32_t, int, 2>::iterator I
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005353 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
Douglas Gregor496c7092011-08-03 15:48:04 +00005354 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5355
5356 return LocalID + I->second;
Douglas Gregor409448c2011-07-21 22:35:25 +00005357}
5358
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00005359bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005360 ModuleFile &M) const {
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00005361 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5362 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5363 return &M == I->second;
5364}
5365
Douglas Gregorcff9f262012-01-27 01:47:08 +00005366ModuleFile *ASTReader::getOwningModuleFile(Decl *D) {
5367 if (!D->isFromASTFile())
5368 return 0;
5369 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5370 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5371 return I->second;
5372}
5373
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005374SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5375 if (ID < NUM_PREDEF_DECL_IDS)
5376 return SourceLocation();
5377
5378 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5379
5380 if (Index > DeclsLoaded.size()) {
5381 Error("declaration ID out-of-range for AST file");
5382 return SourceLocation();
5383 }
5384
5385 if (Decl *D = DeclsLoaded[Index])
5386 return D->getLocation();
5387
5388 unsigned RawLocation = 0;
5389 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5390 return ReadSourceLocation(*Rec.F, RawLocation);
5391}
5392
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005393Decl *ASTReader::GetDecl(DeclID ID) {
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005394 if (ID < NUM_PREDEF_DECL_IDS) {
5395 switch ((PredefinedDeclIDs)ID) {
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00005396 case PREDEF_DECL_NULL_ID:
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005397 return 0;
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00005398
5399 case PREDEF_DECL_TRANSLATION_UNIT_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005400 return Context.getTranslationUnitDecl();
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005401
5402 case PREDEF_DECL_OBJC_ID_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005403 return Context.getObjCIdDecl();
Douglas Gregor79d67262011-08-12 05:59:41 +00005404
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005405 case PREDEF_DECL_OBJC_SEL_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005406 return Context.getObjCSelDecl();
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005407
Douglas Gregor79d67262011-08-12 05:59:41 +00005408 case PREDEF_DECL_OBJC_CLASS_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005409 return Context.getObjCClassDecl();
Douglas Gregor772eeae2011-08-12 06:49:56 +00005410
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005411 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5412 return Context.getObjCProtocolDecl();
5413
Douglas Gregor772eeae2011-08-12 06:49:56 +00005414 case PREDEF_DECL_INT_128_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005415 return Context.getInt128Decl();
Douglas Gregor772eeae2011-08-12 06:49:56 +00005416
5417 case PREDEF_DECL_UNSIGNED_INT_128_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005418 return Context.getUInt128Decl();
Douglas Gregore97179c2011-09-08 01:46:34 +00005419
5420 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005421 return Context.getObjCInstanceTypeDecl();
Meador Ingec5613b22012-06-16 03:34:49 +00005422
5423 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5424 return Context.getBuiltinVaListDecl();
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005425 }
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005426 }
5427
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00005428 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5429
Richard Smith2fbf3732011-12-20 04:39:57 +00005430 if (Index >= DeclsLoaded.size()) {
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00005431 assert(0 && "declaration ID out-of-range for AST file");
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005432 Error("declaration ID out-of-range for AST file");
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00005433 return 0;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005434 }
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00005435
Douglas Gregorfd002a72011-12-16 22:37:11 +00005436 if (!DeclsLoaded[Index]) {
Douglas Gregor496c7092011-08-03 15:48:04 +00005437 ReadDeclRecord(ID);
Sebastian Redl30c514c2010-07-14 23:45:08 +00005438 if (DeserializationListener)
5439 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5440 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005441
5442 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00005443}
5444
Douglas Gregora1be2782011-12-17 23:38:30 +00005445DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5446 DeclID GlobalID) {
5447 if (GlobalID < NUM_PREDEF_DECL_IDS)
5448 return GlobalID;
5449
5450 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5451 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5452 ModuleFile *Owner = I->second;
5453
5454 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5455 = M.GlobalToLocalDeclIDs.find(Owner);
5456 if (Pos == M.GlobalToLocalDeclIDs.end())
5457 return 0;
5458
5459 return GlobalID - Owner->BaseDeclID + Pos->second;
5460}
5461
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005462serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Douglas Gregor409448c2011-07-21 22:35:25 +00005463 const RecordData &Record,
5464 unsigned &Idx) {
5465 if (Idx >= Record.size()) {
5466 Error("Corrupted AST file");
5467 return 0;
5468 }
5469
5470 return getGlobalDeclID(F, Record[Idx++]);
5471}
5472
Chris Lattner887e2b32009-04-27 05:46:25 +00005473/// \brief Resolve the offset of a statement into a statement.
5474///
5475/// This operation will read a new statement from the external
5476/// source each time it is called, and is meant to be used via a
5477/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005478Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
Argyrios Kyrtzidise09a2752010-10-28 09:29:32 +00005479 // Switch case IDs are per Decl.
5480 ClearSwitchCaseIDs();
5481
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00005482 // Offset here is a global offset across the entire chain.
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005483 RecordLocation Loc = getLocalBitOffset(Offset);
5484 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5485 return ReadStmtFromStream(*Loc.F);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00005486}
5487
Douglas Gregor851c75a2011-08-24 21:27:34 +00005488namespace {
5489 class FindExternalLexicalDeclsVisitor {
5490 ASTReader &Reader;
5491 const DeclContext *DC;
5492 bool (*isKindWeWant)(Decl::Kind);
Douglas Gregor2ea054f2011-08-26 22:04:51 +00005493
Douglas Gregor851c75a2011-08-24 21:27:34 +00005494 SmallVectorImpl<Decl*> &Decls;
5495 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5496
5497 public:
5498 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5499 bool (*isKindWeWant)(Decl::Kind),
5500 SmallVectorImpl<Decl*> &Decls)
5501 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5502 {
5503 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5504 PredefsVisited[I] = false;
5505 }
5506
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005507 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
Douglas Gregor851c75a2011-08-24 21:27:34 +00005508 if (Preorder)
5509 return false;
5510
5511 FindExternalLexicalDeclsVisitor *This
5512 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5513
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005514 ModuleFile::DeclContextInfosMap::iterator Info
Douglas Gregor851c75a2011-08-24 21:27:34 +00005515 = M.DeclContextInfos.find(This->DC);
5516 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5517 return false;
5518
5519 // Load all of the declaration IDs
5520 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5521 *IDE = ID + Info->second.NumLexicalDecls;
5522 ID != IDE; ++ID) {
5523 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5524 continue;
5525
5526 // Don't add predefined declarations to the lexical context more
5527 // than once.
5528 if (ID->second < NUM_PREDEF_DECL_IDS) {
5529 if (This->PredefsVisited[ID->second])
5530 continue;
5531
5532 This->PredefsVisited[ID->second] = true;
5533 }
5534
Douglas Gregor2ea054f2011-08-26 22:04:51 +00005535 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5536 if (!This->DC->isDeclInLexicalTraversal(D))
5537 This->Decls.push_back(D);
5538 }
Douglas Gregor851c75a2011-08-24 21:27:34 +00005539 }
5540
5541 return false;
5542 }
5543 };
5544}
5545
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00005546ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00005547 bool (*isKindWeWant)(Decl::Kind),
Chris Lattner5f9e2722011-07-23 10:55:15 +00005548 SmallVectorImpl<Decl*> &Decls) {
Douglas Gregor0d95f772011-08-24 19:03:07 +00005549 // There might be lexical decls in multiple modules, for the TU at
Douglas Gregor851c75a2011-08-24 21:27:34 +00005550 // least. Walk all of the modules in the order they were loaded.
5551 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5552 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
Douglas Gregor25123082009-04-22 22:34:57 +00005553 ++NumLexicalDeclContextsRead;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00005554 return ELR_Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005555}
5556
Douglas Gregor0d95f772011-08-24 19:03:07 +00005557namespace {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005558
5559class DeclIDComp {
5560 ASTReader &Reader;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005561 ModuleFile &Mod;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005562
5563public:
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005564 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005565
5566 bool operator()(LocalDeclID L, LocalDeclID R) const {
5567 SourceLocation LHS = getLocation(L);
5568 SourceLocation RHS = getLocation(R);
5569 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5570 }
5571
5572 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5573 SourceLocation RHS = getLocation(R);
5574 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5575 }
5576
5577 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5578 SourceLocation LHS = getLocation(L);
5579 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5580 }
5581
5582 SourceLocation getLocation(LocalDeclID ID) const {
5583 return Reader.getSourceManager().getFileLoc(
5584 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5585 }
5586};
5587
5588}
5589
5590void ASTReader::FindFileRegionDecls(FileID File,
5591 unsigned Offset, unsigned Length,
5592 SmallVectorImpl<Decl *> &Decls) {
5593 SourceManager &SM = getSourceManager();
5594
5595 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5596 if (I == FileDeclIDs.end())
5597 return;
5598
5599 FileDeclsInfo &DInfo = I->second;
5600 if (DInfo.Decls.empty())
5601 return;
5602
5603 SourceLocation
5604 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5605 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5606
5607 DeclIDComp DIDComp(*this, *DInfo.Mod);
5608 ArrayRef<serialization::LocalDeclID>::iterator
5609 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5610 BeginLoc, DIDComp);
5611 if (BeginIt != DInfo.Decls.begin())
5612 --BeginIt;
5613
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00005614 // If we are pointing at a top-level decl inside an objc container, we need
5615 // to backtrack until we find it otherwise we will fail to report that the
5616 // region overlaps with an objc container.
5617 while (BeginIt != DInfo.Decls.begin() &&
5618 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5619 ->isTopLevelDeclInObjCContainer())
5620 --BeginIt;
5621
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005622 ArrayRef<serialization::LocalDeclID>::iterator
5623 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5624 EndLoc, DIDComp);
5625 if (EndIt != DInfo.Decls.end())
5626 ++EndIt;
5627
5628 for (ArrayRef<serialization::LocalDeclID>::iterator
5629 DIt = BeginIt; DIt != EndIt; ++DIt)
5630 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5631}
5632
5633namespace {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005634 /// \brief ModuleFile visitor used to perform name lookup into a
Douglas Gregor0d95f772011-08-24 19:03:07 +00005635 /// declaration context.
5636 class DeclContextNameLookupVisitor {
5637 ASTReader &Reader;
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005638 llvm::SmallVectorImpl<const DeclContext *> &Contexts;
Douglas Gregor0d95f772011-08-24 19:03:07 +00005639 DeclarationName Name;
5640 SmallVectorImpl<NamedDecl *> &Decls;
5641
5642 public:
5643 DeclContextNameLookupVisitor(ASTReader &Reader,
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005644 SmallVectorImpl<const DeclContext *> &Contexts,
5645 DeclarationName Name,
Douglas Gregor0d95f772011-08-24 19:03:07 +00005646 SmallVectorImpl<NamedDecl *> &Decls)
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005647 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
Douglas Gregor0d95f772011-08-24 19:03:07 +00005648
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005649 static bool visit(ModuleFile &M, void *UserData) {
Douglas Gregor0d95f772011-08-24 19:03:07 +00005650 DeclContextNameLookupVisitor *This
5651 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5652
5653 // Check whether we have any visible declaration information for
5654 // this context in this module.
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005655 ModuleFile::DeclContextInfosMap::iterator Info;
5656 bool FoundInfo = false;
5657 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5658 Info = M.DeclContextInfos.find(This->Contexts[I]);
5659 if (Info != M.DeclContextInfos.end() &&
5660 Info->second.NameLookupTableData) {
5661 FoundInfo = true;
5662 break;
5663 }
5664 }
Douglas Gregor0d95f772011-08-24 19:03:07 +00005665
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005666 if (!FoundInfo)
5667 return false;
5668
Douglas Gregor0d95f772011-08-24 19:03:07 +00005669 // Look for this name within this module.
5670 ASTDeclContextNameLookupTable *LookupTable =
Benjamin Kramerb1758c62012-04-15 12:36:49 +00005671 Info->second.NameLookupTableData;
Douglas Gregor0d95f772011-08-24 19:03:07 +00005672 ASTDeclContextNameLookupTable::iterator Pos
5673 = LookupTable->find(This->Name);
5674 if (Pos == LookupTable->end())
5675 return false;
5676
5677 bool FoundAnything = false;
5678 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5679 for (; Data.first != Data.second; ++Data.first) {
5680 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5681 if (!ND)
5682 continue;
5683
5684 if (ND->getDeclName() != This->Name) {
Axel Naumann3dd82f72012-10-01 09:51:27 +00005685 // A name might be null because the decl's redeclarable part is
5686 // currently read before reading its name. The lookup is triggered by
5687 // building that decl (likely indirectly), and so it is later in the
5688 // sense of "already existing" and can be ignored here.
Douglas Gregor0d95f772011-08-24 19:03:07 +00005689 continue;
5690 }
5691
5692 // Record this declaration.
5693 FoundAnything = true;
5694 This->Decls.push_back(ND);
5695 }
5696
5697 return FoundAnything;
5698 }
5699 };
5700}
5701
John McCall76bd1f32010-06-01 09:23:16 +00005702DeclContext::lookup_result
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005703ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
John McCall76bd1f32010-06-01 09:23:16 +00005704 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00005705 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00005706 "DeclContext has no visible decls in storage");
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00005707 if (!Name)
5708 return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
5709 DeclContext::lookup_iterator(0));
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00005710
Chris Lattner5f9e2722011-07-23 10:55:15 +00005711 SmallVector<NamedDecl *, 64> Decls;
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005712
5713 // Compute the declaration contexts we need to look into. Multiple such
5714 // declaration contexts occur when two declaration contexts from disjoint
5715 // modules get merged, e.g., when two namespaces with the same name are
5716 // independently defined in separate modules.
5717 SmallVector<const DeclContext *, 2> Contexts;
5718 Contexts.push_back(DC);
5719
5720 if (DC->isNamespace()) {
5721 MergedDeclsMap::iterator Merged
5722 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5723 if (Merged != MergedDecls.end()) {
5724 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5725 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5726 }
5727 }
5728
5729 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor0d95f772011-08-24 19:03:07 +00005730 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
Douglas Gregor25123082009-04-22 22:34:57 +00005731 ++NumVisibleDeclContextsRead;
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00005732 SetExternalVisibleDeclsForName(DC, Name, Decls);
John McCall76bd1f32010-06-01 09:23:16 +00005733 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00005734}
5735
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005736namespace {
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005737 /// \brief ModuleFile visitor used to retrieve all visible names in a
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005738 /// declaration context.
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005739 class DeclContextAllNamesVisitor {
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005740 ASTReader &Reader;
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005741 llvm::SmallVectorImpl<const DeclContext *> &Contexts;
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005742 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005743
5744 public:
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005745 DeclContextAllNamesVisitor(ASTReader &Reader,
5746 SmallVectorImpl<const DeclContext *> &Contexts,
5747 llvm::DenseMap<DeclarationName,
5748 SmallVector<NamedDecl *, 8> > &Decls)
5749 : Reader(Reader), Contexts(Contexts), Decls(Decls) { }
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005750
5751 static bool visit(ModuleFile &M, void *UserData) {
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005752 DeclContextAllNamesVisitor *This
5753 = static_cast<DeclContextAllNamesVisitor *>(UserData);
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005754
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005755 // Check whether we have any visible declaration information for
5756 // this context in this module.
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005757 ModuleFile::DeclContextInfosMap::iterator Info;
5758 bool FoundInfo = false;
5759 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5760 Info = M.DeclContextInfos.find(This->Contexts[I]);
5761 if (Info != M.DeclContextInfos.end() &&
5762 Info->second.NameLookupTableData) {
5763 FoundInfo = true;
5764 break;
5765 }
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005766 }
5767
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005768 if (!FoundInfo)
5769 return false;
5770
5771 ASTDeclContextNameLookupTable *LookupTable =
5772 Info->second.NameLookupTableData;
5773 bool FoundAnything = false;
5774 for (ASTDeclContextNameLookupTable::data_iterator
5775 I = LookupTable->data_begin(), E = LookupTable->data_end();
5776 I != E; ++I) {
5777 ASTDeclContextNameLookupTrait::data_type Data = *I;
5778 for (; Data.first != Data.second; ++Data.first) {
5779 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5780 *Data.first);
5781 if (!ND)
5782 continue;
5783
5784 // Record this declaration.
5785 FoundAnything = true;
5786 This->Decls[ND->getDeclName()].push_back(ND);
5787 }
5788 }
5789
5790 return FoundAnything;
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005791 }
5792 };
5793}
5794
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005795void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005796 if (!DC->hasExternalVisibleStorage())
5797 return;
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005798 llvm::DenseMap<DeclarationName, llvm::SmallVector<NamedDecl*, 8> > Decls;
5799
5800 // Compute the declaration contexts we need to look into. Multiple such
5801 // declaration contexts occur when two declaration contexts from disjoint
5802 // modules get merged, e.g., when two namespaces with the same name are
5803 // independently defined in separate modules.
5804 SmallVector<const DeclContext *, 2> Contexts;
5805 Contexts.push_back(DC);
5806
5807 if (DC->isNamespace()) {
5808 MergedDeclsMap::iterator Merged
5809 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5810 if (Merged != MergedDecls.end()) {
5811 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5812 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5813 }
5814 }
5815
5816 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls);
5817 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5818 ++NumVisibleDeclContextsRead;
5819
5820 for (llvm::DenseMap<DeclarationName,
5821 llvm::SmallVector<NamedDecl*, 8> >::iterator
5822 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5823 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5824 }
Argyrios Kyrtzidis394e5392012-04-26 18:34:14 +00005825 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005826}
5827
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00005828/// \brief Under non-PCH compilation the consumer receives the objc methods
5829/// before receiving the implementation, and codegen depends on this.
5830/// We simulate this by deserializing and passing to consumer the methods of the
5831/// implementation before passing the deserialized implementation decl.
5832static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5833 ASTConsumer *Consumer) {
5834 assert(ImplD && Consumer);
5835
5836 for (ObjCImplDecl::method_iterator
5837 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00005838 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00005839
5840 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5841}
5842
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005843void ASTReader::PassInterestingDeclsToConsumer() {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005844 assert(Consumer);
5845 while (!InterestingDecls.empty()) {
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00005846 Decl *D = InterestingDecls.front();
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005847 InterestingDecls.pop_front();
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00005848
Argyrios Kyrtzidis8d39c3d2011-11-30 23:18:26 +00005849 PassInterestingDeclToConsumer(D);
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005850 }
5851}
5852
Argyrios Kyrtzidis8d39c3d2011-11-30 23:18:26 +00005853void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5854 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5855 PassObjCImplDeclToConsumer(ImplD, Consumer);
5856 else
5857 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5858}
5859
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005860void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00005861 this->Consumer = Consumer;
5862
Douglas Gregorfdd01722009-04-14 00:24:19 +00005863 if (!Consumer)
5864 return;
5865
5866 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005867 // Force deserialization of this decl, which will cause it to be queued for
5868 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00005869 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00005870 }
Douglas Gregor1a995dd2011-09-15 18:47:32 +00005871 ExternalDefinitions.clear();
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00005872
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005873 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00005874}
5875
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005876void ASTReader::PrintStats() {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005877 std::fprintf(stderr, "*** AST File Statistics:\n");
Douglas Gregor2cf26342009-04-09 22:27:44 +00005878
Mike Stump1eb44332009-09-09 15:08:12 +00005879 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005880 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00005881 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005882 unsigned NumDeclsLoaded
5883 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5884 (Decl *)0);
5885 unsigned NumIdentifiersLoaded
5886 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5887 IdentifiersLoaded.end(),
5888 (IdentifierInfo *)0);
Douglas Gregora8235d62012-10-09 23:05:51 +00005889 unsigned NumMacrosLoaded
5890 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5891 MacrosLoaded.end(),
5892 (MacroInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00005893 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005894 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5895 SelectorsLoaded.end(),
5896 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00005897
Douglas Gregor4fed3f42009-04-27 18:38:38 +00005898 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
5899 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor0cdd7982011-07-21 18:46:38 +00005900 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00005901 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5902 NumSLocEntriesRead, TotalNumSLocEntries,
5903 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005904 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00005905 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005906 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5907 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5908 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00005909 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005910 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5911 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005912 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00005913 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005914 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5915 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregora8235d62012-10-09 23:05:51 +00005916 if (!MacrosLoaded.empty())
5917 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5918 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5919 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
Sebastian Redl725cd962010-08-04 20:40:17 +00005920 if (!SelectorsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00005921 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
Sebastian Redl725cd962010-08-04 20:40:17 +00005922 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5923 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00005924 if (TotalNumStatements)
5925 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5926 NumStatementsRead, TotalNumStatements,
5927 ((float)NumStatementsRead/TotalNumStatements * 100));
5928 if (TotalNumMacros)
5929 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5930 NumMacrosRead, TotalNumMacros,
5931 ((float)NumMacrosRead/TotalNumMacros * 100));
5932 if (TotalLexicalDeclContexts)
5933 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5934 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5935 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5936 * 100));
5937 if (TotalVisibleDeclContexts)
5938 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5939 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5940 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5941 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00005942 if (TotalNumMethodPoolEntries) {
Douglas Gregor83941df2009-04-25 17:48:32 +00005943 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
Sebastian Redlfa78dec2010-08-04 21:22:45 +00005944 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5945 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
Douglas Gregor83941df2009-04-25 17:48:32 +00005946 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00005947 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
Douglas Gregor83941df2009-04-25 17:48:32 +00005948 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00005949 std::fprintf(stderr, "\n");
Douglas Gregor23d7df52011-07-21 19:50:14 +00005950 dump();
5951 std::fprintf(stderr, "\n");
5952}
5953
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005954template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Douglas Gregor23d7df52011-07-21 19:50:14 +00005955static void
Chris Lattner5f9e2722011-07-23 10:55:15 +00005956dumpModuleIDMap(StringRef Name,
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005957 const ContinuousRangeMap<Key, ModuleFile *,
Douglas Gregor23d7df52011-07-21 19:50:14 +00005958 InitialCapacity> &Map) {
5959 if (Map.begin() == Map.end())
5960 return;
5961
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005962 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
Douglas Gregor23d7df52011-07-21 19:50:14 +00005963 llvm::errs() << Name << ":\n";
5964 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
5965 I != IEnd; ++I) {
5966 llvm::errs() << " " << I->first << " -> " << I->second->FileName
5967 << "\n";
5968 }
5969}
5970
Douglas Gregor23d7df52011-07-21 19:50:14 +00005971void ASTReader::dump() {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005972 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005973 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
Douglas Gregor23d7df52011-07-21 19:50:14 +00005974 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
Douglas Gregor1e849b62011-07-29 00:21:44 +00005975 dumpModuleIDMap("Global type map", GlobalTypeMap);
Douglas Gregor9827a802011-07-29 00:56:45 +00005976 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
Douglas Gregor9827a802011-07-29 00:56:45 +00005977 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
Douglas Gregora8235d62012-10-09 23:05:51 +00005978 dumpModuleIDMap("Global macro map", GlobalMacroMap);
Douglas Gregor26ced122011-12-01 00:59:36 +00005979 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
Douglas Gregor9827a802011-07-29 00:56:45 +00005980 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
Douglas Gregor9827a802011-07-29 00:56:45 +00005981 dumpModuleIDMap("Global preprocessed entity map",
5982 GlobalPreprocessedEntityMap);
Douglas Gregor8df5c9b2011-08-02 11:12:41 +00005983
5984 llvm::errs() << "\n*** PCH/Modules Loaded:";
5985 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
5986 MEnd = ModuleMgr.end();
5987 M != MEnd; ++M)
5988 (*M)->dump();
Douglas Gregor2cf26342009-04-09 22:27:44 +00005989}
5990
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005991/// Return the amount of memory used by memory buffers, breaking down
5992/// by heap-backed versus mmap'ed memory.
5993void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00005994 for (ModuleConstIterator I = ModuleMgr.begin(),
5995 E = ModuleMgr.end(); I != E; ++I) {
5996 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00005997 size_t bytes = buf->getBufferSize();
5998 switch (buf->getBufferKind()) {
5999 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6000 sizes.malloc_bytes += bytes;
6001 break;
6002 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6003 sizes.mmap_bytes += bytes;
6004 break;
6005 }
6006 }
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006007 }
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00006008}
6009
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006010void ASTReader::InitializeSema(Sema &S) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00006011 SemaObj = &S;
Axel Naumann0ec56b72012-10-18 19:05:02 +00006012 S.addExternalSource(this);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00006013
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00006014 // Makes sure any declarations that were deserialized "too early"
6015 // still get added to the identifier's declaration chains.
Douglas Gregor76dc8892010-09-24 23:29:12 +00006016 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Douglas Gregoreee242f2011-10-27 09:33:13 +00006017 SemaObj->pushExternalDeclIntoScope(PreloadedDecls[I],
6018 PreloadedDecls[I]->getDeclName());
Douglas Gregor668c1a42009-04-21 22:25:48 +00006019 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00006020 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00006021
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006022 // Load the offsets of the declarations that Sema references.
6023 // They will be lazily deserialized when needed.
6024 if (!SemaDeclRefs.empty()) {
6025 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
Douglas Gregor1e5b6f62011-07-28 00:57:24 +00006026 if (!SemaObj->StdNamespace)
6027 SemaObj->StdNamespace = SemaDeclRefs[0];
6028 if (!SemaObj->StdBadAlloc)
6029 SemaObj->StdBadAlloc = SemaDeclRefs[1];
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006030 }
6031
Peter Collingbourne84bccea2011-02-15 19:46:30 +00006032 if (!FPPragmaOptions.empty()) {
6033 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6034 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6035 }
6036
6037 if (!OpenCLExtensions.empty()) {
6038 unsigned I = 0;
6039#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6040#include "clang/Basic/OpenCLExtensions.def"
6041
6042 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6043 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00006044}
6045
Douglas Gregor211f6e82011-08-20 04:39:52 +00006046IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00006047 // Note that we are loading an identifier.
6048 Deserializing AnIdentifier(this);
6049
Douglas Gregor057df202012-01-18 20:56:22 +00006050 IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart),
6051 /*PriorGeneration=*/0);
Douglas Gregor211f6e82011-08-20 04:39:52 +00006052 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
Douglas Gregoreee242f2011-10-27 09:33:13 +00006053 IdentifierInfo *II = Visitor.getIdentifierInfo();
Douglas Gregor057df202012-01-18 20:56:22 +00006054 markIdentifierUpToDate(II);
Douglas Gregoreee242f2011-10-27 09:33:13 +00006055 return II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00006056}
6057
Douglas Gregor95f42922010-10-14 22:11:03 +00006058namespace clang {
6059 /// \brief An identifier-lookup iterator that enumerates all of the
6060 /// identifiers stored within a set of AST files.
6061 class ASTIdentifierIterator : public IdentifierIterator {
6062 /// \brief The AST reader whose identifiers are being enumerated.
6063 const ASTReader &Reader;
6064
6065 /// \brief The current index into the chain of AST files stored in
6066 /// the AST reader.
6067 unsigned Index;
6068
6069 /// \brief The current position within the identifier lookup table
6070 /// of the current AST file.
6071 ASTIdentifierLookupTable::key_iterator Current;
6072
6073 /// \brief The end position within the identifier lookup table of
6074 /// the current AST file.
6075 ASTIdentifierLookupTable::key_iterator End;
6076
6077 public:
6078 explicit ASTIdentifierIterator(const ASTReader &Reader);
6079
Chris Lattner5f9e2722011-07-23 10:55:15 +00006080 virtual StringRef Next();
Douglas Gregor95f42922010-10-14 22:11:03 +00006081 };
6082}
6083
6084ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006085 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
Douglas Gregor95f42922010-10-14 22:11:03 +00006086 ASTIdentifierLookupTable *IdTable
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006087 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
Douglas Gregor95f42922010-10-14 22:11:03 +00006088 Current = IdTable->key_begin();
6089 End = IdTable->key_end();
6090}
6091
Chris Lattner5f9e2722011-07-23 10:55:15 +00006092StringRef ASTIdentifierIterator::Next() {
Douglas Gregor95f42922010-10-14 22:11:03 +00006093 while (Current == End) {
6094 // If we have exhausted all of our AST files, we're done.
6095 if (Index == 0)
Chris Lattner5f9e2722011-07-23 10:55:15 +00006096 return StringRef();
Douglas Gregor95f42922010-10-14 22:11:03 +00006097
6098 --Index;
6099 ASTIdentifierLookupTable *IdTable
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006100 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6101 IdentifierLookupTable;
Douglas Gregor95f42922010-10-14 22:11:03 +00006102 Current = IdTable->key_begin();
6103 End = IdTable->key_end();
6104 }
6105
6106 // We have any identifiers remaining in the current AST file; return
6107 // the next one.
6108 std::pair<const char*, unsigned> Key = *Current;
6109 ++Current;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006110 return StringRef(Key.first, Key.second);
Douglas Gregor95f42922010-10-14 22:11:03 +00006111}
6112
6113IdentifierIterator *ASTReader::getIdentifiers() const {
6114 return new ASTIdentifierIterator(*this);
6115}
6116
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006117namespace clang { namespace serialization {
6118 class ReadMethodPoolVisitor {
6119 ASTReader &Reader;
Douglas Gregor8efca6b2012-01-25 01:14:32 +00006120 Selector Sel;
6121 unsigned PriorGeneration;
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006122 llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6123 llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00006124
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006125 public:
Douglas Gregor8efca6b2012-01-25 01:14:32 +00006126 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6127 unsigned PriorGeneration)
6128 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006129
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006130 static bool visit(ModuleFile &M, void *UserData) {
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006131 ReadMethodPoolVisitor *This
6132 = static_cast<ReadMethodPoolVisitor *>(UserData);
6133
6134 if (!M.SelectorLookupTable)
6135 return false;
6136
Douglas Gregor8efca6b2012-01-25 01:14:32 +00006137 // If we've already searched this module file, skip it now.
6138 if (M.Generation <= This->PriorGeneration)
6139 return true;
6140
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006141 ASTSelectorLookupTable *PoolTable
6142 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6143 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6144 if (Pos == PoolTable->end())
6145 return false;
6146
6147 ++This->Reader.NumSelectorsRead;
Sebastian Redlfa78dec2010-08-04 21:22:45 +00006148 // FIXME: Not quite happy with the statistics here. We probably should
6149 // disable this tracking when called via LoadSelector.
6150 // Also, should entries without methods count as misses?
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006151 ++This->Reader.NumMethodPoolEntriesRead;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006152 ASTSelectorLookupTrait::data_type Data = *Pos;
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006153 if (This->Reader.DeserializationListener)
6154 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6155 This->Sel);
6156
6157 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6158 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6159 return true;
Sebastian Redl725cd962010-08-04 20:40:17 +00006160 }
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006161
6162 /// \brief Retrieve the instance methods found by this visitor.
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006163 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6164 return InstanceMethods;
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006165 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00006166
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006167 /// \brief Retrieve the instance methods found by this visitor.
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006168 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6169 return FactoryMethods;
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006170 }
6171 };
6172} } // end namespace clang::serialization
6173
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006174/// \brief Add the given set of methods to the method list.
6175static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6176 ObjCMethodList &List) {
6177 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6178 S.addMethodToGlobalList(&List, Methods[I]);
6179 }
6180}
6181
6182void ASTReader::ReadMethodPool(Selector Sel) {
Douglas Gregor8efca6b2012-01-25 01:14:32 +00006183 // Get the selector generation and update it to the current generation.
6184 unsigned &Generation = SelectorGeneration[Sel];
6185 unsigned PriorGeneration = Generation;
6186 Generation = CurrentGeneration;
6187
6188 // Search for methods defined with this selector.
6189 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006190 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006191
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006192 if (Visitor.getInstanceMethods().empty() &&
6193 Visitor.getFactoryMethods().empty()) {
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006194 ++NumMethodPoolMisses;
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006195 return;
6196 }
6197
6198 if (!getSema())
6199 return;
6200
6201 Sema &S = *getSema();
6202 Sema::GlobalMethodPool::iterator Pos
6203 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6204
6205 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6206 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00006207}
6208
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006209void ASTReader::ReadKnownNamespaces(
Chris Lattner5f9e2722011-07-23 10:55:15 +00006210 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006211 Namespaces.clear();
6212
6213 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6214 if (NamespaceDecl *Namespace
6215 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6216 Namespaces.push_back(Namespace);
6217 }
6218}
6219
Douglas Gregora8623202011-07-27 20:58:46 +00006220void ASTReader::ReadTentativeDefinitions(
6221 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6222 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6223 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6224 if (Var)
6225 TentativeDefs.push_back(Var);
6226 }
6227 TentativeDefinitions.clear();
6228}
6229
Douglas Gregora2ee20a2011-07-27 21:45:57 +00006230void ASTReader::ReadUnusedFileScopedDecls(
6231 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6232 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6233 DeclaratorDecl *D
6234 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6235 if (D)
6236 Decls.push_back(D);
6237 }
6238 UnusedFileScopedDecls.clear();
6239}
6240
Douglas Gregor0129b562011-07-27 21:57:17 +00006241void ASTReader::ReadDelegatingConstructors(
6242 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6243 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6244 CXXConstructorDecl *D
6245 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6246 if (D)
6247 Decls.push_back(D);
6248 }
6249 DelegatingCtorDecls.clear();
6250}
6251
Douglas Gregord58a0a52011-07-28 00:39:29 +00006252void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6253 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6254 TypedefNameDecl *D
6255 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6256 if (D)
6257 Decls.push_back(D);
6258 }
6259 ExtVectorDecls.clear();
6260}
6261
Douglas Gregora126f172011-07-28 00:53:40 +00006262void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6263 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6264 CXXRecordDecl *D
6265 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6266 if (D)
6267 Decls.push_back(D);
6268 }
6269 DynamicClasses.clear();
6270}
6271
Douglas Gregorec12ce22011-07-28 14:20:37 +00006272void
6273ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6274 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
6275 NamedDecl *D
6276 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
6277 if (D)
6278 Decls.push_back(D);
6279 }
6280 LocallyScopedExternalDecls.clear();
6281}
6282
Douglas Gregor5b9dc7c2011-07-28 14:54:22 +00006283void ASTReader::ReadReferencedSelectors(
6284 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6285 if (ReferencedSelectorsData.empty())
6286 return;
6287
6288 // If there are @selector references added them to its pool. This is for
6289 // implementation of -Wselector.
6290 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6291 unsigned I = 0;
6292 while (I < DataSize) {
6293 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6294 SourceLocation SelLoc
6295 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6296 Sels.push_back(std::make_pair(Sel, SelLoc));
6297 }
6298 ReferencedSelectorsData.clear();
6299}
6300
Douglas Gregor31e37b22011-07-28 18:09:57 +00006301void ASTReader::ReadWeakUndeclaredIdentifiers(
6302 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6303 if (WeakUndeclaredIdentifiers.empty())
6304 return;
6305
6306 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6307 IdentifierInfo *WeakId
6308 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6309 IdentifierInfo *AliasId
6310 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6311 SourceLocation Loc
6312 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6313 bool Used = WeakUndeclaredIdentifiers[I++];
6314 WeakInfo WI(AliasId, Loc);
6315 WI.setUsed(Used);
6316 WeakIDs.push_back(std::make_pair(WeakId, WI));
6317 }
6318 WeakUndeclaredIdentifiers.clear();
6319}
6320
Douglas Gregordfe65432011-07-28 19:11:31 +00006321void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6322 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6323 ExternalVTableUse VT;
6324 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6325 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6326 VT.DefinitionRequired = VTableUses[Idx++];
6327 VTables.push_back(VT);
6328 }
6329
6330 VTableUses.clear();
6331}
6332
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00006333void ASTReader::ReadPendingInstantiations(
6334 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6335 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6336 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6337 SourceLocation Loc
6338 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
Axel Naumann39d26c32012-10-02 09:09:43 +00006339
Douglas Gregore5fa3c22012-10-03 18:34:48 +00006340 Pending.push_back(std::make_pair(D, Loc));
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00006341 }
6342 PendingInstantiations.clear();
6343}
6344
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006345void ASTReader::LoadSelector(Selector Sel) {
Sebastian Redle58aa892010-08-04 18:21:41 +00006346 // It would be complicated to avoid reading the methods anyway. So don't.
6347 ReadMethodPool(Sel);
6348}
6349
Douglas Gregor95eab172011-07-28 20:55:49 +00006350void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00006351 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00006352 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00006353 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00006354 if (DeserializationListener)
6355 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregor668c1a42009-04-21 22:25:48 +00006356}
6357
Douglas Gregord89275b2009-07-06 18:54:52 +00006358/// \brief Set the globally-visible declarations associated with the given
6359/// identifier.
6360///
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006361/// If the AST reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00006362/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00006363/// them.
6364///
6365/// \param II an IdentifierInfo that refers to one or more globally-visible
6366/// declarations.
6367///
6368/// \param DeclIDs the set of declaration IDs with the name @p II that are
6369/// visible at global scope.
6370///
6371/// \param Nonrecursive should be true to indicate that the caller knows that
6372/// this call is non-recursive, and therefore the globally-visible declarations
6373/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00006374void
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006375ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006376 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregord89275b2009-07-06 18:54:52 +00006377 bool Nonrecursive) {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00006378 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregord89275b2009-07-06 18:54:52 +00006379 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
6380 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
6381 PII.II = II;
Benjamin Kramer4ea884b2010-09-06 23:43:28 +00006382 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
Douglas Gregord89275b2009-07-06 18:54:52 +00006383 return;
6384 }
Mike Stump1eb44332009-09-09 15:08:12 +00006385
Douglas Gregord89275b2009-07-06 18:54:52 +00006386 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6387 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6388 if (SemaObj) {
Douglas Gregoreee242f2011-10-27 09:33:13 +00006389 // Introduce this declaration into the translation-unit scope
6390 // and add it to the declaration chain for this identifier, so
6391 // that (unqualified) name lookup will find it.
6392 SemaObj->pushExternalDeclIntoScope(D, II);
Douglas Gregord89275b2009-07-06 18:54:52 +00006393 } else {
6394 // Queue this declaration so that it will be added to the
6395 // translation unit scope and identifier's declaration chain
6396 // once a Sema object is known.
6397 PreloadedDecls.push_back(D);
6398 }
6399 }
6400}
6401
Douglas Gregor95eab172011-07-28 20:55:49 +00006402IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00006403 if (ID == 0)
6404 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006405
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00006406 if (IdentifiersLoaded.empty()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006407 Error("no identifier table in AST file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00006408 return 0;
6409 }
Mike Stump1eb44332009-09-09 15:08:12 +00006410
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00006411 ID -= 1;
6412 if (!IdentifiersLoaded[ID]) {
Douglas Gregor67268d02011-07-20 00:59:32 +00006413 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6414 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006415 ModuleFile *M = I->second;
Douglas Gregor9827a802011-07-29 00:56:45 +00006416 unsigned Index = ID - M->BaseIdentifierID;
6417 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
Douglas Gregord6595a42009-04-25 21:04:17 +00006418
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006419 // All of the strings in the AST file are preceded by a 16-bit length.
6420 // Extract that 16-bit length to avoid having to execute strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00006421 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6422 // unsigned integers. This is important to avoid integer overflow when
6423 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00006424 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00006425 unsigned StrLen = (((unsigned) StrLenPtr[0])
6426 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00006427 IdentifiersLoaded[ID]
Douglas Gregor712f2fc2011-09-09 22:02:16 +00006428 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Sebastian Redlf2f0f032010-07-23 23:49:55 +00006429 if (DeserializationListener)
6430 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregorafaf3082009-04-11 00:14:32 +00006431 }
Mike Stump1eb44332009-09-09 15:08:12 +00006432
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00006433 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00006434}
6435
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006436IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
Douglas Gregor95eab172011-07-28 20:55:49 +00006437 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
6438}
6439
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006440IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
Douglas Gregor6ec60e02011-08-03 21:49:18 +00006441 if (LocalID < NUM_PREDEF_IDENT_IDS)
6442 return LocalID;
6443
6444 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6445 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6446 assert(I != M.IdentifierRemap.end()
6447 && "Invalid index into identifier index remap");
6448
6449 return LocalID + I->second;
Douglas Gregor95eab172011-07-28 20:55:49 +00006450}
6451
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00006452MacroInfo *ASTReader::getMacro(MacroID ID, MacroInfo *Hint) {
Douglas Gregora8235d62012-10-09 23:05:51 +00006453 if (ID == 0)
6454 return 0;
6455
6456 if (MacrosLoaded.empty()) {
6457 Error("no macro table in AST file");
6458 return 0;
6459 }
6460
6461 ID -= NUM_PREDEF_MACRO_IDS;
6462 if (!MacrosLoaded[ID]) {
6463 GlobalMacroMapType::iterator I
6464 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6465 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6466 ModuleFile *M = I->second;
6467 unsigned Index = ID - M->BaseMacroID;
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00006468 ReadMacroRecord(*M, M->MacroOffsets[Index], Hint);
Douglas Gregora8235d62012-10-09 23:05:51 +00006469 }
6470
6471 return MacrosLoaded[ID];
6472}
6473
6474MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6475 if (LocalID < NUM_PREDEF_MACRO_IDS)
6476 return LocalID;
6477
6478 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6479 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6480 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6481
6482 return LocalID + I->second;
6483}
6484
Douglas Gregor26ced122011-12-01 00:59:36 +00006485serialization::SubmoduleID
6486ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6487 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6488 return LocalID;
6489
6490 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6491 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6492 assert(I != M.SubmoduleRemap.end()
Douglas Gregora8235d62012-10-09 23:05:51 +00006493 && "Invalid index into submodule index remap");
Douglas Gregor26ced122011-12-01 00:59:36 +00006494
6495 return LocalID + I->second;
6496}
6497
6498Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6499 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6500 assert(GlobalID == 0 && "Unhandled global submodule ID");
6501 return 0;
6502 }
6503
6504 if (GlobalID > SubmodulesLoaded.size()) {
6505 Error("submodule ID out of range in AST file");
6506 return 0;
6507 }
6508
6509 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6510}
6511
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006512Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
Douglas Gregor2d2689a2011-07-28 21:16:51 +00006513 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6514}
6515
6516Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
Steve Naroff90cd1bb2009-04-23 10:39:46 +00006517 if (ID == 0)
6518 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00006519
Sebastian Redl725cd962010-08-04 20:40:17 +00006520 if (ID > SelectorsLoaded.size()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006521 Error("selector ID out of range in AST file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00006522 return Selector();
6523 }
Douglas Gregor83941df2009-04-25 17:48:32 +00006524
Sebastian Redl725cd962010-08-04 20:40:17 +00006525 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
Douglas Gregor83941df2009-04-25 17:48:32 +00006526 // Load this selector from the selector table.
Douglas Gregor96958cb2011-07-20 01:10:58 +00006527 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6528 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006529 ModuleFile &M = *I->second;
Douglas Gregor9827a802011-07-29 00:56:45 +00006530 ASTSelectorLookupTrait Trait(*this, M);
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00006531 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
Douglas Gregor96958cb2011-07-20 01:10:58 +00006532 SelectorsLoaded[ID - 1] =
Douglas Gregor9827a802011-07-29 00:56:45 +00006533 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
Douglas Gregor96958cb2011-07-20 01:10:58 +00006534 if (DeserializationListener)
6535 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
Douglas Gregor83941df2009-04-25 17:48:32 +00006536 }
6537
Sebastian Redl725cd962010-08-04 20:40:17 +00006538 return SelectorsLoaded[ID - 1];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00006539}
6540
Douglas Gregor8451ec72011-07-28 14:41:43 +00006541Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00006542 return DecodeSelector(ID);
6543}
6544
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006545uint32_t ASTReader::GetNumExternalSelectors() {
Sebastian Redl725cd962010-08-04 20:40:17 +00006546 // ID 0 (the null selector) is considered an external selector.
6547 return getTotalNumSelectors() + 1;
Douglas Gregor719770d2010-04-06 17:30:22 +00006548}
6549
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00006550serialization::SelectorID
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006551ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00006552 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6553 return LocalID;
6554
6555 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6556 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6557 assert(I != M.SelectorRemap.end()
Douglas Gregora8235d62012-10-09 23:05:51 +00006558 && "Invalid index into selector index remap");
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00006559
6560 return LocalID + I->second;
Douglas Gregor8451ec72011-07-28 14:41:43 +00006561}
6562
Mike Stump1eb44332009-09-09 15:08:12 +00006563DeclarationName
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006564ASTReader::ReadDeclarationName(ModuleFile &F,
Douglas Gregor393f2492011-07-22 00:38:23 +00006565 const RecordData &Record, unsigned &Idx) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00006566 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6567 switch (Kind) {
6568 case DeclarationName::Identifier:
Douglas Gregor95eab172011-07-28 20:55:49 +00006569 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006570
6571 case DeclarationName::ObjCZeroArgSelector:
6572 case DeclarationName::ObjCOneArgSelector:
6573 case DeclarationName::ObjCMultiArgSelector:
Douglas Gregor2d2689a2011-07-28 21:16:51 +00006574 return DeclarationName(ReadSelector(F, Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006575
6576 case DeclarationName::CXXConstructorName:
Douglas Gregor35942772011-09-09 21:34:22 +00006577 return Context.DeclarationNames.getCXXConstructorName(
6578 Context.getCanonicalType(readType(F, Record, Idx)));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006579
6580 case DeclarationName::CXXDestructorName:
Douglas Gregor35942772011-09-09 21:34:22 +00006581 return Context.DeclarationNames.getCXXDestructorName(
6582 Context.getCanonicalType(readType(F, Record, Idx)));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006583
6584 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor35942772011-09-09 21:34:22 +00006585 return Context.DeclarationNames.getCXXConversionFunctionName(
6586 Context.getCanonicalType(readType(F, Record, Idx)));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006587
6588 case DeclarationName::CXXOperatorName:
Douglas Gregor35942772011-09-09 21:34:22 +00006589 return Context.DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00006590 (OverloadedOperatorKind)Record[Idx++]);
6591
Sean Hunt3e518bd2009-11-29 07:34:05 +00006592 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregor35942772011-09-09 21:34:22 +00006593 return Context.DeclarationNames.getCXXLiteralOperatorName(
Douglas Gregor95eab172011-07-28 20:55:49 +00006594 GetIdentifierInfo(F, Record, Idx));
Sean Hunt3e518bd2009-11-29 07:34:05 +00006595
Douglas Gregor2cf26342009-04-09 22:27:44 +00006596 case DeclarationName::CXXUsingDirective:
6597 return DeclarationName::getUsingDirectiveName();
6598 }
6599
David Blaikie7530c032012-01-17 06:56:22 +00006600 llvm_unreachable("Invalid NameKind!");
Douglas Gregor2cf26342009-04-09 22:27:44 +00006601}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00006602
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006603void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006604 DeclarationNameLoc &DNLoc,
6605 DeclarationName Name,
6606 const RecordData &Record, unsigned &Idx) {
6607 switch (Name.getNameKind()) {
6608 case DeclarationName::CXXConstructorName:
6609 case DeclarationName::CXXDestructorName:
6610 case DeclarationName::CXXConversionFunctionName:
6611 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6612 break;
6613
6614 case DeclarationName::CXXOperatorName:
6615 DNLoc.CXXOperatorName.BeginOpNameLoc
6616 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6617 DNLoc.CXXOperatorName.EndOpNameLoc
6618 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6619 break;
6620
6621 case DeclarationName::CXXLiteralOperatorName:
6622 DNLoc.CXXLiteralOperatorName.OpNameLoc
6623 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6624 break;
6625
6626 case DeclarationName::Identifier:
6627 case DeclarationName::ObjCZeroArgSelector:
6628 case DeclarationName::ObjCOneArgSelector:
6629 case DeclarationName::ObjCMultiArgSelector:
6630 case DeclarationName::CXXUsingDirective:
6631 break;
6632 }
6633}
6634
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006635void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006636 DeclarationNameInfo &NameInfo,
6637 const RecordData &Record, unsigned &Idx) {
Douglas Gregor393f2492011-07-22 00:38:23 +00006638 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006639 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6640 DeclarationNameLoc DNLoc;
6641 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6642 NameInfo.setInfo(DNLoc);
6643}
6644
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006645void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006646 const RecordData &Record, unsigned &Idx) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00006647 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006648 unsigned NumTPLists = Record[Idx++];
6649 Info.NumTemplParamLists = NumTPLists;
6650 if (NumTPLists) {
Douglas Gregor35942772011-09-09 21:34:22 +00006651 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006652 for (unsigned i=0; i != NumTPLists; ++i)
6653 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6654 }
6655}
6656
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006657TemplateName
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006658ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006659 unsigned &Idx) {
Michael J. Spencer20249a12010-10-21 03:16:25 +00006660 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006661 switch (Kind) {
6662 case TemplateName::Template:
Douglas Gregor409448c2011-07-21 22:35:25 +00006663 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006664
6665 case TemplateName::OverloadedTemplate: {
6666 unsigned size = Record[Idx++];
6667 UnresolvedSet<8> Decls;
6668 while (size--)
Douglas Gregor409448c2011-07-21 22:35:25 +00006669 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006670
Douglas Gregor35942772011-09-09 21:34:22 +00006671 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006672 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006673
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006674 case TemplateName::QualifiedTemplate: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006675 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006676 bool hasTemplKeyword = Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00006677 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006678 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006679 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006680
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006681 case TemplateName::DependentTemplate: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006682 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006683 if (Record[Idx++]) // isIdentifier
Douglas Gregor35942772011-09-09 21:34:22 +00006684 return Context.getDependentTemplateName(NNS,
Douglas Gregor95eab172011-07-28 20:55:49 +00006685 GetIdentifierInfo(F, Record,
6686 Idx));
Douglas Gregor35942772011-09-09 21:34:22 +00006687 return Context.getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00006688 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006689 }
John McCall14606042011-06-30 08:33:18 +00006690
6691 case TemplateName::SubstTemplateTemplateParm: {
6692 TemplateTemplateParmDecl *param
Douglas Gregor409448c2011-07-21 22:35:25 +00006693 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
John McCall14606042011-06-30 08:33:18 +00006694 if (!param) return TemplateName();
6695 TemplateName replacement = ReadTemplateName(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006696 return Context.getSubstTemplateTemplateParm(param, replacement);
John McCall14606042011-06-30 08:33:18 +00006697 }
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006698
6699 case TemplateName::SubstTemplateTemplateParmPack: {
6700 TemplateTemplateParmDecl *Param
Douglas Gregor409448c2011-07-21 22:35:25 +00006701 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006702 if (!Param)
6703 return TemplateName();
6704
6705 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6706 if (ArgPack.getKind() != TemplateArgument::Pack)
6707 return TemplateName();
6708
Douglas Gregor35942772011-09-09 21:34:22 +00006709 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006710 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006711 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006712
David Blaikieb219cfc2011-09-23 05:06:16 +00006713 llvm_unreachable("Unhandled template name kind!");
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006714}
6715
6716TemplateArgument
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006717ASTReader::ReadTemplateArgument(ModuleFile &F,
Sebastian Redl577d4792010-07-22 22:43:28 +00006718 const RecordData &Record, unsigned &Idx) {
Douglas Gregora7fc9012011-01-05 18:58:31 +00006719 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6720 switch (Kind) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006721 case TemplateArgument::Null:
6722 return TemplateArgument();
6723 case TemplateArgument::Type:
Douglas Gregor393f2492011-07-22 00:38:23 +00006724 return TemplateArgument(readType(F, Record, Idx));
Eli Friedmand7a6b162012-09-26 02:36:12 +00006725 case TemplateArgument::Declaration: {
6726 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6727 bool ForReferenceParam = Record[Idx++];
6728 return TemplateArgument(D, ForReferenceParam);
6729 }
6730 case TemplateArgument::NullPtr:
6731 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00006732 case TemplateArgument::Integral: {
6733 llvm::APSInt Value = ReadAPSInt(Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00006734 QualType T = readType(F, Record, Idx);
Benjamin Kramer85524372012-06-07 15:09:51 +00006735 return TemplateArgument(Context, Value, T);
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00006736 }
Douglas Gregora7fc9012011-01-05 18:58:31 +00006737 case TemplateArgument::Template:
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006738 return TemplateArgument(ReadTemplateName(F, Record, Idx));
Douglas Gregora7fc9012011-01-05 18:58:31 +00006739 case TemplateArgument::TemplateExpansion: {
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006740 TemplateName Name = ReadTemplateName(F, Record, Idx);
Douglas Gregor2be29f42011-01-14 23:41:42 +00006741 llvm::Optional<unsigned> NumTemplateExpansions;
6742 if (unsigned NumExpansions = Record[Idx++])
6743 NumTemplateExpansions = NumExpansions - 1;
6744 return TemplateArgument(Name, NumTemplateExpansions);
Douglas Gregorba68eca2011-01-05 17:40:24 +00006745 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006746 case TemplateArgument::Expression:
Sebastian Redlc3632732010-10-05 15:59:54 +00006747 return TemplateArgument(ReadExpr(F));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006748 case TemplateArgument::Pack: {
6749 unsigned NumArgs = Record[Idx++];
Douglas Gregor35942772011-09-09 21:34:22 +00006750 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Douglas Gregor910f8002010-11-07 23:05:16 +00006751 for (unsigned I = 0; I != NumArgs; ++I)
6752 Args[I] = ReadTemplateArgument(F, Record, Idx);
6753 return TemplateArgument(Args, NumArgs);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006754 }
6755 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006756
David Blaikieb219cfc2011-09-23 05:06:16 +00006757 llvm_unreachable("Unhandled template argument kind!");
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006758}
6759
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006760TemplateParameterList *
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006761ASTReader::ReadTemplateParameterList(ModuleFile &F,
Sebastian Redlc3632732010-10-05 15:59:54 +00006762 const RecordData &Record, unsigned &Idx) {
6763 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6764 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6765 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006766
6767 unsigned NumParams = Record[Idx++];
Chris Lattner5f9e2722011-07-23 10:55:15 +00006768 SmallVector<NamedDecl *, 16> Params;
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006769 Params.reserve(NumParams);
6770 while (NumParams--)
Douglas Gregor409448c2011-07-21 22:35:25 +00006771 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
Michael J. Spencer20249a12010-10-21 03:16:25 +00006772
6773 TemplateParameterList* TemplateParams =
Douglas Gregor35942772011-09-09 21:34:22 +00006774 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006775 Params.data(), Params.size(), RAngleLoc);
6776 return TemplateParams;
6777}
6778
6779void
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006780ASTReader::
Chris Lattner5f9e2722011-07-23 10:55:15 +00006781ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006782 ModuleFile &F, const RecordData &Record,
Sebastian Redlc3632732010-10-05 15:59:54 +00006783 unsigned &Idx) {
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006784 unsigned NumTemplateArgs = Record[Idx++];
6785 TemplArgs.reserve(NumTemplateArgs);
6786 while (NumTemplateArgs--)
Sebastian Redlc3632732010-10-05 15:59:54 +00006787 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006788}
6789
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00006790/// \brief Read a UnresolvedSet structure.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006791void ASTReader::ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00006792 const RecordData &Record, unsigned &Idx) {
6793 unsigned NumDecls = Record[Idx++];
6794 while (NumDecls--) {
Douglas Gregor409448c2011-07-21 22:35:25 +00006795 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00006796 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6797 Set.addDecl(D, AS);
6798 }
6799}
6800
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00006801CXXBaseSpecifier
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006802ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
Nick Lewycky56062202010-07-26 16:56:01 +00006803 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00006804 bool isVirtual = static_cast<bool>(Record[Idx++]);
6805 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6806 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006807 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Sebastian Redlc3632732010-10-05 15:59:54 +00006808 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6809 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregorf90b27a2011-01-03 22:36:02 +00006810 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006811 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00006812 EllipsisLoc);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006813 Result.setInheritConstructors(inheritConstructors);
6814 return Result;
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00006815}
6816
Sean Huntcbb67482011-01-08 20:30:50 +00006817std::pair<CXXCtorInitializer **, unsigned>
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006818ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
Sean Huntcbb67482011-01-08 20:30:50 +00006819 unsigned &Idx) {
6820 CXXCtorInitializer **CtorInitializers = 0;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006821 unsigned NumInitializers = Record[Idx++];
6822 if (NumInitializers) {
Sean Huntcbb67482011-01-08 20:30:50 +00006823 CtorInitializers
Douglas Gregor35942772011-09-09 21:34:22 +00006824 = new (Context) CXXCtorInitializer*[NumInitializers];
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006825 for (unsigned i=0; i != NumInitializers; ++i) {
Douglas Gregor76852c22011-11-01 01:16:03 +00006826 TypeSourceInfo *TInfo = 0;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006827 bool IsBaseVirtual = false;
6828 FieldDecl *Member = 0;
Francois Pichet00eb3f92010-12-04 09:14:42 +00006829 IndirectFieldDecl *IndirectMember = 0;
Michael J. Spencer20249a12010-10-21 03:16:25 +00006830
Sean Hunt156b6402011-05-04 01:19:08 +00006831 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6832 switch (Type) {
Douglas Gregor76852c22011-11-01 01:16:03 +00006833 case CTOR_INITIALIZER_BASE:
6834 TInfo = GetTypeSourceInfo(F, Record, Idx);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006835 IsBaseVirtual = Record[Idx++];
Sean Hunt156b6402011-05-04 01:19:08 +00006836 break;
Douglas Gregor76852c22011-11-01 01:16:03 +00006837
6838 case CTOR_INITIALIZER_DELEGATING:
6839 TInfo = GetTypeSourceInfo(F, Record, Idx);
Sean Hunt156b6402011-05-04 01:19:08 +00006840 break;
6841
6842 case CTOR_INITIALIZER_MEMBER:
Douglas Gregor409448c2011-07-21 22:35:25 +00006843 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
Sean Hunt156b6402011-05-04 01:19:08 +00006844 break;
6845
6846 case CTOR_INITIALIZER_INDIRECT_MEMBER:
Douglas Gregor409448c2011-07-21 22:35:25 +00006847 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
Sean Hunt156b6402011-05-04 01:19:08 +00006848 break;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006849 }
Sean Hunt156b6402011-05-04 01:19:08 +00006850
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00006851 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
Sebastian Redlc3632732010-10-05 15:59:54 +00006852 Expr *Init = ReadExpr(F);
Sebastian Redlc3632732010-10-05 15:59:54 +00006853 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6854 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006855 bool IsWritten = Record[Idx++];
6856 unsigned SourceOrderOrNumArrayIndices;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006857 SmallVector<VarDecl *, 8> Indices;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006858 if (IsWritten) {
6859 SourceOrderOrNumArrayIndices = Record[Idx++];
6860 } else {
6861 SourceOrderOrNumArrayIndices = Record[Idx++];
6862 Indices.reserve(SourceOrderOrNumArrayIndices);
6863 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
Douglas Gregor409448c2011-07-21 22:35:25 +00006864 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006865 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006866
Sean Huntcbb67482011-01-08 20:30:50 +00006867 CXXCtorInitializer *BOMInit;
Sean Hunt156b6402011-05-04 01:19:08 +00006868 if (Type == CTOR_INITIALIZER_BASE) {
Douglas Gregor76852c22011-11-01 01:16:03 +00006869 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
Sean Huntcbb67482011-01-08 20:30:50 +00006870 LParenLoc, Init, RParenLoc,
6871 MemberOrEllipsisLoc);
Sean Hunt156b6402011-05-04 01:19:08 +00006872 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
Douglas Gregor76852c22011-11-01 01:16:03 +00006873 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6874 Init, RParenLoc);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006875 } else if (IsWritten) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00006876 if (Member)
Douglas Gregor35942772011-09-09 21:34:22 +00006877 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
Sean Huntcbb67482011-01-08 20:30:50 +00006878 LParenLoc, Init, RParenLoc);
Francois Pichet00eb3f92010-12-04 09:14:42 +00006879 else
Douglas Gregor35942772011-09-09 21:34:22 +00006880 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
Sean Huntcbb67482011-01-08 20:30:50 +00006881 MemberOrEllipsisLoc, LParenLoc,
6882 Init, RParenLoc);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006883 } else {
Douglas Gregor35942772011-09-09 21:34:22 +00006884 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
Sean Huntcbb67482011-01-08 20:30:50 +00006885 LParenLoc, Init, RParenLoc,
6886 Indices.data(), Indices.size());
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006887 }
6888
Argyrios Kyrtzidisf84cde12010-09-06 19:04:27 +00006889 if (IsWritten)
6890 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
Sean Huntcbb67482011-01-08 20:30:50 +00006891 CtorInitializers[i] = BOMInit;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006892 }
6893 }
6894
Sean Huntcbb67482011-01-08 20:30:50 +00006895 return std::make_pair(CtorInitializers, NumInitializers);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006896}
6897
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006898NestedNameSpecifier *
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006899ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
Douglas Gregor409448c2011-07-21 22:35:25 +00006900 const RecordData &Record, unsigned &Idx) {
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006901 unsigned N = Record[Idx++];
6902 NestedNameSpecifier *NNS = 0, *Prev = 0;
6903 for (unsigned I = 0; I != N; ++I) {
6904 NestedNameSpecifier::SpecifierKind Kind
6905 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6906 switch (Kind) {
6907 case NestedNameSpecifier::Identifier: {
Douglas Gregor95eab172011-07-28 20:55:49 +00006908 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006909 NNS = NestedNameSpecifier::Create(Context, Prev, II);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006910 break;
6911 }
6912
6913 case NestedNameSpecifier::Namespace: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006914 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006915 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006916 break;
6917 }
6918
Douglas Gregor14aba762011-02-24 02:36:08 +00006919 case NestedNameSpecifier::NamespaceAlias: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006920 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006921 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
Douglas Gregor14aba762011-02-24 02:36:08 +00006922 break;
6923 }
6924
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006925 case NestedNameSpecifier::TypeSpec:
6926 case NestedNameSpecifier::TypeSpecWithTemplate: {
Douglas Gregor393f2492011-07-22 00:38:23 +00006927 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
Douglas Gregor1ab55e92010-12-10 17:03:06 +00006928 if (!T)
6929 return 0;
6930
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006931 bool Template = Record[Idx++];
Douglas Gregor35942772011-09-09 21:34:22 +00006932 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006933 break;
6934 }
6935
6936 case NestedNameSpecifier::Global: {
Douglas Gregor35942772011-09-09 21:34:22 +00006937 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006938 // No associated value, and there can't be a prefix.
6939 break;
6940 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006941 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00006942 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006943 }
6944 return NNS;
6945}
6946
Douglas Gregordc355712011-02-25 00:36:19 +00006947NestedNameSpecifierLoc
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006948ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Douglas Gregordc355712011-02-25 00:36:19 +00006949 unsigned &Idx) {
6950 unsigned N = Record[Idx++];
Douglas Gregor5f791bb2011-02-28 23:58:31 +00006951 NestedNameSpecifierLocBuilder Builder;
Douglas Gregordc355712011-02-25 00:36:19 +00006952 for (unsigned I = 0; I != N; ++I) {
6953 NestedNameSpecifier::SpecifierKind Kind
6954 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6955 switch (Kind) {
6956 case NestedNameSpecifier::Identifier: {
Douglas Gregor95eab172011-07-28 20:55:49 +00006957 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Douglas Gregordc355712011-02-25 00:36:19 +00006958 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006959 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
Douglas Gregordc355712011-02-25 00:36:19 +00006960 break;
6961 }
6962
6963 case NestedNameSpecifier::Namespace: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006964 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Douglas Gregordc355712011-02-25 00:36:19 +00006965 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006966 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
Douglas Gregordc355712011-02-25 00:36:19 +00006967 break;
6968 }
6969
6970 case NestedNameSpecifier::NamespaceAlias: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006971 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Douglas Gregordc355712011-02-25 00:36:19 +00006972 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006973 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
Douglas Gregordc355712011-02-25 00:36:19 +00006974 break;
6975 }
6976
6977 case NestedNameSpecifier::TypeSpec:
6978 case NestedNameSpecifier::TypeSpecWithTemplate: {
Douglas Gregordc355712011-02-25 00:36:19 +00006979 bool Template = Record[Idx++];
6980 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
6981 if (!T)
6982 return NestedNameSpecifierLoc();
Douglas Gregordc355712011-02-25 00:36:19 +00006983 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
Douglas Gregor5f791bb2011-02-28 23:58:31 +00006984
6985 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
Douglas Gregor35942772011-09-09 21:34:22 +00006986 Builder.Extend(Context,
Douglas Gregor5f791bb2011-02-28 23:58:31 +00006987 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
6988 T->getTypeLoc(), ColonColonLoc);
Douglas Gregordc355712011-02-25 00:36:19 +00006989 break;
6990 }
6991
6992 case NestedNameSpecifier::Global: {
Douglas Gregordc355712011-02-25 00:36:19 +00006993 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006994 Builder.MakeGlobal(Context, ColonColonLoc);
Douglas Gregordc355712011-02-25 00:36:19 +00006995 break;
6996 }
6997 }
Douglas Gregordc355712011-02-25 00:36:19 +00006998 }
6999
Douglas Gregor35942772011-09-09 21:34:22 +00007000 return Builder.getWithLocInContext(Context);
Douglas Gregordc355712011-02-25 00:36:19 +00007001}
7002
Chris Lattner6ad9ac02010-05-07 21:43:38 +00007003SourceRange
Douglas Gregor1a4761e2011-11-30 23:21:26 +00007004ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
Sebastian Redlc3632732010-10-05 15:59:54 +00007005 unsigned &Idx) {
7006 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7007 SourceLocation end = ReadSourceLocation(F, Record, Idx);
Daniel Dunbar8ee59392010-06-02 15:47:10 +00007008 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00007009}
7010
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00007011/// \brief Read an integral value
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007012llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00007013 unsigned BitWidth = Record[Idx++];
7014 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7015 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7016 Idx += NumWords;
7017 return Result;
7018}
7019
7020/// \brief Read a signed integral value
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007021llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00007022 bool isUnsigned = Record[Idx++];
7023 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7024}
7025
Douglas Gregor17fc2232009-04-14 21:55:33 +00007026/// \brief Read a floating-point value
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007027llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00007028 return llvm::APFloat(ReadAPInt(Record, Idx));
7029}
7030
Douglas Gregor68a2eb02009-04-15 21:30:51 +00007031// \brief Read a string
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007032std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
Douglas Gregor68a2eb02009-04-15 21:30:51 +00007033 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00007034 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00007035 Idx += Len;
7036 return Result;
7037}
7038
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00007039VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7040 unsigned &Idx) {
7041 unsigned Major = Record[Idx++];
7042 unsigned Minor = Record[Idx++];
7043 unsigned Subminor = Record[Idx++];
7044 if (Minor == 0)
7045 return VersionTuple(Major);
7046 if (Subminor == 0)
7047 return VersionTuple(Major, Minor - 1);
7048 return VersionTuple(Major, Minor - 1, Subminor - 1);
7049}
7050
Douglas Gregor1a4761e2011-11-30 23:21:26 +00007051CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Douglas Gregor409448c2011-07-21 22:35:25 +00007052 const RecordData &Record,
Chris Lattnerd2598362010-05-10 00:25:06 +00007053 unsigned &Idx) {
Douglas Gregor409448c2011-07-21 22:35:25 +00007054 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00007055 return CXXTemporary::Create(Context, Decl);
Chris Lattnerd2598362010-05-10 00:25:06 +00007056}
7057
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007058DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00007059 return Diag(SourceLocation(), DiagID);
7060}
7061
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007062DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00007063 return Diags.Report(Loc, DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00007064}
Douglas Gregor025452f2009-04-17 00:04:06 +00007065
Douglas Gregor668c1a42009-04-21 22:25:48 +00007066/// \brief Retrieve the identifier table associated with the
7067/// preprocessor.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007068IdentifierTable &ASTReader::getIdentifierTable() {
Douglas Gregor712f2fc2011-09-09 22:02:16 +00007069 return PP.getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00007070}
7071
Douglas Gregor025452f2009-04-17 00:04:06 +00007072/// \brief Record that the given ID maps to the given switch-case
7073/// statement.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007074void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Argyrios Kyrtzidisb88acb02012-05-04 01:49:36 +00007075 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7076 "Already have a SwitchCase with this ID");
7077 (*CurrSwitchCaseStmts)[ID] = SC;
Douglas Gregor025452f2009-04-17 00:04:06 +00007078}
7079
7080/// \brief Retrieve the switch-case statement with the given ID.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007081SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Argyrios Kyrtzidisb88acb02012-05-04 01:49:36 +00007082 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7083 return (*CurrSwitchCaseStmts)[ID];
Douglas Gregor025452f2009-04-17 00:04:06 +00007084}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00007085
Argyrios Kyrtzidise09a2752010-10-28 09:29:32 +00007086void ASTReader::ClearSwitchCaseIDs() {
Argyrios Kyrtzidisb88acb02012-05-04 01:49:36 +00007087 CurrSwitchCaseStmts->clear();
Argyrios Kyrtzidise09a2752010-10-28 09:29:32 +00007088}
7089
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00007090void ASTReader::ReadComments() {
Dmitri Gribenko811c8202012-07-06 18:19:34 +00007091 std::vector<RawComment *> Comments;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00007092 for (SmallVectorImpl<std::pair<llvm::BitstreamCursor,
7093 serialization::ModuleFile *> >::iterator
7094 I = CommentsCursors.begin(),
7095 E = CommentsCursors.end();
7096 I != E; ++I) {
7097 llvm::BitstreamCursor &Cursor = I->first;
7098 serialization::ModuleFile &F = *I->second;
7099 SavedStreamPosition SavedPosition(Cursor);
7100
7101 RecordData Record;
7102 while (true) {
7103 unsigned Code = Cursor.ReadCode();
7104 if (Code == llvm::bitc::END_BLOCK)
7105 break;
7106
7107 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
7108 // No known subblocks, always skip them.
7109 Cursor.ReadSubBlockID();
7110 if (Cursor.SkipBlock()) {
7111 Error("malformed block record in AST file");
7112 return;
7113 }
7114 continue;
7115 }
7116
7117 if (Code == llvm::bitc::DEFINE_ABBREV) {
7118 Cursor.ReadAbbrevRecord();
7119 continue;
7120 }
7121
7122 // Read a record.
7123 Record.clear();
7124 switch ((CommentRecordTypes) Cursor.ReadRecord(Code, Record)) {
Chandler Carruth13691bb2012-06-20 06:47:54 +00007125 case COMMENTS_RAW_COMMENT: {
7126 unsigned Idx = 0;
7127 SourceRange SR = ReadSourceRange(F, Record, Idx);
7128 RawComment::CommentKind Kind =
7129 (RawComment::CommentKind) Record[Idx++];
7130 bool IsTrailingComment = Record[Idx++];
7131 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenko811c8202012-07-06 18:19:34 +00007132 Comments.push_back(new (Context) RawComment(SR, Kind,
7133 IsTrailingComment,
7134 IsAlmostTrailingComment));
Chandler Carruth13691bb2012-06-20 06:47:54 +00007135 break;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00007136 }
7137 }
7138 }
7139 }
7140 Context.Comments.addCommentsToFront(Comments);
7141}
7142
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007143void ASTReader::finishPendingActions() {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00007144 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
7145 !PendingMacroIDs.empty()) {
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007146 // If any identifiers with corresponding top-level declarations have
7147 // been loaded, load those declarations now.
7148 while (!PendingIdentifierInfos.empty()) {
7149 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
7150 PendingIdentifierInfos.front().DeclIDs, true);
7151 PendingIdentifierInfos.pop_front();
7152 }
7153
Douglas Gregora1be2782011-12-17 23:38:30 +00007154 // Load pending declaration chains.
7155 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7156 loadPendingDeclChain(PendingDeclChains[I]);
Douglas Gregor56ca8a92012-01-17 19:21:53 +00007157 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Douglas Gregora1be2782011-12-17 23:38:30 +00007158 }
7159 PendingDeclChains.clear();
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00007160
7161 // Load any pending macro definitions.
Douglas Gregore9652bf2012-10-11 17:31:34 +00007162 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
7163 // FIXME: std::move here
7164 SmallVector<MacroID, 2> GlobalIDs = PendingMacroIDs.begin()[I].second;
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00007165 MacroInfo *Hint = 0;
Douglas Gregore9652bf2012-10-11 17:31:34 +00007166 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7167 ++IDIdx) {
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00007168 Hint = getMacro(GlobalIDs[IDIdx], Hint);
Douglas Gregore9652bf2012-10-11 17:31:34 +00007169 }
7170 }
7171 PendingMacroIDs.clear();
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007172 }
Douglas Gregorfc529f72011-12-19 19:00:47 +00007173
Douglas Gregor7c99bb5c2012-01-14 15:13:49 +00007174 // If we deserialized any C++ or Objective-C class definitions, any
7175 // Objective-C protocol definitions, or any redeclarable templates, make sure
7176 // that all redeclarations point to the definitions. Note that this can only
7177 // happen now, after the redeclaration chains have been fully wired.
Douglas Gregorfc529f72011-12-19 19:00:47 +00007178 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7179 DEnd = PendingDefinitions.end();
7180 D != DEnd; ++D) {
Douglas Gregor56ca8a92012-01-17 19:21:53 +00007181 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7182 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7183 // Make sure that the TagType points at the definition.
7184 const_cast<TagType*>(TagT)->decl = TD;
7185 }
Douglas Gregorfc529f72011-12-19 19:00:47 +00007186
Douglas Gregor56ca8a92012-01-17 19:21:53 +00007187 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7188 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7189 REnd = RD->redecls_end();
7190 R != REnd; ++R)
7191 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7192
7193 }
7194
Douglas Gregorfc529f72011-12-19 19:00:47 +00007195 continue;
7196 }
7197
Douglas Gregor1d784b22012-01-01 19:51:50 +00007198 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Douglas Gregor56ca8a92012-01-17 19:21:53 +00007199 // Make sure that the ObjCInterfaceType points at the definition.
7200 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7201 ->Decl = ID;
7202
Douglas Gregor1d784b22012-01-01 19:51:50 +00007203 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7204 REnd = ID->redecls_end();
7205 R != REnd; ++R)
7206 R->Data = ID->Data;
7207
7208 continue;
7209 }
7210
Douglas Gregor7c99bb5c2012-01-14 15:13:49 +00007211 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7212 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7213 REnd = PD->redecls_end();
7214 R != REnd; ++R)
7215 R->Data = PD->Data;
7216
7217 continue;
7218 }
7219
7220 RedeclarableTemplateDecl *RTD
7221 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7222 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7223 REnd = RTD->redecls_end();
Douglas Gregorfc529f72011-12-19 19:00:47 +00007224 R != REnd; ++R)
Douglas Gregor5456b0fe2012-10-09 17:21:28 +00007225 R->Common = RTD->Common;
Douglas Gregorfc529f72011-12-19 19:00:47 +00007226 }
7227 PendingDefinitions.clear();
Douglas Gregor5456b0fe2012-10-09 17:21:28 +00007228
7229 // Load the bodies of any functions or methods we've encountered. We do
7230 // this now (delayed) so that we can be sure that the declaration chains
7231 // have been fully wired up.
Douglas Gregorce12d2f2012-10-09 17:50:23 +00007232 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7233 PBEnd = PendingBodies.end();
Douglas Gregor5456b0fe2012-10-09 17:21:28 +00007234 PB != PBEnd; ++PB) {
7235 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7236 // FIXME: Check for =delete/=default?
7237 // FIXME: Complain about ODR violations here?
7238 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7239 FD->setLazyBody(PB->second);
7240 continue;
7241 }
7242
7243 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7244 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7245 MD->setLazyBody(PB->second);
7246 }
7247 PendingBodies.clear();
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007248}
7249
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007250void ASTReader::FinishedDeserializing() {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00007251 assert(NumCurrentElementsDeserializing &&
7252 "FinishedDeserializing not paired with StartedDeserializing");
7253 if (NumCurrentElementsDeserializing == 1) {
Argyrios Kyrtzidis44d2dbd2012-02-09 07:31:52 +00007254 // We decrease NumCurrentElementsDeserializing only after pending actions
7255 // are finished, to avoid recursively re-calling finishPendingActions().
7256 finishPendingActions();
7257 }
7258 --NumCurrentElementsDeserializing;
Argyrios Kyrtzidis71168332011-12-17 04:13:28 +00007259
Argyrios Kyrtzidis44d2dbd2012-02-09 07:31:52 +00007260 if (NumCurrentElementsDeserializing == 0 &&
7261 Consumer && !PassingDeclsToConsumer) {
7262 // Guard variable to avoid recursively redoing the process of passing
7263 // decls to consumer.
7264 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7265 true);
Argyrios Kyrtzidis71168332011-12-17 04:13:28 +00007266
Argyrios Kyrtzidis44d2dbd2012-02-09 07:31:52 +00007267 while (!InterestingDecls.empty()) {
Argyrios Kyrtzidis8d39c3d2011-11-30 23:18:26 +00007268 // We are not in recursive loading, so it's safe to pass the "interesting"
7269 // decls to the consumer.
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007270 Decl *D = InterestingDecls.front();
7271 InterestingDecls.pop_front();
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007272 PassInterestingDeclToConsumer(D);
7273 }
Douglas Gregord89275b2009-07-06 18:54:52 +00007274 }
Douglas Gregord89275b2009-07-06 18:54:52 +00007275}
Douglas Gregor501c1032010-08-19 00:28:17 +00007276
Douglas Gregorf8a1e512011-09-02 00:26:20 +00007277ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Douglas Gregor832d6202011-07-22 16:35:34 +00007278 StringRef isysroot, bool DisableValidation,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00007279 bool DisableStatCache, bool AllowASTWithCompilerErrors)
Sebastian Redle1dde812010-08-24 00:50:04 +00007280 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7281 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
Douglas Gregor712f2fc2011-09-09 22:02:16 +00007282 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +00007283 Consumer(0), ModuleMgr(PP.getFileManager()),
Douglas Gregorcaed0602012-10-18 21:31:35 +00007284 isysroot(isysroot), DisableValidation(DisableValidation),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00007285 DisableStatCache(DisableStatCache),
7286 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Argyrios Kyrtzidisb88acb02012-05-04 01:49:36 +00007287 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7288 NumStatHits(0), NumStatMisses(0),
Douglas Gregorf62d43d2011-07-19 16:10:42 +00007289 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00007290 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7291 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
7292 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
7293 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
Jonathan D. Turner1da90142011-07-21 21:15:19 +00007294 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7295 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Argyrios Kyrtzidis44d2dbd2012-02-09 07:31:52 +00007296 PassingDeclsToConsumer(false),
Jonathan D. Turner1da90142011-07-21 21:15:19 +00007297 NumCXXBaseSpecifiersLoaded(0)
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00007298{
Douglas Gregorf62d43d2011-07-19 16:10:42 +00007299 SourceMgr.setExternalSLocEntrySource(this);
Sebastian Redle1dde812010-08-24 00:50:04 +00007300}
7301
Sebastian Redle1dde812010-08-24 00:50:04 +00007302ASTReader::~ASTReader() {
Sebastian Redle1dde812010-08-24 00:50:04 +00007303 for (DeclContextVisibleUpdatesPending::iterator
7304 I = PendingVisibleUpdates.begin(),
7305 E = PendingVisibleUpdates.end();
7306 I != E; ++I) {
7307 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7308 F = I->second.end();
7309 J != F; ++J)
Benjamin Kramerb1758c62012-04-15 12:36:49 +00007310 delete J->first;
Sebastian Redle1dde812010-08-24 00:50:04 +00007311 }
7312}