blob: 7e768c67fcb10e8ca356daae2baa8b29be64a15f [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,
Douglas Gregor87699242012-10-25 00:07:54 +0000250 DiagnosticsEngine *Diags,
251 FileManager &FileMgr,
252 std::string &SuggestedPredefines) {
Douglas Gregor4c0c7e82012-10-24 23:41:50 +0000253 // Check macro definitions.
254 MacroDefinitionsMap ASTFileMacros;
255 collectMacroDefinitions(PPOpts, ASTFileMacros);
256 MacroDefinitionsMap ExistingMacros;
257 SmallVector<StringRef, 4> ExistingMacroNames;
258 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
259
260 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
261 // Dig out the macro definition in the existing preprocessor options.
262 StringRef MacroName = ExistingMacroNames[I];
263 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
264
265 // Check whether we know anything about this macro name or not.
266 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
267 = ASTFileMacros.find(MacroName);
268 if (Known == ASTFileMacros.end()) {
269 // FIXME: Check whether this identifier was referenced anywhere in the
270 // AST file. If so, we should reject the AST file. Unfortunately, this
271 // information isn't in the control block. What shall we do about it?
Douglas Gregor87699242012-10-25 00:07:54 +0000272
273 if (Existing.second) {
274 SuggestedPredefines += "#undef ";
275 SuggestedPredefines += MacroName.str();
276 SuggestedPredefines += '\n';
277 } else {
278 SuggestedPredefines += "#define ";
279 SuggestedPredefines += MacroName.str();
280 SuggestedPredefines += Existing.first.str();
281 SuggestedPredefines += '\n';
282 }
Douglas Gregor4c0c7e82012-10-24 23:41:50 +0000283 continue;
284 }
285
286 // If the macro was defined in one but undef'd in the other, we have a
287 // conflict.
288 if (Existing.second != Known->second.second) {
289 if (Diags) {
290 Diags->Report(diag::err_pch_macro_def_undef)
291 << MacroName << Known->second.second;
292 }
293 return true;
294 }
295
296 // If the macro was #undef'd in both, or if the macro bodies are identical,
297 // it's fine.
298 if (Existing.second || Existing.first == Known->second.first)
299 continue;
300
301 // The macro bodies differ; complain.
302 if (Diags) {
303 Diags->Report(diag::err_pch_macro_def_conflict)
304 << MacroName << Known->second.first << Existing.first;
305 }
306 return true;
307 }
308
309 // Check whether we're using predefines.
310 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
311 if (Diags) {
312 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
313 }
314 return true;
315 }
316
Douglas Gregor87699242012-10-25 00:07:54 +0000317 // Compute the #include and #include_macros lines we need.
318 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
319 StringRef File = ExistingPPOpts.Includes[I];
320 if (File == ExistingPPOpts.ImplicitPCHInclude)
321 continue;
322
323 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
324 != PPOpts.Includes.end())
325 continue;
326
327 SuggestedPredefines += "#include \"";
328 SuggestedPredefines +=
329 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
330 SuggestedPredefines += "\"\n";
331 }
332
333 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
334 StringRef File = ExistingPPOpts.MacroIncludes[I];
335 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
336 File)
337 != PPOpts.MacroIncludes.end())
338 continue;
339
340 SuggestedPredefines += "#__include_macros \"";
341 SuggestedPredefines +=
342 HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
343 SuggestedPredefines += "\"\n##\n";
344 }
345
Douglas Gregor4c0c7e82012-10-24 23:41:50 +0000346 return false;
347}
348
349bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
Douglas Gregor87699242012-10-25 00:07:54 +0000350 bool Complain,
351 std::string &SuggestedPredefines) {
Douglas Gregor4c0c7e82012-10-24 23:41:50 +0000352 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
353
354 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Douglas Gregor87699242012-10-25 00:07:54 +0000355 Complain? &Reader.Diags : 0,
356 PP.getFileManager(),
357 SuggestedPredefines);
Douglas Gregor4c0c7e82012-10-24 23:41:50 +0000358}
359
360namespace {
Benjamin Kramer54353f42010-11-25 18:29:30 +0000361 struct EmptyStringRef {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000362 bool operator ()(StringRef r) const { return r.empty(); }
Benjamin Kramer54353f42010-11-25 18:29:30 +0000363 };
364 struct EmptyBlock {
365 bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
366 };
367}
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000368
Chris Lattner5f9e2722011-07-23 10:55:15 +0000369static bool EqualConcatenations(SmallVector<StringRef, 2> L,
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000370 PCHPredefinesBlocks R) {
371 // First, sum up the lengths.
372 unsigned LL = 0, RL = 0;
373 for (unsigned I = 0, N = L.size(); I != N; ++I) {
374 LL += L[I].size();
375 }
376 for (unsigned I = 0, N = R.size(); I != N; ++I) {
377 RL += R[I].Data.size();
378 }
379 if (LL != RL)
380 return false;
381 if (LL == 0 && RL == 0)
382 return true;
383
384 // Kick out empty parts, they confuse the algorithm below.
385 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
386 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
387
388 // Do it the hard way. At this point, both vectors must be non-empty.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000389 StringRef LR = L[0], RR = R[0].Data;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000390 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
Daniel Dunbarc76c9e02010-07-16 00:00:11 +0000391 (void) RN;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000392 for (;;) {
393 // Compare the current pieces.
394 if (LR.size() == RR.size()) {
395 // If they're the same length, it's pretty easy.
396 if (LR != RR)
397 return false;
398 // Both pieces are done, advance.
399 ++LI;
400 ++RI;
401 // If either string is done, they're both done, since they're the same
402 // length.
403 if (LI == LN) {
404 assert(RI == RN && "Strings not the same length after all?");
405 return true;
406 }
407 LR = L[LI];
408 RR = R[RI].Data;
409 } else if (LR.size() < RR.size()) {
410 // Right piece is longer.
411 if (!RR.startswith(LR))
412 return false;
413 ++LI;
414 assert(LI != LN && "Strings not the same length after all?");
415 RR = RR.substr(LR.size());
416 LR = L[LI];
417 } else {
418 // Left piece is longer.
419 if (!LR.startswith(RR))
420 return false;
421 ++RI;
422 assert(RI != RN && "Strings not the same length after all?");
423 LR = LR.substr(RR.size());
424 RR = R[RI].Data;
425 }
426 }
427}
428
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429static std::pair<FileID, StringRef::size_type>
430FindMacro(const PCHPredefinesBlocks &Buffers, StringRef MacroDef) {
431 std::pair<FileID, StringRef::size_type> Res;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000432 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
433 Res.second = Buffers[I].Data.find(MacroDef);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000434 if (Res.second != StringRef::npos) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000435 Res.first = Buffers[I].BufferID;
436 break;
437 }
438 }
439 return Res;
440}
441
442bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000443 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000444 std::string &SuggestedPredefines,
Douglas Gregor38295be2012-10-22 23:51:00 +0000445 FileManager &FileMgr,
446 bool Complain) {
Daniel Dunbarc7162932009-11-11 23:58:53 +0000447 // We are in the context of an implicit include, so the predefines buffer will
448 // have a #include entry for the PCH file itself (as normalized by the
449 // preprocessor initialization). Find it and skip over it in the checking
450 // below.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000451 SmallString<256> PCHInclude;
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000452 PCHInclude += "#include \"";
Chandler Carruthcb381ea2011-12-09 01:33:57 +0000453 PCHInclude += HeaderSearch::NormalizeDashIncludePath(OriginalFileName,
454 FileMgr);
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000455 PCHInclude += "\"\n";
Chris Lattner5f9e2722011-07-23 10:55:15 +0000456 std::pair<StringRef,StringRef> Split =
457 StringRef(PP.getPredefines()).split(PCHInclude.str());
458 StringRef Left = Split.first, Right = Split.second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000459 if (Left == PP.getPredefines()) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000460 if (Complain)
461 Error("Missing PCH include entry!");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000462 return true;
463 }
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000464
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000465 // If the concatenation of all the PCH buffers is equal to the adjusted
466 // command line, we're done.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000467 SmallVector<StringRef, 2> CommandLine;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000468 CommandLine.push_back(Left);
469 CommandLine.push_back(Right);
470 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000471 return false;
472
473 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000475 // The predefines buffers are different. Determine what the differences are,
476 // and whether they require us to reject the PCH file.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000477 SmallVector<StringRef, 8> PCHLines;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000478 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
479 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbare6750492009-11-13 16:46:11 +0000480
Chris Lattner5f9e2722011-07-23 10:55:15 +0000481 SmallVector<StringRef, 8> CmdLineLines;
Daniel Dunbare6750492009-11-13 16:46:11 +0000482 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis297c7062010-09-30 16:53:50 +0000483
484 // Pick out implicit #includes after the PCH and don't consider them for
485 // validation; we will insert them into SuggestedPredefines so that the
486 // preprocessor includes them.
487 std::string IncludesAfterPCH;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000488 SmallVector<StringRef, 8> AfterPCHLines;
Argyrios Kyrtzidis297c7062010-09-30 16:53:50 +0000489 Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
490 for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
491 if (AfterPCHLines[i].startswith("#include ")) {
492 IncludesAfterPCH += AfterPCHLines[i];
493 IncludesAfterPCH += '\n';
494 } else {
495 CmdLineLines.push_back(AfterPCHLines[i]);
496 }
497 }
498
499 // Make sure we add the includes last into SuggestedPredefines before we
500 // exit this function.
501 struct AddIncludesRAII {
502 std::string &SuggestedPredefines;
503 std::string &IncludesAfterPCH;
504
505 AddIncludesRAII(std::string &SuggestedPredefines,
506 std::string &IncludesAfterPCH)
507 : SuggestedPredefines(SuggestedPredefines),
508 IncludesAfterPCH(IncludesAfterPCH) { }
509 ~AddIncludesRAII() {
510 SuggestedPredefines += IncludesAfterPCH;
511 }
512 } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000513
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000514 // Sort both sets of predefined buffer lines, since we allow some extra
515 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000516 std::sort(CmdLineLines.begin(), CmdLineLines.end());
517 std::sort(PCHLines.begin(), PCHLines.end());
518
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000519 // Determine which predefines that were used to build the PCH file are missing
520 // from the command line.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000521 std::vector<StringRef> MissingPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000522 std::set_difference(PCHLines.begin(), PCHLines.end(),
523 CmdLineLines.begin(), CmdLineLines.end(),
524 std::back_inserter(MissingPredefines));
525
526 bool MissingDefines = false;
527 bool ConflictingDefines = false;
528 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000529 StringRef Missing = MissingPredefines[I];
Argyrios Kyrtzidis297c7062010-09-30 16:53:50 +0000530 if (Missing.startswith("#include ")) {
531 // An -include was specified when generating the PCH; it is included in
532 // the PCH, just ignore it.
533 continue;
534 }
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000535 if (!Missing.startswith("#define ")) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000536 if (Complain)
537 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000538 return true;
539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000541 // This is a macro definition. Determine the name of the macro we're
542 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000543 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000544 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000545 = Missing.find_first_of("( \n\r", StartOfMacroName);
546 assert(EndOfMacroName != std::string::npos &&
547 "Couldn't find the end of the macro name");
Chris Lattner5f9e2722011-07-23 10:55:15 +0000548 StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000549
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000550 // Determine whether this macro was given a different definition on the
551 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000552 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000553 std::string::size_type MacroDefLen = MacroDefStart.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000554 SmallVector<StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000555 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
556 MacroDefStart);
557 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000558 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000559 // Different macro; we're done.
560 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000561 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000562 }
Mike Stump1eb44332009-09-09 15:08:12 +0000563
564 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000565 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000566 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000567 (*ConflictPos)[MacroDefLen] != '(')
568 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000570 // We found a conflicting macro definition.
571 break;
572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000574 if (ConflictPos != CmdLineLines.end()) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000575 if (!Complain)
576 return true;
577
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000578 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
579 << MacroName;
580
581 // Show the definition of this macro within the PCH file.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000582 std::pair<FileID, StringRef::size_type> MacroLoc =
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000583 FindMacro(Buffers, Missing);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000584 assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000585 SourceLocation PCHMissingLoc =
586 SourceMgr.getLocForStartOfFile(MacroLoc.first)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000587 .getLocWithOffset(MacroLoc.second);
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000588 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000589
590 ConflictingDefines = true;
591 continue;
592 }
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000594 // If the macro doesn't conflict, then we'll just pick up the macro
595 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000596 if (ConflictingDefines)
597 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000599 if (!MissingDefines) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000600 if (!Complain)
601 return true;
602
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000603 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
604 MissingDefines = true;
605 }
606
Douglas Gregor38295be2012-10-22 23:51:00 +0000607 if (!Complain)
608 return true;
609
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000610 // Show the definition of this macro within the PCH file.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000611 std::pair<FileID, StringRef::size_type> MacroLoc =
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000612 FindMacro(Buffers, Missing);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000613 assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000614 SourceLocation PCHMissingLoc =
615 SourceMgr.getLocForStartOfFile(MacroLoc.first)
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000616 .getLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000617 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
618 }
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000620 if (ConflictingDefines)
621 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000623 // Determine what predefines were introduced based on command-line
624 // parameters that were not present when building the PCH
625 // file. Extra #defines are okay, so long as the identifiers being
626 // defined were not used within the precompiled header.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000627 std::vector<StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000628 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
629 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000630 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000631 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000632 StringRef &Extra = ExtraPredefines[I];
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000633 if (!Extra.startswith("#define ")) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000634 if (Complain)
635 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000636 return true;
637 }
638
639 // This is an extra macro definition. Determine the name of the
640 // macro we're defining.
641 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000642 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000643 = Extra.find_first_of("( \n\r", StartOfMacroName);
644 assert(EndOfMacroName != std::string::npos &&
645 "Couldn't find the end of the macro name");
Chris Lattner5f9e2722011-07-23 10:55:15 +0000646 StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000647
648 // Check whether this name was used somewhere in the PCH file. If
649 // so, defining it as a macro could change behavior, so we reject
650 // the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000651 if (IdentifierInfo *II = Reader.get(MacroName)) {
Douglas Gregor38295be2012-10-22 23:51:00 +0000652 if (Complain)
653 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000654 return true;
655 }
656
657 // Add this definition to the suggested predefines buffer.
658 SuggestedPredefines += Extra;
659 SuggestedPredefines += '\n';
660 }
661
662 // If we get here, it's because the predefines buffer had compatible
663 // contents. Accept the PCH file.
664 return false;
665}
666
Douglas Gregor12fab312010-03-16 16:35:32 +0000667void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
668 unsigned ID) {
669 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
670 ++NumHeaderInfos;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000671}
672
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000673void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000674 PP.setCounterValue(Value);
675}
676
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000677//===----------------------------------------------------------------------===//
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000678// AST reader implementation
Douglas Gregor668c1a42009-04-21 22:25:48 +0000679//===----------------------------------------------------------------------===//
680
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000681void
Sebastian Redl571db7f2010-08-18 23:56:56 +0000682ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000683 DeserializationListener = Listener;
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000684}
685
Chris Lattner4c6f9522009-04-27 05:14:47 +0000686
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000687
Douglas Gregor98339b92011-08-25 20:47:51 +0000688unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
689 return serialization::ComputeHash(Sel);
690}
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000691
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Douglas Gregor98339b92011-08-25 20:47:51 +0000693std::pair<unsigned, unsigned>
694ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
695 using namespace clang::io;
696 unsigned KeyLen = ReadUnalignedLE16(d);
697 unsigned DataLen = ReadUnalignedLE16(d);
698 return std::make_pair(KeyLen, DataLen);
699}
700
701ASTSelectorLookupTrait::internal_key_type
702ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
703 using namespace clang::io;
Douglas Gregor35942772011-09-09 21:34:22 +0000704 SelectorTable &SelTable = Reader.getContext().Selectors;
Douglas Gregor98339b92011-08-25 20:47:51 +0000705 unsigned N = ReadUnalignedLE16(d);
706 IdentifierInfo *FirstII
707 = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
708 if (N == 0)
709 return SelTable.getNullarySelector(FirstII);
710 else if (N == 1)
711 return SelTable.getUnarySelector(FirstII);
712
713 SmallVector<IdentifierInfo *, 16> Args;
714 Args.push_back(FirstII);
715 for (unsigned I = 1; I != N; ++I)
716 Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
717
718 return SelTable.getSelector(N, Args.data());
719}
720
721ASTSelectorLookupTrait::data_type
722ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
723 unsigned DataLen) {
724 using namespace clang::io;
725
726 data_type Result;
727
728 Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
729 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
730 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
731
732 // Load instance methods
Douglas Gregor98339b92011-08-25 20:47:51 +0000733 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
734 if (ObjCMethodDecl *Method
735 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
736 Result.Instance.push_back(Method);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000737 }
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Douglas Gregor98339b92011-08-25 20:47:51 +0000739 // Load factory methods
Douglas Gregor98339b92011-08-25 20:47:51 +0000740 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
741 if (ObjCMethodDecl *Method
742 = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
743 Result.Factory.push_back(Method);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Douglas Gregor98339b92011-08-25 20:47:51 +0000746 return Result;
747}
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Douglas Gregor98339b92011-08-25 20:47:51 +0000749unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
750 return llvm::HashString(StringRef(a.first, a.second));
751}
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Douglas Gregor98339b92011-08-25 20:47:51 +0000753std::pair<unsigned, unsigned>
754ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
755 using namespace clang::io;
756 unsigned DataLen = ReadUnalignedLE16(d);
757 unsigned KeyLen = ReadUnalignedLE16(d);
758 return std::make_pair(KeyLen, DataLen);
759}
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000760
Douglas Gregor98339b92011-08-25 20:47:51 +0000761std::pair<const char*, unsigned>
762ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
763 assert(n >= 2 && d[n-1] == '\0');
764 return std::make_pair((const char*) d, n-1);
765}
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000766
Douglas Gregor98339b92011-08-25 20:47:51 +0000767IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
768 const unsigned char* d,
769 unsigned DataLen) {
770 using namespace clang::io;
771 unsigned RawID = ReadUnalignedLE32(d);
772 bool IsInteresting = RawID & 0x01;
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Douglas Gregor98339b92011-08-25 20:47:51 +0000774 // Wipe out the "is interesting" bit.
775 RawID = RawID >> 1;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000776
Douglas Gregor98339b92011-08-25 20:47:51 +0000777 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
778 if (!IsInteresting) {
779 // For uninteresting identifiers, just build the IdentifierInfo
780 // and associate it with the persistent ID.
Douglas Gregor668c1a42009-04-21 22:25:48 +0000781 IdentifierInfo *II = KnownII;
Douglas Gregor5d5051f2012-01-24 15:24:38 +0000782 if (!II) {
Douglas Gregor6ec60e02011-08-03 21:49:18 +0000783 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
Douglas Gregor5d5051f2012-01-24 15:24:38 +0000784 KnownII = II;
785 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000786 Reader.SetIdentifierInfo(ID, II);
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000787 II->setIsFromAST();
Douglas Gregor057df202012-01-18 20:56:22 +0000788 Reader.markIdentifierUpToDate(II);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000789 return II;
790 }
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +0000792 unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
Douglas Gregor98339b92011-08-25 20:47:51 +0000793 unsigned Bits = ReadUnalignedLE16(d);
794 bool CPlusPlusOperatorKeyword = Bits & 0x01;
795 Bits >>= 1;
796 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
797 Bits >>= 1;
798 bool Poisoned = Bits & 0x01;
799 Bits >>= 1;
800 bool ExtensionToken = Bits & 0x01;
801 Bits >>= 1;
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +0000802 bool hadMacroDefinition = Bits & 0x01;
803 Bits >>= 1;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000804
Douglas Gregor98339b92011-08-25 20:47:51 +0000805 assert(Bits == 0 && "Extra bits in the identifier?");
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +0000806 DataLen -= 8;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000807
Douglas Gregor98339b92011-08-25 20:47:51 +0000808 // Build the IdentifierInfo itself and link the identifier ID with
809 // the new IdentifierInfo.
810 IdentifierInfo *II = KnownII;
Douglas Gregor5d5051f2012-01-24 15:24:38 +0000811 if (!II) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000812 II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
Douglas Gregor5d5051f2012-01-24 15:24:38 +0000813 KnownII = II;
814 }
Douglas Gregor057df202012-01-18 20:56:22 +0000815 Reader.markIdentifierUpToDate(II);
Douglas Gregoreee242f2011-10-27 09:33:13 +0000816 II->setIsFromAST();
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000817
Douglas Gregor98339b92011-08-25 20:47:51 +0000818 // Set or check the various bits in the IdentifierInfo structure.
819 // Token IDs are read-only.
820 if (HasRevertedTokenIDToIdentifier)
821 II->RevertTokenIDToIdentifier();
822 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
823 assert(II->isExtensionToken() == ExtensionToken &&
824 "Incorrect extension token flag");
825 (void)ExtensionToken;
826 if (Poisoned)
827 II->setIsPoisoned(true);
828 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
829 "Incorrect C++ operator keyword flag");
830 (void)CPlusPlusOperatorKeyword;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000831
Douglas Gregor98339b92011-08-25 20:47:51 +0000832 // If this identifier is a macro, deserialize the macro
833 // definition.
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +0000834 if (hadMacroDefinition) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000835 SmallVector<MacroID, 4> MacroIDs;
836 while (uint32_t LocalID = ReadUnalignedLE32(d)) {
837 MacroIDs.push_back(Reader.getGlobalMacroID(F, LocalID));
838 DataLen -= 4;
Douglas Gregor13292642011-12-02 15:45:10 +0000839 }
Douglas Gregor6c6c54a2012-10-11 00:46:49 +0000840 DataLen -= 4;
841 Reader.setIdentifierIsMacro(II, MacroIDs);
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000842 }
843
Douglas Gregoreee242f2011-10-27 09:33:13 +0000844 Reader.SetIdentifierInfo(ID, II);
845
Douglas Gregor98339b92011-08-25 20:47:51 +0000846 // Read all of the declarations visible at global scope with this
847 // name.
Douglas Gregor98339b92011-08-25 20:47:51 +0000848 if (DataLen > 0) {
849 SmallVector<uint32_t, 4> DeclIDs;
850 for (; DataLen > 0; DataLen -= 4)
851 DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
852 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000853 }
854
Douglas Gregor98339b92011-08-25 20:47:51 +0000855 return II;
856}
Michael J. Spencer20249a12010-10-21 03:16:25 +0000857
Douglas Gregor98339b92011-08-25 20:47:51 +0000858unsigned
859ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
860 llvm::FoldingSetNodeID ID;
861 ID.AddInteger(Key.Kind);
862
863 switch (Key.Kind) {
864 case DeclarationName::Identifier:
865 case DeclarationName::CXXLiteralOperatorName:
866 ID.AddString(((IdentifierInfo*)Key.Data)->getName());
867 break;
868 case DeclarationName::ObjCZeroArgSelector:
869 case DeclarationName::ObjCOneArgSelector:
870 case DeclarationName::ObjCMultiArgSelector:
871 ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
872 break;
873 case DeclarationName::CXXOperatorName:
874 ID.AddInteger((OverloadedOperatorKind)Key.Data);
875 break;
876 case DeclarationName::CXXConstructorName:
877 case DeclarationName::CXXDestructorName:
878 case DeclarationName::CXXConversionFunctionName:
879 case DeclarationName::CXXUsingDirective:
880 break;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000881 }
882
Douglas Gregor98339b92011-08-25 20:47:51 +0000883 return ID.ComputeHash();
884}
Argyrios Kyrtzidisa60786b2010-08-20 23:35:55 +0000885
Douglas Gregor98339b92011-08-25 20:47:51 +0000886ASTDeclContextNameLookupTrait::internal_key_type
887ASTDeclContextNameLookupTrait::GetInternalKey(
888 const external_key_type& Name) const {
889 DeclNameKey Key;
890 Key.Kind = Name.getNameKind();
891 switch (Name.getNameKind()) {
892 case DeclarationName::Identifier:
893 Key.Data = (uint64_t)Name.getAsIdentifierInfo();
894 break;
895 case DeclarationName::ObjCZeroArgSelector:
896 case DeclarationName::ObjCOneArgSelector:
897 case DeclarationName::ObjCMultiArgSelector:
898 Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
899 break;
900 case DeclarationName::CXXOperatorName:
901 Key.Data = Name.getCXXOverloadedOperator();
902 break;
903 case DeclarationName::CXXLiteralOperatorName:
904 Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
905 break;
906 case DeclarationName::CXXConstructorName:
907 case DeclarationName::CXXDestructorName:
908 case DeclarationName::CXXConversionFunctionName:
909 case DeclarationName::CXXUsingDirective:
910 Key.Data = 0;
911 break;
Argyrios Kyrtzidisa60786b2010-08-20 23:35:55 +0000912 }
913
Douglas Gregor98339b92011-08-25 20:47:51 +0000914 return Key;
915}
916
Douglas Gregor98339b92011-08-25 20:47:51 +0000917std::pair<unsigned, unsigned>
918ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
919 using namespace clang::io;
920 unsigned KeyLen = ReadUnalignedLE16(d);
921 unsigned DataLen = ReadUnalignedLE16(d);
922 return std::make_pair(KeyLen, DataLen);
923}
Michael J. Spencer20249a12010-10-21 03:16:25 +0000924
Douglas Gregor98339b92011-08-25 20:47:51 +0000925ASTDeclContextNameLookupTrait::internal_key_type
926ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
927 using namespace clang::io;
928
929 DeclNameKey Key;
930 Key.Kind = (DeclarationName::NameKind)*d++;
931 switch (Key.Kind) {
932 case DeclarationName::Identifier:
933 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
934 break;
935 case DeclarationName::ObjCZeroArgSelector:
936 case DeclarationName::ObjCOneArgSelector:
937 case DeclarationName::ObjCMultiArgSelector:
938 Key.Data =
939 (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
940 .getAsOpaquePtr();
941 break;
942 case DeclarationName::CXXOperatorName:
943 Key.Data = *d++; // OverloadedOperatorKind
944 break;
945 case DeclarationName::CXXLiteralOperatorName:
946 Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
947 break;
948 case DeclarationName::CXXConstructorName:
949 case DeclarationName::CXXDestructorName:
950 case DeclarationName::CXXConversionFunctionName:
951 case DeclarationName::CXXUsingDirective:
952 Key.Data = 0;
953 break;
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000954 }
955
Douglas Gregor98339b92011-08-25 20:47:51 +0000956 return Key;
957}
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000958
Douglas Gregor98339b92011-08-25 20:47:51 +0000959ASTDeclContextNameLookupTrait::data_type
960ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
961 const unsigned char* d,
Nick Lewyckyb346d2f2012-04-16 02:51:46 +0000962 unsigned DataLen) {
Douglas Gregor98339b92011-08-25 20:47:51 +0000963 using namespace clang::io;
964 unsigned NumDecls = ReadUnalignedLE16(d);
Douglas Gregor9b8b20f2012-01-06 16:09:53 +0000965 LE32DeclID *Start = (LE32DeclID *)d;
Douglas Gregor98339b92011-08-25 20:47:51 +0000966 return std::make_pair(Start, Start + NumDecls);
967}
Argyrios Kyrtzidis5d267682010-08-20 16:04:27 +0000968
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000969bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
Douglas Gregor0d95f772011-08-24 19:03:07 +0000970 llvm::BitstreamCursor &Cursor,
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +0000971 const std::pair<uint64_t, uint64_t> &Offsets,
972 DeclContextInfo &Info) {
973 SavedStreamPosition SavedPosition(Cursor);
974 // First the lexical decls.
975 if (Offsets.first != 0) {
976 Cursor.JumpToBit(Offsets.first);
977
978 RecordData Record;
979 const char *Blob;
980 unsigned BlobLen;
981 unsigned Code = Cursor.ReadCode();
982 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
983 if (RecCode != DECL_CONTEXT_LEXICAL) {
984 Error("Expected lexical block");
985 return true;
986 }
987
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +0000988 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
989 Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +0000990 }
991
992 // Now the lookup table.
993 if (Offsets.second != 0) {
994 Cursor.JumpToBit(Offsets.second);
995
996 RecordData Record;
997 const char *Blob;
998 unsigned BlobLen;
999 unsigned Code = Cursor.ReadCode();
1000 unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
1001 if (RecCode != DECL_CONTEXT_VISIBLE) {
1002 Error("Expected visible lookup table block");
1003 return true;
1004 }
1005 Info.NameLookupTableData
1006 = ASTDeclContextNameLookupTable::Create(
1007 (const unsigned char *)Blob + Record[0],
1008 (const unsigned char *)Blob,
Douglas Gregor0d95f772011-08-24 19:03:07 +00001009 ASTDeclContextNameLookupTrait(*this, M));
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00001010 }
1011
1012 return false;
1013}
1014
Chris Lattner5f9e2722011-07-23 10:55:15 +00001015void ASTReader::Error(StringRef Msg) {
Argyrios Kyrtzidis8d8f2c22011-04-25 22:23:56 +00001016 Error(diag::err_fe_pch_malformed, Msg);
1017}
1018
1019void ASTReader::Error(unsigned DiagID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001020 StringRef Arg1, StringRef Arg2) {
Argyrios Kyrtzidis8d8f2c22011-04-25 22:23:56 +00001021 if (Diags.isDiagnosticInFlight())
1022 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1023 else
1024 Diag(DiagID) << Arg1 << Arg2;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001025}
1026
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001027/// \brief Tell the AST listener about the predefines buffers in the chain.
Douglas Gregor38295be2012-10-22 23:51:00 +00001028bool ASTReader::CheckPredefinesBuffers(bool Complain) {
Douglas Gregor11407b82012-10-18 21:18:25 +00001029 if (Listener) {
1030 // We only care about the primary module.
1031 ModuleFile &M = ModuleMgr.getPrimaryModule();
Douglas Gregor87699242012-10-25 00:07:54 +00001032 SuggestedPredefines.clear();
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001033 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Douglas Gregor11407b82012-10-18 21:18:25 +00001034 M.ActualOriginalSourceFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +00001035 SuggestedPredefines,
Douglas Gregor38295be2012-10-22 23:51:00 +00001036 FileMgr,
1037 Complain);
Douglas Gregor11407b82012-10-18 21:18:25 +00001038 }
Douglas Gregore721f952009-04-28 18:58:38 +00001039 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001040}
1041
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001042//===----------------------------------------------------------------------===//
1043// Source Manager Deserialization
1044//===----------------------------------------------------------------------===//
1045
Douglas Gregorbd945002009-04-13 16:31:14 +00001046/// \brief Read the line table in the source manager block.
Sebastian Redlc3632732010-10-05 15:59:54 +00001047/// \returns true if there was an error.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001048bool ASTReader::ParseLineTable(ModuleFile &F,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001049 SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +00001050 unsigned Idx = 0;
1051 LineTableInfo &LineTable = SourceMgr.getLineTable();
1052
1053 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +00001054 std::map<int, int> FileIDs;
1055 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +00001056 // Extract the file name
1057 unsigned FilenameLen = Record[Idx++];
1058 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1059 Idx += FilenameLen;
Douglas Gregorcaed0602012-10-18 21:31:35 +00001060 MaybeAddSystemRootToFilename(F, Filename);
Jay Foad65aa6882011-06-21 15:13:30 +00001061 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
Douglas Gregorbd945002009-04-13 16:31:14 +00001062 }
1063
1064 // Parse the line entries
1065 std::vector<LineEntry> Entries;
1066 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +00001067 int FID = Record[Idx++];
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001068 assert(FID >= 0 && "Serialized line entries for non-local file.");
1069 // Remap FileID from 1-based old view.
1070 FID += F.SLocEntryBaseID - 1;
Douglas Gregorbd945002009-04-13 16:31:14 +00001071
1072 // Extract the line entries
1073 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +00001074 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +00001075 Entries.clear();
1076 Entries.reserve(NumEntries);
1077 for (unsigned I = 0; I != NumEntries; ++I) {
1078 unsigned FileOffset = Record[Idx++];
1079 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +00001080 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +00001081 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +00001082 = (SrcMgr::CharacteristicKind)Record[Idx++];
1083 unsigned IncludeOffset = Record[Idx++];
1084 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1085 FileKind, IncludeOffset));
1086 }
Douglas Gregor47d9de62012-06-08 16:40:28 +00001087 LineTable.AddEntry(FileID::get(FID), Entries);
Douglas Gregorbd945002009-04-13 16:31:14 +00001088 }
1089
1090 return false;
1091}
1092
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001093namespace {
1094
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001095class ASTStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001096public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001097 const ino_t ino;
1098 const dev_t dev;
1099 const mode_t mode;
1100 const time_t mtime;
1101 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001103 ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Chris Lattner74e976b2010-11-23 19:28:12 +00001104 : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001105};
1106
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001107class ASTStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001108 public:
1109 typedef const char *external_key_type;
1110 typedef const char *internal_key_type;
1111
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001112 typedef ASTStatData data_type;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001113
1114 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +00001115 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001116 }
1117
1118 static internal_key_type GetInternalKey(const char *path) { return path; }
1119
1120 static bool EqualKey(internal_key_type a, internal_key_type b) {
1121 return strcmp(a, b) == 0;
1122 }
1123
1124 static std::pair<unsigned, unsigned>
1125 ReadKeyDataLength(const unsigned char*& d) {
1126 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1127 unsigned DataLen = (unsigned) *d++;
1128 return std::make_pair(KeyLen + 1, DataLen);
1129 }
1130
1131 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1132 return (const char *)d;
1133 }
1134
1135 static data_type ReadData(const internal_key_type, const unsigned char *d,
1136 unsigned /*DataLen*/) {
1137 using namespace clang::io;
1138
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001139 ino_t ino = (ino_t) ReadUnalignedLE32(d);
1140 dev_t dev = (dev_t) ReadUnalignedLE32(d);
1141 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +00001142 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001143 off_t size = (off_t) ReadUnalignedLE64(d);
1144 return data_type(ino, dev, mode, mtime, size);
1145 }
1146};
1147
1148/// \brief stat() cache for precompiled headers.
1149///
1150/// This cache is very similar to the stat cache used by pretokenized
1151/// headers.
Chris Lattner10e286a2010-11-23 19:19:34 +00001152class ASTStatCache : public FileSystemStatCache {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001153 typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001154 CacheTy *Cache;
1155
1156 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +00001157public:
Chris Lattner74e976b2010-11-23 19:28:12 +00001158 ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
1159 unsigned &NumStatHits, unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001160 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
1161 Cache = CacheTy::Create(Buckets, Base);
1162 }
1163
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001164 ~ASTStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Chris Lattner898a0612010-11-23 21:17:56 +00001166 LookupResult getStat(const char *Path, struct stat &StatBuf,
1167 int *FileDescriptor) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001168 // Do the lookup for the file's data in the AST file.
Chris Lattner10e286a2010-11-23 19:19:34 +00001169 CacheTy::iterator I = Cache->find(Path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001170
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001171 // If we don't get a hit in the AST file just forward to 'stat'.
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001172 if (I == Cache->end()) {
1173 ++NumStatMisses;
Chris Lattner898a0612010-11-23 21:17:56 +00001174 return statChained(Path, StatBuf, FileDescriptor);
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001175 }
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001177 ++NumStatHits;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001178 ASTStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Chris Lattner10e286a2010-11-23 19:19:34 +00001180 StatBuf.st_ino = Data.ino;
1181 StatBuf.st_dev = Data.dev;
1182 StatBuf.st_mtime = Data.mtime;
1183 StatBuf.st_mode = Data.mode;
1184 StatBuf.st_size = Data.size;
Chris Lattnerd6f61112010-11-23 20:05:15 +00001185 return CacheExists;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001186 }
1187};
1188} // end anonymous namespace
1189
1190
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001191/// \brief Read a source manager block
Douglas Gregor4825fd72012-10-22 22:50:17 +00001192bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
Douglas Gregor14f79002009-04-10 03:52:48 +00001193 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001194
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001195 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001196
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001197 // Set the source-location entry cursor to the current position in
1198 // the stream. This cursor will be used to read the contents of the
1199 // source manager block initially, and then lazily read
1200 // source-location entries as needed.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001201 SLocEntryCursor = F.Stream;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001202
1203 // The stream itself is going to skip over the source manager block.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001204 if (F.Stream.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001205 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001206 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001207 }
1208
1209 // Enter the source manager block.
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001210 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001211 Error("malformed source manager block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001212 return true;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001213 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001214
Douglas Gregor14f79002009-04-10 03:52:48 +00001215 RecordData Record;
1216 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001217 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +00001218 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001219 if (SLocEntryCursor.ReadBlockEnd()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001220 Error("error at end of Source Manager block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001221 return true;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001222 }
Douglas Gregor4825fd72012-10-22 22:50:17 +00001223 return false;
Douglas Gregor14f79002009-04-10 03:52:48 +00001224 }
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Douglas Gregor14f79002009-04-10 03:52:48 +00001226 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1227 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001228 SLocEntryCursor.ReadSubBlockID();
1229 if (SLocEntryCursor.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001230 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001231 return true;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001232 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001233 continue;
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Douglas Gregor14f79002009-04-10 03:52:48 +00001236 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001237 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +00001238 continue;
1239 }
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Douglas Gregor14f79002009-04-10 03:52:48 +00001241 // Read a record.
1242 const char *BlobStart;
1243 unsigned BlobLen;
1244 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001245 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +00001246 default: // Default behavior: ignore.
1247 break;
1248
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001249 case SM_SLOC_FILE_ENTRY:
1250 case SM_SLOC_BUFFER_ENTRY:
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001251 case SM_SLOC_EXPANSION_ENTRY:
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001252 // Once we hit one of the source location entries, we're done.
Douglas Gregor4825fd72012-10-22 22:50:17 +00001253 return false;
Douglas Gregor14f79002009-04-10 03:52:48 +00001254 }
1255 }
1256}
1257
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001258/// \brief If a header file is not found at the path that we expect it to be
1259/// and the PCH file was moved from its original location, try to resolve the
1260/// file by assuming that header+PCH were moved together and the header is in
1261/// the same place relative to the PCH.
1262static std::string
1263resolveFileRelativeToOriginalDir(const std::string &Filename,
1264 const std::string &OriginalDir,
1265 const std::string &CurrDir) {
1266 assert(OriginalDir != CurrDir &&
1267 "No point trying to resolve the file if the PCH dir didn't change");
1268 using namespace llvm::sys;
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001269 SmallString<128> filePath(Filename);
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001270 fs::make_absolute(filePath);
1271 assert(path::is_absolute(OriginalDir));
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001272 SmallString<128> currPCHPath(CurrDir);
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00001273
1274 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1275 fileDirE = path::end(path::parent_path(filePath));
1276 path::const_iterator origDirI = path::begin(OriginalDir),
1277 origDirE = path::end(OriginalDir);
1278 // Skip the common path components from filePath and OriginalDir.
1279 while (fileDirI != fileDirE && origDirI != origDirE &&
1280 *fileDirI == *origDirI) {
1281 ++fileDirI;
1282 ++origDirI;
1283 }
1284 for (; origDirI != origDirE; ++origDirI)
1285 path::append(currPCHPath, "..");
1286 path::append(currPCHPath, fileDirI, fileDirE);
1287 path::append(currPCHPath, path::filename(Filename));
1288 return currPCHPath.str();
1289}
1290
Douglas Gregor8b53d142012-10-22 22:53:10 +00001291bool ASTReader::ReadSLocEntry(int ID) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001292 if (ID == 0)
Douglas Gregor4825fd72012-10-22 22:50:17 +00001293 return false;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001294
Douglas Gregor0cdd7982011-07-21 18:46:38 +00001295 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001296 Error("source location entry ID out-of-range for AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001297 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001298 }
1299
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001300 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001301 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Sebastian Redlc3632732010-10-05 15:59:54 +00001302 llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001303 unsigned BaseOffset = F->SLocEntryBaseOffset;
Sebastian Redl9137a522010-07-16 17:50:48 +00001304
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001305 ++NumSLocEntriesRead;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001306 unsigned Code = SLocEntryCursor.ReadCode();
1307 if (Code == llvm::bitc::END_BLOCK ||
1308 Code == llvm::bitc::ENTER_SUBBLOCK ||
1309 Code == llvm::bitc::DEFINE_ABBREV) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001310 Error("incorrectly-formatted source location entry in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001311 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001312 }
1313
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001314 RecordData Record;
1315 const char *BlobStart;
1316 unsigned BlobLen;
1317 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1318 default:
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001319 Error("incorrectly-formatted source location entry in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001320 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001321
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001322 case SM_SLOC_FILE_ENTRY: {
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +00001323 // We will detect whether a file changed and return 'Failure' for it, but
1324 // we will also try to fail gracefully by setting up the SLocEntry.
Douglas Gregora930dc92012-10-22 18:42:04 +00001325 unsigned InputID = Record[4];
1326 InputFile IF = getInputFile(*F, InputID);
1327 const FileEntry *File = IF.getPointer();
1328 bool OverriddenBuffer = IF.getInt();
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +00001329
Douglas Gregora930dc92012-10-22 18:42:04 +00001330 if (!IF.getPointer())
Douglas Gregor4825fd72012-10-22 22:50:17 +00001331 return true;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001332
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001333 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Douglas Gregor72a9ae12011-07-22 16:00:58 +00001334 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001335 // This is the module's main file.
1336 IncludeLoc = getImportLocation(F);
1337 }
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001338 SrcMgr::CharacteristicKind
1339 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1340 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001341 ID, BaseOffset + Record[0]);
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001342 SrcMgr::FileInfo &FileInfo =
1343 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Douglas Gregora930dc92012-10-22 18:42:04 +00001344 FileInfo.NumCreatedFIDs = Record[5];
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001345 if (Record[3])
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +00001346 FileInfo.setHasLineDirectives();
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001347
Douglas Gregora930dc92012-10-22 18:42:04 +00001348 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1349 unsigned NumFileDecls = Record[7];
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001350 if (NumFileDecls) {
1351 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
Argyrios Kyrtzidis9d128d02011-10-31 07:20:08 +00001352 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1353 NumFileDecls));
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00001354 }
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001355
Douglas Gregor35f9ae62011-11-17 01:44:33 +00001356 const SrcMgr::ContentCache *ContentCache
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001357 = SourceMgr.getOrCreateContentCache(File,
1358 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
Douglas Gregor35f9ae62011-11-17 01:44:33 +00001359 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1360 ContentCache->ContentsEntry == ContentCache->OrigEntry) {
Douglas Gregora081da52011-11-16 20:05:18 +00001361 unsigned Code = SLocEntryCursor.ReadCode();
1362 Record.clear();
1363 unsigned RecCode
1364 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1365
1366 if (RecCode != SM_SLOC_BUFFER_BLOB) {
1367 Error("AST record has invalid code");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001368 return true;
Douglas Gregora081da52011-11-16 20:05:18 +00001369 }
1370
1371 llvm::MemoryBuffer *Buffer
1372 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
Douglas Gregora930dc92012-10-22 18:42:04 +00001373 File->getName());
Douglas Gregora081da52011-11-16 20:05:18 +00001374 SourceMgr.overrideFileContents(File, Buffer);
1375 }
Argyrios Kyrtzidisa4c29b62012-02-20 23:58:07 +00001376
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001377 break;
1378 }
1379
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001380 case SM_SLOC_BUFFER_ENTRY: {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001381 const char *Name = BlobStart;
1382 unsigned Offset = Record[0];
1383 unsigned Code = SLocEntryCursor.ReadCode();
1384 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001385 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001386 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001387
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001388 if (RecCode != SM_SLOC_BUFFER_BLOB) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001389 Error("AST record has invalid code");
Douglas Gregor4825fd72012-10-22 22:50:17 +00001390 return true;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001391 }
1392
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001393 llvm::MemoryBuffer *Buffer
Douglas Gregora081da52011-11-16 20:05:18 +00001394 = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
1395 Name);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001396 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID,
1397 BaseOffset + Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Douglas Gregor6236a292011-12-02 21:56:05 +00001399 if (strcmp(Name, "<built-in>") == 0 && F->Kind == MK_PCH) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001400 PCHPredefinesBlock Block = {
1401 BufferID,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001402 StringRef(BlobStart, BlobLen - 1)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001403 };
1404 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001405 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001406
1407 break;
1408 }
1409
Chandler Carruthf70d12d2011-07-15 07:25:21 +00001410 case SM_SLOC_EXPANSION_ENTRY: {
Sebastian Redlc3632732010-10-05 15:59:54 +00001411 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
Chandler Carruthbf340e42011-07-26 03:03:05 +00001412 SourceMgr.createExpansionLoc(SpellingLoc,
Sebastian Redlc3632732010-10-05 15:59:54 +00001413 ReadSourceLocation(*F, Record[2]),
1414 ReadSourceLocation(*F, Record[3]),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001415 Record[4],
1416 ID,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001417 BaseOffset + Record[0]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001418 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001419 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001420 }
1421
Douglas Gregor4825fd72012-10-22 22:50:17 +00001422 return false;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001423}
1424
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001425/// \brief Find the location where the module F is imported.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001426SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001427 if (F->ImportLoc.isValid())
1428 return F->ImportLoc;
Jonathan D. Turner2e091632011-07-29 18:09:09 +00001429
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001430 // Otherwise we have a PCH. It's considered to be "imported" at the first
1431 // location of its includer.
Jonathan D. Turner2e091632011-07-29 18:09:09 +00001432 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001433 // Main file is the importer. We assume that it is the first entry in the
1434 // entry table. We can't ask the manager, because at the time of PCH loading
1435 // the main file entry doesn't exist yet.
1436 // The very first entry is the invalid instantiation loc, which takes up
1437 // offsets 0 and 1.
1438 return SourceLocation::getFromRawEncoding(2U);
1439 }
Jonathan D. Turner2e091632011-07-29 18:09:09 +00001440 //return F->Loaders[0]->FirstLoc;
1441 return F->ImportedBy[0]->FirstLoc;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001442}
1443
Chris Lattner6367f6d2009-04-27 01:05:14 +00001444/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1445/// specified cursor. Read the abbreviations that are at the top of the block
1446/// and then leave the cursor pointing into the block.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00001447bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
Chris Lattner6367f6d2009-04-27 01:05:14 +00001448 unsigned BlockID) {
1449 if (Cursor.EnterSubBlock(BlockID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001450 Error("malformed block record in AST file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001451 return Failure;
1452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Chris Lattner6367f6d2009-04-27 01:05:14 +00001454 while (true) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001455 uint64_t Offset = Cursor.GetCurrentBitNo();
Chris Lattner6367f6d2009-04-27 01:05:14 +00001456 unsigned Code = Cursor.ReadCode();
Michael J. Spencer20249a12010-10-21 03:16:25 +00001457
Chris Lattner6367f6d2009-04-27 01:05:14 +00001458 // We expect all abbrevs to be at the start of the block.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001459 if (Code != llvm::bitc::DEFINE_ABBREV) {
1460 Cursor.JumpToBit(Offset);
Chris Lattner6367f6d2009-04-27 01:05:14 +00001461 return false;
Douglas Gregorecdcb882010-10-20 22:00:55 +00001462 }
Chris Lattner6367f6d2009-04-27 01:05:14 +00001463 Cursor.ReadAbbrevRecord();
1464 }
1465}
1466
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00001467void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset,
1468 MacroInfo *Hint) {
Douglas Gregorecdcb882010-10-20 22:00:55 +00001469 llvm::BitstreamCursor &Stream = F.MacroCursor;
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Douglas Gregor37e26842009-04-21 23:56:24 +00001471 // Keep track of where we are in the stream, then jump back there
1472 // after reading this macro.
1473 SavedStreamPosition SavedPosition(Stream);
1474
1475 Stream.JumpToBit(Offset);
1476 RecordData Record;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001477 SmallVector<IdentifierInfo*, 16> MacroArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001478 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Douglas Gregore8219a62012-10-11 21:07:39 +00001480 // RAII object to add the loaded macro information once we're done
1481 // adding tokens.
1482 struct AddLoadedMacroInfoRAII {
1483 Preprocessor &PP;
1484 MacroInfo *Hint;
1485 MacroInfo *MI;
1486 IdentifierInfo *II;
1487
1488 AddLoadedMacroInfoRAII(Preprocessor &PP, MacroInfo *Hint)
1489 : PP(PP), Hint(Hint), MI(), II() { }
1490 ~AddLoadedMacroInfoRAII( ) {
1491 if (MI) {
1492 // Finally, install the macro.
1493 PP.addLoadedMacroInfo(II, MI, Hint);
1494 }
1495 }
1496 } AddLoadedMacroInfo(PP, Hint);
1497
Douglas Gregor37e26842009-04-21 23:56:24 +00001498 while (true) {
1499 unsigned Code = Stream.ReadCode();
1500 switch (Code) {
1501 case llvm::bitc::END_BLOCK:
Douglas Gregor3b2257c2011-08-04 18:09:14 +00001502 return;
Douglas Gregor37e26842009-04-21 23:56:24 +00001503
1504 case llvm::bitc::ENTER_SUBBLOCK:
1505 // No known subblocks, always skip them.
1506 Stream.ReadSubBlockID();
1507 if (Stream.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001508 Error("malformed block record in AST file");
Douglas Gregor3b2257c2011-08-04 18:09:14 +00001509 return;
Douglas Gregor37e26842009-04-21 23:56:24 +00001510 }
1511 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Douglas Gregor37e26842009-04-21 23:56:24 +00001513 case llvm::bitc::DEFINE_ABBREV:
1514 Stream.ReadAbbrevRecord();
1515 continue;
1516 default: break;
1517 }
1518
1519 // Read a record.
Douglas Gregorecdcb882010-10-20 22:00:55 +00001520 const char *BlobStart = 0;
1521 unsigned BlobLen = 0;
Douglas Gregor37e26842009-04-21 23:56:24 +00001522 Record.clear();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001523 PreprocessorRecordTypes RecType =
Michael J. Spencer20249a12010-10-21 03:16:25 +00001524 (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
Douglas Gregorecdcb882010-10-20 22:00:55 +00001525 BlobLen);
Douglas Gregor37e26842009-04-21 23:56:24 +00001526 switch (RecType) {
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001527 case PP_MACRO_OBJECT_LIKE:
1528 case PP_MACRO_FUNCTION_LIKE: {
Douglas Gregor37e26842009-04-21 23:56:24 +00001529 // If we already have a macro, that means that we've hit the end
1530 // of the definition of the macro we were looking for. We're
1531 // done.
1532 if (Macro)
Douglas Gregor3b2257c2011-08-04 18:09:14 +00001533 return;
Douglas Gregor37e26842009-04-21 23:56:24 +00001534
Douglas Gregor95eab172011-07-28 20:55:49 +00001535 IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
Douglas Gregor37e26842009-04-21 23:56:24 +00001536 if (II == 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001537 Error("macro must have a name in AST file");
Douglas Gregor3b2257c2011-08-04 18:09:14 +00001538 return;
Douglas Gregor37e26842009-04-21 23:56:24 +00001539 }
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Douglas Gregora8235d62012-10-09 23:05:51 +00001541 unsigned GlobalID = getGlobalMacroID(F, Record[1]);
1542
1543 // If this macro has already been loaded, don't do so again.
1544 if (MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS])
1545 return;
1546
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001547 SubmoduleID GlobalSubmoduleID = getGlobalSubmoduleID(F, Record[2]);
1548 unsigned NextIndex = 3;
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001549 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Douglas Gregor712f2fc2011-09-09 22:02:16 +00001550 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001551
Douglas Gregora8235d62012-10-09 23:05:51 +00001552 // Record this macro.
1553 MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS] = MI;
1554
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001555 SourceLocation UndefLoc = ReadSourceLocation(F, Record, NextIndex);
1556 if (UndefLoc.isValid())
1557 MI->setUndefLoc(UndefLoc);
1558
1559 MI->setIsUsed(Record[NextIndex++]);
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001560 MI->setIsFromAST();
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001562 bool IsPublic = Record[NextIndex++];
Douglas Gregoraa93a872011-10-17 15:32:29 +00001563 MI->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
Alexander Kornienko4d7e0ce2012-09-25 17:18:14 +00001564
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001565 if (RecType == PP_MACRO_FUNCTION_LIKE) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001566 // Decode function-like macro info.
Douglas Gregor7143aab2011-09-01 17:04:32 +00001567 bool isC99VarArgs = Record[NextIndex++];
1568 bool isGNUVarArgs = Record[NextIndex++];
Douglas Gregor37e26842009-04-21 23:56:24 +00001569 MacroArgs.clear();
Douglas Gregor7143aab2011-09-01 17:04:32 +00001570 unsigned NumArgs = Record[NextIndex++];
Douglas Gregor37e26842009-04-21 23:56:24 +00001571 for (unsigned i = 0; i != NumArgs; ++i)
Douglas Gregor7143aab2011-09-01 17:04:32 +00001572 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Douglas Gregor37e26842009-04-21 23:56:24 +00001573
1574 // Install function-like macro info.
1575 MI->setIsFunctionLike();
1576 if (isC99VarArgs) MI->setIsC99Varargs();
1577 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001578 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Douglas Gregor712f2fc2011-09-09 22:02:16 +00001579 PP.getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001580 }
1581
Douglas Gregora8235d62012-10-09 23:05:51 +00001582 if (DeserializationListener)
1583 DeserializationListener->MacroRead(GlobalID, MI);
1584
1585 // If an update record marked this as undefined, do so now.
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001586 // FIXME: Only if the submodule this update came from is visible?
Douglas Gregora8235d62012-10-09 23:05:51 +00001587 MacroUpdatesMap::iterator Update = MacroUpdates.find(GlobalID);
1588 if (Update != MacroUpdates.end()) {
1589 if (MI->getUndefLoc().isInvalid()) {
Douglas Gregor54c8a402012-10-12 00:16:50 +00001590 for (unsigned I = 0, N = Update->second.size(); I != N; ++I) {
1591 bool Hidden = false;
1592 if (unsigned SubmoduleID = Update->second[I].first) {
1593 if (Module *Owner = getSubmodule(SubmoduleID)) {
1594 if (Owner->NameVisibility == Module::Hidden) {
1595 // Note that this #undef is hidden.
1596 Hidden = true;
1597
1598 // Record this hiding for later.
1599 HiddenNamesMap[Owner].push_back(
1600 HiddenName(II, MI, Update->second[I].second.UndefLoc));
1601 }
1602 }
1603 }
1604
1605 if (!Hidden) {
1606 MI->setUndefLoc(Update->second[I].second.UndefLoc);
1607 if (PPMutationListener *Listener = PP.getPPMutationListener())
1608 Listener->UndefinedMacro(MI);
1609 break;
1610 }
1611 }
Douglas Gregora8235d62012-10-09 23:05:51 +00001612 }
1613 MacroUpdates.erase(Update);
1614 }
1615
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001616 // Determine whether this macro definition is visible.
1617 bool Hidden = !MI->isPublic();
1618 if (!Hidden && GlobalSubmoduleID) {
1619 if (Module *Owner = getSubmodule(GlobalSubmoduleID)) {
1620 if (Owner->NameVisibility == Module::Hidden) {
1621 // The owning module is not visible, and this macro definition
1622 // should not be, either.
1623 Hidden = true;
1624
1625 // Note that this macro definition was hidden because its owning
1626 // module is not yet visible.
1627 HiddenNamesMap[Owner].push_back(HiddenName(II, MI));
1628 }
1629 }
1630 }
1631 MI->setHidden(Hidden);
1632
Douglas Gregore8219a62012-10-11 21:07:39 +00001633 // Make sure we install the macro once we're done.
1634 AddLoadedMacroInfo.MI = MI;
1635 AddLoadedMacroInfo.II = II;
Douglas Gregor37e26842009-04-21 23:56:24 +00001636
1637 // Remember that we saw this macro last so that we add the tokens that
1638 // form its body to it.
1639 Macro = MI;
Michael J. Spencer20249a12010-10-21 03:16:25 +00001640
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00001641 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1642 Record[NextIndex]) {
1643 // We have a macro definition. Register the association
1644 PreprocessedEntityID
1645 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1646 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1647 PPRec.RegisterMacroDefinition(Macro,
1648 PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true));
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001649 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00001650
Douglas Gregor37e26842009-04-21 23:56:24 +00001651 ++NumMacrosRead;
1652 break;
1653 }
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001655 case PP_TOKEN: {
Douglas Gregor37e26842009-04-21 23:56:24 +00001656 // If we see a TOKEN before a PP_MACRO_*, then the file is
1657 // erroneous, just pretend we didn't see this.
1658 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Douglas Gregor37e26842009-04-21 23:56:24 +00001660 Token Tok;
1661 Tok.startToken();
Sebastian Redlc3632732010-10-05 15:59:54 +00001662 Tok.setLocation(ReadSourceLocation(F, Record[0]));
Douglas Gregor37e26842009-04-21 23:56:24 +00001663 Tok.setLength(Record[1]);
Douglas Gregor95eab172011-07-28 20:55:49 +00001664 if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
Douglas Gregor37e26842009-04-21 23:56:24 +00001665 Tok.setIdentifierInfo(II);
1666 Tok.setKind((tok::TokenKind)Record[3]);
1667 Tok.setFlag((Token::TokenFlags)Record[4]);
1668 Macro->AddTokenToBody(Tok);
1669 break;
1670 }
David Blaikie7530c032012-01-17 06:56:22 +00001671 }
Douglas Gregor4800a5c2011-02-08 21:58:10 +00001672 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001673}
1674
Douglas Gregor86c67d82011-07-28 22:39:26 +00001675PreprocessedEntityID
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001676ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
Argyrios Kyrtzidis1f6d2252011-09-19 20:40:02 +00001677 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Douglas Gregor272b6bc2011-08-04 18:56:47 +00001678 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1679 assert(I != M.PreprocessedEntityRemap.end()
1680 && "Invalid index into preprocessed entity index remap");
1681
1682 return LocalID + I->second;
Douglas Gregor86c67d82011-07-28 22:39:26 +00001683}
1684
Douglas Gregor98339b92011-08-25 20:47:51 +00001685unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1686 return llvm::HashString(llvm::sys::path::filename(path));
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001687}
Douglas Gregor98339b92011-08-25 20:47:51 +00001688
1689HeaderFileInfoTrait::internal_key_type
1690HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1691
1692bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1693 if (strcmp(a, b) == 0)
1694 return true;
1695
1696 if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1697 return false;
Douglas Gregor99a922b2011-12-09 16:22:07 +00001698
1699 // Determine whether the actual files are equivalent.
1700 bool Result = false;
1701 if (llvm::sys::fs::equivalent(a, b, Result))
Douglas Gregor98339b92011-08-25 20:47:51 +00001702 return false;
1703
Douglas Gregor99a922b2011-12-09 16:22:07 +00001704 return Result;
Douglas Gregor98339b92011-08-25 20:47:51 +00001705}
1706
1707std::pair<unsigned, unsigned>
1708HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1709 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1710 unsigned DataLen = (unsigned) *d++;
1711 return std::make_pair(KeyLen + 1, DataLen);
1712}
1713
1714HeaderFileInfoTrait::data_type
1715HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1716 unsigned DataLen) {
1717 const unsigned char *End = d + DataLen;
1718 using namespace clang::io;
1719 HeaderFileInfo HFI;
1720 unsigned Flags = *d++;
1721 HFI.isImport = (Flags >> 5) & 0x01;
1722 HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1723 HFI.DirInfo = (Flags >> 2) & 0x03;
1724 HFI.Resolved = (Flags >> 1) & 0x01;
1725 HFI.IndexHeaderMapHeader = Flags & 0x01;
1726 HFI.NumIncludes = ReadUnalignedLE16(d);
Douglas Gregor541ba162011-10-17 18:53:12 +00001727 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1728 ReadUnalignedLE32(d));
Douglas Gregor98339b92011-08-25 20:47:51 +00001729 if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1730 // The framework offset is 1 greater than the actual offset,
1731 // since 0 is used as an indicator for "no framework name".
1732 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1733 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1734 }
1735
1736 assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1737 (void)End;
1738
1739 // This HeaderFileInfo was externally loaded.
1740 HFI.External = true;
1741 return HFI;
1742}
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00001743
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001744void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ArrayRef<MacroID> IDs){
1745 II->setHadMacroDefinition(true);
1746 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1747 PendingMacroIDs[II].append(IDs.begin(), IDs.end());
Douglas Gregor295a2a62010-10-30 00:23:06 +00001748}
1749
Sebastian Redlc43b54c2010-08-18 23:56:43 +00001750void ASTReader::ReadDefinedMacros() {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001751 // Note that we are loading defined macros.
1752 Deserializing Macros(this);
1753
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00001754 for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1755 E = ModuleMgr.rend(); I != E; ++I) {
1756 llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001757
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001758 // If there was no preprocessor block, skip this file.
1759 if (!MacroCursor.getBitStreamReader())
1760 continue;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001761
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001762 llvm::BitstreamCursor Cursor = MacroCursor;
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00001763 Cursor.JumpToBit((*I)->MacroStartOffset);
Michael J. Spencer20249a12010-10-21 03:16:25 +00001764
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001765 RecordData Record;
1766 while (true) {
1767 unsigned Code = Cursor.ReadCode();
Douglas Gregorecdcb882010-10-20 22:00:55 +00001768 if (Code == llvm::bitc::END_BLOCK)
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001769 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001770
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001771 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1772 // No known subblocks, always skip them.
1773 Cursor.ReadSubBlockID();
1774 if (Cursor.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00001775 Error("malformed block record in AST file");
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001776 return;
1777 }
1778 continue;
1779 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001780
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001781 if (Code == llvm::bitc::DEFINE_ABBREV) {
1782 Cursor.ReadAbbrevRecord();
1783 continue;
1784 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001785
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001786 // Read a record.
1787 const char *BlobStart;
1788 unsigned BlobLen;
1789 Record.clear();
1790 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1791 default: // Default behavior: ignore.
1792 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001793
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001794 case PP_MACRO_OBJECT_LIKE:
1795 case PP_MACRO_FUNCTION_LIKE:
Douglas Gregor95eab172011-07-28 20:55:49 +00001796 getLocalIdentifier(**I, Record[0]);
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001797 break;
1798
Sebastian Redl8538e8d2010-08-18 23:57:32 +00001799 case PP_TOKEN:
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001800 // Ignore tokens.
1801 break;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001802 }
Douglas Gregor88a35862010-01-04 19:18:44 +00001803 }
1804 }
Douglas Gregor295a2a62010-10-30 00:23:06 +00001805}
1806
Douglas Gregoreee242f2011-10-27 09:33:13 +00001807namespace {
1808 /// \brief Visitor class used to look up identifirs in an AST file.
1809 class IdentifierLookupVisitor {
1810 StringRef Name;
Douglas Gregor057df202012-01-18 20:56:22 +00001811 unsigned PriorGeneration;
Douglas Gregoreee242f2011-10-27 09:33:13 +00001812 IdentifierInfo *Found;
1813 public:
Douglas Gregor057df202012-01-18 20:56:22 +00001814 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration)
1815 : Name(Name), PriorGeneration(PriorGeneration), Found() { }
Douglas Gregoreee242f2011-10-27 09:33:13 +00001816
Douglas Gregor1a4761e2011-11-30 23:21:26 +00001817 static bool visit(ModuleFile &M, void *UserData) {
Douglas Gregoreee242f2011-10-27 09:33:13 +00001818 IdentifierLookupVisitor *This
1819 = static_cast<IdentifierLookupVisitor *>(UserData);
1820
Douglas Gregor057df202012-01-18 20:56:22 +00001821 // If we've already searched this module file, skip it now.
1822 if (M.Generation <= This->PriorGeneration)
1823 return true;
1824
Douglas Gregoreee242f2011-10-27 09:33:13 +00001825 ASTIdentifierLookupTable *IdTable
1826 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1827 if (!IdTable)
1828 return false;
1829
Douglas Gregor5d5051f2012-01-24 15:24:38 +00001830 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1831 M, This->Found);
1832
Douglas Gregoreee242f2011-10-27 09:33:13 +00001833 std::pair<const char*, unsigned> Key(This->Name.begin(),
1834 This->Name.size());
Douglas Gregor5d5051f2012-01-24 15:24:38 +00001835 ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Trait);
Douglas Gregoreee242f2011-10-27 09:33:13 +00001836 if (Pos == IdTable->end())
1837 return false;
1838
1839 // Dereferencing the iterator has the effect of building the
1840 // IdentifierInfo node and populating it with the various
1841 // declarations it needs.
1842 This->Found = *Pos;
1843 return true;
1844 }
1845
1846 // \brief Retrieve the identifier info found within the module
1847 // files.
1848 IdentifierInfo *getIdentifierInfo() const { return Found; }
1849 };
1850}
1851
1852void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00001853 // Note that we are loading an identifier.
1854 Deserializing AnIdentifier(this);
1855
Douglas Gregor057df202012-01-18 20:56:22 +00001856 unsigned PriorGeneration = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00001857 if (getContext().getLangOpts().Modules)
Douglas Gregor057df202012-01-18 20:56:22 +00001858 PriorGeneration = IdentifierGeneration[&II];
1859
1860 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration);
1861 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
1862 markIdentifierUpToDate(&II);
1863}
1864
1865void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1866 if (!II)
1867 return;
1868
1869 II->setOutOfDate(false);
1870
1871 // Update the generation for this identifier.
David Blaikie4e4d0842012-03-11 07:00:24 +00001872 if (getContext().getLangOpts().Modules)
Douglas Gregor057df202012-01-18 20:56:22 +00001873 IdentifierGeneration[II] = CurrentGeneration;
Douglas Gregoreee242f2011-10-27 09:33:13 +00001874}
1875
Douglas Gregora930dc92012-10-22 18:42:04 +00001876llvm::PointerIntPair<const FileEntry *, 1, bool>
Douglas Gregor38295be2012-10-22 23:51:00 +00001877ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Douglas Gregora930dc92012-10-22 18:42:04 +00001878 // If this ID is bogus, just return an empty input file.
1879 if (ID == 0 || ID > F.InputFilesLoaded.size())
1880 return InputFile();
1881
1882 // If we've already loaded this input file, return it.
1883 if (F.InputFilesLoaded[ID-1].getPointer())
1884 return F.InputFilesLoaded[ID-1];
1885
1886 // Go find this input file.
1887 llvm::BitstreamCursor &Cursor = F.InputFilesCursor;
1888 SavedStreamPosition SavedPosition(Cursor);
1889 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1890
1891 unsigned Code = Cursor.ReadCode();
1892 RecordData Record;
1893 const char *BlobStart = 0;
1894 unsigned BlobLen = 0;
1895 switch ((InputFileRecordTypes)Cursor.ReadRecord(Code, Record,
1896 &BlobStart, &BlobLen)) {
1897 case INPUT_FILE: {
1898 unsigned StoredID = Record[0];
1899 assert(ID == StoredID && "Bogus stored ID or offset");
NAKAMURA Takumi6b8194e2012-10-22 21:50:39 +00001900 (void)StoredID;
Douglas Gregora930dc92012-10-22 18:42:04 +00001901 off_t StoredSize = (off_t)Record[1];
1902 time_t StoredTime = (time_t)Record[2];
1903 bool Overridden = (bool)Record[3];
1904
1905 // Get the file entry for this input file.
1906 StringRef OrigFilename(BlobStart, BlobLen);
1907 std::string Filename = OrigFilename;
1908 MaybeAddSystemRootToFilename(F, Filename);
1909 const FileEntry *File
1910 = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1911 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1912
1913 // If we didn't find the file, resolve it relative to the
1914 // original directory from which this AST file was created.
1915 if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1916 F.OriginalDir != CurrentDir) {
1917 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1918 F.OriginalDir,
1919 CurrentDir);
1920 if (!Resolved.empty())
1921 File = FileMgr.getFile(Resolved);
1922 }
1923
1924 // For an overridden file, create a virtual file with the stored
1925 // size/timestamp.
1926 if (Overridden && File == 0) {
1927 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1928 }
1929
1930 if (File == 0) {
Douglas Gregor38295be2012-10-22 23:51:00 +00001931 if (Complain) {
1932 std::string ErrorStr = "could not find file '";
1933 ErrorStr += Filename;
1934 ErrorStr += "' referenced by AST file";
1935 Error(ErrorStr.c_str());
1936 }
Douglas Gregora930dc92012-10-22 18:42:04 +00001937 return InputFile();
1938 }
1939
1940 // Note that we've loaded this input file.
1941 F.InputFilesLoaded[ID-1] = InputFile(File, Overridden);
1942
1943 // Check if there was a request to override the contents of the file
1944 // that was part of the precompiled header. Overridding such a file
1945 // can lead to problems when lexing using the source locations from the
1946 // PCH.
1947 SourceManager &SM = getSourceManager();
1948 if (!Overridden && SM.isFileOverridden(File)) {
1949 Error(diag::err_fe_pch_file_overridden, Filename);
1950 // After emitting the diagnostic, recover by disabling the override so
1951 // that the original file will be used.
1952 SM.disableFileContentsOverride(File);
1953 // The FileEntry is a virtual file entry with the size of the contents
1954 // that would override the original contents. Set it to the original's
1955 // size/time.
1956 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1957 StoredSize, StoredTime);
1958 }
1959
1960 // For an overridden file, there is nothing to validate.
1961 if (Overridden)
1962 return InputFile(File, Overridden);
1963
1964 // The stat info from the FileEntry came from the cached stat
1965 // info of the PCH, so we cannot trust it.
1966 struct stat StatBuf;
1967 if (::stat(File->getName(), &StatBuf) != 0) {
1968 StatBuf.st_size = File->getSize();
1969 StatBuf.st_mtime = File->getModificationTime();
1970 }
1971
1972 if ((StoredSize != StatBuf.st_size
1973#if !defined(LLVM_ON_WIN32)
1974 // In our regression testing, the Windows file system seems to
1975 // have inconsistent modification times that sometimes
1976 // erroneously trigger this error-handling path.
1977 || StoredTime != StatBuf.st_mtime
1978#endif
1979 )) {
Douglas Gregor38295be2012-10-22 23:51:00 +00001980 if (Complain)
1981 Error(diag::err_fe_pch_file_modified, Filename);
1982
Douglas Gregora930dc92012-10-22 18:42:04 +00001983 return InputFile();
1984 }
1985
1986 return InputFile(File, Overridden);
1987 }
1988 }
1989
1990 return InputFile();
1991}
1992
Chris Lattner5f9e2722011-07-23 10:55:15 +00001993const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
Douglas Gregor69e16082012-10-18 21:47:16 +00001994 ModuleFile &M = ModuleMgr.getPrimaryModule();
Argyrios Kyrtzidisb68ffb12011-06-01 05:43:53 +00001995 std::string Filename = filenameStrRef;
Douglas Gregor69e16082012-10-18 21:47:16 +00001996 MaybeAddSystemRootToFilename(M, Filename);
Argyrios Kyrtzidisb68ffb12011-06-01 05:43:53 +00001997 const FileEntry *File = FileMgr.getFile(Filename);
Douglas Gregor69e16082012-10-18 21:47:16 +00001998 if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1999 M.OriginalDir != CurrentDir) {
Argyrios Kyrtzidisb68ffb12011-06-01 05:43:53 +00002000 std::string resolved = resolveFileRelativeToOriginalDir(Filename,
Douglas Gregor69e16082012-10-18 21:47:16 +00002001 M.OriginalDir,
Argyrios Kyrtzidisb68ffb12011-06-01 05:43:53 +00002002 CurrentDir);
2003 if (!resolved.empty())
2004 File = FileMgr.getFile(resolved);
2005 }
2006
2007 return File;
2008}
2009
Douglas Gregore650c8c2009-07-07 00:12:59 +00002010/// \brief If we are loading a relocatable PCH file, and the filename is
2011/// not an absolute path, add the system root to the beginning of the file
2012/// name.
Douglas Gregora930dc92012-10-22 18:42:04 +00002013StringRef ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2014 std::string &Filename) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00002015 // If this is not a relocatable PCH file, there's nothing to do.
Douglas Gregorcaed0602012-10-18 21:31:35 +00002016 if (!M.RelocatablePCH)
Douglas Gregora930dc92012-10-22 18:42:04 +00002017 return Filename;
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Michael J. Spencer256053b2010-12-17 21:22:22 +00002019 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
Douglas Gregora930dc92012-10-22 18:42:04 +00002020 return Filename;
Douglas Gregore650c8c2009-07-07 00:12:59 +00002021
Douglas Gregor832d6202011-07-22 16:35:34 +00002022 if (isysroot.empty()) {
Douglas Gregore650c8c2009-07-07 00:12:59 +00002023 // If no system root was given, default to '/'
2024 Filename.insert(Filename.begin(), '/');
Douglas Gregora930dc92012-10-22 18:42:04 +00002025 return Filename;
Douglas Gregore650c8c2009-07-07 00:12:59 +00002026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregor832d6202011-07-22 16:35:34 +00002028 unsigned Length = isysroot.size();
Douglas Gregore650c8c2009-07-07 00:12:59 +00002029 if (isysroot[Length - 1] != '/')
2030 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Douglas Gregor832d6202011-07-22 16:35:34 +00002032 Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
Douglas Gregora930dc92012-10-22 18:42:04 +00002033 return Filename;
Douglas Gregore650c8c2009-07-07 00:12:59 +00002034}
2035
Douglas Gregor38295be2012-10-22 23:51:00 +00002036ASTReader::ASTReadResult
2037ASTReader::ReadControlBlock(ModuleFile &F,
2038 llvm::SmallVectorImpl<ModuleFile *> &Loaded,
2039 unsigned ClientLoadCapabilities) {
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002040 llvm::BitstreamCursor &Stream = F.Stream;
2041
2042 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2043 Error("malformed block record in AST file");
2044 return Failure;
2045 }
2046
2047 // Read all of the records and blocks in the control block.
2048 RecordData Record;
2049 while (!Stream.AtEndOfStream()) {
2050 unsigned Code = Stream.ReadCode();
2051 if (Code == llvm::bitc::END_BLOCK) {
2052 if (Stream.ReadBlockEnd()) {
2053 Error("error at end of control block in AST file");
2054 return Failure;
2055 }
2056
Douglas Gregora930dc92012-10-22 18:42:04 +00002057 // Validate all of the input files.
2058 if (!DisableValidation) {
Douglas Gregor38295be2012-10-22 23:51:00 +00002059 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Douglas Gregora930dc92012-10-22 18:42:04 +00002060 for (unsigned I = 0, N = Record[0]; I < N; ++I)
Douglas Gregor38295be2012-10-22 23:51:00 +00002061 if (!getInputFile(F, I+1, Complain).getPointer())
Douglas Gregor4825fd72012-10-22 22:50:17 +00002062 return OutOfDate;
Douglas Gregora930dc92012-10-22 18:42:04 +00002063 }
2064
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002065 return Success;
2066 }
2067
2068 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor745e6f12012-10-19 00:38:02 +00002069 switch (Stream.ReadSubBlockID()) {
2070 case INPUT_FILES_BLOCK_ID:
Douglas Gregora930dc92012-10-22 18:42:04 +00002071 F.InputFilesCursor = Stream;
2072 if (Stream.SkipBlock() || // Skip with the main cursor
2073 // Read the abbreviations
2074 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2075 Error("malformed block record in AST file");
Douglas Gregor745e6f12012-10-19 00:38:02 +00002076 return Failure;
Douglas Gregor745e6f12012-10-19 00:38:02 +00002077 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002078 continue;
Douglas Gregor745e6f12012-10-19 00:38:02 +00002079
2080 default:
2081 if (!Stream.SkipBlock())
2082 continue;
2083 break;
2084 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002085
2086 Error("malformed block record in AST file");
2087 return Failure;
2088 }
2089
2090 if (Code == llvm::bitc::DEFINE_ABBREV) {
2091 Stream.ReadAbbrevRecord();
2092 continue;
2093 }
2094
2095 // Read and process a record.
2096 Record.clear();
2097 const char *BlobStart = 0;
2098 unsigned BlobLen = 0;
2099 switch ((ControlRecordTypes)Stream.ReadRecord(Code, Record,
2100 &BlobStart, &BlobLen)) {
2101 case METADATA: {
2102 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
Douglas Gregor38295be2012-10-22 23:51:00 +00002103 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2104 Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
2105 : diag::warn_pch_version_too_new);
Douglas Gregor4825fd72012-10-22 22:50:17 +00002106 return VersionMismatch;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002107 }
2108
2109 bool hasErrors = Record[5];
2110 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2111 Diag(diag::err_pch_with_compiler_errors);
Douglas Gregor4825fd72012-10-22 22:50:17 +00002112 return HadErrors;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002113 }
2114
Douglas Gregorcaed0602012-10-18 21:31:35 +00002115 F.RelocatablePCH = Record[4];
Douglas Gregor7ae467f2012-10-18 18:27:37 +00002116
2117 const std::string &CurBranch = getClangFullRepositoryVersion();
2118 StringRef ASTBranch(BlobStart, BlobLen);
2119 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
Douglas Gregor38295be2012-10-22 23:51:00 +00002120 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2121 Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
Douglas Gregor4825fd72012-10-22 22:50:17 +00002122 return VersionMismatch;
Douglas Gregor7ae467f2012-10-18 18:27:37 +00002123 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002124 break;
2125 }
2126
2127 case IMPORTS: {
2128 // Load each of the imported PCH files.
2129 unsigned Idx = 0, N = Record.size();
2130 while (Idx < N) {
2131 // Read information about the AST file.
2132 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2133 unsigned Length = Record[Idx++];
2134 SmallString<128> ImportedFile(Record.begin() + Idx,
2135 Record.begin() + Idx + Length);
2136 Idx += Length;
2137
2138 // Load the AST file.
Douglas Gregor38295be2012-10-22 23:51:00 +00002139 switch(ReadASTCore(ImportedFile, ImportedKind, &F, Loaded,
2140 ClientLoadCapabilities)) {
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002141 case Failure: return Failure;
2142 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor4825fd72012-10-22 22:50:17 +00002143 case OutOfDate: return OutOfDate;
2144 case VersionMismatch: return VersionMismatch;
2145 case ConfigurationMismatch: return ConfigurationMismatch;
2146 case HadErrors: return HadErrors;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002147 case Success: break;
2148 }
2149 }
2150 break;
2151 }
2152
Douglas Gregor38295be2012-10-22 23:51:00 +00002153 case LANGUAGE_OPTIONS: {
2154 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2155 if (Listener && &F == *ModuleMgr.begin() &&
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00002156 ParseLanguageOptions(Record, Complain, *Listener) &&
2157 !DisableValidation)
Douglas Gregor4825fd72012-10-22 22:50:17 +00002158 return ConfigurationMismatch;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002159 break;
Douglas Gregor38295be2012-10-22 23:51:00 +00002160 }
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002161
Douglas Gregoree097c12012-10-18 17:58:09 +00002162 case TARGET_OPTIONS: {
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00002163 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2164 if (Listener && &F == *ModuleMgr.begin() &&
2165 ParseTargetOptions(Record, Complain, *Listener) &&
2166 !DisableValidation)
2167 return ConfigurationMismatch;
Douglas Gregoree097c12012-10-18 17:58:09 +00002168 break;
2169 }
2170
Douglas Gregor5f3d8222012-10-24 15:17:15 +00002171 case DIAGNOSTIC_OPTIONS: {
2172 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2173 if (Listener && &F == *ModuleMgr.begin() &&
2174 ParseDiagnosticOptions(Record, Complain, *Listener) &&
2175 !DisableValidation)
2176 return ConfigurationMismatch;
2177 break;
2178 }
Douglas Gregor1b2c3c02012-10-24 15:49:58 +00002179
2180 case FILE_SYSTEM_OPTIONS: {
2181 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2182 if (Listener && &F == *ModuleMgr.begin() &&
2183 ParseFileSystemOptions(Record, Complain, *Listener) &&
2184 !DisableValidation)
2185 return ConfigurationMismatch;
2186 break;
2187 }
2188
Douglas Gregorbbf38312012-10-24 16:50:34 +00002189 case HEADER_SEARCH_OPTIONS: {
2190 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2191 if (Listener && &F == *ModuleMgr.begin() &&
2192 ParseHeaderSearchOptions(Record, Complain, *Listener) &&
2193 !DisableValidation)
2194 return ConfigurationMismatch;
2195 break;
2196 }
2197
Douglas Gregora71a7d82012-10-24 20:05:57 +00002198 case PREPROCESSOR_OPTIONS: {
2199 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2200 if (Listener && &F == *ModuleMgr.begin() &&
Douglas Gregor87699242012-10-25 00:07:54 +00002201 ParsePreprocessorOptions(Record, Complain, *Listener,
2202 SuggestedPredefines) &&
Douglas Gregora71a7d82012-10-24 20:05:57 +00002203 !DisableValidation)
2204 return ConfigurationMismatch;
2205 break;
2206 }
2207
Douglas Gregor39c497b2012-10-18 18:36:53 +00002208 case ORIGINAL_FILE:
Douglas Gregor69e16082012-10-18 21:47:16 +00002209 F.OriginalSourceFileID = FileID::get(Record[0]);
2210 F.ActualOriginalSourceFileName.assign(BlobStart, BlobLen);
2211 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2212 MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002213 break;
2214
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002215 case ORIGINAL_PCH_DIR:
Douglas Gregor69e16082012-10-18 21:47:16 +00002216 F.OriginalDir.assign(BlobStart, BlobLen);
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002217 break;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002218
Douglas Gregora930dc92012-10-22 18:42:04 +00002219 case INPUT_FILE_OFFSETS:
2220 F.InputFileOffsets = (const uint32_t *)BlobStart;
2221 F.InputFilesLoaded.resize(Record[0]);
Douglas Gregor745e6f12012-10-19 00:38:02 +00002222 break;
2223 }
Douglas Gregor745e6f12012-10-19 00:38:02 +00002224 }
2225
2226 Error("premature end of bitstream in AST file");
2227 return Failure;
2228}
2229
Douglas Gregor4825fd72012-10-22 22:50:17 +00002230bool ASTReader::ReadASTBlock(ModuleFile &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00002231 llvm::BitstreamCursor &Stream = F.Stream;
2232
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002233 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002234 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002235 return true;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002236 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002237
Douglas Gregor1d9d9892012-10-18 05:31:06 +00002238 // Read all of the records and blocks for the AST file.
Douglas Gregor8038d512009-04-10 17:25:41 +00002239 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002240 while (!Stream.AtEndOfStream()) {
2241 unsigned Code = Stream.ReadCode();
2242 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002243 if (Stream.ReadBlockEnd()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002244 Error("error at end of module block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002245 return true;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002246 }
Chris Lattner7356a312009-04-11 21:15:38 +00002247
Argyrios Kyrtzidis1f941242012-09-21 01:30:00 +00002248 DeclContext *DC = Context.getTranslationUnitDecl();
2249 if (!DC->hasExternalVisibleStorage() && DC->hasExternalLexicalStorage())
2250 DC->setMustBuildLookupTable();
2251
Douglas Gregor4825fd72012-10-22 22:50:17 +00002252 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002253 }
2254
2255 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2256 switch (Stream.ReadSubBlockID()) {
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002257 case DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00002258 // We lazily load the decls block, but we want to set up the
2259 // DeclsCursor cursor to point into it. Clone our current bitcode
2260 // cursor to it, enter the block and read the abbrevs in that block.
2261 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00002262 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00002263 if (Stream.SkipBlock() || // Skip with the main cursor.
2264 // Read the abbrevs.
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002265 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002266 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002267 return true;
Chris Lattner6367f6d2009-04-27 01:05:14 +00002268 }
2269 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002271 case DECL_UPDATES_BLOCK_ID:
2272 if (Stream.SkipBlock()) {
2273 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002274 return true;
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002275 }
2276 break;
2277
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002278 case PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00002279 F.MacroCursor = Stream;
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002280 if (!PP.getExternalSource())
2281 PP.setExternalSource(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00002282
Douglas Gregorecdcb882010-10-20 22:00:55 +00002283 if (Stream.SkipBlock() ||
2284 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002285 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002286 return true;
Chris Lattner7356a312009-04-11 21:15:38 +00002287 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00002288 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
Chris Lattner7356a312009-04-11 21:15:38 +00002289 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002290
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002291 case PREPROCESSOR_DETAIL_BLOCK_ID:
2292 F.PreprocessorDetailCursor = Stream;
2293 if (Stream.SkipBlock() ||
2294 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2295 PREPROCESSOR_DETAIL_BLOCK_ID)) {
2296 Error("malformed preprocessor detail record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002297 return true;
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002298 }
2299 F.PreprocessorDetailStartOffset
2300 = F.PreprocessorDetailCursor.GetCurrentBitNo();
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002301
2302 if (!PP.getPreprocessingRecord())
Argyrios Kyrtzidisc6c54522012-03-05 05:48:17 +00002303 PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002304 if (!PP.getPreprocessingRecord()->getExternalSource())
2305 PP.getPreprocessingRecord()->SetExternalSource(*this);
Douglas Gregor4800a5c2011-02-08 21:58:10 +00002306 break;
2307
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002308 case SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor4825fd72012-10-22 22:50:17 +00002309 if (ReadSourceManagerBlock(F))
2310 return true;
Douglas Gregor14f79002009-04-10 03:52:48 +00002311 break;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002312
2313 case SUBMODULE_BLOCK_ID:
Douglas Gregor4825fd72012-10-22 22:50:17 +00002314 if (ReadSubmoduleBlock(F))
2315 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002316 break;
2317
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002318 case COMMENTS_BLOCK_ID: {
2319 llvm::BitstreamCursor C = Stream;
2320 if (Stream.SkipBlock() ||
2321 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2322 Error("malformed comments block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002323 return true;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00002324 }
2325 CommentsCursors.push_back(std::make_pair(C, &F));
2326 break;
2327 }
2328
Douglas Gregor392ed2b2011-11-30 17:33:56 +00002329 default:
2330 if (!Stream.SkipBlock())
2331 break;
2332 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002333 return true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002334 }
Douglas Gregor8038d512009-04-10 17:25:41 +00002335 continue;
2336 }
2337
2338 if (Code == llvm::bitc::DEFINE_ABBREV) {
2339 Stream.ReadAbbrevRecord();
2340 continue;
2341 }
2342
2343 // Read and process a record.
2344 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00002345 const char *BlobStart = 0;
2346 unsigned BlobLen = 0;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002347 switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
Sebastian Redlc3632732010-10-05 15:59:54 +00002348 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00002349 default: // Default behavior: ignore.
2350 break;
2351
Douglas Gregora119da02011-08-02 16:26:37 +00002352 case TYPE_OFFSET: {
Sebastian Redl12d6da02010-07-19 22:06:55 +00002353 if (F.LocalNumTypes != 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002354 Error("duplicate TYPE_OFFSET record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002355 return true;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002356 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00002357 F.TypeOffsets = (const uint32_t *)BlobStart;
2358 F.LocalNumTypes = Record[0];
Douglas Gregore3605012011-08-02 18:32:54 +00002359 unsigned LocalBaseTypeIndex = Record[1];
2360 F.BaseTypeIndex = getTotalNumTypes();
Douglas Gregor1e849b62011-07-29 00:21:44 +00002361
Douglas Gregora119da02011-08-02 16:26:37 +00002362 if (F.LocalNumTypes > 0) {
2363 // Introduce the global -> local mapping for types within this module.
2364 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2365
2366 // Introduce the local -> global mapping for types within this module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002367 F.TypeRemap.insertOrReplace(
2368 std::make_pair(LocalBaseTypeIndex,
2369 F.BaseTypeIndex - LocalBaseTypeIndex));
Douglas Gregora119da02011-08-02 16:26:37 +00002370
2371 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2372 }
Douglas Gregor8038d512009-04-10 17:25:41 +00002373 break;
Douglas Gregora119da02011-08-02 16:26:37 +00002374 }
2375
Douglas Gregor496c7092011-08-03 15:48:04 +00002376 case DECL_OFFSET: {
Sebastian Redl12d6da02010-07-19 22:06:55 +00002377 if (F.LocalNumDecls != 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002378 Error("duplicate DECL_OFFSET record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002379 return true;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002380 }
Argyrios Kyrtzidis9d31fa72011-10-27 18:47:35 +00002381 F.DeclOffsets = (const DeclOffset *)BlobStart;
Sebastian Redl12d6da02010-07-19 22:06:55 +00002382 F.LocalNumDecls = Record[0];
Douglas Gregor496c7092011-08-03 15:48:04 +00002383 unsigned LocalBaseDeclID = Record[1];
Douglas Gregor9827a802011-07-29 00:56:45 +00002384 F.BaseDeclID = getTotalNumDecls();
Douglas Gregor96e973f2011-07-20 00:27:43 +00002385
Douglas Gregor496c7092011-08-03 15:48:04 +00002386 if (F.LocalNumDecls > 0) {
2387 // Introduce the global -> local mapping for declarations within this
2388 // module.
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00002389 GlobalDeclMap.insert(
2390 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
Douglas Gregor496c7092011-08-03 15:48:04 +00002391
2392 // Introduce the local -> global mapping for declarations within this
2393 // module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002394 F.DeclRemap.insertOrReplace(
2395 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
Douglas Gregor496c7092011-08-03 15:48:04 +00002396
Douglas Gregora1be2782011-12-17 23:38:30 +00002397 // Introduce the global -> local mapping for declarations within this
2398 // module.
2399 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2400
Douglas Gregor496c7092011-08-03 15:48:04 +00002401 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2402 }
Douglas Gregor8038d512009-04-10 17:25:41 +00002403 break;
Douglas Gregor496c7092011-08-03 15:48:04 +00002404 }
2405
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002406 case TU_UPDATE_LEXICAL: {
Douglas Gregor35942772011-09-09 21:34:22 +00002407 DeclContext *TU = Context.getTranslationUnitDecl();
Douglas Gregor0d95f772011-08-24 19:03:07 +00002408 DeclContextInfo &Info = F.DeclContextInfos[TU];
2409 Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
2410 Info.NumLexicalDecls
2411 = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
Douglas Gregor35942772011-09-09 21:34:22 +00002412 TU->setHasExternalLexicalStorage(true);
Sebastian Redld692af72010-07-27 18:24:41 +00002413 break;
2414 }
2415
Sebastian Redle1dde812010-08-24 00:50:04 +00002416 case UPDATE_VISIBLE: {
Douglas Gregor496c7092011-08-03 15:48:04 +00002417 unsigned Idx = 0;
2418 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Benjamin Kramerb1758c62012-04-15 12:36:49 +00002419 ASTDeclContextNameLookupTable *Table =
2420 ASTDeclContextNameLookupTable::Create(
Douglas Gregor496c7092011-08-03 15:48:04 +00002421 (const unsigned char *)BlobStart + Record[Idx++],
Sebastian Redle1dde812010-08-24 00:50:04 +00002422 (const unsigned char *)BlobStart,
Douglas Gregor393f2492011-07-22 00:38:23 +00002423 ASTDeclContextNameLookupTrait(*this, F));
Douglas Gregor35942772011-09-09 21:34:22 +00002424 if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2425 DeclContext *TU = Context.getTranslationUnitDecl();
Douglas Gregor0d95f772011-08-24 19:03:07 +00002426 F.DeclContextInfos[TU].NameLookupTableData = Table;
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00002427 TU->setHasExternalVisibleStorage(true);
Sebastian Redle1dde812010-08-24 00:50:04 +00002428 } else
Douglas Gregor496c7092011-08-03 15:48:04 +00002429 PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
Sebastian Redle1dde812010-08-24 00:50:04 +00002430 break;
2431 }
2432
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002433 case IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00002434 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002435 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00002436 F.IdentifierLookupTable
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002437 = ASTIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00002438 (const unsigned char *)F.IdentifierTableData + Record[0],
2439 (const unsigned char *)F.IdentifierTableData,
Sebastian Redlc3632732010-10-05 15:59:54 +00002440 ASTIdentifierLookupTrait(*this, F));
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002441
2442 PP.getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002443 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00002444 break;
2445
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002446 case IDENTIFIER_OFFSET: {
Sebastian Redl2da08f92010-07-19 22:28:42 +00002447 if (F.LocalNumIdentifiers != 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002448 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002449 return true;
Douglas Gregorafaf3082009-04-11 00:14:32 +00002450 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00002451 F.IdentifierOffsets = (const uint32_t *)BlobStart;
2452 F.LocalNumIdentifiers = Record[0];
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002453 unsigned LocalBaseIdentifierID = Record[1];
Douglas Gregor9827a802011-07-29 00:56:45 +00002454 F.BaseIdentifierID = getTotalNumIdentifiers();
Douglas Gregor67268d02011-07-20 00:59:32 +00002455
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002456 if (F.LocalNumIdentifiers > 0) {
2457 // Introduce the global -> local mapping for identifiers within this
2458 // module.
2459 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2460 &F));
2461
2462 // Introduce the local -> global mapping for identifiers within this
2463 // module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002464 F.IdentifierRemap.insertOrReplace(
2465 std::make_pair(LocalBaseIdentifierID,
2466 F.BaseIdentifierID - LocalBaseIdentifierID));
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002467
2468 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2469 + F.LocalNumIdentifiers);
2470 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00002471 break;
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002472 }
Douglas Gregora8235d62012-10-09 23:05:51 +00002473
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002474 case EXTERNAL_DEFINITIONS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002475 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2476 ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregorfdd01722009-04-14 00:24:19 +00002477 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00002478
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002479 case SPECIAL_TYPES:
Douglas Gregor393f2492011-07-22 00:38:23 +00002480 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2481 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
Douglas Gregorad1de002009-04-18 05:55:16 +00002482 break;
2483
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002484 case STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00002485 TotalNumStatements += Record[0];
2486 TotalNumMacros += Record[1];
2487 TotalLexicalDeclContexts += Record[2];
2488 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00002489 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002490
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002491 case UNUSED_FILESCOPED_DECLS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002492 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2493 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
Tanya Lattnere6bbc012010-02-12 00:07:30 +00002494 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00002495
Sean Huntebcbe1d2011-05-04 23:29:54 +00002496 case DELEGATING_CTORS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002497 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2498 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
Sean Huntebcbe1d2011-05-04 23:29:54 +00002499 break;
2500
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002501 case WEAK_UNDECLARED_IDENTIFIERS:
Douglas Gregor31e37b22011-07-28 18:09:57 +00002502 if (Record.size() % 4 != 0) {
2503 Error("invalid weak identifiers record");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002504 return true;
Douglas Gregor31e37b22011-07-28 18:09:57 +00002505 }
2506
2507 // FIXME: Ignore weak undeclared identifiers from non-original PCH
2508 // files. This isn't the way to do it :)
2509 WeakUndeclaredIdentifiers.clear();
2510
2511 // Translate the weak, undeclared identifiers into global IDs.
2512 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2513 WeakUndeclaredIdentifiers.push_back(
2514 getGlobalIdentifierID(F, Record[I++]));
2515 WeakUndeclaredIdentifiers.push_back(
2516 getGlobalIdentifierID(F, Record[I++]));
2517 WeakUndeclaredIdentifiers.push_back(
2518 ReadSourceLocation(F, Record, I).getRawEncoding());
2519 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2520 }
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00002521 break;
2522
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002523 case LOCALLY_SCOPED_EXTERNAL_DECLS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002524 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2525 LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregor14c22f22009-04-22 22:18:58 +00002526 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002527
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002528 case SELECTOR_OFFSETS: {
Sebastian Redl059612d2010-08-03 21:58:15 +00002529 F.SelectorOffsets = (const uint32_t *)BlobStart;
Sebastian Redl725cd962010-08-04 20:40:17 +00002530 F.LocalNumSelectors = Record[0];
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002531 unsigned LocalBaseSelectorID = Record[1];
Douglas Gregor9827a802011-07-29 00:56:45 +00002532 F.BaseSelectorID = getTotalNumSelectors();
Douglas Gregor96958cb2011-07-20 01:10:58 +00002533
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002534 if (F.LocalNumSelectors > 0) {
2535 // Introduce the global -> local mapping for selectors within this
2536 // module.
2537 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2538
2539 // Introduce the local -> global mapping for selectors within this
2540 // module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002541 F.SelectorRemap.insertOrReplace(
2542 std::make_pair(LocalBaseSelectorID,
2543 F.BaseSelectorID - LocalBaseSelectorID));
Douglas Gregor83941df2009-04-25 17:48:32 +00002544
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002545 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2546 }
2547 break;
2548 }
2549
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002550 case METHOD_POOL:
Sebastian Redl725cd962010-08-04 20:40:17 +00002551 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
Douglas Gregor83941df2009-04-25 17:48:32 +00002552 if (Record[0])
Sebastian Redl725cd962010-08-04 20:40:17 +00002553 F.SelectorLookupTable
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002554 = ASTSelectorLookupTable::Create(
Sebastian Redl725cd962010-08-04 20:40:17 +00002555 F.SelectorLookupTableData + Record[0],
2556 F.SelectorLookupTableData,
Douglas Gregor409448c2011-07-21 22:35:25 +00002557 ASTSelectorLookupTrait(*this, F));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00002558 TotalNumMethodPoolEntries += Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002559 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00002560
Sebastian Redl4ee5a6f2010-09-22 00:42:30 +00002561 case REFERENCED_SELECTOR_POOL:
Douglas Gregor8451ec72011-07-28 14:41:43 +00002562 if (!Record.empty()) {
2563 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2564 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2565 Record[Idx++]));
2566 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2567 getRawEncoding());
2568 }
2569 }
Fariborz Jahanian32019832010-07-23 19:11:11 +00002570 break;
2571
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002572 case PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002573 if (!Record.empty() && Listener)
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002574 Listener->ReadCounter(F, Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00002575 break;
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00002576
2577 case FILE_SORTED_DECLS:
2578 F.FileSortedDecls = (const DeclID *)BlobStart;
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002579 F.NumFileSortedDecls = Record[0];
Argyrios Kyrtzidis10f3df52011-10-28 22:54:21 +00002580 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002581
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002582 case SOURCE_LOCATION_OFFSETS: {
2583 F.SLocEntryOffsets = (const uint32_t *)BlobStart;
Sebastian Redl518d8cb2010-07-20 21:20:32 +00002584 F.LocalNumSLocEntries = Record[0];
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002585 unsigned SLocSpaceSize = Record[1];
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002586 llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002587 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2588 SLocSpaceSize);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002589 // Make our entry in the range map. BaseID is negative and growing, so
2590 // we invert it. Because we invert it, though, we need the other end of
2591 // the range.
2592 unsigned RangeStart =
2593 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2594 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2595 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2596
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002597 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2598 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2599 GlobalSLocOffsetMap.insert(
2600 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2601 - SLocSpaceSize,&F));
2602
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002603 // Initialize the remapping table.
2604 // Invalid stays invalid.
2605 F.SLocRemap.insert(std::make_pair(0U, 0));
2606 // This module. Base was 2 when being compiled.
2607 F.SLocRemap.insert(std::make_pair(2U,
2608 static_cast<int>(F.SLocEntryBaseOffset - 2)));
Douglas Gregor0cdd7982011-07-21 18:46:38 +00002609
2610 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002611 break;
2612 }
2613
Douglas Gregor5d51a1d2011-08-01 16:01:55 +00002614 case MODULE_OFFSET_MAP: {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002615 // Additional remapping information.
2616 const unsigned char *Data = (const unsigned char*)BlobStart;
2617 const unsigned char *DataEnd = Data + BlobLen;
Douglas Gregorf33740e2011-08-02 10:56:51 +00002618
2619 // Continuous range maps we may be updating in our module.
2620 ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002621 ContinuousRangeMap<uint32_t, int, 2>::Builder
2622 IdentifierRemap(F.IdentifierRemap);
Douglas Gregora8235d62012-10-09 23:05:51 +00002623 ContinuousRangeMap<uint32_t, int, 2>::Builder
2624 MacroRemap(F.MacroRemap);
2625 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002626 PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2627 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregor26ced122011-12-01 00:59:36 +00002628 SubmoduleRemap(F.SubmoduleRemap);
2629 ContinuousRangeMap<uint32_t, int, 2>::Builder
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002630 SelectorRemap(F.SelectorRemap);
Douglas Gregor496c7092011-08-03 15:48:04 +00002631 ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
Douglas Gregora119da02011-08-02 16:26:37 +00002632 ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2633
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002634 while(Data < DataEnd) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002635 uint16_t Len = io::ReadUnalignedLE16(Data);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002636 StringRef Name = StringRef((const char*)Data, Len);
Douglas Gregorf33740e2011-08-02 10:56:51 +00002637 Data += Len;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002638 ModuleFile *OM = ModuleMgr.lookup(Name);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002639 if (!OM) {
2640 Error("SourceLocation remap refers to unknown module");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002641 return true;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002642 }
Douglas Gregorf33740e2011-08-02 10:56:51 +00002643
2644 uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2645 uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregora8235d62012-10-09 23:05:51 +00002646 uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregorf33740e2011-08-02 10:56:51 +00002647 uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregor26ced122011-12-01 00:59:36 +00002648 uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregorf33740e2011-08-02 10:56:51 +00002649 uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2650 uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
Douglas Gregora119da02011-08-02 16:26:37 +00002651 uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
Douglas Gregorf33740e2011-08-02 10:56:51 +00002652
2653 // Source location offset is mapped to OM->SLocEntryBaseOffset.
2654 SLocRemap.insert(std::make_pair(SLocOffset,
2655 static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
Douglas Gregor6ec60e02011-08-03 21:49:18 +00002656 IdentifierRemap.insert(
2657 std::make_pair(IdentifierIDOffset,
2658 OM->BaseIdentifierID - IdentifierIDOffset));
Douglas Gregora8235d62012-10-09 23:05:51 +00002659 MacroRemap.insert(std::make_pair(MacroIDOffset,
2660 OM->BaseMacroID - MacroIDOffset));
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002661 PreprocessedEntityRemap.insert(
2662 std::make_pair(PreprocessedEntityIDOffset,
2663 OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
Douglas Gregor26ced122011-12-01 00:59:36 +00002664 SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2665 OM->BaseSubmoduleID - SubmoduleIDOffset));
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00002666 SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2667 OM->BaseSelectorID - SelectorIDOffset));
Douglas Gregor496c7092011-08-03 15:48:04 +00002668 DeclRemap.insert(std::make_pair(DeclIDOffset,
2669 OM->BaseDeclID - DeclIDOffset));
2670
Douglas Gregora119da02011-08-02 16:26:37 +00002671 TypeRemap.insert(std::make_pair(TypeIndexOffset,
Douglas Gregore3605012011-08-02 18:32:54 +00002672 OM->BaseTypeIndex - TypeIndexOffset));
Douglas Gregora1be2782011-12-17 23:38:30 +00002673
2674 // Global -> local mappings.
2675 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002676 }
2677 break;
2678 }
2679
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002680 case SOURCE_MANAGER_LINE_TABLE:
2681 if (ParseLineTable(F, Record))
Douglas Gregor4825fd72012-10-22 22:50:17 +00002682 return true;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002683 break;
2684
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002685 case SOURCE_LOCATION_PRELOADS: {
2686 // Need to transform from the local view (1-based IDs) to the global view,
2687 // which is based off F.SLocEntryBaseID.
Douglas Gregorf249bf32011-08-25 21:09:44 +00002688 if (!F.PreloadSLocEntries.empty()) {
2689 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002690 return true;
Douglas Gregorf249bf32011-08-25 21:09:44 +00002691 }
2692
2693 F.PreloadSLocEntries.swap(Record);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002694 break;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002695 }
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002696
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002697 case STAT_CACHE: {
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002698 if (!DisableStatCache) {
2699 ASTStatCache *MyStatCache =
2700 new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2701 (const unsigned char *)BlobStart,
2702 NumStatHits, NumStatMisses);
2703 FileMgr.addStatCache(MyStatCache);
2704 F.StatCache = MyStatCache;
2705 }
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002706 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00002707 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00002708
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002709 case EXT_VECTOR_DECLS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002710 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2711 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregorb81c1702009-04-27 20:06:05 +00002712 break;
2713
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002714 case VTABLE_USES:
Douglas Gregordfe65432011-07-28 19:11:31 +00002715 if (Record.size() % 3 != 0) {
2716 Error("Invalid VTABLE_USES record");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002717 return true;
Douglas Gregordfe65432011-07-28 19:11:31 +00002718 }
2719
Sebastian Redl40566802010-08-05 18:21:25 +00002720 // Later tables overwrite earlier ones.
Douglas Gregordfe65432011-07-28 19:11:31 +00002721 // FIXME: Modules will have some trouble with this. This is clearly not
2722 // the right way to do this.
Douglas Gregor409448c2011-07-21 22:35:25 +00002723 VTableUses.clear();
Douglas Gregordfe65432011-07-28 19:11:31 +00002724
2725 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2726 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2727 VTableUses.push_back(
2728 ReadSourceLocation(F, Record, Idx).getRawEncoding());
2729 VTableUses.push_back(Record[Idx++]);
2730 }
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00002731 break;
2732
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002733 case DYNAMIC_CLASSES:
Douglas Gregor409448c2011-07-21 22:35:25 +00002734 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2735 DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00002736 break;
2737
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002738 case PENDING_IMPLICIT_INSTANTIATIONS:
Douglas Gregorf2abb522011-07-28 19:26:52 +00002739 if (PendingInstantiations.size() % 2 != 0) {
Axel Naumann39d26c32012-10-02 09:09:43 +00002740 Error("Invalid existing PendingInstantiations");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002741 return true;
Axel Naumann39d26c32012-10-02 09:09:43 +00002742 }
2743
2744 if (Record.size() % 2 != 0) {
Douglas Gregorf2abb522011-07-28 19:26:52 +00002745 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002746 return true;
Douglas Gregorf2abb522011-07-28 19:26:52 +00002747 }
Axel Naumann39d26c32012-10-02 09:09:43 +00002748
Douglas Gregorf2abb522011-07-28 19:26:52 +00002749 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2750 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2751 PendingInstantiations.push_back(
2752 ReadSourceLocation(F, Record, I).getRawEncoding());
2753 }
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00002754 break;
2755
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002756 case SEMA_DECL_REFS:
Sebastian Redl40566802010-08-05 18:21:25 +00002757 // Later tables overwrite earlier ones.
Douglas Gregor409448c2011-07-21 22:35:25 +00002758 // FIXME: Modules will have some trouble with this.
2759 SemaDeclRefs.clear();
2760 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2761 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00002762 break;
2763
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002764 case PPD_ENTITIES_OFFSETS: {
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00002765 F.PreprocessedEntityOffsets = (const PPEntityOffset *)BlobStart;
2766 assert(BlobLen % sizeof(PPEntityOffset) == 0);
2767 F.NumPreprocessedEntities = BlobLen / sizeof(PPEntityOffset);
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002768
2769 unsigned LocalBasePreprocessedEntityID = Record[0];
Douglas Gregorfb2d9e02011-08-04 16:36:56 +00002770
Douglas Gregor4c30bb12011-07-21 00:47:40 +00002771 unsigned StartingID;
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002772 if (!PP.getPreprocessingRecord())
Argyrios Kyrtzidisc6c54522012-03-05 05:48:17 +00002773 PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002774 if (!PP.getPreprocessingRecord()->getExternalSource())
2775 PP.getPreprocessingRecord()->SetExternalSource(*this);
2776 StartingID
2777 = PP.getPreprocessingRecord()
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002778 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Douglas Gregor9827a802011-07-29 00:56:45 +00002779 F.BasePreprocessedEntityID = StartingID;
Douglas Gregor4c30bb12011-07-21 00:47:40 +00002780
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00002781 if (F.NumPreprocessedEntities > 0) {
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002782 // Introduce the global -> local mapping for preprocessed entities in
2783 // this module.
2784 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2785
2786 // Introduce the local -> global mapping for preprocessed entities in
2787 // this module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00002788 F.PreprocessedEntityRemap.insertOrReplace(
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002789 std::make_pair(LocalBasePreprocessedEntityID,
2790 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2791 }
Douglas Gregor272b6bc2011-08-04 18:56:47 +00002792
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002793 break;
Douglas Gregor4c30bb12011-07-21 00:47:40 +00002794 }
2795
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002796 case DECL_UPDATE_OFFSETS: {
2797 if (Record.size() % 2 != 0) {
2798 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002799 return true;
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002800 }
2801 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
Douglas Gregor496c7092011-08-03 15:48:04 +00002802 DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2803 .push_back(std::make_pair(&F, Record[I+1]));
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00002804 break;
2805 }
2806
Sebastian Redl8538e8d2010-08-18 23:57:32 +00002807 case DECL_REPLACEMENTS: {
Argyrios Kyrtzidisef23b602011-10-31 07:20:15 +00002808 if (Record.size() % 3 != 0) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002809 Error("invalid DECL_REPLACEMENTS block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002810 return true;
Sebastian Redl0b17c612010-08-13 00:28:03 +00002811 }
Argyrios Kyrtzidisef23b602011-10-31 07:20:15 +00002812 for (unsigned I = 0, N = Record.size(); I != N; I += 3)
Douglas Gregor496c7092011-08-03 15:48:04 +00002813 ReplacedDecls[getGlobalDeclID(F, Record[I])]
Argyrios Kyrtzidisef23b602011-10-31 07:20:15 +00002814 = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
Sebastian Redl0b17c612010-08-13 00:28:03 +00002815 break;
2816 }
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00002817
Douglas Gregorcff9f262012-01-27 01:47:08 +00002818 case OBJC_CATEGORIES_MAP: {
2819 if (F.LocalNumObjCCategoriesInMap != 0) {
2820 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002821 return true;
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00002822 }
Douglas Gregorcff9f262012-01-27 01:47:08 +00002823
2824 F.LocalNumObjCCategoriesInMap = Record[0];
2825 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)BlobStart;
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00002826 break;
2827 }
Douglas Gregor7c789c12010-10-29 22:39:52 +00002828
Douglas Gregorcff9f262012-01-27 01:47:08 +00002829 case OBJC_CATEGORIES:
2830 F.ObjCCategories.swap(Record);
2831 break;
2832
Douglas Gregor7c789c12010-10-29 22:39:52 +00002833 case CXX_BASE_SPECIFIER_OFFSETS: {
2834 if (F.LocalNumCXXBaseSpecifiers != 0) {
2835 Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002836 return true;
Douglas Gregor7c789c12010-10-29 22:39:52 +00002837 }
2838
2839 F.LocalNumCXXBaseSpecifiers = Record[0];
2840 F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
Jonathan D. Turner1da90142011-07-21 21:15:19 +00002841 NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
Douglas Gregor7c789c12010-10-29 22:39:52 +00002842 break;
2843 }
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002844
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +00002845 case DIAG_PRAGMA_MAPPINGS:
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002846 if (Record.size() % 2 != 0) {
2847 Error("invalid DIAG_USER_MAPPINGS block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002848 return true;
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002849 }
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002850
2851 if (F.PragmaDiagMappings.empty())
2852 F.PragmaDiagMappings.swap(Record);
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002853 else
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002854 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2855 Record.begin(), Record.end());
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00002856 break;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002857
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00002858 case CUDA_SPECIAL_DECL_REFS:
2859 // Later tables overwrite earlier ones.
Douglas Gregor409448c2011-07-21 22:35:25 +00002860 // FIXME: Modules will have trouble with this.
2861 CUDASpecialDeclRefs.clear();
2862 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2863 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00002864 break;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002865
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002866 case HEADER_SEARCH_TABLE: {
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002867 F.HeaderFileInfoTableData = BlobStart;
2868 F.LocalNumHeaderFileInfos = Record[1];
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002869 F.HeaderFileFrameworkStrings = BlobStart + Record[2];
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002870 if (Record[0]) {
2871 F.HeaderFileInfoTable
2872 = HeaderFileInfoLookupTable::Create(
2873 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002874 (const unsigned char *)F.HeaderFileInfoTableData,
Douglas Gregor95eab172011-07-28 20:55:49 +00002875 HeaderFileInfoTrait(*this, F,
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002876 &PP.getHeaderSearchInfo(),
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002877 BlobStart + Record[2]));
Douglas Gregor712f2fc2011-09-09 22:02:16 +00002878
2879 PP.getHeaderSearchInfo().SetExternalSource(this);
2880 if (!PP.getHeaderSearchInfo().getExternalLookup())
2881 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00002882 }
2883 break;
Douglas Gregorb4dc4852011-07-28 04:50:02 +00002884 }
2885
Peter Collingbourne84bccea2011-02-15 19:46:30 +00002886 case FP_PRAGMA_OPTIONS:
2887 // Later tables overwrite earlier ones.
2888 FPPragmaOptions.swap(Record);
2889 break;
2890
2891 case OPENCL_EXTENSIONS:
2892 // Later tables overwrite earlier ones.
2893 OpenCLExtensions.swap(Record);
2894 break;
Sean Huntebcbe1d2011-05-04 23:29:54 +00002895
2896 case TENTATIVE_DEFINITIONS:
Douglas Gregor409448c2011-07-21 22:35:25 +00002897 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2898 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
Sean Huntebcbe1d2011-05-04 23:29:54 +00002899 break;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002900
2901 case KNOWN_NAMESPACES:
Douglas Gregor409448c2011-07-21 22:35:25 +00002902 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2903 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002904 break;
Douglas Gregorf6137e42011-12-03 00:59:55 +00002905
2906 case IMPORTED_MODULES: {
2907 if (F.Kind != MK_Module) {
2908 // If we aren't loading a module (which has its own exports), make
2909 // all of the imported modules visible.
2910 // FIXME: Deal with macros-only imports.
2911 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2912 if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2913 ImportedModules.push_back(GlobalID);
2914 }
2915 }
2916 break;
Douglas Gregora1be2782011-12-17 23:38:30 +00002917 }
Douglas Gregor2171bf12012-01-15 16:58:34 +00002918
Douglas Gregora1be2782011-12-17 23:38:30 +00002919 case LOCAL_REDECLARATIONS: {
Douglas Gregor2171bf12012-01-15 16:58:34 +00002920 F.RedeclarationChains.swap(Record);
2921 break;
2922 }
2923
2924 case LOCAL_REDECLARATIONS_MAP: {
2925 if (F.LocalNumRedeclarationsInMap != 0) {
2926 Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002927 return true;
Douglas Gregora1be2782011-12-17 23:38:30 +00002928 }
Douglas Gregorf6137e42011-12-03 00:59:55 +00002929
Douglas Gregor2171bf12012-01-15 16:58:34 +00002930 F.LocalNumRedeclarationsInMap = Record[0];
2931 F.RedeclarationsMap = (const LocalRedeclarationsInfo *)BlobStart;
Douglas Gregora1be2782011-12-17 23:38:30 +00002932 break;
Douglas Gregorf6137e42011-12-03 00:59:55 +00002933 }
Douglas Gregorc3cfd2a2011-12-22 21:40:42 +00002934
2935 case MERGED_DECLARATIONS: {
2936 for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2937 GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2938 SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2939 for (unsigned N = Record[Idx++]; N > 0; --N)
2940 Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2941 }
2942 break;
2943 }
Douglas Gregora8235d62012-10-09 23:05:51 +00002944
2945 case MACRO_OFFSET: {
2946 if (F.LocalNumMacros != 0) {
2947 Error("duplicate MACRO_OFFSET record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002948 return true;
Douglas Gregora8235d62012-10-09 23:05:51 +00002949 }
2950 F.MacroOffsets = (const uint32_t *)BlobStart;
2951 F.LocalNumMacros = Record[0];
2952 unsigned LocalBaseMacroID = Record[1];
2953 F.BaseMacroID = getTotalNumMacros();
2954
2955 if (F.LocalNumMacros > 0) {
2956 // Introduce the global -> local mapping for macros within this module.
2957 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2958
2959 // Introduce the local -> global mapping for macros within this module.
2960 F.MacroRemap.insertOrReplace(
2961 std::make_pair(LocalBaseMacroID,
2962 F.BaseMacroID - LocalBaseMacroID));
2963
2964 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2965 }
2966 break;
2967 }
2968
2969 case MACRO_UPDATES: {
2970 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2971 MacroID ID = getGlobalMacroID(F, Record[I++]);
2972 if (I == N)
2973 break;
2974
Douglas Gregor54c8a402012-10-12 00:16:50 +00002975 SourceLocation UndefLoc = ReadSourceLocation(F, Record, I);
2976 SubmoduleID SubmoduleID = getGlobalSubmoduleID(F, Record[I++]);;
2977 MacroUpdate Update;
2978 Update.UndefLoc = UndefLoc;
2979 MacroUpdates[ID].push_back(std::make_pair(SubmoduleID, Update));
Douglas Gregora8235d62012-10-09 23:05:51 +00002980 }
2981 break;
2982 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00002983 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002984 }
Sebastian Redl3c7f4132010-08-18 23:57:06 +00002985 Error("premature end of bitstream in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00002986 return true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002987}
2988
Douglas Gregorecc2c092011-12-01 22:20:10 +00002989void ASTReader::makeNamesVisible(const HiddenNames &Names) {
Douglas Gregor13292642011-12-02 15:45:10 +00002990 for (unsigned I = 0, N = Names.size(); I != N; ++I) {
Douglas Gregor54c8a402012-10-12 00:16:50 +00002991 switch (Names[I].getKind()) {
2992 case HiddenName::Declaration:
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00002993 Names[I].getDecl()->Hidden = false;
Douglas Gregor54c8a402012-10-12 00:16:50 +00002994 break;
2995
2996 case HiddenName::MacroVisibility: {
2997 std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2998 Macro.second->setHidden(!Macro.second->isPublic());
2999 if (Macro.second->isDefined()) {
3000 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
3001 }
3002 break;
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00003003 }
3004
Douglas Gregor54c8a402012-10-12 00:16:50 +00003005 case HiddenName::MacroUndef: {
3006 std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
3007 if (Macro.second->isDefined()) {
3008 Macro.second->setUndefLoc(Names[I].getMacroUndefLoc());
3009 if (PPMutationListener *Listener = PP.getPPMutationListener())
3010 Listener->UndefinedMacro(Macro.second);
3011 PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
3012 }
3013 break;
3014 }
Douglas Gregor1d4c1132011-12-20 22:06:13 +00003015 }
Douglas Gregor13292642011-12-02 15:45:10 +00003016 }
Douglas Gregorecc2c092011-12-01 22:20:10 +00003017}
3018
Douglas Gregor5e356932011-12-01 17:11:21 +00003019void ASTReader::makeModuleVisible(Module *Mod,
3020 Module::NameVisibilityKind NameVisibility) {
3021 llvm::SmallPtrSet<Module *, 4> Visited;
3022 llvm::SmallVector<Module *, 4> Stack;
3023 Stack.push_back(Mod);
3024 while (!Stack.empty()) {
3025 Mod = Stack.back();
3026 Stack.pop_back();
3027
3028 if (NameVisibility <= Mod->NameVisibility) {
3029 // This module already has this level of visibility (or greater), so
3030 // there is nothing more to do.
3031 continue;
3032 }
3033
Douglas Gregor51f564f2011-12-31 04:05:44 +00003034 if (!Mod->isAvailable()) {
3035 // Modules that aren't available cannot be made visible.
3036 continue;
3037 }
3038
Douglas Gregor5e356932011-12-01 17:11:21 +00003039 // Update the module's name visibility.
3040 Mod->NameVisibility = NameVisibility;
3041
Douglas Gregorecc2c092011-12-01 22:20:10 +00003042 // If we've already deserialized any names from this module,
Douglas Gregor5e356932011-12-01 17:11:21 +00003043 // mark them as visible.
Douglas Gregorecc2c092011-12-01 22:20:10 +00003044 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3045 if (Hidden != HiddenNamesMap.end()) {
3046 makeNamesVisible(Hidden->second);
3047 HiddenNamesMap.erase(Hidden);
3048 }
Douglas Gregor5e356932011-12-01 17:11:21 +00003049
3050 // Push any non-explicit submodules onto the stack to be marked as
3051 // visible.
Douglas Gregorb7a78192012-01-04 23:32:19 +00003052 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3053 SubEnd = Mod->submodule_end();
Douglas Gregor5e356932011-12-01 17:11:21 +00003054 Sub != SubEnd; ++Sub) {
Douglas Gregorb7a78192012-01-04 23:32:19 +00003055 if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
3056 Stack.push_back(*Sub);
Douglas Gregor5e356932011-12-01 17:11:21 +00003057 }
Douglas Gregor07165b92011-12-02 19:11:09 +00003058
3059 // Push any exported modules onto the stack to be marked as visible.
Douglas Gregor0adaa882011-12-05 17:28:06 +00003060 bool AnyWildcard = false;
3061 bool UnrestrictedWildcard = false;
3062 llvm::SmallVector<Module *, 4> WildcardRestrictions;
Douglas Gregor07165b92011-12-02 19:11:09 +00003063 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
3064 Module *Exported = Mod->Exports[I].getPointer();
Douglas Gregor0adaa882011-12-05 17:28:06 +00003065 if (!Mod->Exports[I].getInt()) {
3066 // Export a named module directly; no wildcards involved.
3067 if (Visited.insert(Exported))
Douglas Gregor07165b92011-12-02 19:11:09 +00003068 Stack.push_back(Exported);
Douglas Gregor0adaa882011-12-05 17:28:06 +00003069
3070 continue;
Douglas Gregor07165b92011-12-02 19:11:09 +00003071 }
Douglas Gregor0adaa882011-12-05 17:28:06 +00003072
3073 // Wildcard export: export all of the imported modules that match
3074 // the given pattern.
3075 AnyWildcard = true;
3076 if (UnrestrictedWildcard)
3077 continue;
3078
3079 if (Module *Restriction = Mod->Exports[I].getPointer())
3080 WildcardRestrictions.push_back(Restriction);
3081 else {
3082 WildcardRestrictions.clear();
3083 UnrestrictedWildcard = true;
3084 }
3085 }
3086
3087 // If there were any wildcards, push any imported modules that were
3088 // re-exported by the wildcard restriction.
3089 if (!AnyWildcard)
3090 continue;
3091
3092 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
3093 Module *Imported = Mod->Imports[I];
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00003094 if (!Visited.insert(Imported))
Douglas Gregor0adaa882011-12-05 17:28:06 +00003095 continue;
3096
3097 bool Acceptable = UnrestrictedWildcard;
3098 if (!Acceptable) {
3099 // Check whether this module meets one of the restrictions.
3100 for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
3101 Module *Restriction = WildcardRestrictions[R];
3102 if (Imported == Restriction || Imported->isSubModuleOf(Restriction)) {
3103 Acceptable = true;
3104 break;
3105 }
3106 }
3107 }
3108
3109 if (!Acceptable)
3110 continue;
3111
Douglas Gregor0adaa882011-12-05 17:28:06 +00003112 Stack.push_back(Imported);
Douglas Gregor07165b92011-12-02 19:11:09 +00003113 }
Douglas Gregor5e356932011-12-01 17:11:21 +00003114 }
3115}
3116
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00003117ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
Douglas Gregor38295be2012-10-22 23:51:00 +00003118 ModuleKind Type,
3119 unsigned ClientLoadCapabilities) {
Douglas Gregor057df202012-01-18 20:56:22 +00003120 // Bump the generation number.
Douglas Gregorcff9f262012-01-27 01:47:08 +00003121 unsigned PreviousGeneration = CurrentGeneration++;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003122
3123 // Load the core of the AST files.
3124 llvm::SmallVector<ModuleFile *, 4> Loaded;
Douglas Gregor38295be2012-10-22 23:51:00 +00003125 switch(ReadASTCore(FileName, Type, /*ImportedBy=*/0, Loaded,
3126 ClientLoadCapabilities)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00003127 case Failure: return Failure;
Douglas Gregor4825fd72012-10-22 22:50:17 +00003128 case OutOfDate: return OutOfDate;
3129 case VersionMismatch: return VersionMismatch;
3130 case ConfigurationMismatch: return ConfigurationMismatch;
3131 case HadErrors: return HadErrors;
Sebastian Redlcdf3b832010-07-16 20:41:52 +00003132 case Success: break;
3133 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003134
3135 // Here comes stuff that we only do once the entire chain is loaded.
Douglas Gregor057df202012-01-18 20:56:22 +00003136
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003137 // Load the AST blocks of all of the modules that we loaded.
3138 for (llvm::SmallVectorImpl<ModuleFile *>::iterator M = Loaded.begin(),
3139 MEnd = Loaded.end();
3140 M != MEnd; ++M) {
3141 ModuleFile &F = **M;
3142
3143 // Read the AST block.
Douglas Gregor4825fd72012-10-22 22:50:17 +00003144 if (ReadASTBlock(F))
3145 return Failure;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003146
3147 // Once read, set the ModuleFile bit base offset and update the size in
3148 // bits of all files we've seen.
3149 F.GlobalBitOffset = TotalModulesSizeInBits;
3150 TotalModulesSizeInBits += F.SizeInBits;
3151 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3152
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003153 // Preload SLocEntries.
3154 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3155 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Douglas Gregor8b53d142012-10-22 22:53:10 +00003156 // Load it through the SourceManager and don't call ReadSLocEntry()
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003157 // directly because the entry may have already been loaded in which case
Douglas Gregor8b53d142012-10-22 22:53:10 +00003158 // calling ReadSLocEntry() directly would trigger an assertion in
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003159 // SourceManager.
3160 SourceMgr.getLoadedSLocEntryByID(Index);
3161 }
3162 }
3163
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003164 // Check the predefines buffers.
Douglas Gregor38295be2012-10-22 23:51:00 +00003165 bool ConfigComplain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
Douglas Gregor6236a292011-12-02 21:56:05 +00003166 if (!DisableValidation && Type == MK_PCH &&
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00003167 // FIXME: CheckPredefinesBuffers also sets the SuggestedPredefines;
3168 // if DisableValidation is true, defines that were set on command-line
3169 // but not in the PCH file will not be added to SuggestedPredefines.
Douglas Gregor38295be2012-10-22 23:51:00 +00003170 CheckPredefinesBuffers(ConfigComplain))
Douglas Gregor4825fd72012-10-22 22:50:17 +00003171 return ConfigurationMismatch;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003172
Douglas Gregoreee242f2011-10-27 09:33:13 +00003173 // Mark all of the identifiers in the identifier table as being out of date,
3174 // so that various accessors know to check the loaded modules when the
3175 // identifier is used.
Douglas Gregor712f2fc2011-09-09 22:02:16 +00003176 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3177 IdEnd = PP.getIdentifierTable().end();
3178 Id != IdEnd; ++Id)
Douglas Gregoreee242f2011-10-27 09:33:13 +00003179 Id->second->setOutOfDate(true);
Douglas Gregor057df202012-01-18 20:56:22 +00003180
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003181 // Resolve any unresolved module exports.
Douglas Gregor55988682011-12-05 16:33:54 +00003182 for (unsigned I = 0, N = UnresolvedModuleImportExports.size(); I != N; ++I) {
3183 UnresolvedModuleImportExport &Unresolved = UnresolvedModuleImportExports[I];
3184 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
Douglas Gregor0adaa882011-12-05 17:28:06 +00003185 Module *ResolvedMod = getSubmodule(GlobalID);
3186
3187 if (Unresolved.IsImport) {
3188 if (ResolvedMod)
Douglas Gregor55988682011-12-05 16:33:54 +00003189 Unresolved.Mod->Imports.push_back(ResolvedMod);
Douglas Gregor0adaa882011-12-05 17:28:06 +00003190 continue;
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003191 }
Douglas Gregor0adaa882011-12-05 17:28:06 +00003192
3193 if (ResolvedMod || Unresolved.IsWildcard)
3194 Unresolved.Mod->Exports.push_back(
3195 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003196 }
Douglas Gregor55988682011-12-05 16:33:54 +00003197 UnresolvedModuleImportExports.clear();
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003198
Douglas Gregor35942772011-09-09 21:34:22 +00003199 InitializeContext();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003200
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00003201 if (DeserializationListener)
3202 DeserializationListener->ReaderInitialized(this);
3203
Douglas Gregor11407b82012-10-18 21:18:25 +00003204 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3205 if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3206 PrimaryModule.OriginalSourceFileID
3207 = FileID::get(PrimaryModule.SLocEntryBaseID
3208 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +00003209
Douglas Gregor11407b82012-10-18 21:18:25 +00003210 // If this AST file is a precompiled preamble, then set the
3211 // preamble file ID of the source manager to the file source file
3212 // from which the preamble was built.
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +00003213 if (Type == MK_Preamble) {
Douglas Gregor11407b82012-10-18 21:18:25 +00003214 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +00003215 } else if (Type == MK_MainFile) {
Douglas Gregor11407b82012-10-18 21:18:25 +00003216 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00003217 }
Douglas Gregor414cb642010-11-30 05:23:00 +00003218 }
3219
Douglas Gregorcff9f262012-01-27 01:47:08 +00003220 // For any Objective-C class definitions we have already loaded, make sure
3221 // that we load any additional categories.
3222 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3223 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3224 ObjCClassesLoaded[I],
3225 PreviousGeneration);
3226 }
3227
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003228 return Success;
3229}
3230
Douglas Gregor38295be2012-10-22 23:51:00 +00003231ASTReader::ASTReadResult
3232ASTReader::ReadASTCore(StringRef FileName,
3233 ModuleKind Type,
3234 ModuleFile *ImportedBy,
3235 llvm::SmallVectorImpl<ModuleFile *> &Loaded,
3236 unsigned ClientLoadCapabilities) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003237 ModuleFile *M;
Douglas Gregorfac4ece2011-08-19 02:29:29 +00003238 bool NewModule;
3239 std::string ErrorStr;
3240 llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
Douglas Gregor057df202012-01-18 20:56:22 +00003241 CurrentGeneration, ErrorStr);
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003242
Douglas Gregorfac4ece2011-08-19 02:29:29 +00003243 if (!M) {
3244 // We couldn't load the module.
3245 std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3246 + ErrorStr;
3247 Error(Msg);
3248 return Failure;
3249 }
3250
3251 if (!NewModule) {
3252 // We've already loaded this module.
3253 return Success;
3254 }
3255
3256 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3257 // module?
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +00003258 if (FileName != "-") {
3259 CurrentDir = llvm::sys::path::parent_path(FileName);
3260 if (CurrentDir.empty()) CurrentDir = ".";
3261 }
3262
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003263 ModuleFile &F = *M;
Sebastian Redl9137a522010-07-16 17:50:48 +00003264 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003265 Stream.init(F.StreamFile);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00003266 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Douglas Gregor8f1231b2011-07-22 06:10:01 +00003267
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00003268 // Sniff for the signature.
3269 if (Stream.Read(8) != 'C' ||
3270 Stream.Read(8) != 'P' ||
3271 Stream.Read(8) != 'C' ||
3272 Stream.Read(8) != 'H') {
3273 Diag(diag::err_not_a_pch_file) << FileName;
3274 return Failure;
3275 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003276
Douglas Gregor2cf26342009-04-09 22:27:44 +00003277 while (!Stream.AtEndOfStream()) {
3278 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00003279
Douglas Gregore1d918e2009-04-10 23:10:45 +00003280 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003281 Error("invalid record at top-level of AST file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00003282 return Failure;
3283 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003284
3285 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003286
Douglas Gregor7ae467f2012-10-18 18:27:37 +00003287 // We only know the control subblock ID.
Douglas Gregor2cf26342009-04-09 22:27:44 +00003288 switch (BlockID) {
3289 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00003290 if (Stream.ReadBlockInfoBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003291 Error("malformed BlockInfoBlock in AST file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00003292 return Failure;
3293 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003294 break;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003295 case CONTROL_BLOCK_ID:
Douglas Gregor38295be2012-10-22 23:51:00 +00003296 switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003297 case Success:
3298 break;
3299
Douglas Gregor4825fd72012-10-22 22:50:17 +00003300 case Failure: return Failure;
3301 case OutOfDate: return OutOfDate;
3302 case VersionMismatch: return VersionMismatch;
3303 case ConfigurationMismatch: return ConfigurationMismatch;
3304 case HadErrors: return HadErrors;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003305 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003306 break;
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003307 case AST_BLOCK_ID:
3308 // Record that we've loaded this module.
3309 Loaded.push_back(M);
3310 return Success;
3311
Douglas Gregor2cf26342009-04-09 22:27:44 +00003312 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00003313 if (Stream.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003314 Error("malformed block record in AST file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00003315 return Failure;
3316 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003317 break;
3318 }
Mike Stump1eb44332009-09-09 15:08:12 +00003319 }
Douglas Gregor8f1231b2011-07-22 06:10:01 +00003320
Sebastian Redlcdf3b832010-07-16 20:41:52 +00003321 return Success;
3322}
3323
Douglas Gregor712f2fc2011-09-09 22:02:16 +00003324void ASTReader::InitializeContext() {
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00003325 // If there's a listener, notify them that we "read" the translation unit.
3326 if (DeserializationListener)
Douglas Gregor35942772011-09-09 21:34:22 +00003327 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3328 Context.getTranslationUnitDecl());
Douglas Gregor3747ee72010-10-01 01:18:02 +00003329
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00003330 // Make sure we load the declaration update records for the translation unit,
3331 // if there are any.
Douglas Gregor35942772011-09-09 21:34:22 +00003332 loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3333 Context.getTranslationUnitDecl());
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00003334
Douglas Gregor5f957282011-08-11 22:18:49 +00003335 // FIXME: Find a better way to deal with collisions between these
3336 // built-in types. Right now, we just ignore the problem.
3337
3338 // Load the special types.
Douglas Gregora6ea10e2012-01-17 18:09:05 +00003339 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
Douglas Gregor02a5e872011-09-10 00:30:18 +00003340 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3341 if (!Context.CFConstantStringTypeDecl)
3342 Context.setCFConstantStringType(GetType(String));
3343 }
3344
3345 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3346 QualType FileType = GetType(File);
3347 if (FileType.isNull()) {
3348 Error("FILE type is NULL");
3349 return;
3350 }
3351
3352 if (!Context.FILEDecl) {
3353 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3354 Context.setFILEDecl(Typedef->getDecl());
3355 else {
3356 const TagType *Tag = FileType->getAs<TagType>();
3357 if (!Tag) {
3358 Error("Invalid FILE type in AST file");
3359 return;
3360 }
3361 Context.setFILEDecl(Tag->getDecl());
Jonathan D. Turnerde91db52011-08-05 23:07:10 +00003362 }
Jonathan D. Turnerde91db52011-08-05 23:07:10 +00003363 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00003364 }
Douglas Gregor5f957282011-08-11 22:18:49 +00003365
Douglas Gregor72cd7a02011-11-11 19:13:12 +00003366 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
Douglas Gregor02a5e872011-09-10 00:30:18 +00003367 QualType Jmp_bufType = GetType(Jmp_buf);
3368 if (Jmp_bufType.isNull()) {
3369 Error("jmp_buf type is NULL");
3370 return;
3371 }
3372
3373 if (!Context.jmp_bufDecl) {
3374 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3375 Context.setjmp_bufDecl(Typedef->getDecl());
3376 else {
3377 const TagType *Tag = Jmp_bufType->getAs<TagType>();
3378 if (!Tag) {
3379 Error("Invalid jmp_buf type in AST file");
3380 return;
3381 }
3382 Context.setjmp_bufDecl(Tag->getDecl());
Jonathan D. Turnerde91db52011-08-05 23:07:10 +00003383 }
Jonathan D. Turnerde91db52011-08-05 23:07:10 +00003384 }
Mike Stump782fa302009-07-28 02:25:19 +00003385 }
Douglas Gregor02a5e872011-09-10 00:30:18 +00003386
Douglas Gregor72cd7a02011-11-11 19:13:12 +00003387 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
Douglas Gregor02a5e872011-09-10 00:30:18 +00003388 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3389 if (Sigjmp_bufType.isNull()) {
3390 Error("sigjmp_buf type is NULL");
3391 return;
3392 }
3393
3394 if (!Context.sigjmp_bufDecl) {
3395 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3396 Context.setsigjmp_bufDecl(Typedef->getDecl());
3397 else {
3398 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3399 assert(Tag && "Invalid sigjmp_buf type in AST file");
3400 Context.setsigjmp_bufDecl(Tag->getDecl());
3401 }
3402 }
3403 }
3404
3405 if (unsigned ObjCIdRedef
3406 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3407 if (Context.ObjCIdRedefinitionType.isNull())
3408 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3409 }
3410
3411 if (unsigned ObjCClassRedef
3412 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3413 if (Context.ObjCClassRedefinitionType.isNull())
3414 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3415 }
3416
3417 if (unsigned ObjCSelRedef
3418 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3419 if (Context.ObjCSelRedefinitionType.isNull())
3420 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3421 }
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00003422
3423 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3424 QualType Ucontext_tType = GetType(Ucontext_t);
3425 if (Ucontext_tType.isNull()) {
3426 Error("ucontext_t type is NULL");
3427 return;
3428 }
3429
3430 if (!Context.ucontext_tDecl) {
3431 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3432 Context.setucontext_tDecl(Typedef->getDecl());
3433 else {
3434 const TagType *Tag = Ucontext_tType->getAs<TagType>();
3435 assert(Tag && "Invalid ucontext_t type in AST file");
3436 Context.setucontext_tDecl(Tag->getDecl());
3437 }
3438 }
3439 }
Douglas Gregor5f957282011-08-11 22:18:49 +00003440 }
3441
Douglas Gregor35942772011-09-09 21:34:22 +00003442 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00003443
3444 // If there were any CUDA special declarations, deserialize them.
3445 if (!CUDASpecialDeclRefs.empty()) {
3446 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
Douglas Gregor35942772011-09-09 21:34:22 +00003447 Context.setcudaConfigureCallDecl(
Peter Collingbourne14b6ba72011-02-09 21:04:32 +00003448 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3449 }
Douglas Gregorf6137e42011-12-03 00:59:55 +00003450
3451 // Re-export any modules that were imported by a non-module AST file.
3452 for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3453 if (Module *Imported = getSubmodule(ImportedModules[I]))
3454 makeModuleVisible(Imported, Module::AllVisible);
3455 }
3456 ImportedModules.clear();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003457}
3458
Douglas Gregorecc2c092011-12-01 22:20:10 +00003459void ASTReader::finalizeForWriting() {
3460 for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3461 HiddenEnd = HiddenNamesMap.end();
3462 Hidden != HiddenEnd; ++Hidden) {
3463 makeNamesVisible(Hidden->second);
3464 }
3465 HiddenNamesMap.clear();
3466}
3467
Douglas Gregorb64c1932009-05-12 01:31:05 +00003468/// \brief Retrieve the name of the original source file name
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003469/// directly from the AST file, without actually loading the AST
Douglas Gregorb64c1932009-05-12 01:31:05 +00003470/// file.
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003471std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00003472 FileManager &FileMgr,
David Blaikied6471f72011-09-25 23:23:43 +00003473 DiagnosticsEngine &Diags) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003474 // Open the AST file.
Douglas Gregorb64c1932009-05-12 01:31:05 +00003475 std::string ErrStr;
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00003476 OwningPtr<llvm::MemoryBuffer> Buffer;
Chris Lattner39b49bc2010-11-23 08:35:12 +00003477 Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
Douglas Gregorb64c1932009-05-12 01:31:05 +00003478 if (!Buffer) {
Kaelyn Uhrainda01f622012-06-20 00:36:03 +00003479 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003480 return std::string();
3481 }
3482
3483 // Initialize the stream
3484 llvm::BitstreamReader StreamFile;
3485 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00003486 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00003487 (const unsigned char *)Buffer->getBufferEnd());
3488 Stream.init(StreamFile);
3489
3490 // Sniff for the signature.
3491 if (Stream.Read(8) != 'C' ||
3492 Stream.Read(8) != 'P' ||
3493 Stream.Read(8) != 'C' ||
3494 Stream.Read(8) != 'H') {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003495 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003496 return std::string();
3497 }
3498
3499 RecordData Record;
3500 while (!Stream.AtEndOfStream()) {
3501 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Douglas Gregorb64c1932009-05-12 01:31:05 +00003503 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3504 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003506 // We only know the AST subblock ID.
Douglas Gregorb64c1932009-05-12 01:31:05 +00003507 switch (BlockID) {
Douglas Gregor1d9d9892012-10-18 05:31:06 +00003508 case CONTROL_BLOCK_ID:
3509 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003510 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003511 return std::string();
3512 }
3513 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Douglas Gregorb64c1932009-05-12 01:31:05 +00003515 default:
3516 if (Stream.SkipBlock()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003517 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003518 return std::string();
3519 }
3520 break;
3521 }
3522 continue;
3523 }
3524
3525 if (Code == llvm::bitc::END_BLOCK) {
3526 if (Stream.ReadBlockEnd()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003527 Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00003528 return std::string();
3529 }
3530 continue;
3531 }
3532
3533 if (Code == llvm::bitc::DEFINE_ABBREV) {
3534 Stream.ReadAbbrevRecord();
3535 continue;
3536 }
3537
3538 Record.clear();
3539 const char *BlobStart = 0;
3540 unsigned BlobLen = 0;
Douglas Gregor39c497b2012-10-18 18:36:53 +00003541 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen) == ORIGINAL_FILE)
Douglas Gregorb64c1932009-05-12 01:31:05 +00003542 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00003543 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00003544
3545 return std::string();
3546}
3547
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003548namespace {
3549 class SimplePCHValidator : public ASTReaderListener {
3550 const LangOptions &ExistingLangOpts;
3551 const TargetOptions &ExistingTargetOpts;
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003552 const PreprocessorOptions &ExistingPPOpts;
Douglas Gregor87699242012-10-25 00:07:54 +00003553 FileManager &FileMgr;
3554
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003555 public:
3556 SimplePCHValidator(const LangOptions &ExistingLangOpts,
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003557 const TargetOptions &ExistingTargetOpts,
Douglas Gregor87699242012-10-25 00:07:54 +00003558 const PreprocessorOptions &ExistingPPOpts,
3559 FileManager &FileMgr)
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003560 : ExistingLangOpts(ExistingLangOpts),
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003561 ExistingTargetOpts(ExistingTargetOpts),
Douglas Gregor87699242012-10-25 00:07:54 +00003562 ExistingPPOpts(ExistingPPOpts),
3563 FileMgr(FileMgr)
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003564 {
3565 }
3566
3567 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3568 bool Complain) {
3569 return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3570 }
3571 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3572 bool Complain) {
3573 return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3574 }
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003575 virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
Douglas Gregor87699242012-10-25 00:07:54 +00003576 bool Complain,
3577 std::string &SuggestedPredefines) {
3578 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3579 SuggestedPredefines);
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003580 }
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003581 };
3582}
3583
3584bool ASTReader::isAcceptableASTFile(StringRef Filename,
3585 FileManager &FileMgr,
3586 const LangOptions &LangOpts,
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00003587 const TargetOptions &TargetOpts,
3588 const PreprocessorOptions &PPOpts) {
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003589 // Open the AST file.
3590 std::string ErrStr;
3591 OwningPtr<llvm::MemoryBuffer> Buffer;
3592 Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3593 if (!Buffer) {
3594 return false;
3595 }
3596
3597 // Initialize the stream
3598 llvm::BitstreamReader StreamFile;
3599 llvm::BitstreamCursor Stream;
3600 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3601 (const unsigned char *)Buffer->getBufferEnd());
3602 Stream.init(StreamFile);
3603
3604 // Sniff for the signature.
3605 if (Stream.Read(8) != 'C' ||
3606 Stream.Read(8) != 'P' ||
3607 Stream.Read(8) != 'C' ||
3608 Stream.Read(8) != 'H') {
3609 return false;
3610 }
3611
Douglas Gregor87699242012-10-25 00:07:54 +00003612 SimplePCHValidator Validator(LangOpts, TargetOpts, PPOpts, FileMgr);
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003613 RecordData Record;
3614 bool InControlBlock = false;
3615 while (!Stream.AtEndOfStream()) {
3616 unsigned Code = Stream.ReadCode();
3617
3618 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3619 unsigned BlockID = Stream.ReadSubBlockID();
3620
3621 // We only know the control subblock ID.
3622 switch (BlockID) {
3623 case CONTROL_BLOCK_ID:
3624 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3625 return false;
3626 } else {
3627 InControlBlock = true;
3628 }
3629 break;
3630
3631 default:
3632 if (Stream.SkipBlock())
3633 return false;
3634 break;
3635 }
3636 continue;
3637 }
3638
3639 if (Code == llvm::bitc::END_BLOCK) {
3640 if (Stream.ReadBlockEnd()) {
3641 return false;
3642 }
3643 InControlBlock = false;
3644 continue;
3645 }
3646
3647 if (Code == llvm::bitc::DEFINE_ABBREV) {
3648 Stream.ReadAbbrevRecord();
3649 continue;
3650 }
3651
3652 Record.clear();
3653 const char *BlobStart = 0;
3654 unsigned BlobLen = 0;
3655 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
3656 if (InControlBlock) {
3657 switch ((ControlRecordTypes)RecCode) {
3658 case METADATA: {
3659 if (Record[0] != VERSION_MAJOR) {
3660 return false;
3661 }
3662
3663 const std::string &CurBranch = getClangFullRepositoryVersion();
3664 StringRef ASTBranch(BlobStart, BlobLen);
3665 if (StringRef(CurBranch) != ASTBranch)
3666 return false;
3667
3668 break;
3669 }
3670 case LANGUAGE_OPTIONS:
3671 if (ParseLanguageOptions(Record, false, Validator))
3672 return false;
3673 break;
3674
3675 case TARGET_OPTIONS:
3676 if (ParseTargetOptions(Record, false, Validator))
3677 return false;
3678 break;
3679
Douglas Gregor5f3d8222012-10-24 15:17:15 +00003680 case DIAGNOSTIC_OPTIONS:
3681 if (ParseDiagnosticOptions(Record, false, Validator))
3682 return false;
3683 break;
3684
Douglas Gregorbbf38312012-10-24 16:50:34 +00003685 case FILE_SYSTEM_OPTIONS:
3686 if (ParseFileSystemOptions(Record, false, Validator))
3687 return false;
3688 break;
3689
3690 case HEADER_SEARCH_OPTIONS:
3691 if (ParseHeaderSearchOptions(Record, false, Validator))
3692 return false;
3693 break;
3694
Douglas Gregor87699242012-10-25 00:07:54 +00003695 case PREPROCESSOR_OPTIONS: {
3696 std::string IgnoredSuggestedPredefines;
3697 if (ParsePreprocessorOptions(Record, false, Validator,
3698 IgnoredSuggestedPredefines))
Douglas Gregora71a7d82012-10-24 20:05:57 +00003699 return false;
3700 break;
Douglas Gregor87699242012-10-25 00:07:54 +00003701 }
Douglas Gregora71a7d82012-10-24 20:05:57 +00003702
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00003703 default:
3704 // No other validation to perform.
3705 break;
3706 }
3707 }
3708 }
3709
3710 return true;
3711}
3712
Douglas Gregor4825fd72012-10-22 22:50:17 +00003713bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003714 // Enter the submodule block.
3715 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3716 Error("malformed submodule block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003717 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003718 }
3719
3720 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
Douglas Gregor26ced122011-12-01 00:59:36 +00003721 bool First = true;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003722 Module *CurrentModule = 0;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003723 RecordData Record;
3724 while (true) {
3725 unsigned Code = F.Stream.ReadCode();
3726 if (Code == llvm::bitc::END_BLOCK) {
3727 if (F.Stream.ReadBlockEnd()) {
3728 Error("error at end of submodule block in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003729 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003730 }
Douglas Gregor4825fd72012-10-22 22:50:17 +00003731 return false;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003732 }
3733
3734 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3735 // No known subblocks, always skip them.
3736 F.Stream.ReadSubBlockID();
3737 if (F.Stream.SkipBlock()) {
3738 Error("malformed block record in AST file");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003739 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003740 }
3741 continue;
3742 }
3743
3744 if (Code == llvm::bitc::DEFINE_ABBREV) {
3745 F.Stream.ReadAbbrevRecord();
3746 continue;
3747 }
3748
3749 // Read a record.
3750 const char *BlobStart;
3751 unsigned BlobLen;
3752 Record.clear();
3753 switch (F.Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
3754 default: // Default behavior: ignore.
3755 break;
3756
3757 case SUBMODULE_DEFINITION: {
Douglas Gregor26ced122011-12-01 00:59:36 +00003758 if (First) {
3759 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003760 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003761 }
3762
Douglas Gregore209e502011-12-06 01:10:29 +00003763 if (Record.size() < 7) {
Douglas Gregor1e123682011-12-05 22:27:44 +00003764 Error("malformed module definition");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003765 return true;
Douglas Gregor1e123682011-12-05 22:27:44 +00003766 }
3767
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003768 StringRef Name(BlobStart, BlobLen);
Douglas Gregore209e502011-12-06 01:10:29 +00003769 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3770 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3771 bool IsFramework = Record[2];
3772 bool IsExplicit = Record[3];
Douglas Gregora1f1fad2012-01-27 19:52:33 +00003773 bool IsSystem = Record[4];
3774 bool InferSubmodules = Record[5];
3775 bool InferExplicitSubmodules = Record[6];
3776 bool InferExportWildcard = Record[7];
Douglas Gregor1e123682011-12-05 22:27:44 +00003777
Douglas Gregor1a4761e2011-11-30 23:21:26 +00003778 Module *ParentModule = 0;
Douglas Gregor26ced122011-12-01 00:59:36 +00003779 if (Parent)
3780 ParentModule = getSubmodule(Parent);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003781
3782 // Retrieve this (sub)module from the module map, creating it if
3783 // necessary.
3784 CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3785 IsFramework,
3786 IsExplicit).first;
Douglas Gregore209e502011-12-06 01:10:29 +00003787 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3788 if (GlobalIndex >= SubmodulesLoaded.size() ||
3789 SubmodulesLoaded[GlobalIndex]) {
Douglas Gregor26ced122011-12-01 00:59:36 +00003790 Error("too many submodules");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003791 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003792 }
Douglas Gregora015cab2011-12-02 17:30:13 +00003793
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +00003794 CurrentModule->setASTFile(F.File);
Douglas Gregor305dc3e2011-12-20 00:28:52 +00003795 CurrentModule->IsFromModuleFile = true;
Douglas Gregora1f1fad2012-01-27 19:52:33 +00003796 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Douglas Gregor1e123682011-12-05 22:27:44 +00003797 CurrentModule->InferSubmodules = InferSubmodules;
3798 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3799 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregora015cab2011-12-02 17:30:13 +00003800 if (DeserializationListener)
Douglas Gregore209e502011-12-06 01:10:29 +00003801 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
Douglas Gregora015cab2011-12-02 17:30:13 +00003802
Douglas Gregore209e502011-12-06 01:10:29 +00003803 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003804 break;
3805 }
3806
Douglas Gregor77d029f2011-12-08 19:11:24 +00003807 case SUBMODULE_UMBRELLA_HEADER: {
Douglas Gregor26ced122011-12-01 00:59:36 +00003808 if (First) {
3809 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003810 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003811 }
3812
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003813 if (!CurrentModule)
3814 break;
3815
3816 StringRef FileName(BlobStart, BlobLen);
3817 if (const FileEntry *Umbrella = PP.getFileManager().getFile(FileName)) {
Douglas Gregor10694ce2011-12-08 17:39:04 +00003818 if (!CurrentModule->getUmbrellaHeader())
Douglas Gregore209e502011-12-06 01:10:29 +00003819 ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
Douglas Gregor10694ce2011-12-08 17:39:04 +00003820 else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003821 Error("mismatched umbrella headers in submodule");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003822 return true;
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003823 }
3824 }
3825 break;
3826 }
3827
3828 case SUBMODULE_HEADER: {
Douglas Gregor26ced122011-12-01 00:59:36 +00003829 if (First) {
3830 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003831 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003832 }
3833
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003834 if (!CurrentModule)
3835 break;
3836
3837 // FIXME: Be more lazy about this!
3838 StringRef FileName(BlobStart, BlobLen);
3839 if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3840 if (std::find(CurrentModule->Headers.begin(),
3841 CurrentModule->Headers.end(),
3842 File) == CurrentModule->Headers.end())
Douglas Gregor2b49d1f2012-10-15 06:28:11 +00003843 ModMap.addHeader(CurrentModule, File, false);
3844 }
3845 break;
3846 }
3847
3848 case SUBMODULE_EXCLUDED_HEADER: {
3849 if (First) {
3850 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003851 return true;
Douglas Gregor2b49d1f2012-10-15 06:28:11 +00003852 }
3853
3854 if (!CurrentModule)
3855 break;
3856
3857 // FIXME: Be more lazy about this!
3858 StringRef FileName(BlobStart, BlobLen);
3859 if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3860 if (std::find(CurrentModule->Headers.begin(),
3861 CurrentModule->Headers.end(),
3862 File) == CurrentModule->Headers.end())
3863 ModMap.addHeader(CurrentModule, File, true);
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003864 }
3865 break;
3866 }
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +00003867
3868 case SUBMODULE_TOPHEADER: {
3869 if (First) {
3870 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003871 return true;
Argyrios Kyrtzidisc7782d92012-10-05 00:22:33 +00003872 }
3873
3874 if (!CurrentModule)
3875 break;
3876
3877 // FIXME: Be more lazy about this!
3878 StringRef FileName(BlobStart, BlobLen);
3879 if (const FileEntry *File = PP.getFileManager().getFile(FileName))
3880 CurrentModule->TopHeaders.insert(File);
3881 break;
3882 }
3883
Douglas Gregor77d029f2011-12-08 19:11:24 +00003884 case SUBMODULE_UMBRELLA_DIR: {
3885 if (First) {
3886 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003887 return true;
Douglas Gregor77d029f2011-12-08 19:11:24 +00003888 }
3889
3890 if (!CurrentModule)
3891 break;
3892
3893 StringRef DirName(BlobStart, BlobLen);
3894 if (const DirectoryEntry *Umbrella
3895 = PP.getFileManager().getDirectory(DirName)) {
3896 if (!CurrentModule->getUmbrellaDir())
3897 ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3898 else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3899 Error("mismatched umbrella directories in submodule");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003900 return true;
Douglas Gregor77d029f2011-12-08 19:11:24 +00003901 }
3902 }
3903 break;
3904 }
3905
Douglas Gregor26ced122011-12-01 00:59:36 +00003906 case SUBMODULE_METADATA: {
3907 if (!First) {
3908 Error("submodule metadata record not at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003909 return true;
Douglas Gregor26ced122011-12-01 00:59:36 +00003910 }
3911 First = false;
3912
3913 F.BaseSubmoduleID = getTotalNumSubmodules();
Douglas Gregor26ced122011-12-01 00:59:36 +00003914 F.LocalNumSubmodules = Record[0];
3915 unsigned LocalBaseSubmoduleID = Record[1];
3916 if (F.LocalNumSubmodules > 0) {
3917 // Introduce the global -> local mapping for submodules within this
3918 // module.
3919 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3920
3921 // Introduce the local -> global mapping for submodules within this
3922 // module.
Douglas Gregoradafc2e2011-12-19 16:14:14 +00003923 F.SubmoduleRemap.insertOrReplace(
Douglas Gregor26ced122011-12-01 00:59:36 +00003924 std::make_pair(LocalBaseSubmoduleID,
3925 F.BaseSubmoduleID - LocalBaseSubmoduleID));
3926
3927 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3928 }
3929 break;
3930 }
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003931
Douglas Gregor55988682011-12-05 16:33:54 +00003932 case SUBMODULE_IMPORTS: {
3933 if (First) {
3934 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003935 return true;
Douglas Gregor55988682011-12-05 16:33:54 +00003936 }
3937
3938 if (!CurrentModule)
3939 break;
3940
3941 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
3942 UnresolvedModuleImportExport Unresolved;
3943 Unresolved.File = &F;
3944 Unresolved.Mod = CurrentModule;
3945 Unresolved.ID = Record[Idx];
3946 Unresolved.IsImport = true;
3947 Unresolved.IsWildcard = false;
3948 UnresolvedModuleImportExports.push_back(Unresolved);
3949 }
3950 break;
3951 }
3952
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003953 case SUBMODULE_EXPORTS: {
3954 if (First) {
3955 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003956 return true;
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003957 }
3958
3959 if (!CurrentModule)
3960 break;
3961
3962 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregor55988682011-12-05 16:33:54 +00003963 UnresolvedModuleImportExport Unresolved;
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003964 Unresolved.File = &F;
Douglas Gregor55988682011-12-05 16:33:54 +00003965 Unresolved.Mod = CurrentModule;
3966 Unresolved.ID = Record[Idx];
3967 Unresolved.IsImport = false;
3968 Unresolved.IsWildcard = Record[Idx + 1];
3969 UnresolvedModuleImportExports.push_back(Unresolved);
Douglas Gregoraf13bfc2011-12-02 18:58:38 +00003970 }
3971
3972 // Once we've loaded the set of exports, there's no reason to keep
3973 // the parsed, unresolved exports around.
3974 CurrentModule->UnresolvedExports.clear();
3975 break;
3976 }
Douglas Gregor51f564f2011-12-31 04:05:44 +00003977 case SUBMODULE_REQUIRES: {
3978 if (First) {
3979 Error("missing submodule metadata record at beginning of block");
Douglas Gregor4825fd72012-10-22 22:50:17 +00003980 return true;
Douglas Gregor51f564f2011-12-31 04:05:44 +00003981 }
3982
3983 if (!CurrentModule)
3984 break;
3985
3986 CurrentModule->addRequirement(StringRef(BlobStart, BlobLen),
David Blaikie4e4d0842012-03-11 07:00:24 +00003987 Context.getLangOpts(),
Douglas Gregordc58aa72012-01-30 06:01:29 +00003988 Context.getTargetInfo());
Douglas Gregor51f564f2011-12-31 04:05:44 +00003989 break;
3990 }
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003991 }
3992 }
Douglas Gregor392ed2b2011-11-30 17:33:56 +00003993}
3994
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003995/// \brief Parse the record that corresponds to a LangOptions data
3996/// structure.
3997///
Sebastian Redl3c7f4132010-08-18 23:57:06 +00003998/// This routine parses the language options from the AST file and then gives
3999/// them to the AST listener if one is set.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00004000///
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004001/// \returns true if the listener deems the file unacceptable, false otherwise.
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00004002bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4003 bool Complain,
4004 ASTReaderListener &Listener) {
4005 LangOptions LangOpts;
4006 unsigned Idx = 0;
Douglas Gregor7d5e81b2011-09-13 18:26:39 +00004007#define LANGOPT(Name, Bits, Default, Description) \
4008 LangOpts.Name = Record[Idx++];
4009#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4010 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4011#include "clang/Basic/LangOptions.def"
John McCall260611a2012-06-20 06:18:46 +00004012
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00004013 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4014 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4015 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4016
4017 unsigned Length = Record[Idx++];
4018 LangOpts.CurrentModule.assign(Record.begin() + Idx,
4019 Record.begin() + Idx + Length);
4020 return Listener.ReadLanguageOptions(LangOpts, Complain);
4021}
4022
4023bool ASTReader::ParseTargetOptions(const RecordData &Record,
4024 bool Complain,
4025 ASTReaderListener &Listener) {
4026 unsigned Idx = 0;
4027 TargetOptions TargetOpts;
4028 TargetOpts.Triple = ReadString(Record, Idx);
4029 TargetOpts.CPU = ReadString(Record, Idx);
4030 TargetOpts.ABI = ReadString(Record, Idx);
4031 TargetOpts.CXXABI = ReadString(Record, Idx);
4032 TargetOpts.LinkerVersion = ReadString(Record, Idx);
4033 for (unsigned N = Record[Idx++]; N; --N) {
4034 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4035 }
4036 for (unsigned N = Record[Idx++]; N; --N) {
4037 TargetOpts.Features.push_back(ReadString(Record, Idx));
Douglas Gregor0a0428e2009-04-10 20:39:37 +00004038 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00004039
Douglas Gregor27ffa6c2012-10-23 06:18:24 +00004040 return Listener.ReadTargetOptions(TargetOpts, Complain);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00004041}
4042
Douglas Gregor5f3d8222012-10-24 15:17:15 +00004043bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4044 ASTReaderListener &Listener) {
4045 DiagnosticOptions DiagOpts;
4046 unsigned Idx = 0;
4047#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4048#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4049 DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4050#include "clang/Basic/DiagnosticOptions.def"
4051
4052 for (unsigned N = Record[Idx++]; N; --N) {
4053 DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4054 }
4055
4056 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4057}
4058
Douglas Gregor1b2c3c02012-10-24 15:49:58 +00004059bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4060 ASTReaderListener &Listener) {
4061 FileSystemOptions FSOpts;
4062 unsigned Idx = 0;
4063 FSOpts.WorkingDir = ReadString(Record, Idx);
4064 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4065}
4066
Douglas Gregorbbf38312012-10-24 16:50:34 +00004067bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4068 bool Complain,
4069 ASTReaderListener &Listener) {
4070 HeaderSearchOptions HSOpts;
4071 unsigned Idx = 0;
4072 HSOpts.Sysroot = ReadString(Record, Idx);
4073
4074 // Include entries.
4075 for (unsigned N = Record[Idx++]; N; --N) {
4076 std::string Path = ReadString(Record, Idx);
4077 frontend::IncludeDirGroup Group
4078 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4079 bool IsUserSupplied = Record[Idx++];
4080 bool IsFramework = Record[Idx++];
4081 bool IgnoreSysRoot = Record[Idx++];
4082 bool IsInternal = Record[Idx++];
4083 bool ImplicitExternC = Record[Idx++];
4084 HSOpts.UserEntries.push_back(
4085 HeaderSearchOptions::Entry(Path, Group, IsUserSupplied, IsFramework,
4086 IgnoreSysRoot, IsInternal, ImplicitExternC));
4087 }
4088
4089 // System header prefixes.
4090 for (unsigned N = Record[Idx++]; N; --N) {
4091 std::string Prefix = ReadString(Record, Idx);
4092 bool IsSystemHeader = Record[Idx++];
4093 HSOpts.SystemHeaderPrefixes.push_back(
4094 HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4095 }
4096
4097 HSOpts.ResourceDir = ReadString(Record, Idx);
4098 HSOpts.ModuleCachePath = ReadString(Record, Idx);
4099 HSOpts.DisableModuleHash = Record[Idx++];
4100 HSOpts.UseBuiltinIncludes = Record[Idx++];
4101 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4102 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4103 HSOpts.UseLibcxx = Record[Idx++];
4104
4105 return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4106}
4107
Douglas Gregora71a7d82012-10-24 20:05:57 +00004108bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4109 bool Complain,
Douglas Gregor87699242012-10-25 00:07:54 +00004110 ASTReaderListener &Listener,
4111 std::string &SuggestedPredefines) {
Douglas Gregora71a7d82012-10-24 20:05:57 +00004112 PreprocessorOptions PPOpts;
4113 unsigned Idx = 0;
4114
4115 // Macro definitions/undefs
4116 for (unsigned N = Record[Idx++]; N; --N) {
4117 std::string Macro = ReadString(Record, Idx);
4118 bool IsUndef = Record[Idx++];
4119 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4120 }
4121
4122 // Includes
4123 for (unsigned N = Record[Idx++]; N; --N) {
4124 PPOpts.Includes.push_back(ReadString(Record, Idx));
4125 }
4126
4127 // Macro Includes
4128 for (unsigned N = Record[Idx++]; N; --N) {
4129 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4130 }
4131
Douglas Gregor4c0c7e82012-10-24 23:41:50 +00004132 PPOpts.UsePredefines = Record[Idx++];
Douglas Gregora71a7d82012-10-24 20:05:57 +00004133 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4134 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4135 PPOpts.ObjCXXARCStandardLibrary =
4136 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
Douglas Gregor87699242012-10-25 00:07:54 +00004137 SuggestedPredefines.clear();
4138 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4139 SuggestedPredefines);
Douglas Gregora71a7d82012-10-24 20:05:57 +00004140}
4141
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004142std::pair<ModuleFile *, unsigned>
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004143ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00004144 GlobalPreprocessedEntityMapType::iterator
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004145 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00004146 assert(I != GlobalPreprocessedEntityMap.end() &&
4147 "Corrupted global preprocessed entity map");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004148 ModuleFile *M = I->second;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004149 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4150 return std::make_pair(M, LocalIndex);
4151}
4152
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00004153std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4154ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4155 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4156 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4157 Mod.NumPreprocessedEntities);
4158
4159 return std::make_pair(PreprocessingRecord::iterator(),
4160 PreprocessingRecord::iterator());
4161}
4162
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00004163std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4164ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4165 return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4166 ModuleDeclIterator(this, &Mod,
4167 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4168}
4169
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004170PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4171 PreprocessedEntityID PPID = Index+1;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004172 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4173 ModuleFile &M = *PPInfo.first;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004174 unsigned LocalIndex = PPInfo.second;
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004175 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
Douglas Gregor4800a5c2011-02-08 21:58:10 +00004176
Argyrios Kyrtzidise24692b2011-09-15 18:02:56 +00004177 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004178 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004179
4180 unsigned Code = M.PreprocessorDetailCursor.ReadCode();
4181 switch (Code) {
4182 case llvm::bitc::END_BLOCK:
4183 return 0;
4184
4185 case llvm::bitc::ENTER_SUBBLOCK:
4186 Error("unexpected subblock record in preprocessor detail block");
4187 return 0;
4188
4189 case llvm::bitc::DEFINE_ABBREV:
4190 Error("unexpected abbrevation record in preprocessor detail block");
4191 return 0;
4192
4193 default:
4194 break;
4195 }
4196
4197 if (!PP.getPreprocessingRecord()) {
4198 Error("no preprocessing record");
4199 return 0;
4200 }
4201
4202 // Read the record.
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004203 SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4204 ReadSourceLocation(M, PPOffs.End));
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004205 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4206 const char *BlobStart = 0;
4207 unsigned BlobLen = 0;
4208 RecordData Record;
4209 PreprocessorDetailRecordTypes RecType =
4210 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.ReadRecord(
4211 Code, Record, BlobStart, BlobLen);
4212 switch (RecType) {
4213 case PPD_MACRO_EXPANSION: {
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004214 bool isBuiltin = Record[0];
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004215 IdentifierInfo *Name = 0;
4216 MacroDefinition *Def = 0;
4217 if (isBuiltin)
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004218 Name = getLocalIdentifier(M, Record[1]);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004219 else {
4220 PreprocessedEntityID
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004221 GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004222 Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4223 }
4224
4225 MacroExpansion *ME;
4226 if (isBuiltin)
4227 ME = new (PPRec) MacroExpansion(Name, Range);
4228 else
4229 ME = new (PPRec) MacroExpansion(Def, Range);
4230
4231 return ME;
4232 }
4233
4234 case PPD_MACRO_DEFINITION: {
4235 // Decode the identifier info and then check again; if the macro is
4236 // still defined and associated with the identifier,
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004237 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004238 MacroDefinition *MD
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004239 = new (PPRec) MacroDefinition(II, Range);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004240
4241 if (DeserializationListener)
4242 DeserializationListener->MacroDefinitionRead(PPID, MD);
4243
4244 return MD;
4245 }
4246
4247 case PPD_INCLUSION_DIRECTIVE: {
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004248 const char *FullFileNameStart = BlobStart + Record[0];
Argyrios Kyrtzidis29f98b42012-03-08 01:08:28 +00004249 StringRef FullFileName(FullFileNameStart, BlobLen - Record[0]);
4250 const FileEntry *File = 0;
4251 if (!FullFileName.empty())
4252 File = PP.getFileManager().getFile(FullFileName);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004253
4254 // FIXME: Stable encoding
4255 InclusionDirective::InclusionKind Kind
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004256 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004257 InclusionDirective *ID
4258 = new (PPRec) InclusionDirective(PPRec, Kind,
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004259 StringRef(BlobStart, Record[0]),
Argyrios Kyrtzidis8dd927c2012-10-02 16:10:46 +00004260 Record[1], Record[3],
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004261 File,
Argyrios Kyrtzidis8f958f12011-09-20 23:27:41 +00004262 Range);
Argyrios Kyrtzidis290ad8c2011-09-20 23:27:38 +00004263 return ID;
4264 }
4265 }
David Blaikie7530c032012-01-17 06:56:22 +00004266
4267 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00004268}
4269
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004270/// \brief \arg SLocMapI points at a chunk of a module that contains no
4271/// preprocessed entities or the entities it contains are not the ones we are
4272/// looking for. Find the next module that contains entities and return the ID
4273/// of the first entry.
4274PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4275 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4276 ++SLocMapI;
4277 for (GlobalSLocOffsetMapType::const_iterator
4278 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004279 ModuleFile &M = *SLocMapI->second;
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004280 if (M.NumPreprocessedEntities)
4281 return getGlobalPreprocessedEntityID(M, M.BasePreprocessedEntityID);
4282 }
4283
4284 return getTotalNumPreprocessedEntities();
4285}
4286
4287namespace {
4288
4289template <unsigned PPEntityOffset::*PPLoc>
4290struct PPEntityComp {
4291 const ASTReader &Reader;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004292 ModuleFile &M;
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004293
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004294 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004295
Benjamin Kramer88df1252011-09-21 06:42:26 +00004296 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4297 SourceLocation LHS = getLoc(L);
4298 SourceLocation RHS = getLoc(R);
4299 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4300 }
4301
4302 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004303 SourceLocation LHS = getLoc(L);
4304 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4305 }
4306
Benjamin Kramer88df1252011-09-21 06:42:26 +00004307 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004308 SourceLocation RHS = getLoc(R);
4309 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4310 }
4311
4312 SourceLocation getLoc(const PPEntityOffset &PPE) const {
4313 return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4314 }
4315};
4316
4317}
4318
4319/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4320PreprocessedEntityID
4321ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4322 if (SourceMgr.isLocalSourceLocation(BLoc))
4323 return getTotalNumPreprocessedEntities();
4324
4325 GlobalSLocOffsetMapType::const_iterator
4326 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4327 BLoc.getOffset());
4328 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4329 "Corrupted global sloc offset map");
4330
4331 if (SLocMapI->second->NumPreprocessedEntities == 0)
4332 return findNextPreprocessedEntity(SLocMapI);
4333
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004334 ModuleFile &M = *SLocMapI->second;
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004335 typedef const PPEntityOffset *pp_iterator;
4336 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4337 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
Argyrios Kyrtzidis4cd06342011-09-22 21:17:02 +00004338
4339 size_t Count = M.NumPreprocessedEntities;
4340 size_t Half;
4341 pp_iterator First = pp_begin;
4342 pp_iterator PPI;
4343
4344 // Do a binary search manually instead of using std::lower_bound because
4345 // The end locations of entities may be unordered (when a macro expansion
4346 // is inside another macro argument), but for this case it is not important
4347 // whether we get the first macro expansion or its containing macro.
4348 while (Count > 0) {
4349 Half = Count/2;
4350 PPI = First;
4351 std::advance(PPI, Half);
4352 if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4353 BLoc)){
4354 First = PPI;
4355 ++First;
4356 Count = Count - Half - 1;
4357 } else
4358 Count = Half;
4359 }
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004360
4361 if (PPI == pp_end)
4362 return findNextPreprocessedEntity(SLocMapI);
4363
4364 return getGlobalPreprocessedEntityID(M,
4365 M.BasePreprocessedEntityID + (PPI - pp_begin));
4366}
4367
4368/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4369PreprocessedEntityID
4370ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4371 if (SourceMgr.isLocalSourceLocation(ELoc))
4372 return getTotalNumPreprocessedEntities();
4373
4374 GlobalSLocOffsetMapType::const_iterator
4375 SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4376 ELoc.getOffset());
4377 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4378 "Corrupted global sloc offset map");
4379
4380 if (SLocMapI->second->NumPreprocessedEntities == 0)
4381 return findNextPreprocessedEntity(SLocMapI);
4382
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004383 ModuleFile &M = *SLocMapI->second;
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +00004384 typedef const PPEntityOffset *pp_iterator;
4385 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4386 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4387 pp_iterator PPI =
4388 std::upper_bound(pp_begin, pp_end, ELoc,
4389 PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4390
4391 if (PPI == pp_end)
4392 return findNextPreprocessedEntity(SLocMapI);
4393
4394 return getGlobalPreprocessedEntityID(M,
4395 M.BasePreprocessedEntityID + (PPI - pp_begin));
4396}
4397
4398/// \brief Returns a pair of [Begin, End) indices of preallocated
4399/// preprocessed entities that \arg Range encompasses.
4400std::pair<unsigned, unsigned>
4401 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4402 if (Range.isInvalid())
4403 return std::make_pair(0,0);
4404 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4405
4406 PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4407 PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4408 return std::make_pair(BeginID, EndID);
4409}
4410
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004411/// \brief Optionally returns true or false if the preallocated preprocessed
4412/// entity with index \arg Index came from file \arg FID.
4413llvm::Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
4414 FileID FID) {
4415 if (FID.isInvalid())
4416 return false;
4417
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004418 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4419 ModuleFile &M = *PPInfo.first;
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00004420 unsigned LocalIndex = PPInfo.second;
4421 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4422
4423 SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4424 if (Loc.isInvalid())
4425 return false;
4426
4427 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4428 return true;
4429 else
4430 return false;
4431}
4432
Douglas Gregord10a3812011-08-25 18:14:34 +00004433namespace {
4434 /// \brief Visitor used to search for information about a header file.
4435 class HeaderFileInfoVisitor {
4436 ASTReader &Reader;
4437 const FileEntry *FE;
4438
4439 llvm::Optional<HeaderFileInfo> HFI;
4440
4441 public:
4442 HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
4443 : Reader(Reader), FE(FE) { }
4444
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004445 static bool visit(ModuleFile &M, void *UserData) {
Douglas Gregord10a3812011-08-25 18:14:34 +00004446 HeaderFileInfoVisitor *This
4447 = static_cast<HeaderFileInfoVisitor *>(UserData);
4448
4449 HeaderFileInfoTrait Trait(This->Reader, M,
4450 &This->Reader.getPreprocessor().getHeaderSearchInfo(),
4451 M.HeaderFileFrameworkStrings,
4452 This->FE->getName());
4453
4454 HeaderFileInfoLookupTable *Table
4455 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4456 if (!Table)
4457 return false;
4458
4459 // Look in the on-disk hash table for an entry for this file name.
4460 HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
4461 &Trait);
4462 if (Pos == Table->end())
4463 return false;
4464
4465 This->HFI = *Pos;
4466 return true;
4467 }
4468
4469 llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4470 };
4471}
4472
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00004473HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Douglas Gregord10a3812011-08-25 18:14:34 +00004474 HeaderFileInfoVisitor Visitor(*this, FE);
4475 ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4476 if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00004477 if (Listener)
Douglas Gregord10a3812011-08-25 18:14:34 +00004478 Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4479 return *HFI;
Douglas Gregorcfbf1c72011-02-10 17:09:37 +00004480 }
4481
4482 return HeaderFileInfo();
4483}
4484
David Blaikied6471f72011-09-25 23:23:43 +00004485void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00004486 for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004487 ModuleFile &F = *(*I);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00004488 unsigned Idx = 0;
4489 while (Idx < F.PragmaDiagMappings.size()) {
4490 SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
Argyrios Kyrtzidis87429a02011-11-09 01:24:17 +00004491 Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4492 Diag.DiagStatePoints.push_back(
4493 DiagnosticsEngine::DiagStatePoint(&Diag.DiagStates.back(),
4494 FullSourceLoc(Loc, SourceMgr)));
Douglas Gregorf62d43d2011-07-19 16:10:42 +00004495 while (1) {
4496 assert(Idx < F.PragmaDiagMappings.size() &&
4497 "Invalid data, didn't find '-1' marking end of diag/map pairs");
4498 if (Idx >= F.PragmaDiagMappings.size()) {
4499 break; // Something is messed up but at least avoid infinite loop in
4500 // release build.
4501 }
4502 unsigned DiagID = F.PragmaDiagMappings[Idx++];
4503 if (DiagID == (unsigned)-1) {
4504 break; // no more diag/map pairs for this location.
4505 }
4506 diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
Argyrios Kyrtzidis87429a02011-11-09 01:24:17 +00004507 DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4508 Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00004509 }
Argyrios Kyrtzidis3efd52c2011-01-14 20:54:07 +00004510 }
Argyrios Kyrtzidisf41d3be2010-11-05 22:10:18 +00004511 }
4512}
4513
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00004514/// \brief Get the correct cursor and offset for loading a type.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00004515ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
Douglas Gregora119da02011-08-02 16:26:37 +00004516 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
Jonathan D. Turnere9b76c12011-07-20 21:31:32 +00004517 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004518 ModuleFile *M = I->second;
Douglas Gregore3605012011-08-02 18:32:54 +00004519 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00004520}
4521
4522/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00004523///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00004524/// The index is the type ID, shifted and minus the number of predefs. This
4525/// routine actually reads the record corresponding to the type at the given
4526/// location. It is a helper routine for GetType, which deals with reading type
4527/// IDs.
Douglas Gregor393f2492011-07-22 00:38:23 +00004528QualType ASTReader::readTypeRecord(unsigned Index) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00004529 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redlc3632732010-10-05 15:59:54 +00004530 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00004531
Douglas Gregor0b748912009-04-14 21:18:50 +00004532 // Keep track of where we are in the stream, then jump back there
4533 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004534 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00004535
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00004536 ReadingKindTracker ReadingKind(Read_Type, *this);
Sebastian Redl27372b42010-08-11 18:52:41 +00004537
Douglas Gregord89275b2009-07-06 18:54:52 +00004538 // Note that we are loading a type record.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00004539 Deserializing AType(this);
Mike Stump1eb44332009-09-09 15:08:12 +00004540
Douglas Gregor393f2492011-07-22 00:38:23 +00004541 unsigned Idx = 0;
Sebastian Redlc3632732010-10-05 15:59:54 +00004542 DeclsCursor.JumpToBit(Loc.Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004543 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00004544 unsigned Code = DeclsCursor.ReadCode();
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004545 switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
4546 case TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004547 if (Record.size() != 2) {
4548 Error("Incorrect encoding of extended qualifier type");
4549 return QualType();
4550 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004551 QualType Base = readType(*Loc.F, Record, Idx);
4552 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Douglas Gregor35942772011-09-09 21:34:22 +00004553 return Context.getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00004554 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004555
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004556 case TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004557 if (Record.size() != 1) {
4558 Error("Incorrect encoding of complex type");
4559 return QualType();
4560 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004561 QualType ElemType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004562 return Context.getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004563 }
4564
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004565 case TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004566 if (Record.size() != 1) {
4567 Error("Incorrect encoding of pointer type");
4568 return QualType();
4569 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004570 QualType PointeeType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004571 return Context.getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004572 }
4573
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004574 case TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004575 if (Record.size() != 1) {
4576 Error("Incorrect encoding of block pointer type");
4577 return QualType();
4578 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004579 QualType PointeeType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004580 return Context.getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004581 }
4582
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004583 case TYPE_LVALUE_REFERENCE: {
Richard Smithdf1550f2011-04-12 10:38:03 +00004584 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004585 Error("Incorrect encoding of lvalue reference type");
4586 return QualType();
4587 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004588 QualType PointeeType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004589 return Context.getLValueReferenceType(PointeeType, Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004590 }
4591
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004592 case TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004593 if (Record.size() != 1) {
4594 Error("Incorrect encoding of rvalue reference type");
4595 return QualType();
4596 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004597 QualType PointeeType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004598 return Context.getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00004599 }
4600
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004601 case TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00004602 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004603 Error("Incorrect encoding of member pointer type");
4604 return QualType();
4605 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004606 QualType PointeeType = readType(*Loc.F, Record, Idx);
4607 QualType ClassType = readType(*Loc.F, Record, Idx);
Douglas Gregor1ab55e92010-12-10 17:03:06 +00004608 if (PointeeType.isNull() || ClassType.isNull())
4609 return QualType();
4610
Douglas Gregor35942772011-09-09 21:34:22 +00004611 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00004612 }
4613
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004614 case TYPE_CONSTANT_ARRAY: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004615 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004616 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4617 unsigned IndexTypeQuals = Record[2];
4618 unsigned Idx = 3;
4619 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004620 return Context.getConstantArrayType(ElementType, Size,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004621 ASM, IndexTypeQuals);
4622 }
4623
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004624 case TYPE_INCOMPLETE_ARRAY: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004625 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004626 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4627 unsigned IndexTypeQuals = Record[2];
Douglas Gregor35942772011-09-09 21:34:22 +00004628 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004629 }
4630
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004631 case TYPE_VARIABLE_ARRAY: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004632 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregor0b748912009-04-14 21:18:50 +00004633 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4634 unsigned IndexTypeQuals = Record[2];
Sebastian Redlc3632732010-10-05 15:59:54 +00004635 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4636 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
Douglas Gregor35942772011-09-09 21:34:22 +00004637 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004638 ASM, IndexTypeQuals,
4639 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004640 }
4641
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004642 case TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00004643 if (Record.size() != 3) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004644 Error("incorrect encoding of vector type in AST file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004645 return QualType();
4646 }
4647
Douglas Gregor393f2492011-07-22 00:38:23 +00004648 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004649 unsigned NumElements = Record[1];
Bob Wilsone86d78c2010-11-10 21:56:12 +00004650 unsigned VecKind = Record[2];
Douglas Gregor35942772011-09-09 21:34:22 +00004651 return Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00004652 (VectorType::VectorKind)VecKind);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004653 }
4654
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004655 case TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00004656 if (Record.size() != 3) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004657 Error("incorrect encoding of extended vector type in AST file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004658 return QualType();
4659 }
4660
Douglas Gregor393f2492011-07-22 00:38:23 +00004661 QualType ElementType = readType(*Loc.F, Record, Idx);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004662 unsigned NumElements = Record[1];
Douglas Gregor35942772011-09-09 21:34:22 +00004663 return Context.getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004664 }
4665
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004666 case TYPE_FUNCTION_NO_PROTO: {
John McCallf85e1932011-06-15 23:02:42 +00004667 if (Record.size() != 6) {
Douglas Gregora02b1472009-04-28 21:53:25 +00004668 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004669 return QualType();
4670 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004671 QualType ResultType = readType(*Loc.F, Record, Idx);
John McCallf85e1932011-06-15 23:02:42 +00004672 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4673 (CallingConv)Record[4], Record[5]);
Douglas Gregor35942772011-09-09 21:34:22 +00004674 return Context.getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004675 }
4676
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004677 case TYPE_FUNCTION_PROTO: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004678 QualType ResultType = readType(*Loc.F, Record, Idx);
John McCalle23cf432010-12-14 08:05:40 +00004679
4680 FunctionProtoType::ExtProtoInfo EPI;
4681 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
Eli Friedmana49218e2011-04-09 08:18:08 +00004682 /*hasregparm*/ Record[2],
4683 /*regparm*/ Record[3],
John McCallf85e1932011-06-15 23:02:42 +00004684 static_cast<CallingConv>(Record[4]),
4685 /*produces*/ Record[5]);
John McCalle23cf432010-12-14 08:05:40 +00004686
John McCallf85e1932011-06-15 23:02:42 +00004687 unsigned Idx = 6;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004688 unsigned NumParams = Record[Idx++];
Chris Lattner5f9e2722011-07-23 10:55:15 +00004689 SmallVector<QualType, 16> ParamTypes;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004690 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor393f2492011-07-22 00:38:23 +00004691 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
John McCalle23cf432010-12-14 08:05:40 +00004692
4693 EPI.Variadic = Record[Idx++];
Richard Smitheefb3d52012-02-10 09:58:53 +00004694 EPI.HasTrailingReturn = Record[Idx++];
John McCalle23cf432010-12-14 08:05:40 +00004695 EPI.TypeQuals = Record[Idx++];
Douglas Gregorc938c162011-01-26 05:01:58 +00004696 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Sebastian Redl60618fa2011-03-12 11:50:43 +00004697 ExceptionSpecificationType EST =
4698 static_cast<ExceptionSpecificationType>(Record[Idx++]);
4699 EPI.ExceptionSpecType = EST;
Douglas Gregorb0d06e22012-04-04 00:34:49 +00004700 SmallVector<QualType, 2> Exceptions;
Sebastian Redl60618fa2011-03-12 11:50:43 +00004701 if (EST == EST_Dynamic) {
4702 EPI.NumExceptions = Record[Idx++];
Sebastian Redl60618fa2011-03-12 11:50:43 +00004703 for (unsigned I = 0; I != EPI.NumExceptions; ++I)
Douglas Gregor393f2492011-07-22 00:38:23 +00004704 Exceptions.push_back(readType(*Loc.F, Record, Idx));
Sebastian Redl60618fa2011-03-12 11:50:43 +00004705 EPI.Exceptions = Exceptions.data();
4706 } else if (EST == EST_ComputedNoexcept) {
4707 EPI.NoexceptExpr = ReadExpr(*Loc.F);
Richard Smith7bb698a2012-04-21 17:47:47 +00004708 } else if (EST == EST_Uninstantiated) {
4709 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4710 EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
Richard Smithb9d0b762012-07-27 04:22:15 +00004711 } else if (EST == EST_Unevaluated) {
4712 EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
Sebastian Redl60618fa2011-03-12 11:50:43 +00004713 }
Douglas Gregor35942772011-09-09 21:34:22 +00004714 return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
John McCalle23cf432010-12-14 08:05:40 +00004715 EPI);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004716 }
4717
Douglas Gregor409448c2011-07-21 22:35:25 +00004718 case TYPE_UNRESOLVED_USING: {
4719 unsigned Idx = 0;
Douglas Gregor35942772011-09-09 21:34:22 +00004720 return Context.getTypeDeclType(
Douglas Gregor409448c2011-07-21 22:35:25 +00004721 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4722 }
4723
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004724 case TYPE_TYPEDEF: {
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00004725 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004726 Error("incorrect encoding of typedef type");
4727 return QualType();
4728 }
Douglas Gregor409448c2011-07-21 22:35:25 +00004729 unsigned Idx = 0;
4730 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004731 QualType Canonical = readType(*Loc.F, Record, Idx);
Douglas Gregor32adc8b2010-10-26 00:51:02 +00004732 if (!Canonical.isNull())
Douglas Gregor35942772011-09-09 21:34:22 +00004733 Canonical = Context.getCanonicalType(Canonical);
4734 return Context.getTypedefType(Decl, Canonical);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00004735 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004736
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004737 case TYPE_TYPEOF_EXPR:
Douglas Gregor35942772011-09-09 21:34:22 +00004738 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004739
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004740 case TYPE_TYPEOF: {
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004741 if (Record.size() != 1) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004742 Error("incorrect encoding of typeof(type) in AST file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004743 return QualType();
4744 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004745 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004746 return Context.getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004747 }
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Douglas Gregorf8af9822012-02-12 18:42:33 +00004749 case TYPE_DECLTYPE: {
4750 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4751 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4752 }
Anders Carlsson395b4752009-06-24 19:06:50 +00004753
Sean Huntca63c202011-05-24 22:41:36 +00004754 case TYPE_UNARY_TRANSFORM: {
Douglas Gregor393f2492011-07-22 00:38:23 +00004755 QualType BaseType = readType(*Loc.F, Record, Idx);
4756 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Sean Huntca63c202011-05-24 22:41:36 +00004757 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Douglas Gregor35942772011-09-09 21:34:22 +00004758 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
Sean Huntca63c202011-05-24 22:41:36 +00004759 }
4760
Richard Smith34b41d92011-02-20 03:19:35 +00004761 case TYPE_AUTO:
Douglas Gregor35942772011-09-09 21:34:22 +00004762 return Context.getAutoType(readType(*Loc.F, Record, Idx));
Richard Smith34b41d92011-02-20 03:19:35 +00004763
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004764 case TYPE_RECORD: {
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004765 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004766 Error("incorrect encoding of record type");
4767 return QualType();
4768 }
Douglas Gregor409448c2011-07-21 22:35:25 +00004769 unsigned Idx = 0;
4770 bool IsDependent = Record[Idx++];
Douglas Gregor56ca8a92012-01-17 19:21:53 +00004771 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4772 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4773 QualType T = Context.getRecordType(RD);
John McCallf4c73712011-01-19 06:33:43 +00004774 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004775 return T;
4776 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004777
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004778 case TYPE_ENUM: {
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004779 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00004780 Error("incorrect encoding of enum type");
4781 return QualType();
4782 }
Douglas Gregor409448c2011-07-21 22:35:25 +00004783 unsigned Idx = 0;
4784 bool IsDependent = Record[Idx++];
4785 QualType T
Douglas Gregor35942772011-09-09 21:34:22 +00004786 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
John McCallf4c73712011-01-19 06:33:43 +00004787 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004788 return T;
4789 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00004790
John McCall9d156a72011-01-06 01:58:22 +00004791 case TYPE_ATTRIBUTED: {
4792 if (Record.size() != 3) {
4793 Error("incorrect encoding of attributed type");
4794 return QualType();
4795 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004796 QualType modifiedType = readType(*Loc.F, Record, Idx);
4797 QualType equivalentType = readType(*Loc.F, Record, Idx);
John McCall9d156a72011-01-06 01:58:22 +00004798 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Douglas Gregor35942772011-09-09 21:34:22 +00004799 return Context.getAttributedType(kind, modifiedType, equivalentType);
John McCall9d156a72011-01-06 01:58:22 +00004800 }
4801
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004802 case TYPE_PAREN: {
4803 if (Record.size() != 1) {
4804 Error("incorrect encoding of paren type");
4805 return QualType();
4806 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004807 QualType InnerType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004808 return Context.getParenType(InnerType);
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004809 }
4810
Douglas Gregor7536dd52010-12-20 02:24:11 +00004811 case TYPE_PACK_EXPANSION: {
Douglas Gregorf9997a02011-02-01 15:24:58 +00004812 if (Record.size() != 2) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00004813 Error("incorrect encoding of pack expansion type");
4814 return QualType();
4815 }
Douglas Gregor393f2492011-07-22 00:38:23 +00004816 QualType Pattern = readType(*Loc.F, Record, Idx);
Douglas Gregor7536dd52010-12-20 02:24:11 +00004817 if (Pattern.isNull())
4818 return QualType();
Douglas Gregorcded4f62011-01-14 17:04:44 +00004819 llvm::Optional<unsigned> NumExpansions;
4820 if (Record[1])
4821 NumExpansions = Record[1] - 1;
Douglas Gregor35942772011-09-09 21:34:22 +00004822 return Context.getPackExpansionType(Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00004823 }
4824
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004825 case TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004826 unsigned Idx = 0;
4827 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00004828 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004829 QualType NamedType = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004830 return Context.getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00004831 }
4832
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004833 case TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00004834 unsigned Idx = 0;
Douglas Gregor409448c2011-07-21 22:35:25 +00004835 ObjCInterfaceDecl *ItfD
4836 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Douglas Gregor56ca8a92012-01-17 19:21:53 +00004837 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
John McCallc12c5bb2010-05-15 11:32:37 +00004838 }
4839
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004840 case TYPE_OBJC_OBJECT: {
John McCallc12c5bb2010-05-15 11:32:37 +00004841 unsigned Idx = 0;
Douglas Gregor393f2492011-07-22 00:38:23 +00004842 QualType Base = readType(*Loc.F, Record, Idx);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00004843 unsigned NumProtos = Record[Idx++];
Chris Lattner5f9e2722011-07-23 10:55:15 +00004844 SmallVector<ObjCProtocolDecl*, 4> Protos;
Chris Lattnerc6fa4452009-04-22 06:45:28 +00004845 for (unsigned I = 0; I != NumProtos; ++I)
Douglas Gregor409448c2011-07-21 22:35:25 +00004846 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregor35942772011-09-09 21:34:22 +00004847 return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00004848 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00004849
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004850 case TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00004851 unsigned Idx = 0;
Douglas Gregor393f2492011-07-22 00:38:23 +00004852 QualType Pointee = readType(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004853 return Context.getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00004854 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00004855
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004856 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
John McCall49a832b2009-10-18 09:09:24 +00004857 unsigned Idx = 0;
Douglas Gregor393f2492011-07-22 00:38:23 +00004858 QualType Parm = readType(*Loc.F, Record, Idx);
4859 QualType Replacement = readType(*Loc.F, Record, Idx);
John McCall49a832b2009-10-18 09:09:24 +00004860 return
Douglas Gregor35942772011-09-09 21:34:22 +00004861 Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
John McCall49a832b2009-10-18 09:09:24 +00004862 Replacement);
4863 }
John McCall3cb0ebd2010-03-10 03:28:59 +00004864
Douglas Gregorc3069d62011-01-14 02:55:32 +00004865 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4866 unsigned Idx = 0;
Douglas Gregor393f2492011-07-22 00:38:23 +00004867 QualType Parm = readType(*Loc.F, Record, Idx);
Douglas Gregorc3069d62011-01-14 02:55:32 +00004868 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004869 return Context.getSubstTemplateTypeParmPackType(
Douglas Gregorc3069d62011-01-14 02:55:32 +00004870 cast<TemplateTypeParmType>(Parm),
4871 ArgPack);
4872 }
4873
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004874 case TYPE_INJECTED_CLASS_NAME: {
Douglas Gregor409448c2011-07-21 22:35:25 +00004875 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004876 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00004877 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
Sebastian Redl3c7f4132010-08-18 23:57:06 +00004878 // for AST reading, too much interdependencies.
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00004879 return
Douglas Gregor35942772011-09-09 21:34:22 +00004880 QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00004881 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004882
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004883 case TYPE_TEMPLATE_TYPE_PARM: {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00004884 unsigned Idx = 0;
4885 unsigned Depth = Record[Idx++];
4886 unsigned Index = Record[Idx++];
4887 bool Pack = Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00004888 TemplateTypeParmDecl *D
4889 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00004890 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00004891 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004892
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004893 case TYPE_DEPENDENT_NAME: {
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00004894 unsigned Idx = 0;
4895 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00004896 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregor95eab172011-07-28 20:55:49 +00004897 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004898 QualType Canon = readType(*Loc.F, Record, Idx);
Douglas Gregor32adc8b2010-10-26 00:51:02 +00004899 if (!Canon.isNull())
Douglas Gregor35942772011-09-09 21:34:22 +00004900 Canon = Context.getCanonicalType(Canon);
4901 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00004902 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004903
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004904 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004905 unsigned Idx = 0;
4906 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00004907 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Douglas Gregor95eab172011-07-28 20:55:49 +00004908 const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004909 unsigned NumArgs = Record[Idx++];
Chris Lattner5f9e2722011-07-23 10:55:15 +00004910 SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004911 Args.reserve(NumArgs);
4912 while (NumArgs--)
Sebastian Redlc3632732010-10-05 15:59:54 +00004913 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
Douglas Gregor35942772011-09-09 21:34:22 +00004914 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00004915 Args.size(), Args.data());
4916 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00004917
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004918 case TYPE_DEPENDENT_SIZED_ARRAY: {
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00004919 unsigned Idx = 0;
4920
4921 // ArrayType
Douglas Gregor393f2492011-07-22 00:38:23 +00004922 QualType ElementType = readType(*Loc.F, Record, Idx);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00004923 ArrayType::ArraySizeModifier ASM
4924 = (ArrayType::ArraySizeModifier)Record[Idx++];
4925 unsigned IndexTypeQuals = Record[Idx++];
4926
4927 // DependentSizedArrayType
Sebastian Redlc3632732010-10-05 15:59:54 +00004928 Expr *NumElts = ReadExpr(*Loc.F);
4929 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00004930
Douglas Gregor35942772011-09-09 21:34:22 +00004931 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00004932 IndexTypeQuals, Brackets);
4933 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00004934
Sebastian Redl8538e8d2010-08-18 23:57:32 +00004935 case TYPE_TEMPLATE_SPECIALIZATION: {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00004936 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004937 bool IsDependent = Record[Idx++];
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004938 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
Chris Lattner5f9e2722011-07-23 10:55:15 +00004939 SmallVector<TemplateArgument, 8> Args;
Sebastian Redlc3632732010-10-05 15:59:54 +00004940 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00004941 QualType Underlying = readType(*Loc.F, Record, Idx);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004942 QualType T;
Richard Smith3e4c6c42011-05-05 21:57:07 +00004943 if (Underlying.isNull())
Douglas Gregor35942772011-09-09 21:34:22 +00004944 T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004945 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00004946 else
Douglas Gregor35942772011-09-09 21:34:22 +00004947 T = Context.getTemplateSpecializationType(Name, Args.data(),
Richard Smith3e4c6c42011-05-05 21:57:07 +00004948 Args.size(), Underlying);
John McCallf4c73712011-01-19 06:33:43 +00004949 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00004950 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00004951 }
Eli Friedmanb001de72011-10-06 23:00:33 +00004952
4953 case TYPE_ATOMIC: {
4954 if (Record.size() != 1) {
4955 Error("Incorrect encoding of atomic type");
4956 return QualType();
4957 }
4958 QualType ValueType = readType(*Loc.F, Record, Idx);
4959 return Context.getAtomicType(ValueType);
4960 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00004961 }
David Blaikie7530c032012-01-17 06:56:22 +00004962 llvm_unreachable("Invalid TypeCode!");
Douglas Gregor2cf26342009-04-09 22:27:44 +00004963}
4964
Sebastian Redlc3632732010-10-05 15:59:54 +00004965class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
Sebastian Redlc43b54c2010-08-18 23:56:43 +00004966 ASTReader &Reader;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004967 ModuleFile &F;
Sebastian Redlc43b54c2010-08-18 23:56:43 +00004968 const ASTReader::RecordData &Record;
John McCalla1ee0c52009-10-16 21:56:05 +00004969 unsigned &Idx;
4970
Sebastian Redlc3632732010-10-05 15:59:54 +00004971 SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4972 unsigned &I) {
4973 return Reader.ReadSourceLocation(F, R, I);
4974 }
4975
Douglas Gregor409448c2011-07-21 22:35:25 +00004976 template<typename T>
4977 T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4978 return Reader.ReadDeclAs<T>(F, Record, Idx);
4979 }
4980
John McCalla1ee0c52009-10-16 21:56:05 +00004981public:
Douglas Gregor1a4761e2011-11-30 23:21:26 +00004982 TypeLocReader(ASTReader &Reader, ModuleFile &F,
Sebastian Redlc43b54c2010-08-18 23:56:43 +00004983 const ASTReader::RecordData &Record, unsigned &Idx)
Benjamin Kramerfacde172012-06-06 17:32:50 +00004984 : Reader(Reader), F(F), Record(Record), Idx(Idx)
Sebastian Redlc3632732010-10-05 15:59:54 +00004985 { }
John McCalla1ee0c52009-10-16 21:56:05 +00004986
John McCall51bd8032009-10-18 01:05:36 +00004987 // We want compile-time assurance that we've enumerated all of
4988 // these, so unfortunately we have to declare them first, then
4989 // define them out-of-line.
4990#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00004991#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00004992 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00004993#include "clang/AST/TypeLocNodes.def"
4994
John McCall51bd8032009-10-18 01:05:36 +00004995 void VisitFunctionTypeLoc(FunctionTypeLoc);
4996 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00004997};
4998
John McCall51bd8032009-10-18 01:05:36 +00004999void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00005000 // nothing to do
5001}
John McCall51bd8032009-10-18 01:05:36 +00005002void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005003 TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
Douglas Gregorddf889a2010-01-18 18:04:31 +00005004 if (TL.needsExtraLocalData()) {
5005 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5006 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5007 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5008 TL.setModeAttr(Record[Idx++]);
5009 }
John McCalla1ee0c52009-10-16 21:56:05 +00005010}
John McCall51bd8032009-10-18 01:05:36 +00005011void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005012 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005013}
John McCall51bd8032009-10-18 01:05:36 +00005014void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005015 TL.setStarLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005016}
John McCall51bd8032009-10-18 01:05:36 +00005017void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005018 TL.setCaretLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005019}
John McCall51bd8032009-10-18 01:05:36 +00005020void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005021 TL.setAmpLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005022}
John McCall51bd8032009-10-18 01:05:36 +00005023void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005024 TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005025}
John McCall51bd8032009-10-18 01:05:36 +00005026void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005027 TL.setStarLoc(ReadSourceLocation(Record, Idx));
Abramo Bagnarab6ab6c12011-03-05 14:42:21 +00005028 TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005029}
John McCall51bd8032009-10-18 01:05:36 +00005030void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005031 TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5032 TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005033 if (Record[Idx++])
Sebastian Redlc3632732010-10-05 15:59:54 +00005034 TL.setSizeExpr(Reader.ReadExpr(F));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00005035 else
John McCall51bd8032009-10-18 01:05:36 +00005036 TL.setSizeExpr(0);
5037}
5038void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5039 VisitArrayTypeLoc(TL);
5040}
5041void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5042 VisitArrayTypeLoc(TL);
5043}
5044void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5045 VisitArrayTypeLoc(TL);
5046}
5047void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5048 DependentSizedArrayTypeLoc TL) {
5049 VisitArrayTypeLoc(TL);
5050}
5051void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5052 DependentSizedExtVectorTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005053 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005054}
5055void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005056 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005057}
5058void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005059 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005060}
5061void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Abramo Bagnara796aa442011-03-12 11:17:06 +00005062 TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
Abramo Bagnara59c0a812012-10-04 21:42:10 +00005063 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5064 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
Abramo Bagnara796aa442011-03-12 11:17:06 +00005065 TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005066 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
Douglas Gregor409448c2011-07-21 22:35:25 +00005067 TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005068 }
5069}
5070void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5071 VisitFunctionTypeLoc(TL);
5072}
5073void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5074 VisitFunctionTypeLoc(TL);
5075}
John McCalled976492009-12-04 22:46:56 +00005076void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005077 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCalled976492009-12-04 22:46:56 +00005078}
John McCall51bd8032009-10-18 01:05:36 +00005079void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005080 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005081}
5082void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005083 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5084 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5085 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005086}
5087void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005088 TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5089 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5090 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5091 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005092}
5093void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005094 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005095}
Sean Huntca63c202011-05-24 22:41:36 +00005096void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5097 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5098 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5099 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5100 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5101}
Richard Smith34b41d92011-02-20 03:19:35 +00005102void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5103 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5104}
John McCall51bd8032009-10-18 01:05:36 +00005105void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005106 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005107}
5108void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005109 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005110}
John McCall9d156a72011-01-06 01:58:22 +00005111void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5112 TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5113 if (TL.hasAttrOperand()) {
5114 SourceRange range;
5115 range.setBegin(ReadSourceLocation(Record, Idx));
5116 range.setEnd(ReadSourceLocation(Record, Idx));
5117 TL.setAttrOperandParensRange(range);
5118 }
5119 if (TL.hasAttrExprOperand()) {
5120 if (Record[Idx++])
5121 TL.setAttrExprOperand(Reader.ReadExpr(F));
5122 else
5123 TL.setAttrExprOperand(0);
5124 } else if (TL.hasAttrEnumOperand())
5125 TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5126}
John McCall51bd8032009-10-18 01:05:36 +00005127void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005128 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005129}
John McCall49a832b2009-10-18 09:09:24 +00005130void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5131 SubstTemplateTypeParmTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005132 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall49a832b2009-10-18 09:09:24 +00005133}
Douglas Gregorc3069d62011-01-14 02:55:32 +00005134void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5135 SubstTemplateTypeParmPackTypeLoc TL) {
5136 TL.setNameLoc(ReadSourceLocation(Record, Idx));
5137}
John McCall51bd8032009-10-18 01:05:36 +00005138void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5139 TemplateSpecializationTypeLoc TL) {
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005140 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
Sebastian Redlc3632732010-10-05 15:59:54 +00005141 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5142 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5143 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCall833ca992009-10-29 08:12:44 +00005144 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5145 TL.setArgLocInfo(i,
Sebastian Redlc3632732010-10-05 15:59:54 +00005146 Reader.GetTemplateArgumentLocInfo(F,
5147 TL.getTypePtr()->getArg(i).getKind(),
5148 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005149}
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005150void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5151 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5152 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5153}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005154void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnara38a42912012-02-06 19:09:27 +00005155 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregor9e876872011-03-01 18:12:44 +00005156 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005157}
John McCall3cb0ebd2010-03-10 03:28:59 +00005158void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005159 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall3cb0ebd2010-03-10 03:28:59 +00005160}
Douglas Gregor4714c122010-03-31 17:34:00 +00005161void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara38a42912012-02-06 19:09:27 +00005162 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregor2494dd02011-03-01 01:34:45 +00005163 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
Sebastian Redlc3632732010-10-05 15:59:54 +00005164 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005165}
John McCall33500952010-06-11 00:33:02 +00005166void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5167 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005168 TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
Douglas Gregor94fdffa2011-03-01 20:11:18 +00005169 TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
Abramo Bagnara66581d42012-02-06 22:45:07 +00005170 TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005171 TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
Sebastian Redlc3632732010-10-05 15:59:54 +00005172 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5173 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCall33500952010-06-11 00:33:02 +00005174 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5175 TL.setArgLocInfo(I,
Sebastian Redlc3632732010-10-05 15:59:54 +00005176 Reader.GetTemplateArgumentLocInfo(F,
5177 TL.getTypePtr()->getArg(I).getKind(),
5178 Record, Idx));
John McCall33500952010-06-11 00:33:02 +00005179}
Douglas Gregor7536dd52010-12-20 02:24:11 +00005180void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5181 TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5182}
John McCall51bd8032009-10-18 01:05:36 +00005183void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005184 TL.setNameLoc(ReadSourceLocation(Record, Idx));
John McCallc12c5bb2010-05-15 11:32:37 +00005185}
5186void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5187 TL.setHasBaseTypeAsWritten(Record[Idx++]);
Sebastian Redlc3632732010-10-05 15:59:54 +00005188 TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5189 TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00005190 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Sebastian Redlc3632732010-10-05 15:59:54 +00005191 TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
John McCalla1ee0c52009-10-16 21:56:05 +00005192}
John McCall54e14c42009-10-22 22:37:11 +00005193void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005194 TL.setStarLoc(ReadSourceLocation(Record, Idx));
John McCall54e14c42009-10-22 22:37:11 +00005195}
Eli Friedmanb001de72011-10-06 23:00:33 +00005196void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5197 TL.setKWLoc(ReadSourceLocation(Record, Idx));
5198 TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5199 TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5200}
John McCalla1ee0c52009-10-16 21:56:05 +00005201
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005202TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
Sebastian Redl577d4792010-07-22 22:43:28 +00005203 const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00005204 unsigned &Idx) {
Douglas Gregor393f2492011-07-22 00:38:23 +00005205 QualType InfoTy = readType(F, Record, Idx);
John McCalla1ee0c52009-10-16 21:56:05 +00005206 if (InfoTy.isNull())
5207 return 0;
5208
Douglas Gregor35942772011-09-09 21:34:22 +00005209 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Sebastian Redlc3632732010-10-05 15:59:54 +00005210 TypeLocReader TLR(*this, F, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00005211 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00005212 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00005213 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00005214}
Douglas Gregor2cf26342009-04-09 22:27:44 +00005215
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005216QualType ASTReader::GetType(TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00005217 unsigned FastQuals = ID & Qualifiers::FastMask;
5218 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005219
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005220 if (Index < NUM_PREDEF_TYPE_IDS) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00005221 QualType T;
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005222 switch ((PredefinedTypeIDs)Index) {
5223 case PREDEF_TYPE_NULL_ID: return QualType();
Douglas Gregor35942772011-09-09 21:34:22 +00005224 case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5225 case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005226
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005227 case PREDEF_TYPE_CHAR_U_ID:
5228 case PREDEF_TYPE_CHAR_S_ID:
Douglas Gregor2cf26342009-04-09 22:27:44 +00005229 // FIXME: Check that the signedness of CharTy is correct!
Douglas Gregor35942772011-09-09 21:34:22 +00005230 T = Context.CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005231 break;
5232
Douglas Gregor35942772011-09-09 21:34:22 +00005233 case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5234 case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
5235 case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5236 case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5237 case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
5238 case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
5239 case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5240 case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5241 case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5242 case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5243 case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5244 case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5245 case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00005246 case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
Douglas Gregor35942772011-09-09 21:34:22 +00005247 case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5248 case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5249 case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
5250 case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5251 case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
John McCall3c3b7f92011-10-25 17:37:35 +00005252 case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
Douglas Gregor35942772011-09-09 21:34:22 +00005253 case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5254 case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5255 case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5256 case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5257 case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5258 case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5259 case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
5260 case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
5261 case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
Douglas Gregor3b8043b2011-08-09 15:13:55 +00005262
5263 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
Douglas Gregor35942772011-09-09 21:34:22 +00005264 T = Context.getAutoRRefDeductType();
Douglas Gregor3b8043b2011-08-09 15:13:55 +00005265 break;
John McCall0ddaeb92011-10-17 18:09:15 +00005266
5267 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5268 T = Context.ARCUnbridgedCastTy;
5269 break;
5270
Meador Ingefb40e3f2012-07-01 15:57:25 +00005271 case PREDEF_TYPE_VA_LIST_TAG:
5272 T = Context.getVaListTagType();
5273 break;
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005274
5275 case PREDEF_TYPE_BUILTIN_FN:
5276 T = Context.BuiltinFnTy;
5277 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005278 }
5279
5280 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00005281 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00005282 }
5283
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005284 Index -= NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00005285 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00005286 if (TypesLoaded[Index].isNull()) {
Douglas Gregor393f2492011-07-22 00:38:23 +00005287 TypesLoaded[Index] = readTypeRecord(Index);
Douglas Gregor97475832010-10-05 18:37:06 +00005288 if (TypesLoaded[Index].isNull())
5289 return QualType();
5290
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005291 TypesLoaded[Index]->setFromAST();
Sebastian Redl30c514c2010-07-14 23:45:08 +00005292 if (DeserializationListener)
Argyrios Kyrtzidisc8e5d512010-08-20 16:03:59 +00005293 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
Sebastian Redl1476ed42010-07-16 16:36:56 +00005294 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00005295 }
Mike Stump1eb44332009-09-09 15:08:12 +00005296
John McCall0953e762009-09-24 19:53:00 +00005297 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00005298}
5299
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005300QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
Douglas Gregor393f2492011-07-22 00:38:23 +00005301 return GetType(getGlobalTypeID(F, LocalID));
5302}
5303
5304serialization::TypeID
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005305ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
Douglas Gregora119da02011-08-02 16:26:37 +00005306 unsigned FastQuals = LocalID & Qualifiers::FastMask;
5307 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5308
5309 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5310 return LocalID;
5311
5312 ContinuousRangeMap<uint32_t, int, 2>::iterator I
5313 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5314 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5315
5316 unsigned GlobalIndex = LocalIndex + I->second;
5317 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5318}
5319
John McCall833ca992009-10-29 08:12:44 +00005320TemplateArgumentLocInfo
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005321ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
Sebastian Redlc3632732010-10-05 15:59:54 +00005322 TemplateArgument::ArgKind Kind,
John McCall833ca992009-10-29 08:12:44 +00005323 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00005324 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00005325 switch (Kind) {
5326 case TemplateArgument::Expression:
Sebastian Redlc3632732010-10-05 15:59:54 +00005327 return ReadExpr(F);
John McCall833ca992009-10-29 08:12:44 +00005328 case TemplateArgument::Type:
Sebastian Redlc3632732010-10-05 15:59:54 +00005329 return GetTypeSourceInfo(F, Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00005330 case TemplateArgument::Template: {
Douglas Gregorb6744ef2011-03-02 17:09:35 +00005331 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5332 Index);
Sebastian Redlc3632732010-10-05 15:59:54 +00005333 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregorb6744ef2011-03-02 17:09:35 +00005334 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Douglas Gregora7fc9012011-01-05 18:58:31 +00005335 SourceLocation());
5336 }
5337 case TemplateArgument::TemplateExpansion: {
Douglas Gregorb6744ef2011-03-02 17:09:35 +00005338 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5339 Index);
Douglas Gregora7fc9012011-01-05 18:58:31 +00005340 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregorba68eca2011-01-05 17:40:24 +00005341 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
Douglas Gregorb6744ef2011-03-02 17:09:35 +00005342 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Douglas Gregorba68eca2011-01-05 17:40:24 +00005343 EllipsisLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00005344 }
John McCall833ca992009-10-29 08:12:44 +00005345 case TemplateArgument::Null:
5346 case TemplateArgument::Integral:
5347 case TemplateArgument::Declaration:
Eli Friedmand7a6b162012-09-26 02:36:12 +00005348 case TemplateArgument::NullPtr:
John McCall833ca992009-10-29 08:12:44 +00005349 case TemplateArgument::Pack:
Eli Friedmand7a6b162012-09-26 02:36:12 +00005350 // FIXME: Is this right?
John McCall833ca992009-10-29 08:12:44 +00005351 return TemplateArgumentLocInfo();
5352 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005353 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00005354}
5355
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00005356TemplateArgumentLoc
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005357ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
Sebastian Redl577d4792010-07-22 22:43:28 +00005358 const RecordData &Record, unsigned &Index) {
Sebastian Redlc3632732010-10-05 15:59:54 +00005359 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00005360
5361 if (Arg.getKind() == TemplateArgument::Expression) {
5362 if (Record[Index++]) // bool InfoHasSameExpr.
5363 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5364 }
Sebastian Redlc3632732010-10-05 15:59:54 +00005365 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00005366 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00005367}
5368
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005369Decl *ASTReader::GetExternalDecl(uint32_t ID) {
John McCall76bd1f32010-06-01 09:23:16 +00005370 return GetDecl(ID);
5371}
5372
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005373uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
Douglas Gregore92b8a12011-08-04 00:01:48 +00005374 unsigned &Idx){
5375 if (Idx >= Record.size())
Douglas Gregor7c789c12010-10-29 22:39:52 +00005376 return 0;
Douglas Gregor7c789c12010-10-29 22:39:52 +00005377
Douglas Gregore92b8a12011-08-04 00:01:48 +00005378 unsigned LocalID = Record[Idx++];
5379 return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005380}
5381
5382CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005383 RecordLocation Loc = getLocalBitOffset(Offset);
5384 llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Douglas Gregor7c789c12010-10-29 22:39:52 +00005385 SavedStreamPosition SavedPosition(Cursor);
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005386 Cursor.JumpToBit(Loc.Offset);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005387 ReadingKindTracker ReadingKind(Read_Decl, *this);
5388 RecordData Record;
5389 unsigned Code = Cursor.ReadCode();
5390 unsigned RecCode = Cursor.ReadRecord(Code, Record);
5391 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5392 Error("Malformed AST file: missing C++ base specifiers");
5393 return 0;
5394 }
5395
5396 unsigned Idx = 0;
5397 unsigned NumBases = Record[Idx++];
Douglas Gregor35942772011-09-09 21:34:22 +00005398 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005399 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5400 for (unsigned I = 0; I != NumBases; ++I)
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005401 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
Douglas Gregor7c789c12010-10-29 22:39:52 +00005402 return Bases;
5403}
5404
Douglas Gregor409448c2011-07-21 22:35:25 +00005405serialization::DeclID
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00005406ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005407 if (LocalID < NUM_PREDEF_DECL_IDS)
Douglas Gregor496c7092011-08-03 15:48:04 +00005408 return LocalID;
5409
5410 ContinuousRangeMap<uint32_t, int, 2>::iterator I
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005411 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
Douglas Gregor496c7092011-08-03 15:48:04 +00005412 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5413
5414 return LocalID + I->second;
Douglas Gregor409448c2011-07-21 22:35:25 +00005415}
5416
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00005417bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005418 ModuleFile &M) const {
Argyrios Kyrtzidise6b8d682011-09-01 00:58:55 +00005419 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5420 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5421 return &M == I->second;
5422}
5423
Douglas Gregorcff9f262012-01-27 01:47:08 +00005424ModuleFile *ASTReader::getOwningModuleFile(Decl *D) {
5425 if (!D->isFromASTFile())
5426 return 0;
5427 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5428 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5429 return I->second;
5430}
5431
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005432SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5433 if (ID < NUM_PREDEF_DECL_IDS)
5434 return SourceLocation();
5435
5436 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5437
5438 if (Index > DeclsLoaded.size()) {
5439 Error("declaration ID out-of-range for AST file");
5440 return SourceLocation();
5441 }
5442
5443 if (Decl *D = DeclsLoaded[Index])
5444 return D->getLocation();
5445
5446 unsigned RawLocation = 0;
5447 RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5448 return ReadSourceLocation(*Rec.F, RawLocation);
5449}
5450
Sebastian Redl8538e8d2010-08-18 23:57:32 +00005451Decl *ASTReader::GetDecl(DeclID ID) {
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005452 if (ID < NUM_PREDEF_DECL_IDS) {
5453 switch ((PredefinedDeclIDs)ID) {
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00005454 case PREDEF_DECL_NULL_ID:
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005455 return 0;
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00005456
5457 case PREDEF_DECL_TRANSLATION_UNIT_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005458 return Context.getTranslationUnitDecl();
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00005459
5460 case PREDEF_DECL_OBJC_ID_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005461 return Context.getObjCIdDecl();
Douglas Gregor79d67262011-08-12 05:59:41 +00005462
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005463 case PREDEF_DECL_OBJC_SEL_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005464 return Context.getObjCSelDecl();
Douglas Gregor7a27ea52011-08-12 06:17:30 +00005465
Douglas Gregor79d67262011-08-12 05:59:41 +00005466 case PREDEF_DECL_OBJC_CLASS_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005467 return Context.getObjCClassDecl();
Douglas Gregor772eeae2011-08-12 06:49:56 +00005468
Douglas Gregora6ea10e2012-01-17 18:09:05 +00005469 case PREDEF_DECL_OBJC_PROTOCOL_ID:
5470 return Context.getObjCProtocolDecl();
5471
Douglas Gregor772eeae2011-08-12 06:49:56 +00005472 case PREDEF_DECL_INT_128_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005473 return Context.getInt128Decl();
Douglas Gregor772eeae2011-08-12 06:49:56 +00005474
5475 case PREDEF_DECL_UNSIGNED_INT_128_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005476 return Context.getUInt128Decl();
Douglas Gregore97179c2011-09-08 01:46:34 +00005477
5478 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
Douglas Gregor35942772011-09-09 21:34:22 +00005479 return Context.getObjCInstanceTypeDecl();
Meador Ingec5613b22012-06-16 03:34:49 +00005480
5481 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5482 return Context.getBuiltinVaListDecl();
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005483 }
Douglas Gregor0a14e4b2011-08-03 16:05:40 +00005484 }
5485
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00005486 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5487
Richard Smith2fbf3732011-12-20 04:39:57 +00005488 if (Index >= DeclsLoaded.size()) {
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00005489 assert(0 && "declaration ID out-of-range for AST file");
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005490 Error("declaration ID out-of-range for AST file");
Argyrios Kyrtzidis7518b372012-07-02 19:19:01 +00005491 return 0;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005492 }
Douglas Gregor6bf2b9f2011-08-12 00:15:20 +00005493
Douglas Gregorfd002a72011-12-16 22:37:11 +00005494 if (!DeclsLoaded[Index]) {
Douglas Gregor496c7092011-08-03 15:48:04 +00005495 ReadDeclRecord(ID);
Sebastian Redl30c514c2010-07-14 23:45:08 +00005496 if (DeserializationListener)
5497 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5498 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005499
5500 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00005501}
5502
Douglas Gregora1be2782011-12-17 23:38:30 +00005503DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5504 DeclID GlobalID) {
5505 if (GlobalID < NUM_PREDEF_DECL_IDS)
5506 return GlobalID;
5507
5508 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5509 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5510 ModuleFile *Owner = I->second;
5511
5512 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5513 = M.GlobalToLocalDeclIDs.find(Owner);
5514 if (Pos == M.GlobalToLocalDeclIDs.end())
5515 return 0;
5516
5517 return GlobalID - Owner->BaseDeclID + Pos->second;
5518}
5519
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005520serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Douglas Gregor409448c2011-07-21 22:35:25 +00005521 const RecordData &Record,
5522 unsigned &Idx) {
5523 if (Idx >= Record.size()) {
5524 Error("Corrupted AST file");
5525 return 0;
5526 }
5527
5528 return getGlobalDeclID(F, Record[Idx++]);
5529}
5530
Chris Lattner887e2b32009-04-27 05:46:25 +00005531/// \brief Resolve the offset of a statement into a statement.
5532///
5533/// This operation will read a new statement from the external
5534/// source each time it is called, and is meant to be used via a
5535/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005536Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
Argyrios Kyrtzidise09a2752010-10-28 09:29:32 +00005537 // Switch case IDs are per Decl.
5538 ClearSwitchCaseIDs();
5539
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00005540 // Offset here is a global offset across the entire chain.
Douglas Gregor8f1231b2011-07-22 06:10:01 +00005541 RecordLocation Loc = getLocalBitOffset(Offset);
5542 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5543 return ReadStmtFromStream(*Loc.F);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00005544}
5545
Douglas Gregor851c75a2011-08-24 21:27:34 +00005546namespace {
5547 class FindExternalLexicalDeclsVisitor {
5548 ASTReader &Reader;
5549 const DeclContext *DC;
5550 bool (*isKindWeWant)(Decl::Kind);
Douglas Gregor2ea054f2011-08-26 22:04:51 +00005551
Douglas Gregor851c75a2011-08-24 21:27:34 +00005552 SmallVectorImpl<Decl*> &Decls;
5553 bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5554
5555 public:
5556 FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5557 bool (*isKindWeWant)(Decl::Kind),
5558 SmallVectorImpl<Decl*> &Decls)
5559 : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5560 {
5561 for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5562 PredefsVisited[I] = false;
5563 }
5564
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005565 static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
Douglas Gregor851c75a2011-08-24 21:27:34 +00005566 if (Preorder)
5567 return false;
5568
5569 FindExternalLexicalDeclsVisitor *This
5570 = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5571
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005572 ModuleFile::DeclContextInfosMap::iterator Info
Douglas Gregor851c75a2011-08-24 21:27:34 +00005573 = M.DeclContextInfos.find(This->DC);
5574 if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5575 return false;
5576
5577 // Load all of the declaration IDs
5578 for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5579 *IDE = ID + Info->second.NumLexicalDecls;
5580 ID != IDE; ++ID) {
5581 if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5582 continue;
5583
5584 // Don't add predefined declarations to the lexical context more
5585 // than once.
5586 if (ID->second < NUM_PREDEF_DECL_IDS) {
5587 if (This->PredefsVisited[ID->second])
5588 continue;
5589
5590 This->PredefsVisited[ID->second] = true;
5591 }
5592
Douglas Gregor2ea054f2011-08-26 22:04:51 +00005593 if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5594 if (!This->DC->isDeclInLexicalTraversal(D))
5595 This->Decls.push_back(D);
5596 }
Douglas Gregor851c75a2011-08-24 21:27:34 +00005597 }
5598
5599 return false;
5600 }
5601 };
5602}
5603
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00005604ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00005605 bool (*isKindWeWant)(Decl::Kind),
Chris Lattner5f9e2722011-07-23 10:55:15 +00005606 SmallVectorImpl<Decl*> &Decls) {
Douglas Gregor0d95f772011-08-24 19:03:07 +00005607 // There might be lexical decls in multiple modules, for the TU at
Douglas Gregor851c75a2011-08-24 21:27:34 +00005608 // least. Walk all of the modules in the order they were loaded.
5609 FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5610 ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
Douglas Gregor25123082009-04-22 22:34:57 +00005611 ++NumLexicalDeclContextsRead;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00005612 return ELR_Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00005613}
5614
Douglas Gregor0d95f772011-08-24 19:03:07 +00005615namespace {
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005616
5617class DeclIDComp {
5618 ASTReader &Reader;
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005619 ModuleFile &Mod;
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005620
5621public:
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005622 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005623
5624 bool operator()(LocalDeclID L, LocalDeclID R) const {
5625 SourceLocation LHS = getLocation(L);
5626 SourceLocation RHS = getLocation(R);
5627 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5628 }
5629
5630 bool operator()(SourceLocation LHS, LocalDeclID R) const {
5631 SourceLocation RHS = getLocation(R);
5632 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5633 }
5634
5635 bool operator()(LocalDeclID L, SourceLocation RHS) const {
5636 SourceLocation LHS = getLocation(L);
5637 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5638 }
5639
5640 SourceLocation getLocation(LocalDeclID ID) const {
5641 return Reader.getSourceManager().getFileLoc(
5642 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5643 }
5644};
5645
5646}
5647
5648void ASTReader::FindFileRegionDecls(FileID File,
5649 unsigned Offset, unsigned Length,
5650 SmallVectorImpl<Decl *> &Decls) {
5651 SourceManager &SM = getSourceManager();
5652
5653 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5654 if (I == FileDeclIDs.end())
5655 return;
5656
5657 FileDeclsInfo &DInfo = I->second;
5658 if (DInfo.Decls.empty())
5659 return;
5660
5661 SourceLocation
5662 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5663 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5664
5665 DeclIDComp DIDComp(*this, *DInfo.Mod);
5666 ArrayRef<serialization::LocalDeclID>::iterator
5667 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5668 BeginLoc, DIDComp);
5669 if (BeginIt != DInfo.Decls.begin())
5670 --BeginIt;
5671
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00005672 // If we are pointing at a top-level decl inside an objc container, we need
5673 // to backtrack until we find it otherwise we will fail to report that the
5674 // region overlaps with an objc container.
5675 while (BeginIt != DInfo.Decls.begin() &&
5676 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5677 ->isTopLevelDeclInObjCContainer())
5678 --BeginIt;
5679
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00005680 ArrayRef<serialization::LocalDeclID>::iterator
5681 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5682 EndLoc, DIDComp);
5683 if (EndIt != DInfo.Decls.end())
5684 ++EndIt;
5685
5686 for (ArrayRef<serialization::LocalDeclID>::iterator
5687 DIt = BeginIt; DIt != EndIt; ++DIt)
5688 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5689}
5690
5691namespace {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005692 /// \brief ModuleFile visitor used to perform name lookup into a
Douglas Gregor0d95f772011-08-24 19:03:07 +00005693 /// declaration context.
5694 class DeclContextNameLookupVisitor {
5695 ASTReader &Reader;
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005696 llvm::SmallVectorImpl<const DeclContext *> &Contexts;
Douglas Gregor0d95f772011-08-24 19:03:07 +00005697 DeclarationName Name;
5698 SmallVectorImpl<NamedDecl *> &Decls;
5699
5700 public:
5701 DeclContextNameLookupVisitor(ASTReader &Reader,
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005702 SmallVectorImpl<const DeclContext *> &Contexts,
5703 DeclarationName Name,
Douglas Gregor0d95f772011-08-24 19:03:07 +00005704 SmallVectorImpl<NamedDecl *> &Decls)
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005705 : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
Douglas Gregor0d95f772011-08-24 19:03:07 +00005706
Douglas Gregor1a4761e2011-11-30 23:21:26 +00005707 static bool visit(ModuleFile &M, void *UserData) {
Douglas Gregor0d95f772011-08-24 19:03:07 +00005708 DeclContextNameLookupVisitor *This
5709 = static_cast<DeclContextNameLookupVisitor *>(UserData);
5710
5711 // Check whether we have any visible declaration information for
5712 // this context in this module.
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005713 ModuleFile::DeclContextInfosMap::iterator Info;
5714 bool FoundInfo = false;
5715 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5716 Info = M.DeclContextInfos.find(This->Contexts[I]);
5717 if (Info != M.DeclContextInfos.end() &&
5718 Info->second.NameLookupTableData) {
5719 FoundInfo = true;
5720 break;
5721 }
5722 }
Douglas Gregor0d95f772011-08-24 19:03:07 +00005723
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005724 if (!FoundInfo)
5725 return false;
5726
Douglas Gregor0d95f772011-08-24 19:03:07 +00005727 // Look for this name within this module.
5728 ASTDeclContextNameLookupTable *LookupTable =
Benjamin Kramerb1758c62012-04-15 12:36:49 +00005729 Info->second.NameLookupTableData;
Douglas Gregor0d95f772011-08-24 19:03:07 +00005730 ASTDeclContextNameLookupTable::iterator Pos
5731 = LookupTable->find(This->Name);
5732 if (Pos == LookupTable->end())
5733 return false;
5734
5735 bool FoundAnything = false;
5736 ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5737 for (; Data.first != Data.second; ++Data.first) {
5738 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5739 if (!ND)
5740 continue;
5741
5742 if (ND->getDeclName() != This->Name) {
Axel Naumann3dd82f72012-10-01 09:51:27 +00005743 // A name might be null because the decl's redeclarable part is
5744 // currently read before reading its name. The lookup is triggered by
5745 // building that decl (likely indirectly), and so it is later in the
5746 // sense of "already existing" and can be ignored here.
Douglas Gregor0d95f772011-08-24 19:03:07 +00005747 continue;
5748 }
5749
5750 // Record this declaration.
5751 FoundAnything = true;
5752 This->Decls.push_back(ND);
5753 }
5754
5755 return FoundAnything;
5756 }
5757 };
5758}
5759
John McCall76bd1f32010-06-01 09:23:16 +00005760DeclContext::lookup_result
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005761ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
John McCall76bd1f32010-06-01 09:23:16 +00005762 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00005763 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00005764 "DeclContext has no visible decls in storage");
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00005765 if (!Name)
5766 return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
5767 DeclContext::lookup_iterator(0));
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00005768
Chris Lattner5f9e2722011-07-23 10:55:15 +00005769 SmallVector<NamedDecl *, 64> Decls;
Douglas Gregorc6c8e0e2012-01-09 17:30:44 +00005770
5771 // Compute the declaration contexts we need to look into. Multiple such
5772 // declaration contexts occur when two declaration contexts from disjoint
5773 // modules get merged, e.g., when two namespaces with the same name are
5774 // independently defined in separate modules.
5775 SmallVector<const DeclContext *, 2> Contexts;
5776 Contexts.push_back(DC);
5777
5778 if (DC->isNamespace()) {
5779 MergedDeclsMap::iterator Merged
5780 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5781 if (Merged != MergedDecls.end()) {
5782 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5783 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5784 }
5785 }
5786
5787 DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
Douglas Gregor0d95f772011-08-24 19:03:07 +00005788 ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
Douglas Gregor25123082009-04-22 22:34:57 +00005789 ++NumVisibleDeclContextsRead;
Argyrios Kyrtzidis074dcc82010-08-20 16:04:35 +00005790 SetExternalVisibleDeclsForName(DC, Name, Decls);
John McCall76bd1f32010-06-01 09:23:16 +00005791 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00005792}
5793
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005794namespace {
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005795 /// \brief ModuleFile visitor used to retrieve all visible names in a
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005796 /// declaration context.
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005797 class DeclContextAllNamesVisitor {
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005798 ASTReader &Reader;
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005799 llvm::SmallVectorImpl<const DeclContext *> &Contexts;
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005800 llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005801
5802 public:
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005803 DeclContextAllNamesVisitor(ASTReader &Reader,
5804 SmallVectorImpl<const DeclContext *> &Contexts,
5805 llvm::DenseMap<DeclarationName,
5806 SmallVector<NamedDecl *, 8> > &Decls)
5807 : Reader(Reader), Contexts(Contexts), Decls(Decls) { }
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005808
5809 static bool visit(ModuleFile &M, void *UserData) {
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005810 DeclContextAllNamesVisitor *This
5811 = static_cast<DeclContextAllNamesVisitor *>(UserData);
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005812
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005813 // Check whether we have any visible declaration information for
5814 // this context in this module.
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005815 ModuleFile::DeclContextInfosMap::iterator Info;
5816 bool FoundInfo = false;
5817 for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5818 Info = M.DeclContextInfos.find(This->Contexts[I]);
5819 if (Info != M.DeclContextInfos.end() &&
5820 Info->second.NameLookupTableData) {
5821 FoundInfo = true;
5822 break;
5823 }
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005824 }
5825
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005826 if (!FoundInfo)
5827 return false;
5828
5829 ASTDeclContextNameLookupTable *LookupTable =
5830 Info->second.NameLookupTableData;
5831 bool FoundAnything = false;
5832 for (ASTDeclContextNameLookupTable::data_iterator
5833 I = LookupTable->data_begin(), E = LookupTable->data_end();
5834 I != E; ++I) {
5835 ASTDeclContextNameLookupTrait::data_type Data = *I;
5836 for (; Data.first != Data.second; ++Data.first) {
5837 NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5838 *Data.first);
5839 if (!ND)
5840 continue;
5841
5842 // Record this declaration.
5843 FoundAnything = true;
5844 This->Decls[ND->getDeclName()].push_back(ND);
5845 }
5846 }
5847
5848 return FoundAnything;
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005849 }
5850 };
5851}
5852
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005853void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005854 if (!DC->hasExternalVisibleStorage())
5855 return;
Nick Lewyckyb346d2f2012-04-16 02:51:46 +00005856 llvm::DenseMap<DeclarationName, llvm::SmallVector<NamedDecl*, 8> > Decls;
5857
5858 // Compute the declaration contexts we need to look into. Multiple such
5859 // declaration contexts occur when two declaration contexts from disjoint
5860 // modules get merged, e.g., when two namespaces with the same name are
5861 // independently defined in separate modules.
5862 SmallVector<const DeclContext *, 2> Contexts;
5863 Contexts.push_back(DC);
5864
5865 if (DC->isNamespace()) {
5866 MergedDeclsMap::iterator Merged
5867 = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5868 if (Merged != MergedDecls.end()) {
5869 for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5870 Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5871 }
5872 }
5873
5874 DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls);
5875 ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5876 ++NumVisibleDeclContextsRead;
5877
5878 for (llvm::DenseMap<DeclarationName,
5879 llvm::SmallVector<NamedDecl*, 8> >::iterator
5880 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5881 SetExternalVisibleDeclsForName(DC, I->first, I->second);
5882 }
Argyrios Kyrtzidis394e5392012-04-26 18:34:14 +00005883 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
Argyrios Kyrtzidis643586f2012-03-22 16:08:04 +00005884}
5885
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00005886/// \brief Under non-PCH compilation the consumer receives the objc methods
5887/// before receiving the implementation, and codegen depends on this.
5888/// We simulate this by deserializing and passing to consumer the methods of the
5889/// implementation before passing the deserialized implementation decl.
5890static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5891 ASTConsumer *Consumer) {
5892 assert(ImplD && Consumer);
5893
5894 for (ObjCImplDecl::method_iterator
5895 I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00005896 Consumer->HandleInterestingDecl(DeclGroupRef(*I));
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00005897
5898 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5899}
5900
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005901void ASTReader::PassInterestingDeclsToConsumer() {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005902 assert(Consumer);
5903 while (!InterestingDecls.empty()) {
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00005904 Decl *D = InterestingDecls.front();
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005905 InterestingDecls.pop_front();
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00005906
Argyrios Kyrtzidis8d39c3d2011-11-30 23:18:26 +00005907 PassInterestingDeclToConsumer(D);
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005908 }
5909}
5910
Argyrios Kyrtzidis8d39c3d2011-11-30 23:18:26 +00005911void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5912 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5913 PassObjCImplDeclToConsumer(ImplD, Consumer);
5914 else
5915 Consumer->HandleInterestingDecl(DeclGroupRef(D));
5916}
5917
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005918void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00005919 this->Consumer = Consumer;
5920
Douglas Gregorfdd01722009-04-14 00:24:19 +00005921 if (!Consumer)
5922 return;
5923
5924 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005925 // Force deserialization of this decl, which will cause it to be queued for
5926 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00005927 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00005928 }
Douglas Gregor1a995dd2011-09-15 18:47:32 +00005929 ExternalDefinitions.clear();
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00005930
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00005931 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00005932}
5933
Sebastian Redlc43b54c2010-08-18 23:56:43 +00005934void ASTReader::PrintStats() {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00005935 std::fprintf(stderr, "*** AST File Statistics:\n");
Douglas Gregor2cf26342009-04-09 22:27:44 +00005936
Mike Stump1eb44332009-09-09 15:08:12 +00005937 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005938 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00005939 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005940 unsigned NumDeclsLoaded
5941 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5942 (Decl *)0);
5943 unsigned NumIdentifiersLoaded
5944 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5945 IdentifiersLoaded.end(),
5946 (IdentifierInfo *)0);
Douglas Gregora8235d62012-10-09 23:05:51 +00005947 unsigned NumMacrosLoaded
5948 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5949 MacrosLoaded.end(),
5950 (MacroInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00005951 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005952 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5953 SelectorsLoaded.end(),
5954 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00005955
Douglas Gregor4fed3f42009-04-27 18:38:38 +00005956 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
5957 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor0cdd7982011-07-21 18:46:38 +00005958 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00005959 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
5960 NumSLocEntriesRead, TotalNumSLocEntries,
5961 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005962 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00005963 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005964 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5965 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5966 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00005967 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00005968 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5969 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005970 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00005971 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00005972 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5973 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregora8235d62012-10-09 23:05:51 +00005974 if (!MacrosLoaded.empty())
5975 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5976 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5977 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
Sebastian Redl725cd962010-08-04 20:40:17 +00005978 if (!SelectorsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00005979 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
Sebastian Redl725cd962010-08-04 20:40:17 +00005980 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5981 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00005982 if (TotalNumStatements)
5983 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
5984 NumStatementsRead, TotalNumStatements,
5985 ((float)NumStatementsRead/TotalNumStatements * 100));
5986 if (TotalNumMacros)
5987 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
5988 NumMacrosRead, TotalNumMacros,
5989 ((float)NumMacrosRead/TotalNumMacros * 100));
5990 if (TotalLexicalDeclContexts)
5991 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
5992 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5993 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5994 * 100));
5995 if (TotalVisibleDeclContexts)
5996 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
5997 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5998 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5999 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00006000 if (TotalNumMethodPoolEntries) {
Douglas Gregor83941df2009-04-25 17:48:32 +00006001 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
Sebastian Redlfa78dec2010-08-04 21:22:45 +00006002 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6003 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
Douglas Gregor83941df2009-04-25 17:48:32 +00006004 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00006005 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
Douglas Gregor83941df2009-04-25 17:48:32 +00006006 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00006007 std::fprintf(stderr, "\n");
Douglas Gregor23d7df52011-07-21 19:50:14 +00006008 dump();
6009 std::fprintf(stderr, "\n");
6010}
6011
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006012template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Douglas Gregor23d7df52011-07-21 19:50:14 +00006013static void
Chris Lattner5f9e2722011-07-23 10:55:15 +00006014dumpModuleIDMap(StringRef Name,
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006015 const ContinuousRangeMap<Key, ModuleFile *,
Douglas Gregor23d7df52011-07-21 19:50:14 +00006016 InitialCapacity> &Map) {
6017 if (Map.begin() == Map.end())
6018 return;
6019
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006020 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
Douglas Gregor23d7df52011-07-21 19:50:14 +00006021 llvm::errs() << Name << ":\n";
6022 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6023 I != IEnd; ++I) {
6024 llvm::errs() << " " << I->first << " -> " << I->second->FileName
6025 << "\n";
6026 }
6027}
6028
Douglas Gregor23d7df52011-07-21 19:50:14 +00006029void ASTReader::dump() {
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006030 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
Douglas Gregor8f1231b2011-07-22 06:10:01 +00006031 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
Douglas Gregor23d7df52011-07-21 19:50:14 +00006032 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
Douglas Gregor1e849b62011-07-29 00:21:44 +00006033 dumpModuleIDMap("Global type map", GlobalTypeMap);
Douglas Gregor9827a802011-07-29 00:56:45 +00006034 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
Douglas Gregor9827a802011-07-29 00:56:45 +00006035 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
Douglas Gregora8235d62012-10-09 23:05:51 +00006036 dumpModuleIDMap("Global macro map", GlobalMacroMap);
Douglas Gregor26ced122011-12-01 00:59:36 +00006037 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
Douglas Gregor9827a802011-07-29 00:56:45 +00006038 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
Douglas Gregor9827a802011-07-29 00:56:45 +00006039 dumpModuleIDMap("Global preprocessed entity map",
6040 GlobalPreprocessedEntityMap);
Douglas Gregor8df5c9b2011-08-02 11:12:41 +00006041
6042 llvm::errs() << "\n*** PCH/Modules Loaded:";
6043 for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6044 MEnd = ModuleMgr.end();
6045 M != MEnd; ++M)
6046 (*M)->dump();
Douglas Gregor2cf26342009-04-09 22:27:44 +00006047}
6048
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00006049/// Return the amount of memory used by memory buffers, breaking down
6050/// by heap-backed versus mmap'ed memory.
6051void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006052 for (ModuleConstIterator I = ModuleMgr.begin(),
6053 E = ModuleMgr.end(); I != E; ++I) {
6054 if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00006055 size_t bytes = buf->getBufferSize();
6056 switch (buf->getBufferKind()) {
6057 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6058 sizes.malloc_bytes += bytes;
6059 break;
6060 case llvm::MemoryBuffer::MemoryBuffer_MMap:
6061 sizes.mmap_bytes += bytes;
6062 break;
6063 }
6064 }
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006065 }
Ted Kremeneke9b5f3d2011-04-28 23:46:20 +00006066}
6067
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006068void ASTReader::InitializeSema(Sema &S) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00006069 SemaObj = &S;
Axel Naumann0ec56b72012-10-18 19:05:02 +00006070 S.addExternalSource(this);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00006071
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00006072 // Makes sure any declarations that were deserialized "too early"
6073 // still get added to the identifier's declaration chains.
Douglas Gregor76dc8892010-09-24 23:29:12 +00006074 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
Douglas Gregoreee242f2011-10-27 09:33:13 +00006075 SemaObj->pushExternalDeclIntoScope(PreloadedDecls[I],
6076 PreloadedDecls[I]->getDeclName());
Douglas Gregor668c1a42009-04-21 22:25:48 +00006077 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00006078 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00006079
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006080 // Load the offsets of the declarations that Sema references.
6081 // They will be lazily deserialized when needed.
6082 if (!SemaDeclRefs.empty()) {
6083 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
Douglas Gregor1e5b6f62011-07-28 00:57:24 +00006084 if (!SemaObj->StdNamespace)
6085 SemaObj->StdNamespace = SemaDeclRefs[0];
6086 if (!SemaObj->StdBadAlloc)
6087 SemaObj->StdBadAlloc = SemaDeclRefs[1];
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006088 }
6089
Peter Collingbourne84bccea2011-02-15 19:46:30 +00006090 if (!FPPragmaOptions.empty()) {
6091 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6092 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6093 }
6094
6095 if (!OpenCLExtensions.empty()) {
6096 unsigned I = 0;
6097#define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6098#include "clang/Basic/OpenCLExtensions.def"
6099
6100 assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6101 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00006102}
6103
Douglas Gregor211f6e82011-08-20 04:39:52 +00006104IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00006105 // Note that we are loading an identifier.
6106 Deserializing AnIdentifier(this);
6107
Douglas Gregor057df202012-01-18 20:56:22 +00006108 IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart),
6109 /*PriorGeneration=*/0);
Douglas Gregor211f6e82011-08-20 04:39:52 +00006110 ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
Douglas Gregoreee242f2011-10-27 09:33:13 +00006111 IdentifierInfo *II = Visitor.getIdentifierInfo();
Douglas Gregor057df202012-01-18 20:56:22 +00006112 markIdentifierUpToDate(II);
Douglas Gregoreee242f2011-10-27 09:33:13 +00006113 return II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00006114}
6115
Douglas Gregor95f42922010-10-14 22:11:03 +00006116namespace clang {
6117 /// \brief An identifier-lookup iterator that enumerates all of the
6118 /// identifiers stored within a set of AST files.
6119 class ASTIdentifierIterator : public IdentifierIterator {
6120 /// \brief The AST reader whose identifiers are being enumerated.
6121 const ASTReader &Reader;
6122
6123 /// \brief The current index into the chain of AST files stored in
6124 /// the AST reader.
6125 unsigned Index;
6126
6127 /// \brief The current position within the identifier lookup table
6128 /// of the current AST file.
6129 ASTIdentifierLookupTable::key_iterator Current;
6130
6131 /// \brief The end position within the identifier lookup table of
6132 /// the current AST file.
6133 ASTIdentifierLookupTable::key_iterator End;
6134
6135 public:
6136 explicit ASTIdentifierIterator(const ASTReader &Reader);
6137
Chris Lattner5f9e2722011-07-23 10:55:15 +00006138 virtual StringRef Next();
Douglas Gregor95f42922010-10-14 22:11:03 +00006139 };
6140}
6141
6142ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006143 : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
Douglas Gregor95f42922010-10-14 22:11:03 +00006144 ASTIdentifierLookupTable *IdTable
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006145 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
Douglas Gregor95f42922010-10-14 22:11:03 +00006146 Current = IdTable->key_begin();
6147 End = IdTable->key_end();
6148}
6149
Chris Lattner5f9e2722011-07-23 10:55:15 +00006150StringRef ASTIdentifierIterator::Next() {
Douglas Gregor95f42922010-10-14 22:11:03 +00006151 while (Current == End) {
6152 // If we have exhausted all of our AST files, we're done.
6153 if (Index == 0)
Chris Lattner5f9e2722011-07-23 10:55:15 +00006154 return StringRef();
Douglas Gregor95f42922010-10-14 22:11:03 +00006155
6156 --Index;
6157 ASTIdentifierLookupTable *IdTable
Jonathan D. Turner5d6d89f2011-07-25 20:32:21 +00006158 = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6159 IdentifierLookupTable;
Douglas Gregor95f42922010-10-14 22:11:03 +00006160 Current = IdTable->key_begin();
6161 End = IdTable->key_end();
6162 }
6163
6164 // We have any identifiers remaining in the current AST file; return
6165 // the next one.
6166 std::pair<const char*, unsigned> Key = *Current;
6167 ++Current;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006168 return StringRef(Key.first, Key.second);
Douglas Gregor95f42922010-10-14 22:11:03 +00006169}
6170
6171IdentifierIterator *ASTReader::getIdentifiers() const {
6172 return new ASTIdentifierIterator(*this);
6173}
6174
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006175namespace clang { namespace serialization {
6176 class ReadMethodPoolVisitor {
6177 ASTReader &Reader;
Douglas Gregor8efca6b2012-01-25 01:14:32 +00006178 Selector Sel;
6179 unsigned PriorGeneration;
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006180 llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6181 llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00006182
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006183 public:
Douglas Gregor8efca6b2012-01-25 01:14:32 +00006184 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6185 unsigned PriorGeneration)
6186 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006187
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006188 static bool visit(ModuleFile &M, void *UserData) {
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006189 ReadMethodPoolVisitor *This
6190 = static_cast<ReadMethodPoolVisitor *>(UserData);
6191
6192 if (!M.SelectorLookupTable)
6193 return false;
6194
Douglas Gregor8efca6b2012-01-25 01:14:32 +00006195 // If we've already searched this module file, skip it now.
6196 if (M.Generation <= This->PriorGeneration)
6197 return true;
6198
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006199 ASTSelectorLookupTable *PoolTable
6200 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6201 ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6202 if (Pos == PoolTable->end())
6203 return false;
6204
6205 ++This->Reader.NumSelectorsRead;
Sebastian Redlfa78dec2010-08-04 21:22:45 +00006206 // FIXME: Not quite happy with the statistics here. We probably should
6207 // disable this tracking when called via LoadSelector.
6208 // Also, should entries without methods count as misses?
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006209 ++This->Reader.NumMethodPoolEntriesRead;
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006210 ASTSelectorLookupTrait::data_type Data = *Pos;
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006211 if (This->Reader.DeserializationListener)
6212 This->Reader.DeserializationListener->SelectorRead(Data.ID,
6213 This->Sel);
6214
6215 This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6216 This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6217 return true;
Sebastian Redl725cd962010-08-04 20:40:17 +00006218 }
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006219
6220 /// \brief Retrieve the instance methods found by this visitor.
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006221 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6222 return InstanceMethods;
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006223 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00006224
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006225 /// \brief Retrieve the instance methods found by this visitor.
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006226 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6227 return FactoryMethods;
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006228 }
6229 };
6230} } // end namespace clang::serialization
6231
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006232/// \brief Add the given set of methods to the method list.
6233static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6234 ObjCMethodList &List) {
6235 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6236 S.addMethodToGlobalList(&List, Methods[I]);
6237 }
6238}
6239
6240void ASTReader::ReadMethodPool(Selector Sel) {
Douglas Gregor8efca6b2012-01-25 01:14:32 +00006241 // Get the selector generation and update it to the current generation.
6242 unsigned &Generation = SelectorGeneration[Sel];
6243 unsigned PriorGeneration = Generation;
6244 Generation = CurrentGeneration;
6245
6246 // Search for methods defined with this selector.
6247 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006248 ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006249
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006250 if (Visitor.getInstanceMethods().empty() &&
6251 Visitor.getFactoryMethods().empty()) {
Douglas Gregor3d15ab82011-08-25 14:51:20 +00006252 ++NumMethodPoolMisses;
Douglas Gregor5ac4b692012-01-25 00:49:42 +00006253 return;
6254 }
6255
6256 if (!getSema())
6257 return;
6258
6259 Sema &S = *getSema();
6260 Sema::GlobalMethodPool::iterator Pos
6261 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6262
6263 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6264 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00006265}
6266
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006267void ASTReader::ReadKnownNamespaces(
Chris Lattner5f9e2722011-07-23 10:55:15 +00006268 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006269 Namespaces.clear();
6270
6271 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6272 if (NamespaceDecl *Namespace
6273 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6274 Namespaces.push_back(Namespace);
6275 }
6276}
6277
Douglas Gregora8623202011-07-27 20:58:46 +00006278void ASTReader::ReadTentativeDefinitions(
6279 SmallVectorImpl<VarDecl *> &TentativeDefs) {
6280 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6281 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6282 if (Var)
6283 TentativeDefs.push_back(Var);
6284 }
6285 TentativeDefinitions.clear();
6286}
6287
Douglas Gregora2ee20a2011-07-27 21:45:57 +00006288void ASTReader::ReadUnusedFileScopedDecls(
6289 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6290 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6291 DeclaratorDecl *D
6292 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6293 if (D)
6294 Decls.push_back(D);
6295 }
6296 UnusedFileScopedDecls.clear();
6297}
6298
Douglas Gregor0129b562011-07-27 21:57:17 +00006299void ASTReader::ReadDelegatingConstructors(
6300 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6301 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6302 CXXConstructorDecl *D
6303 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6304 if (D)
6305 Decls.push_back(D);
6306 }
6307 DelegatingCtorDecls.clear();
6308}
6309
Douglas Gregord58a0a52011-07-28 00:39:29 +00006310void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6311 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6312 TypedefNameDecl *D
6313 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6314 if (D)
6315 Decls.push_back(D);
6316 }
6317 ExtVectorDecls.clear();
6318}
6319
Douglas Gregora126f172011-07-28 00:53:40 +00006320void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6321 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6322 CXXRecordDecl *D
6323 = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6324 if (D)
6325 Decls.push_back(D);
6326 }
6327 DynamicClasses.clear();
6328}
6329
Douglas Gregorec12ce22011-07-28 14:20:37 +00006330void
6331ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6332 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
6333 NamedDecl *D
6334 = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
6335 if (D)
6336 Decls.push_back(D);
6337 }
6338 LocallyScopedExternalDecls.clear();
6339}
6340
Douglas Gregor5b9dc7c2011-07-28 14:54:22 +00006341void ASTReader::ReadReferencedSelectors(
6342 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6343 if (ReferencedSelectorsData.empty())
6344 return;
6345
6346 // If there are @selector references added them to its pool. This is for
6347 // implementation of -Wselector.
6348 unsigned int DataSize = ReferencedSelectorsData.size()-1;
6349 unsigned I = 0;
6350 while (I < DataSize) {
6351 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6352 SourceLocation SelLoc
6353 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6354 Sels.push_back(std::make_pair(Sel, SelLoc));
6355 }
6356 ReferencedSelectorsData.clear();
6357}
6358
Douglas Gregor31e37b22011-07-28 18:09:57 +00006359void ASTReader::ReadWeakUndeclaredIdentifiers(
6360 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6361 if (WeakUndeclaredIdentifiers.empty())
6362 return;
6363
6364 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6365 IdentifierInfo *WeakId
6366 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6367 IdentifierInfo *AliasId
6368 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6369 SourceLocation Loc
6370 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6371 bool Used = WeakUndeclaredIdentifiers[I++];
6372 WeakInfo WI(AliasId, Loc);
6373 WI.setUsed(Used);
6374 WeakIDs.push_back(std::make_pair(WeakId, WI));
6375 }
6376 WeakUndeclaredIdentifiers.clear();
6377}
6378
Douglas Gregordfe65432011-07-28 19:11:31 +00006379void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6380 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6381 ExternalVTableUse VT;
6382 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6383 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6384 VT.DefinitionRequired = VTableUses[Idx++];
6385 VTables.push_back(VT);
6386 }
6387
6388 VTableUses.clear();
6389}
6390
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00006391void ASTReader::ReadPendingInstantiations(
6392 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6393 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6394 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6395 SourceLocation Loc
6396 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
Axel Naumann39d26c32012-10-02 09:09:43 +00006397
Douglas Gregore5fa3c22012-10-03 18:34:48 +00006398 Pending.push_back(std::make_pair(D, Loc));
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00006399 }
6400 PendingInstantiations.clear();
6401}
6402
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006403void ASTReader::LoadSelector(Selector Sel) {
Sebastian Redle58aa892010-08-04 18:21:41 +00006404 // It would be complicated to avoid reading the methods anyway. So don't.
6405 ReadMethodPool(Sel);
6406}
6407
Douglas Gregor95eab172011-07-28 20:55:49 +00006408void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00006409 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00006410 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00006411 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00006412 if (DeserializationListener)
6413 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregor668c1a42009-04-21 22:25:48 +00006414}
6415
Douglas Gregord89275b2009-07-06 18:54:52 +00006416/// \brief Set the globally-visible declarations associated with the given
6417/// identifier.
6418///
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006419/// If the AST reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00006420/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00006421/// them.
6422///
6423/// \param II an IdentifierInfo that refers to one or more globally-visible
6424/// declarations.
6425///
6426/// \param DeclIDs the set of declaration IDs with the name @p II that are
6427/// visible at global scope.
6428///
6429/// \param Nonrecursive should be true to indicate that the caller knows that
6430/// this call is non-recursive, and therefore the globally-visible declarations
6431/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00006432void
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006433ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006434 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregord89275b2009-07-06 18:54:52 +00006435 bool Nonrecursive) {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00006436 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregord89275b2009-07-06 18:54:52 +00006437 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
6438 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
6439 PII.II = II;
Benjamin Kramer4ea884b2010-09-06 23:43:28 +00006440 PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
Douglas Gregord89275b2009-07-06 18:54:52 +00006441 return;
6442 }
Mike Stump1eb44332009-09-09 15:08:12 +00006443
Douglas Gregord89275b2009-07-06 18:54:52 +00006444 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6445 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6446 if (SemaObj) {
Douglas Gregoreee242f2011-10-27 09:33:13 +00006447 // Introduce this declaration into the translation-unit scope
6448 // and add it to the declaration chain for this identifier, so
6449 // that (unqualified) name lookup will find it.
6450 SemaObj->pushExternalDeclIntoScope(D, II);
Douglas Gregord89275b2009-07-06 18:54:52 +00006451 } else {
6452 // Queue this declaration so that it will be added to the
6453 // translation unit scope and identifier's declaration chain
6454 // once a Sema object is known.
6455 PreloadedDecls.push_back(D);
6456 }
6457 }
6458}
6459
Douglas Gregor95eab172011-07-28 20:55:49 +00006460IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00006461 if (ID == 0)
6462 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006463
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00006464 if (IdentifiersLoaded.empty()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006465 Error("no identifier table in AST file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00006466 return 0;
6467 }
Mike Stump1eb44332009-09-09 15:08:12 +00006468
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00006469 ID -= 1;
6470 if (!IdentifiersLoaded[ID]) {
Douglas Gregor67268d02011-07-20 00:59:32 +00006471 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6472 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006473 ModuleFile *M = I->second;
Douglas Gregor9827a802011-07-29 00:56:45 +00006474 unsigned Index = ID - M->BaseIdentifierID;
6475 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
Douglas Gregord6595a42009-04-25 21:04:17 +00006476
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006477 // All of the strings in the AST file are preceded by a 16-bit length.
6478 // Extract that 16-bit length to avoid having to execute strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00006479 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6480 // unsigned integers. This is important to avoid integer overflow when
6481 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00006482 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00006483 unsigned StrLen = (((unsigned) StrLenPtr[0])
6484 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00006485 IdentifiersLoaded[ID]
Douglas Gregor712f2fc2011-09-09 22:02:16 +00006486 = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
Sebastian Redlf2f0f032010-07-23 23:49:55 +00006487 if (DeserializationListener)
6488 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregorafaf3082009-04-11 00:14:32 +00006489 }
Mike Stump1eb44332009-09-09 15:08:12 +00006490
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00006491 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00006492}
6493
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006494IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
Douglas Gregor95eab172011-07-28 20:55:49 +00006495 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
6496}
6497
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006498IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
Douglas Gregor6ec60e02011-08-03 21:49:18 +00006499 if (LocalID < NUM_PREDEF_IDENT_IDS)
6500 return LocalID;
6501
6502 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6503 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6504 assert(I != M.IdentifierRemap.end()
6505 && "Invalid index into identifier index remap");
6506
6507 return LocalID + I->second;
Douglas Gregor95eab172011-07-28 20:55:49 +00006508}
6509
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00006510MacroInfo *ASTReader::getMacro(MacroID ID, MacroInfo *Hint) {
Douglas Gregora8235d62012-10-09 23:05:51 +00006511 if (ID == 0)
6512 return 0;
6513
6514 if (MacrosLoaded.empty()) {
6515 Error("no macro table in AST file");
6516 return 0;
6517 }
6518
6519 ID -= NUM_PREDEF_MACRO_IDS;
6520 if (!MacrosLoaded[ID]) {
6521 GlobalMacroMapType::iterator I
6522 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6523 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6524 ModuleFile *M = I->second;
6525 unsigned Index = ID - M->BaseMacroID;
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00006526 ReadMacroRecord(*M, M->MacroOffsets[Index], Hint);
Douglas Gregora8235d62012-10-09 23:05:51 +00006527 }
6528
6529 return MacrosLoaded[ID];
6530}
6531
6532MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6533 if (LocalID < NUM_PREDEF_MACRO_IDS)
6534 return LocalID;
6535
6536 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6537 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6538 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6539
6540 return LocalID + I->second;
6541}
6542
Douglas Gregor26ced122011-12-01 00:59:36 +00006543serialization::SubmoduleID
6544ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6545 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6546 return LocalID;
6547
6548 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6549 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6550 assert(I != M.SubmoduleRemap.end()
Douglas Gregora8235d62012-10-09 23:05:51 +00006551 && "Invalid index into submodule index remap");
Douglas Gregor26ced122011-12-01 00:59:36 +00006552
6553 return LocalID + I->second;
6554}
6555
6556Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6557 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6558 assert(GlobalID == 0 && "Unhandled global submodule ID");
6559 return 0;
6560 }
6561
6562 if (GlobalID > SubmodulesLoaded.size()) {
6563 Error("submodule ID out of range in AST file");
6564 return 0;
6565 }
6566
6567 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6568}
6569
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006570Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
Douglas Gregor2d2689a2011-07-28 21:16:51 +00006571 return DecodeSelector(getGlobalSelectorID(M, LocalID));
6572}
6573
6574Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
Steve Naroff90cd1bb2009-04-23 10:39:46 +00006575 if (ID == 0)
6576 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00006577
Sebastian Redl725cd962010-08-04 20:40:17 +00006578 if (ID > SelectorsLoaded.size()) {
Sebastian Redl3c7f4132010-08-18 23:57:06 +00006579 Error("selector ID out of range in AST file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00006580 return Selector();
6581 }
Douglas Gregor83941df2009-04-25 17:48:32 +00006582
Sebastian Redl725cd962010-08-04 20:40:17 +00006583 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
Douglas Gregor83941df2009-04-25 17:48:32 +00006584 // Load this selector from the selector table.
Douglas Gregor96958cb2011-07-20 01:10:58 +00006585 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6586 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006587 ModuleFile &M = *I->second;
Douglas Gregor9827a802011-07-29 00:56:45 +00006588 ASTSelectorLookupTrait Trait(*this, M);
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00006589 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
Douglas Gregor96958cb2011-07-20 01:10:58 +00006590 SelectorsLoaded[ID - 1] =
Douglas Gregor9827a802011-07-29 00:56:45 +00006591 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
Douglas Gregor96958cb2011-07-20 01:10:58 +00006592 if (DeserializationListener)
6593 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
Douglas Gregor83941df2009-04-25 17:48:32 +00006594 }
6595
Sebastian Redl725cd962010-08-04 20:40:17 +00006596 return SelectorsLoaded[ID - 1];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00006597}
6598
Douglas Gregor8451ec72011-07-28 14:41:43 +00006599Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00006600 return DecodeSelector(ID);
6601}
6602
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006603uint32_t ASTReader::GetNumExternalSelectors() {
Sebastian Redl725cd962010-08-04 20:40:17 +00006604 // ID 0 (the null selector) is considered an external selector.
6605 return getTotalNumSelectors() + 1;
Douglas Gregor719770d2010-04-06 17:30:22 +00006606}
6607
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00006608serialization::SelectorID
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006609ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00006610 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6611 return LocalID;
6612
6613 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6614 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6615 assert(I != M.SelectorRemap.end()
Douglas Gregora8235d62012-10-09 23:05:51 +00006616 && "Invalid index into selector index remap");
Douglas Gregorb18b1fd2011-08-03 23:28:44 +00006617
6618 return LocalID + I->second;
Douglas Gregor8451ec72011-07-28 14:41:43 +00006619}
6620
Mike Stump1eb44332009-09-09 15:08:12 +00006621DeclarationName
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006622ASTReader::ReadDeclarationName(ModuleFile &F,
Douglas Gregor393f2492011-07-22 00:38:23 +00006623 const RecordData &Record, unsigned &Idx) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00006624 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6625 switch (Kind) {
6626 case DeclarationName::Identifier:
Douglas Gregor95eab172011-07-28 20:55:49 +00006627 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006628
6629 case DeclarationName::ObjCZeroArgSelector:
6630 case DeclarationName::ObjCOneArgSelector:
6631 case DeclarationName::ObjCMultiArgSelector:
Douglas Gregor2d2689a2011-07-28 21:16:51 +00006632 return DeclarationName(ReadSelector(F, Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006633
6634 case DeclarationName::CXXConstructorName:
Douglas Gregor35942772011-09-09 21:34:22 +00006635 return Context.DeclarationNames.getCXXConstructorName(
6636 Context.getCanonicalType(readType(F, Record, Idx)));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006637
6638 case DeclarationName::CXXDestructorName:
Douglas Gregor35942772011-09-09 21:34:22 +00006639 return Context.DeclarationNames.getCXXDestructorName(
6640 Context.getCanonicalType(readType(F, Record, Idx)));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006641
6642 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor35942772011-09-09 21:34:22 +00006643 return Context.DeclarationNames.getCXXConversionFunctionName(
6644 Context.getCanonicalType(readType(F, Record, Idx)));
Douglas Gregor2cf26342009-04-09 22:27:44 +00006645
6646 case DeclarationName::CXXOperatorName:
Douglas Gregor35942772011-09-09 21:34:22 +00006647 return Context.DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00006648 (OverloadedOperatorKind)Record[Idx++]);
6649
Sean Hunt3e518bd2009-11-29 07:34:05 +00006650 case DeclarationName::CXXLiteralOperatorName:
Douglas Gregor35942772011-09-09 21:34:22 +00006651 return Context.DeclarationNames.getCXXLiteralOperatorName(
Douglas Gregor95eab172011-07-28 20:55:49 +00006652 GetIdentifierInfo(F, Record, Idx));
Sean Hunt3e518bd2009-11-29 07:34:05 +00006653
Douglas Gregor2cf26342009-04-09 22:27:44 +00006654 case DeclarationName::CXXUsingDirective:
6655 return DeclarationName::getUsingDirectiveName();
6656 }
6657
David Blaikie7530c032012-01-17 06:56:22 +00006658 llvm_unreachable("Invalid NameKind!");
Douglas Gregor2cf26342009-04-09 22:27:44 +00006659}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00006660
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006661void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006662 DeclarationNameLoc &DNLoc,
6663 DeclarationName Name,
6664 const RecordData &Record, unsigned &Idx) {
6665 switch (Name.getNameKind()) {
6666 case DeclarationName::CXXConstructorName:
6667 case DeclarationName::CXXDestructorName:
6668 case DeclarationName::CXXConversionFunctionName:
6669 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6670 break;
6671
6672 case DeclarationName::CXXOperatorName:
6673 DNLoc.CXXOperatorName.BeginOpNameLoc
6674 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6675 DNLoc.CXXOperatorName.EndOpNameLoc
6676 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6677 break;
6678
6679 case DeclarationName::CXXLiteralOperatorName:
6680 DNLoc.CXXLiteralOperatorName.OpNameLoc
6681 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6682 break;
6683
6684 case DeclarationName::Identifier:
6685 case DeclarationName::ObjCZeroArgSelector:
6686 case DeclarationName::ObjCOneArgSelector:
6687 case DeclarationName::ObjCMultiArgSelector:
6688 case DeclarationName::CXXUsingDirective:
6689 break;
6690 }
6691}
6692
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006693void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006694 DeclarationNameInfo &NameInfo,
6695 const RecordData &Record, unsigned &Idx) {
Douglas Gregor393f2492011-07-22 00:38:23 +00006696 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006697 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6698 DeclarationNameLoc DNLoc;
6699 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6700 NameInfo.setInfo(DNLoc);
6701}
6702
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006703void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006704 const RecordData &Record, unsigned &Idx) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00006705 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006706 unsigned NumTPLists = Record[Idx++];
6707 Info.NumTemplParamLists = NumTPLists;
6708 if (NumTPLists) {
Douglas Gregor35942772011-09-09 21:34:22 +00006709 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Argyrios Kyrtzidis40451072010-10-15 18:21:24 +00006710 for (unsigned i=0; i != NumTPLists; ++i)
6711 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6712 }
6713}
6714
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006715TemplateName
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006716ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006717 unsigned &Idx) {
Michael J. Spencer20249a12010-10-21 03:16:25 +00006718 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006719 switch (Kind) {
6720 case TemplateName::Template:
Douglas Gregor409448c2011-07-21 22:35:25 +00006721 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006722
6723 case TemplateName::OverloadedTemplate: {
6724 unsigned size = Record[Idx++];
6725 UnresolvedSet<8> Decls;
6726 while (size--)
Douglas Gregor409448c2011-07-21 22:35:25 +00006727 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006728
Douglas Gregor35942772011-09-09 21:34:22 +00006729 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006730 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006731
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006732 case TemplateName::QualifiedTemplate: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006733 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006734 bool hasTemplKeyword = Record[Idx++];
Douglas Gregor409448c2011-07-21 22:35:25 +00006735 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006736 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006737 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006738
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006739 case TemplateName::DependentTemplate: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006740 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006741 if (Record[Idx++]) // isIdentifier
Douglas Gregor35942772011-09-09 21:34:22 +00006742 return Context.getDependentTemplateName(NNS,
Douglas Gregor95eab172011-07-28 20:55:49 +00006743 GetIdentifierInfo(F, Record,
6744 Idx));
Douglas Gregor35942772011-09-09 21:34:22 +00006745 return Context.getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00006746 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006747 }
John McCall14606042011-06-30 08:33:18 +00006748
6749 case TemplateName::SubstTemplateTemplateParm: {
6750 TemplateTemplateParmDecl *param
Douglas Gregor409448c2011-07-21 22:35:25 +00006751 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
John McCall14606042011-06-30 08:33:18 +00006752 if (!param) return TemplateName();
6753 TemplateName replacement = ReadTemplateName(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006754 return Context.getSubstTemplateTemplateParm(param, replacement);
John McCall14606042011-06-30 08:33:18 +00006755 }
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006756
6757 case TemplateName::SubstTemplateTemplateParmPack: {
6758 TemplateTemplateParmDecl *Param
Douglas Gregor409448c2011-07-21 22:35:25 +00006759 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006760 if (!Param)
6761 return TemplateName();
6762
6763 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6764 if (ArgPack.getKind() != TemplateArgument::Pack)
6765 return TemplateName();
6766
Douglas Gregor35942772011-09-09 21:34:22 +00006767 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006768 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006769 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006770
David Blaikieb219cfc2011-09-23 05:06:16 +00006771 llvm_unreachable("Unhandled template name kind!");
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006772}
6773
6774TemplateArgument
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006775ASTReader::ReadTemplateArgument(ModuleFile &F,
Sebastian Redl577d4792010-07-22 22:43:28 +00006776 const RecordData &Record, unsigned &Idx) {
Douglas Gregora7fc9012011-01-05 18:58:31 +00006777 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6778 switch (Kind) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006779 case TemplateArgument::Null:
6780 return TemplateArgument();
6781 case TemplateArgument::Type:
Douglas Gregor393f2492011-07-22 00:38:23 +00006782 return TemplateArgument(readType(F, Record, Idx));
Eli Friedmand7a6b162012-09-26 02:36:12 +00006783 case TemplateArgument::Declaration: {
6784 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6785 bool ForReferenceParam = Record[Idx++];
6786 return TemplateArgument(D, ForReferenceParam);
6787 }
6788 case TemplateArgument::NullPtr:
6789 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00006790 case TemplateArgument::Integral: {
6791 llvm::APSInt Value = ReadAPSInt(Record, Idx);
Douglas Gregor393f2492011-07-22 00:38:23 +00006792 QualType T = readType(F, Record, Idx);
Benjamin Kramer85524372012-06-07 15:09:51 +00006793 return TemplateArgument(Context, Value, T);
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00006794 }
Douglas Gregora7fc9012011-01-05 18:58:31 +00006795 case TemplateArgument::Template:
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006796 return TemplateArgument(ReadTemplateName(F, Record, Idx));
Douglas Gregora7fc9012011-01-05 18:58:31 +00006797 case TemplateArgument::TemplateExpansion: {
Douglas Gregor1aee05d2011-01-15 06:45:20 +00006798 TemplateName Name = ReadTemplateName(F, Record, Idx);
Douglas Gregor2be29f42011-01-14 23:41:42 +00006799 llvm::Optional<unsigned> NumTemplateExpansions;
6800 if (unsigned NumExpansions = Record[Idx++])
6801 NumTemplateExpansions = NumExpansions - 1;
6802 return TemplateArgument(Name, NumTemplateExpansions);
Douglas Gregorba68eca2011-01-05 17:40:24 +00006803 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006804 case TemplateArgument::Expression:
Sebastian Redlc3632732010-10-05 15:59:54 +00006805 return TemplateArgument(ReadExpr(F));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006806 case TemplateArgument::Pack: {
6807 unsigned NumArgs = Record[Idx++];
Douglas Gregor35942772011-09-09 21:34:22 +00006808 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Douglas Gregor910f8002010-11-07 23:05:16 +00006809 for (unsigned I = 0; I != NumArgs; ++I)
6810 Args[I] = ReadTemplateArgument(F, Record, Idx);
6811 return TemplateArgument(Args, NumArgs);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006812 }
6813 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006814
David Blaikieb219cfc2011-09-23 05:06:16 +00006815 llvm_unreachable("Unhandled template argument kind!");
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00006816}
6817
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006818TemplateParameterList *
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006819ASTReader::ReadTemplateParameterList(ModuleFile &F,
Sebastian Redlc3632732010-10-05 15:59:54 +00006820 const RecordData &Record, unsigned &Idx) {
6821 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6822 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6823 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006824
6825 unsigned NumParams = Record[Idx++];
Chris Lattner5f9e2722011-07-23 10:55:15 +00006826 SmallVector<NamedDecl *, 16> Params;
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006827 Params.reserve(NumParams);
6828 while (NumParams--)
Douglas Gregor409448c2011-07-21 22:35:25 +00006829 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
Michael J. Spencer20249a12010-10-21 03:16:25 +00006830
6831 TemplateParameterList* TemplateParams =
Douglas Gregor35942772011-09-09 21:34:22 +00006832 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006833 Params.data(), Params.size(), RAngleLoc);
6834 return TemplateParams;
6835}
6836
6837void
Sebastian Redlc43b54c2010-08-18 23:56:43 +00006838ASTReader::
Chris Lattner5f9e2722011-07-23 10:55:15 +00006839ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006840 ModuleFile &F, const RecordData &Record,
Sebastian Redlc3632732010-10-05 15:59:54 +00006841 unsigned &Idx) {
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006842 unsigned NumTemplateArgs = Record[Idx++];
6843 TemplArgs.reserve(NumTemplateArgs);
6844 while (NumTemplateArgs--)
Sebastian Redlc3632732010-10-05 15:59:54 +00006845 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00006846}
6847
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00006848/// \brief Read a UnresolvedSet structure.
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006849void ASTReader::ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00006850 const RecordData &Record, unsigned &Idx) {
6851 unsigned NumDecls = Record[Idx++];
6852 while (NumDecls--) {
Douglas Gregor409448c2011-07-21 22:35:25 +00006853 NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00006854 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6855 Set.addDecl(D, AS);
6856 }
6857}
6858
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00006859CXXBaseSpecifier
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006860ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
Nick Lewycky56062202010-07-26 16:56:01 +00006861 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00006862 bool isVirtual = static_cast<bool>(Record[Idx++]);
6863 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6864 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006865 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Sebastian Redlc3632732010-10-05 15:59:54 +00006866 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6867 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregorf90b27a2011-01-03 22:36:02 +00006868 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006869 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00006870 EllipsisLoc);
Sebastian Redlf677ea32011-02-05 19:23:19 +00006871 Result.setInheritConstructors(inheritConstructors);
6872 return Result;
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00006873}
6874
Sean Huntcbb67482011-01-08 20:30:50 +00006875std::pair<CXXCtorInitializer **, unsigned>
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006876ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
Sean Huntcbb67482011-01-08 20:30:50 +00006877 unsigned &Idx) {
6878 CXXCtorInitializer **CtorInitializers = 0;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006879 unsigned NumInitializers = Record[Idx++];
6880 if (NumInitializers) {
Sean Huntcbb67482011-01-08 20:30:50 +00006881 CtorInitializers
Douglas Gregor35942772011-09-09 21:34:22 +00006882 = new (Context) CXXCtorInitializer*[NumInitializers];
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006883 for (unsigned i=0; i != NumInitializers; ++i) {
Douglas Gregor76852c22011-11-01 01:16:03 +00006884 TypeSourceInfo *TInfo = 0;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006885 bool IsBaseVirtual = false;
6886 FieldDecl *Member = 0;
Francois Pichet00eb3f92010-12-04 09:14:42 +00006887 IndirectFieldDecl *IndirectMember = 0;
Michael J. Spencer20249a12010-10-21 03:16:25 +00006888
Sean Hunt156b6402011-05-04 01:19:08 +00006889 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6890 switch (Type) {
Douglas Gregor76852c22011-11-01 01:16:03 +00006891 case CTOR_INITIALIZER_BASE:
6892 TInfo = GetTypeSourceInfo(F, Record, Idx);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006893 IsBaseVirtual = Record[Idx++];
Sean Hunt156b6402011-05-04 01:19:08 +00006894 break;
Douglas Gregor76852c22011-11-01 01:16:03 +00006895
6896 case CTOR_INITIALIZER_DELEGATING:
6897 TInfo = GetTypeSourceInfo(F, Record, Idx);
Sean Hunt156b6402011-05-04 01:19:08 +00006898 break;
6899
6900 case CTOR_INITIALIZER_MEMBER:
Douglas Gregor409448c2011-07-21 22:35:25 +00006901 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
Sean Hunt156b6402011-05-04 01:19:08 +00006902 break;
6903
6904 case CTOR_INITIALIZER_INDIRECT_MEMBER:
Douglas Gregor409448c2011-07-21 22:35:25 +00006905 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
Sean Hunt156b6402011-05-04 01:19:08 +00006906 break;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006907 }
Sean Hunt156b6402011-05-04 01:19:08 +00006908
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00006909 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
Sebastian Redlc3632732010-10-05 15:59:54 +00006910 Expr *Init = ReadExpr(F);
Sebastian Redlc3632732010-10-05 15:59:54 +00006911 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6912 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006913 bool IsWritten = Record[Idx++];
6914 unsigned SourceOrderOrNumArrayIndices;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006915 SmallVector<VarDecl *, 8> Indices;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006916 if (IsWritten) {
6917 SourceOrderOrNumArrayIndices = Record[Idx++];
6918 } else {
6919 SourceOrderOrNumArrayIndices = Record[Idx++];
6920 Indices.reserve(SourceOrderOrNumArrayIndices);
6921 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
Douglas Gregor409448c2011-07-21 22:35:25 +00006922 Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006923 }
Michael J. Spencer20249a12010-10-21 03:16:25 +00006924
Sean Huntcbb67482011-01-08 20:30:50 +00006925 CXXCtorInitializer *BOMInit;
Sean Hunt156b6402011-05-04 01:19:08 +00006926 if (Type == CTOR_INITIALIZER_BASE) {
Douglas Gregor76852c22011-11-01 01:16:03 +00006927 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
Sean Huntcbb67482011-01-08 20:30:50 +00006928 LParenLoc, Init, RParenLoc,
6929 MemberOrEllipsisLoc);
Sean Hunt156b6402011-05-04 01:19:08 +00006930 } else if (Type == CTOR_INITIALIZER_DELEGATING) {
Douglas Gregor76852c22011-11-01 01:16:03 +00006931 BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6932 Init, RParenLoc);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006933 } else if (IsWritten) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00006934 if (Member)
Douglas Gregor35942772011-09-09 21:34:22 +00006935 BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
Sean Huntcbb67482011-01-08 20:30:50 +00006936 LParenLoc, Init, RParenLoc);
Francois Pichet00eb3f92010-12-04 09:14:42 +00006937 else
Douglas Gregor35942772011-09-09 21:34:22 +00006938 BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
Sean Huntcbb67482011-01-08 20:30:50 +00006939 MemberOrEllipsisLoc, LParenLoc,
6940 Init, RParenLoc);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006941 } else {
Douglas Gregor35942772011-09-09 21:34:22 +00006942 BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
Sean Huntcbb67482011-01-08 20:30:50 +00006943 LParenLoc, Init, RParenLoc,
6944 Indices.data(), Indices.size());
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006945 }
6946
Argyrios Kyrtzidisf84cde12010-09-06 19:04:27 +00006947 if (IsWritten)
6948 BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
Sean Huntcbb67482011-01-08 20:30:50 +00006949 CtorInitializers[i] = BOMInit;
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006950 }
6951 }
6952
Sean Huntcbb67482011-01-08 20:30:50 +00006953 return std::make_pair(CtorInitializers, NumInitializers);
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00006954}
6955
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006956NestedNameSpecifier *
Douglas Gregor1a4761e2011-11-30 23:21:26 +00006957ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
Douglas Gregor409448c2011-07-21 22:35:25 +00006958 const RecordData &Record, unsigned &Idx) {
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006959 unsigned N = Record[Idx++];
6960 NestedNameSpecifier *NNS = 0, *Prev = 0;
6961 for (unsigned I = 0; I != N; ++I) {
6962 NestedNameSpecifier::SpecifierKind Kind
6963 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6964 switch (Kind) {
6965 case NestedNameSpecifier::Identifier: {
Douglas Gregor95eab172011-07-28 20:55:49 +00006966 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006967 NNS = NestedNameSpecifier::Create(Context, Prev, II);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006968 break;
6969 }
6970
6971 case NestedNameSpecifier::Namespace: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006972 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006973 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006974 break;
6975 }
6976
Douglas Gregor14aba762011-02-24 02:36:08 +00006977 case NestedNameSpecifier::NamespaceAlias: {
Douglas Gregor409448c2011-07-21 22:35:25 +00006978 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00006979 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
Douglas Gregor14aba762011-02-24 02:36:08 +00006980 break;
6981 }
6982
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006983 case NestedNameSpecifier::TypeSpec:
6984 case NestedNameSpecifier::TypeSpecWithTemplate: {
Douglas Gregor393f2492011-07-22 00:38:23 +00006985 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
Douglas Gregor1ab55e92010-12-10 17:03:06 +00006986 if (!T)
6987 return 0;
6988
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006989 bool Template = Record[Idx++];
Douglas Gregor35942772011-09-09 21:34:22 +00006990 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006991 break;
6992 }
6993
6994 case NestedNameSpecifier::Global: {
Douglas Gregor35942772011-09-09 21:34:22 +00006995 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006996 // No associated value, and there can't be a prefix.
6997 break;
6998 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00006999 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00007000 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00007001 }
7002 return NNS;
7003}
7004
Douglas Gregordc355712011-02-25 00:36:19 +00007005NestedNameSpecifierLoc
Douglas Gregor1a4761e2011-11-30 23:21:26 +00007006ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Douglas Gregordc355712011-02-25 00:36:19 +00007007 unsigned &Idx) {
7008 unsigned N = Record[Idx++];
Douglas Gregor5f791bb2011-02-28 23:58:31 +00007009 NestedNameSpecifierLocBuilder Builder;
Douglas Gregordc355712011-02-25 00:36:19 +00007010 for (unsigned I = 0; I != N; ++I) {
7011 NestedNameSpecifier::SpecifierKind Kind
7012 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7013 switch (Kind) {
7014 case NestedNameSpecifier::Identifier: {
Douglas Gregor95eab172011-07-28 20:55:49 +00007015 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Douglas Gregordc355712011-02-25 00:36:19 +00007016 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00007017 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
Douglas Gregordc355712011-02-25 00:36:19 +00007018 break;
7019 }
7020
7021 case NestedNameSpecifier::Namespace: {
Douglas Gregor409448c2011-07-21 22:35:25 +00007022 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Douglas Gregordc355712011-02-25 00:36:19 +00007023 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00007024 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
Douglas Gregordc355712011-02-25 00:36:19 +00007025 break;
7026 }
7027
7028 case NestedNameSpecifier::NamespaceAlias: {
Douglas Gregor409448c2011-07-21 22:35:25 +00007029 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Douglas Gregordc355712011-02-25 00:36:19 +00007030 SourceRange Range = ReadSourceRange(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00007031 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
Douglas Gregordc355712011-02-25 00:36:19 +00007032 break;
7033 }
7034
7035 case NestedNameSpecifier::TypeSpec:
7036 case NestedNameSpecifier::TypeSpecWithTemplate: {
Douglas Gregordc355712011-02-25 00:36:19 +00007037 bool Template = Record[Idx++];
7038 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7039 if (!T)
7040 return NestedNameSpecifierLoc();
Douglas Gregordc355712011-02-25 00:36:19 +00007041 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
Douglas Gregor5f791bb2011-02-28 23:58:31 +00007042
7043 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
Douglas Gregor35942772011-09-09 21:34:22 +00007044 Builder.Extend(Context,
Douglas Gregor5f791bb2011-02-28 23:58:31 +00007045 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7046 T->getTypeLoc(), ColonColonLoc);
Douglas Gregordc355712011-02-25 00:36:19 +00007047 break;
7048 }
7049
7050 case NestedNameSpecifier::Global: {
Douglas Gregordc355712011-02-25 00:36:19 +00007051 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00007052 Builder.MakeGlobal(Context, ColonColonLoc);
Douglas Gregordc355712011-02-25 00:36:19 +00007053 break;
7054 }
7055 }
Douglas Gregordc355712011-02-25 00:36:19 +00007056 }
7057
Douglas Gregor35942772011-09-09 21:34:22 +00007058 return Builder.getWithLocInContext(Context);
Douglas Gregordc355712011-02-25 00:36:19 +00007059}
7060
Chris Lattner6ad9ac02010-05-07 21:43:38 +00007061SourceRange
Douglas Gregor1a4761e2011-11-30 23:21:26 +00007062ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
Sebastian Redlc3632732010-10-05 15:59:54 +00007063 unsigned &Idx) {
7064 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7065 SourceLocation end = ReadSourceLocation(F, Record, Idx);
Daniel Dunbar8ee59392010-06-02 15:47:10 +00007066 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00007067}
7068
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00007069/// \brief Read an integral value
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007070llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00007071 unsigned BitWidth = Record[Idx++];
7072 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7073 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7074 Idx += NumWords;
7075 return Result;
7076}
7077
7078/// \brief Read a signed integral value
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007079llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00007080 bool isUnsigned = Record[Idx++];
7081 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7082}
7083
Douglas Gregor17fc2232009-04-14 21:55:33 +00007084/// \brief Read a floating-point value
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007085llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00007086 return llvm::APFloat(ReadAPInt(Record, Idx));
7087}
7088
Douglas Gregor68a2eb02009-04-15 21:30:51 +00007089// \brief Read a string
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007090std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
Douglas Gregor68a2eb02009-04-15 21:30:51 +00007091 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00007092 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00007093 Idx += Len;
7094 return Result;
7095}
7096
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00007097VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7098 unsigned &Idx) {
7099 unsigned Major = Record[Idx++];
7100 unsigned Minor = Record[Idx++];
7101 unsigned Subminor = Record[Idx++];
7102 if (Minor == 0)
7103 return VersionTuple(Major);
7104 if (Subminor == 0)
7105 return VersionTuple(Major, Minor - 1);
7106 return VersionTuple(Major, Minor - 1, Subminor - 1);
7107}
7108
Douglas Gregor1a4761e2011-11-30 23:21:26 +00007109CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Douglas Gregor409448c2011-07-21 22:35:25 +00007110 const RecordData &Record,
Chris Lattnerd2598362010-05-10 00:25:06 +00007111 unsigned &Idx) {
Douglas Gregor409448c2011-07-21 22:35:25 +00007112 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Douglas Gregor35942772011-09-09 21:34:22 +00007113 return CXXTemporary::Create(Context, Decl);
Chris Lattnerd2598362010-05-10 00:25:06 +00007114}
7115
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007116DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00007117 return Diag(SourceLocation(), DiagID);
7118}
7119
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007120DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00007121 return Diags.Report(Loc, DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00007122}
Douglas Gregor025452f2009-04-17 00:04:06 +00007123
Douglas Gregor668c1a42009-04-21 22:25:48 +00007124/// \brief Retrieve the identifier table associated with the
7125/// preprocessor.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007126IdentifierTable &ASTReader::getIdentifierTable() {
Douglas Gregor712f2fc2011-09-09 22:02:16 +00007127 return PP.getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00007128}
7129
Douglas Gregor025452f2009-04-17 00:04:06 +00007130/// \brief Record that the given ID maps to the given switch-case
7131/// statement.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007132void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Argyrios Kyrtzidisb88acb02012-05-04 01:49:36 +00007133 assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7134 "Already have a SwitchCase with this ID");
7135 (*CurrSwitchCaseStmts)[ID] = SC;
Douglas Gregor025452f2009-04-17 00:04:06 +00007136}
7137
7138/// \brief Retrieve the switch-case statement with the given ID.
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007139SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Argyrios Kyrtzidisb88acb02012-05-04 01:49:36 +00007140 assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7141 return (*CurrSwitchCaseStmts)[ID];
Douglas Gregor025452f2009-04-17 00:04:06 +00007142}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00007143
Argyrios Kyrtzidise09a2752010-10-28 09:29:32 +00007144void ASTReader::ClearSwitchCaseIDs() {
Argyrios Kyrtzidisb88acb02012-05-04 01:49:36 +00007145 CurrSwitchCaseStmts->clear();
Argyrios Kyrtzidise09a2752010-10-28 09:29:32 +00007146}
7147
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00007148void ASTReader::ReadComments() {
Dmitri Gribenko811c8202012-07-06 18:19:34 +00007149 std::vector<RawComment *> Comments;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00007150 for (SmallVectorImpl<std::pair<llvm::BitstreamCursor,
7151 serialization::ModuleFile *> >::iterator
7152 I = CommentsCursors.begin(),
7153 E = CommentsCursors.end();
7154 I != E; ++I) {
7155 llvm::BitstreamCursor &Cursor = I->first;
7156 serialization::ModuleFile &F = *I->second;
7157 SavedStreamPosition SavedPosition(Cursor);
7158
7159 RecordData Record;
7160 while (true) {
7161 unsigned Code = Cursor.ReadCode();
7162 if (Code == llvm::bitc::END_BLOCK)
7163 break;
7164
7165 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
7166 // No known subblocks, always skip them.
7167 Cursor.ReadSubBlockID();
7168 if (Cursor.SkipBlock()) {
7169 Error("malformed block record in AST file");
7170 return;
7171 }
7172 continue;
7173 }
7174
7175 if (Code == llvm::bitc::DEFINE_ABBREV) {
7176 Cursor.ReadAbbrevRecord();
7177 continue;
7178 }
7179
7180 // Read a record.
7181 Record.clear();
7182 switch ((CommentRecordTypes) Cursor.ReadRecord(Code, Record)) {
Chandler Carruth13691bb2012-06-20 06:47:54 +00007183 case COMMENTS_RAW_COMMENT: {
7184 unsigned Idx = 0;
7185 SourceRange SR = ReadSourceRange(F, Record, Idx);
7186 RawComment::CommentKind Kind =
7187 (RawComment::CommentKind) Record[Idx++];
7188 bool IsTrailingComment = Record[Idx++];
7189 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenko811c8202012-07-06 18:19:34 +00007190 Comments.push_back(new (Context) RawComment(SR, Kind,
7191 IsTrailingComment,
7192 IsAlmostTrailingComment));
Chandler Carruth13691bb2012-06-20 06:47:54 +00007193 break;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +00007194 }
7195 }
7196 }
7197 }
7198 Context.Comments.addCommentsToFront(Comments);
7199}
7200
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007201void ASTReader::finishPendingActions() {
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00007202 while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
7203 !PendingMacroIDs.empty()) {
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007204 // If any identifiers with corresponding top-level declarations have
7205 // been loaded, load those declarations now.
7206 while (!PendingIdentifierInfos.empty()) {
7207 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
7208 PendingIdentifierInfos.front().DeclIDs, true);
7209 PendingIdentifierInfos.pop_front();
7210 }
7211
Douglas Gregora1be2782011-12-17 23:38:30 +00007212 // Load pending declaration chains.
7213 for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7214 loadPendingDeclChain(PendingDeclChains[I]);
Douglas Gregor56ca8a92012-01-17 19:21:53 +00007215 PendingDeclChainsKnown.erase(PendingDeclChains[I]);
Douglas Gregora1be2782011-12-17 23:38:30 +00007216 }
7217 PendingDeclChains.clear();
Douglas Gregor6c6c54a2012-10-11 00:46:49 +00007218
7219 // Load any pending macro definitions.
Douglas Gregore9652bf2012-10-11 17:31:34 +00007220 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
7221 // FIXME: std::move here
7222 SmallVector<MacroID, 2> GlobalIDs = PendingMacroIDs.begin()[I].second;
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00007223 MacroInfo *Hint = 0;
Douglas Gregore9652bf2012-10-11 17:31:34 +00007224 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7225 ++IDIdx) {
Douglas Gregor3ab50fe2012-10-11 17:41:54 +00007226 Hint = getMacro(GlobalIDs[IDIdx], Hint);
Douglas Gregore9652bf2012-10-11 17:31:34 +00007227 }
7228 }
7229 PendingMacroIDs.clear();
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007230 }
Douglas Gregorfc529f72011-12-19 19:00:47 +00007231
Douglas Gregor7c99bb5c2012-01-14 15:13:49 +00007232 // If we deserialized any C++ or Objective-C class definitions, any
7233 // Objective-C protocol definitions, or any redeclarable templates, make sure
7234 // that all redeclarations point to the definitions. Note that this can only
7235 // happen now, after the redeclaration chains have been fully wired.
Douglas Gregorfc529f72011-12-19 19:00:47 +00007236 for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7237 DEnd = PendingDefinitions.end();
7238 D != DEnd; ++D) {
Douglas Gregor56ca8a92012-01-17 19:21:53 +00007239 if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7240 if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7241 // Make sure that the TagType points at the definition.
7242 const_cast<TagType*>(TagT)->decl = TD;
7243 }
Douglas Gregorfc529f72011-12-19 19:00:47 +00007244
Douglas Gregor56ca8a92012-01-17 19:21:53 +00007245 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7246 for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7247 REnd = RD->redecls_end();
7248 R != REnd; ++R)
7249 cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7250
7251 }
7252
Douglas Gregorfc529f72011-12-19 19:00:47 +00007253 continue;
7254 }
7255
Douglas Gregor1d784b22012-01-01 19:51:50 +00007256 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
Douglas Gregor56ca8a92012-01-17 19:21:53 +00007257 // Make sure that the ObjCInterfaceType points at the definition.
7258 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7259 ->Decl = ID;
7260
Douglas Gregor1d784b22012-01-01 19:51:50 +00007261 for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7262 REnd = ID->redecls_end();
7263 R != REnd; ++R)
7264 R->Data = ID->Data;
7265
7266 continue;
7267 }
7268
Douglas Gregor7c99bb5c2012-01-14 15:13:49 +00007269 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7270 for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7271 REnd = PD->redecls_end();
7272 R != REnd; ++R)
7273 R->Data = PD->Data;
7274
7275 continue;
7276 }
7277
7278 RedeclarableTemplateDecl *RTD
7279 = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7280 for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7281 REnd = RTD->redecls_end();
Douglas Gregorfc529f72011-12-19 19:00:47 +00007282 R != REnd; ++R)
Douglas Gregor5456b0fe2012-10-09 17:21:28 +00007283 R->Common = RTD->Common;
Douglas Gregorfc529f72011-12-19 19:00:47 +00007284 }
7285 PendingDefinitions.clear();
Douglas Gregor5456b0fe2012-10-09 17:21:28 +00007286
7287 // Load the bodies of any functions or methods we've encountered. We do
7288 // this now (delayed) so that we can be sure that the declaration chains
7289 // have been fully wired up.
Douglas Gregorce12d2f2012-10-09 17:50:23 +00007290 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7291 PBEnd = PendingBodies.end();
Douglas Gregor5456b0fe2012-10-09 17:21:28 +00007292 PB != PBEnd; ++PB) {
7293 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7294 // FIXME: Check for =delete/=default?
7295 // FIXME: Complain about ODR violations here?
7296 if (!getContext().getLangOpts().Modules || !FD->hasBody())
7297 FD->setLazyBody(PB->second);
7298 continue;
7299 }
7300
7301 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7302 if (!getContext().getLangOpts().Modules || !MD->hasBody())
7303 MD->setLazyBody(PB->second);
7304 }
7305 PendingBodies.clear();
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007306}
7307
Sebastian Redlc43b54c2010-08-18 23:56:43 +00007308void ASTReader::FinishedDeserializing() {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00007309 assert(NumCurrentElementsDeserializing &&
7310 "FinishedDeserializing not paired with StartedDeserializing");
7311 if (NumCurrentElementsDeserializing == 1) {
Argyrios Kyrtzidis44d2dbd2012-02-09 07:31:52 +00007312 // We decrease NumCurrentElementsDeserializing only after pending actions
7313 // are finished, to avoid recursively re-calling finishPendingActions().
7314 finishPendingActions();
7315 }
7316 --NumCurrentElementsDeserializing;
Argyrios Kyrtzidis71168332011-12-17 04:13:28 +00007317
Argyrios Kyrtzidis44d2dbd2012-02-09 07:31:52 +00007318 if (NumCurrentElementsDeserializing == 0 &&
7319 Consumer && !PassingDeclsToConsumer) {
7320 // Guard variable to avoid recursively redoing the process of passing
7321 // decls to consumer.
7322 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7323 true);
Argyrios Kyrtzidis71168332011-12-17 04:13:28 +00007324
Argyrios Kyrtzidis44d2dbd2012-02-09 07:31:52 +00007325 while (!InterestingDecls.empty()) {
Argyrios Kyrtzidis8d39c3d2011-11-30 23:18:26 +00007326 // We are not in recursive loading, so it's safe to pass the "interesting"
7327 // decls to the consumer.
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007328 Decl *D = InterestingDecls.front();
7329 InterestingDecls.pop_front();
Argyrios Kyrtzidis91707832011-12-17 08:11:25 +00007330 PassInterestingDeclToConsumer(D);
7331 }
Douglas Gregord89275b2009-07-06 18:54:52 +00007332 }
Douglas Gregord89275b2009-07-06 18:54:52 +00007333}
Douglas Gregor501c1032010-08-19 00:28:17 +00007334
Douglas Gregorf8a1e512011-09-02 00:26:20 +00007335ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
Douglas Gregor832d6202011-07-22 16:35:34 +00007336 StringRef isysroot, bool DisableValidation,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00007337 bool DisableStatCache, bool AllowASTWithCompilerErrors)
Sebastian Redle1dde812010-08-24 00:50:04 +00007338 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7339 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
Douglas Gregor712f2fc2011-09-09 22:02:16 +00007340 Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
Argyrios Kyrtzidisd64c26f2012-10-03 01:58:42 +00007341 Consumer(0), ModuleMgr(PP.getFileManager()),
Douglas Gregorcaed0602012-10-18 21:31:35 +00007342 isysroot(isysroot), DisableValidation(DisableValidation),
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00007343 DisableStatCache(DisableStatCache),
7344 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
Argyrios Kyrtzidisb88acb02012-05-04 01:49:36 +00007345 CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7346 NumStatHits(0), NumStatMisses(0),
Douglas Gregorf62d43d2011-07-19 16:10:42 +00007347 NumSLocEntriesRead(0), TotalNumSLocEntries(0),
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00007348 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7349 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
7350 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
7351 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
Jonathan D. Turner1da90142011-07-21 21:15:19 +00007352 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7353 TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
Argyrios Kyrtzidis44d2dbd2012-02-09 07:31:52 +00007354 PassingDeclsToConsumer(false),
Jonathan D. Turner1da90142011-07-21 21:15:19 +00007355 NumCXXBaseSpecifiersLoaded(0)
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00007356{
Douglas Gregorf62d43d2011-07-19 16:10:42 +00007357 SourceMgr.setExternalSLocEntrySource(this);
Sebastian Redle1dde812010-08-24 00:50:04 +00007358}
7359
Sebastian Redle1dde812010-08-24 00:50:04 +00007360ASTReader::~ASTReader() {
Sebastian Redle1dde812010-08-24 00:50:04 +00007361 for (DeclContextVisibleUpdatesPending::iterator
7362 I = PendingVisibleUpdates.begin(),
7363 E = PendingVisibleUpdates.end();
7364 I != E; ++I) {
7365 for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7366 F = I->second.end();
7367 J != F; ++J)
Benjamin Kramerb1758c62012-04-15 12:36:49 +00007368 delete J->first;
Sebastian Redle1dde812010-08-24 00:50:04 +00007369 }
7370}