blob: b415f8dea540febf7ac794c0c740461f30c3e1e8 [file] [log] [blame]
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner92ba5ff2009-04-27 05:14:47 +000013
Douglas Gregoref84c4b2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Sebastian Redl85b2a6a2010-07-14 23:45:08 +000016#include "clang/Frontend/PCHDeserializationListener.h"
Daniel Dunbar732ef8a2009-11-11 23:58:53 +000017#include "clang/Frontend/Utils.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000018#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000021#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000023#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000024#include "clang/Lex/MacroInfo.h"
Douglas Gregoraae92242010-03-19 21:51:54 +000025#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000026#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000027#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000028#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000029#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000030#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000031#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000032#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000033#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000035#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000036#include "llvm/Support/MemoryBuffer.h"
John McCall0ad16662009-10-29 08:12:44 +000037#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +000038#include "llvm/System/Path.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000039#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000040#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000041#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000042#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000043using namespace clang;
44
45//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000046// PCH reader validator implementation
47//===----------------------------------------------------------------------===//
48
49PCHReaderListener::~PCHReaderListener() {}
50
51bool
52PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
53 const LangOptions &PPLangOpts = PP.getLangOptions();
54#define PARSE_LANGOPT_BENIGN(Option)
55#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
56 if (PPLangOpts.Option != LangOpts.Option) { \
57 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
58 return true; \
59 }
60
61 PARSE_LANGOPT_BENIGN(Trigraphs);
62 PARSE_LANGOPT_BENIGN(BCPLComment);
63 PARSE_LANGOPT_BENIGN(DollarIdents);
64 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
65 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
Chandler Carruthe03aa552010-04-17 20:17:31 +000066 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000067 PARSE_LANGOPT_BENIGN(ImplicitInt);
68 PARSE_LANGOPT_BENIGN(Digraphs);
69 PARSE_LANGOPT_BENIGN(HexFloats);
70 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
71 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
72 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
73 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
74 PARSE_LANGOPT_BENIGN(CXXOperatorName);
75 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
76 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
77 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian45878032010-02-09 19:31:38 +000078 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +000079 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
80 diag::warn_pch_no_constant_cfstrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000081 PARSE_LANGOPT_BENIGN(PascalStrings);
82 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000084 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000085 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +000087 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000088 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
89 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
90 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000092 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000093 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000094 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
95 PARSE_LANGOPT_BENIGN(EmitAllDecls);
96 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
Chris Lattner51924e512010-06-26 21:25:03 +000097 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
Mike Stump11289f42009-09-09 15:08:12 +000098 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000099 diag::warn_pch_heinous_extensions);
100 // FIXME: Most of the options below are benign if the macro wasn't
101 // used. Unfortunately, this means that a PCH compiled without
102 // optimization can't be used with optimization turned on, even
103 // though the only thing that changes is whether __OPTIMIZE__ was
104 // defined... but if __OPTIMIZE__ never showed up in the header, it
105 // doesn't matter. We could consider making this some special kind
106 // of check.
107 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
108 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
109 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
110 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
111 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
112 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
113 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
114 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsoned4e2952009-11-05 20:14:16 +0000115 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000116 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000117 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000118 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
119 return true;
120 }
121 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000122 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
123 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000124 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000125 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stumpd9546382009-12-12 01:27:46 +0000126 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000127 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +0000128 PARSE_LANGOPT_BENIGN(SpellChecking);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +0000129#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000130#undef PARSE_LANGOPT_BENIGN
131
132 return false;
133}
134
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000135bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
136 if (Triple == PP.getTargetInfo().getTriple().str())
137 return false;
138
139 Reader.Diag(diag::warn_pch_target_triple)
140 << Triple << PP.getTargetInfo().getTriple().str();
141 return true;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000142}
143
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000144struct EmptyStringRef {
Benjamin Kramer8d5609b2010-07-14 23:19:41 +0000145 bool operator ()(llvm::StringRef r) const { return r.empty(); }
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000146};
147struct EmptyBlock {
148 bool operator ()(const PCHPredefinesBlock &r) const { return r.Data.empty(); }
149};
150
151static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
152 PCHPredefinesBlocks R) {
153 // First, sum up the lengths.
154 unsigned LL = 0, RL = 0;
155 for (unsigned I = 0, N = L.size(); I != N; ++I) {
156 LL += L[I].size();
157 }
158 for (unsigned I = 0, N = R.size(); I != N; ++I) {
159 RL += R[I].Data.size();
160 }
161 if (LL != RL)
162 return false;
163 if (LL == 0 && RL == 0)
164 return true;
165
166 // Kick out empty parts, they confuse the algorithm below.
167 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
168 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
169
170 // Do it the hard way. At this point, both vectors must be non-empty.
171 llvm::StringRef LR = L[0], RR = R[0].Data;
172 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
Daniel Dunbar01ad0a72010-07-16 00:00:11 +0000173 (void) RN;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000174 for (;;) {
175 // Compare the current pieces.
176 if (LR.size() == RR.size()) {
177 // If they're the same length, it's pretty easy.
178 if (LR != RR)
179 return false;
180 // Both pieces are done, advance.
181 ++LI;
182 ++RI;
183 // If either string is done, they're both done, since they're the same
184 // length.
185 if (LI == LN) {
186 assert(RI == RN && "Strings not the same length after all?");
187 return true;
188 }
189 LR = L[LI];
190 RR = R[RI].Data;
191 } else if (LR.size() < RR.size()) {
192 // Right piece is longer.
193 if (!RR.startswith(LR))
194 return false;
195 ++LI;
196 assert(LI != LN && "Strings not the same length after all?");
197 RR = RR.substr(LR.size());
198 LR = L[LI];
199 } else {
200 // Left piece is longer.
201 if (!LR.startswith(RR))
202 return false;
203 ++RI;
204 assert(RI != RN && "Strings not the same length after all?");
205 LR = LR.substr(RR.size());
206 RR = R[RI].Data;
207 }
208 }
209}
210
211static std::pair<FileID, llvm::StringRef::size_type>
212FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
213 std::pair<FileID, llvm::StringRef::size_type> Res;
214 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
215 Res.second = Buffers[I].Data.find(MacroDef);
216 if (Res.second != llvm::StringRef::npos) {
217 Res.first = Buffers[I].BufferID;
218 break;
219 }
220 }
221 return Res;
222}
223
224bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000225 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000226 std::string &SuggestedPredefines) {
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000227 // We are in the context of an implicit include, so the predefines buffer will
228 // have a #include entry for the PCH file itself (as normalized by the
229 // preprocessor initialization). Find it and skip over it in the checking
230 // below.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000231 llvm::SmallString<256> PCHInclude;
232 PCHInclude += "#include \"";
Daniel Dunbar732ef8a2009-11-11 23:58:53 +0000233 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000234 PCHInclude += "\"\n";
235 std::pair<llvm::StringRef,llvm::StringRef> Split =
236 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
237 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000238 if (Left == PP.getPredefines()) {
239 Error("Missing PCH include entry!");
240 return true;
241 }
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000242
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000243 // If the concatenation of all the PCH buffers is equal to the adjusted
244 // command line, we're done.
245 // We build a SmallVector of the command line here, because we'll eventually
246 // need to support an arbitrary amount of pieces anyway (when we have chained
247 // PCH reading).
248 llvm::SmallVector<llvm::StringRef, 2> CommandLine;
249 CommandLine.push_back(Left);
250 CommandLine.push_back(Right);
251 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000252 return false;
253
254 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000255
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000256 // The predefines buffers are different. Determine what the differences are,
257 // and whether they require us to reject the PCH file.
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000258 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000259 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
260 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000261
262 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
263 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
264 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000265
Daniel Dunbar499baed2009-11-11 05:26:28 +0000266 // Sort both sets of predefined buffer lines, since we allow some extra
267 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000268 std::sort(CmdLineLines.begin(), CmdLineLines.end());
269 std::sort(PCHLines.begin(), PCHLines.end());
270
Daniel Dunbar499baed2009-11-11 05:26:28 +0000271 // Determine which predefines that were used to build the PCH file are missing
272 // from the command line.
273 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000274 std::set_difference(PCHLines.begin(), PCHLines.end(),
275 CmdLineLines.begin(), CmdLineLines.end(),
276 std::back_inserter(MissingPredefines));
277
278 bool MissingDefines = false;
279 bool ConflictingDefines = false;
280 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000281 llvm::StringRef Missing = MissingPredefines[I];
282 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000283 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
284 return true;
285 }
Mike Stump11289f42009-09-09 15:08:12 +0000286
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000287 // This is a macro definition. Determine the name of the macro we're
288 // defining.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000289 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000290 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000291 = Missing.find_first_of("( \n\r", StartOfMacroName);
292 assert(EndOfMacroName != std::string::npos &&
293 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000294 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000295
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000296 // Determine whether this macro was given a different definition on the
297 // command line.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000298 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000299 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbar045f917e2009-11-13 16:46:11 +0000300 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000301 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
302 MacroDefStart);
303 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000304 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000305 // Different macro; we're done.
306 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000307 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
310 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000311 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000312 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000313 (*ConflictPos)[MacroDefLen] != '(')
314 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000316 // We found a conflicting macro definition.
317 break;
318 }
Mike Stump11289f42009-09-09 15:08:12 +0000319
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000320 if (ConflictPos != CmdLineLines.end()) {
321 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
322 << MacroName;
323
324 // Show the definition of this macro within the PCH file.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000325 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
326 FindMacro(Buffers, Missing);
327 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
328 SourceLocation PCHMissingLoc =
329 SourceMgr.getLocForStartOfFile(MacroLoc.first)
330 .getFileLocWithOffset(MacroLoc.second);
Daniel Dunbar499baed2009-11-11 05:26:28 +0000331 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000332
333 ConflictingDefines = true;
334 continue;
335 }
Mike Stump11289f42009-09-09 15:08:12 +0000336
Daniel Dunbar8665c7e2009-11-11 03:45:59 +0000337 // If the macro doesn't conflict, then we'll just pick up the macro
338 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000339 if (ConflictingDefines)
340 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000341
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000342 if (!MissingDefines) {
343 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
344 MissingDefines = true;
345 }
346
347 // Show the definition of this macro within the PCH file.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000348 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
349 FindMacro(Buffers, Missing);
350 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
351 SourceLocation PCHMissingLoc =
352 SourceMgr.getLocForStartOfFile(MacroLoc.first)
353 .getFileLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000354 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
355 }
Mike Stump11289f42009-09-09 15:08:12 +0000356
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000357 if (ConflictingDefines)
358 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000360 // Determine what predefines were introduced based on command-line
361 // parameters that were not present when building the PCH
362 // file. Extra #defines are okay, so long as the identifiers being
363 // defined were not used within the precompiled header.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000364 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000365 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
366 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000367 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000368 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar499baed2009-11-11 05:26:28 +0000369 llvm::StringRef &Extra = ExtraPredefines[I];
370 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000371 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
372 return true;
373 }
374
375 // This is an extra macro definition. Determine the name of the
376 // macro we're defining.
377 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000378 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000379 = Extra.find_first_of("( \n\r", StartOfMacroName);
380 assert(EndOfMacroName != std::string::npos &&
381 "Couldn't find the end of the macro name");
Daniel Dunbar499baed2009-11-11 05:26:28 +0000382 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000383
384 // Check whether this name was used somewhere in the PCH file. If
385 // so, defining it as a macro could change behavior, so we reject
386 // the PCH file.
Daniel Dunbar499baed2009-11-11 05:26:28 +0000387 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar045c92f2009-11-11 00:52:00 +0000388 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000389 return true;
390 }
391
392 // Add this definition to the suggested predefines buffer.
393 SuggestedPredefines += Extra;
394 SuggestedPredefines += '\n';
395 }
396
397 // If we get here, it's because the predefines buffer had compatible
398 // contents. Accept the PCH file.
399 return false;
400}
401
Douglas Gregor5712ebc2010-03-16 16:35:32 +0000402void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
403 unsigned ID) {
404 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
405 ++NumHeaderInfos;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000406}
407
408void PCHValidator::ReadCounter(unsigned Value) {
409 PP.setCounterValue(Value);
410}
411
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000412//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000413// PCH reader implementation
414//===----------------------------------------------------------------------===//
415
Mike Stump11289f42009-09-09 15:08:12 +0000416PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000417 const char *isysroot, bool DisableValidation)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000418 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
419 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
420 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
Sebastian Redlbd1b5be2010-07-19 22:28:42 +0000421 Consumer(0), MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000422 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregorce3a8292010-07-27 00:27:13 +0000423 TotalNumSelectors(0), isysroot(isysroot),
424 DisableValidation(DisableValidation), NumStatHits(0), NumStatMisses(0),
Sebastian Redlb293a452010-07-20 21:20:32 +0000425 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
426 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
427 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
428 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +0000429 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000430 RelocatablePCH = false;
431}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000432
433PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorce3a8292010-07-27 00:27:13 +0000434 Diagnostic &Diags, const char *isysroot,
435 bool DisableValidation)
Sebastian Redl85b2a6a2010-07-14 23:45:08 +0000436 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl34522812010-07-16 17:50:48 +0000437 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000438 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
439 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregorce3a8292010-07-27 00:27:13 +0000440 TotalNumSelectors(0), isysroot(isysroot),
441 DisableValidation(DisableValidation), NumStatHits(0), NumStatMisses(0),
Sebastian Redlb293a452010-07-20 21:20:32 +0000442 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
443 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
444 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
445 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +0000446 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000447 RelocatablePCH = false;
448}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000449
Sebastian Redl34522812010-07-16 17:50:48 +0000450PCHReader::~PCHReader() {
451 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
452 delete Chain[e - i - 1];
453}
454
455PCHReader::PerFileData::PerFileData()
Sebastian Redl9e687992010-07-19 22:06:55 +0000456 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redlbd1b5be2010-07-19 22:28:42 +0000457 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
Sebastian Redlfa061442010-07-21 20:07:32 +0000458 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
459 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
460 NumPreallocatedPreprocessingEntities(0)
Sebastian Redl34522812010-07-16 17:50:48 +0000461{}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000462
Sebastian Redl07a89a82010-07-30 00:29:29 +0000463void
464PCHReader::setDeserializationListener(PCHDeserializationListener *Listener) {
465 DeserializationListener = Listener;
466 if (DeserializationListener)
467 DeserializationListener->SetReader(this);
468}
469
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000470
Douglas Gregora868bbd2009-04-21 22:25:48 +0000471namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000472class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000473 PCHReader &Reader;
474
475public:
476 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
477
478 typedef Selector external_key_type;
479 typedef external_key_type internal_key_type;
480
481 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregorc78d3462009-04-24 21:10:55 +0000483 static bool EqualKey(const internal_key_type& a,
484 const internal_key_type& b) {
485 return a == b;
486 }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregorc78d3462009-04-24 21:10:55 +0000488 static unsigned ComputeHash(Selector Sel) {
489 unsigned N = Sel.getNumArgs();
490 if (N == 0)
491 ++N;
492 unsigned R = 5381;
493 for (unsigned I = 0; I != N; ++I)
494 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000495 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000496 return R;
497 }
Mike Stump11289f42009-09-09 15:08:12 +0000498
Douglas Gregorc78d3462009-04-24 21:10:55 +0000499 // This hopefully will just get inlined and removed by the optimizer.
500 static const internal_key_type&
501 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000502
Douglas Gregorc78d3462009-04-24 21:10:55 +0000503 static std::pair<unsigned, unsigned>
504 ReadKeyDataLength(const unsigned char*& d) {
505 using namespace clang::io;
506 unsigned KeyLen = ReadUnalignedLE16(d);
507 unsigned DataLen = ReadUnalignedLE16(d);
508 return std::make_pair(KeyLen, DataLen);
509 }
Mike Stump11289f42009-09-09 15:08:12 +0000510
Douglas Gregor95c13f52009-04-25 17:48:32 +0000511 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000512 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000513 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000514 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000515 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000516 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
517 if (N == 0)
518 return SelTable.getNullarySelector(FirstII);
519 else if (N == 1)
520 return SelTable.getUnarySelector(FirstII);
521
522 llvm::SmallVector<IdentifierInfo *, 16> Args;
523 Args.push_back(FirstII);
524 for (unsigned I = 1; I != N; ++I)
525 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
526
Douglas Gregor038c3382009-05-22 22:45:36 +0000527 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000528 }
Mike Stump11289f42009-09-09 15:08:12 +0000529
Douglas Gregorc78d3462009-04-24 21:10:55 +0000530 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
531 using namespace clang::io;
532 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
533 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
534
535 data_type Result;
536
537 // Load instance methods
538 ObjCMethodList *Prev = 0;
539 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000540 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000541 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
542 if (!Result.first.Method) {
543 // This is the first method, which is the easy case.
544 Result.first.Method = Method;
545 Prev = &Result.first;
546 continue;
547 }
548
Ted Kremenekda4abf12010-02-11 00:53:01 +0000549 ObjCMethodList *Mem =
550 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
551 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000552 Prev = Prev->Next;
553 }
554
555 // Load factory methods
556 Prev = 0;
557 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000558 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000559 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
560 if (!Result.second.Method) {
561 // This is the first method, which is the easy case.
562 Result.second.Method = Method;
563 Prev = &Result.second;
564 continue;
565 }
566
Ted Kremenekda4abf12010-02-11 00:53:01 +0000567 ObjCMethodList *Mem =
568 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
569 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000570 Prev = Prev->Next;
571 }
572
573 return Result;
574 }
575};
Mike Stump11289f42009-09-09 15:08:12 +0000576
577} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000578
579/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000580typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000581 PCHMethodPoolLookupTable;
582
583namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000584class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000585 PCHReader &Reader;
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000586 llvm::BitstreamCursor &Stream;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000587
588 // If we know the IdentifierInfo in advance, it is here and we will
589 // not build a new one. Used when deserializing information about an
590 // identifier that was constructed before the PCH file was read.
591 IdentifierInfo *KnownII;
592
593public:
594 typedef IdentifierInfo * data_type;
595
596 typedef const std::pair<const char*, unsigned> external_key_type;
597
598 typedef external_key_type internal_key_type;
599
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000600 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
601 IdentifierInfo *II = 0)
602 : Reader(Reader), Stream(Stream), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000603
Douglas Gregora868bbd2009-04-21 22:25:48 +0000604 static bool EqualKey(const internal_key_type& a,
605 const internal_key_type& b) {
606 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
607 : false;
608 }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Douglas Gregora868bbd2009-04-21 22:25:48 +0000610 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000611 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000612 }
Mike Stump11289f42009-09-09 15:08:12 +0000613
Douglas Gregora868bbd2009-04-21 22:25:48 +0000614 // This hopefully will just get inlined and removed by the optimizer.
615 static const internal_key_type&
616 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregora868bbd2009-04-21 22:25:48 +0000618 static std::pair<unsigned, unsigned>
619 ReadKeyDataLength(const unsigned char*& d) {
620 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000621 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000622 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000623 return std::make_pair(KeyLen, DataLen);
624 }
Mike Stump11289f42009-09-09 15:08:12 +0000625
Douglas Gregora868bbd2009-04-21 22:25:48 +0000626 static std::pair<const char*, unsigned>
627 ReadKey(const unsigned char* d, unsigned n) {
628 assert(n >= 2 && d[n-1] == '\0');
629 return std::make_pair((const char*) d, n-1);
630 }
Mike Stump11289f42009-09-09 15:08:12 +0000631
632 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000633 const unsigned char* d,
634 unsigned DataLen) {
635 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000636 pch::IdentID ID = ReadUnalignedLE32(d);
637 bool IsInteresting = ID & 0x01;
638
639 // Wipe out the "is interesting" bit.
640 ID = ID >> 1;
641
642 if (!IsInteresting) {
Sebastian Redl98912122010-07-27 23:01:28 +0000643 // For uninteresting identifiers, just build the IdentifierInfo
Douglas Gregor1d583f22009-04-28 21:18:29 +0000644 // and associate it with the persistent ID.
645 IdentifierInfo *II = KnownII;
646 if (!II)
Sebastian Redl07a89a82010-07-30 00:29:29 +0000647 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregor1d583f22009-04-28 21:18:29 +0000648 Reader.SetIdentifierInfo(ID, II);
Sebastian Redl07a89a82010-07-30 00:29:29 +0000649 II->setIsFromPCH();
Douglas Gregor1d583f22009-04-28 21:18:29 +0000650 return II;
651 }
652
Douglas Gregorb9256522009-04-28 21:32:13 +0000653 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000654 bool CPlusPlusOperatorKeyword = Bits & 0x01;
655 Bits >>= 1;
656 bool Poisoned = Bits & 0x01;
657 Bits >>= 1;
658 bool ExtensionToken = Bits & 0x01;
659 Bits >>= 1;
660 bool hasMacroDefinition = Bits & 0x01;
661 Bits >>= 1;
662 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
663 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000664
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000665 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000666 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000667
668 // Build the IdentifierInfo itself and link the identifier ID with
669 // the new IdentifierInfo.
670 IdentifierInfo *II = KnownII;
671 if (!II)
Sebastian Redl07a89a82010-07-30 00:29:29 +0000672 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000673 Reader.SetIdentifierInfo(ID, II);
674
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000675 // Set or check the various bits in the IdentifierInfo structure.
676 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000677 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000678 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000679 "Incorrect extension token flag");
680 (void)ExtensionToken;
681 II->setIsPoisoned(Poisoned);
682 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
683 "Incorrect C++ operator keyword flag");
684 (void)CPlusPlusOperatorKeyword;
685
Douglas Gregorc3366a52009-04-21 23:56:24 +0000686 // If this identifier is a macro, deserialize the macro
687 // definition.
688 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000689 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000690 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000691 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000692 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000693
694 // Read all of the declarations visible at global scope with this
695 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000696 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000697 if (DataLen > 0) {
698 llvm::SmallVector<uint32_t, 4> DeclIDs;
699 for (; DataLen > 0; DataLen -= 4)
700 DeclIDs.push_back(ReadUnalignedLE32(d));
701 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000702 }
Mike Stump11289f42009-09-09 15:08:12 +0000703
Sebastian Redl07a89a82010-07-30 00:29:29 +0000704 II->setIsFromPCH();
Douglas Gregora868bbd2009-04-21 22:25:48 +0000705 return II;
706 }
707};
Mike Stump11289f42009-09-09 15:08:12 +0000708
709} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000710
711/// \brief The on-disk hash table used to contain information about
712/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000713typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000714 PCHIdentifierLookupTable;
715
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000716void PCHReader::Error(const char *Msg) {
717 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000718}
719
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000720/// \brief Check the contents of the concatenation of all predefines buffers in
721/// the PCH chain against the contents of the predefines buffer of the current
722/// compiler invocation.
Douglas Gregor92863e42009-04-10 23:10:45 +0000723///
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000724/// The contents should be the same. If not, then some command-line option
725/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregor92863e42009-04-10 23:10:45 +0000726///
727/// \returns true if there was a mismatch (in which case the PCH file
728/// should be ignored), or false otherwise.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000729bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000730 if (Listener)
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000731 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000732 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000733 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000734 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000735}
736
Douglas Gregorc5046832009-04-27 18:38:38 +0000737//===----------------------------------------------------------------------===//
738// Source Manager Deserialization
739//===----------------------------------------------------------------------===//
740
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000741/// \brief Read the line table in the source manager block.
742/// \returns true if ther was an error.
Sebastian Redlb293a452010-07-20 21:20:32 +0000743bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000744 unsigned Idx = 0;
745 LineTableInfo &LineTable = SourceMgr.getLineTable();
746
747 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000748 std::map<int, int> FileIDs;
749 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000750 // Extract the file name
751 unsigned FilenameLen = Record[Idx++];
752 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
753 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000754 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000755 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000756 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000757 }
758
759 // Parse the line entries
760 std::vector<LineEntry> Entries;
761 while (Idx < Record.size()) {
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000762 int FID = Record[Idx++];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000763
764 // Extract the line entries
765 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000766 assert(NumEntries && "Numentries is 00000");
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000767 Entries.clear();
768 Entries.reserve(NumEntries);
769 for (unsigned I = 0; I != NumEntries; ++I) {
770 unsigned FileOffset = Record[Idx++];
771 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000772 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump11289f42009-09-09 15:08:12 +0000773 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000774 = (SrcMgr::CharacteristicKind)Record[Idx++];
775 unsigned IncludeOffset = Record[Idx++];
776 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
777 FileKind, IncludeOffset));
778 }
779 LineTable.AddEntry(FID, Entries);
780 }
781
782 return false;
783}
784
Douglas Gregorc5046832009-04-27 18:38:38 +0000785namespace {
786
Benjamin Kramer16634c22009-11-28 10:07:24 +0000787class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000788public:
789 const bool hasStat;
790 const ino_t ino;
791 const dev_t dev;
792 const mode_t mode;
793 const time_t mtime;
794 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000795
Douglas Gregorc5046832009-04-27 18:38:38 +0000796 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000797 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
798
Douglas Gregorc5046832009-04-27 18:38:38 +0000799 PCHStatData()
800 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
801};
802
Benjamin Kramer16634c22009-11-28 10:07:24 +0000803class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000804 public:
805 typedef const char *external_key_type;
806 typedef const char *internal_key_type;
807
808 typedef PCHStatData data_type;
809
810 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000811 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000812 }
813
814 static internal_key_type GetInternalKey(const char *path) { return path; }
815
816 static bool EqualKey(internal_key_type a, internal_key_type b) {
817 return strcmp(a, b) == 0;
818 }
819
820 static std::pair<unsigned, unsigned>
821 ReadKeyDataLength(const unsigned char*& d) {
822 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
823 unsigned DataLen = (unsigned) *d++;
824 return std::make_pair(KeyLen + 1, DataLen);
825 }
826
827 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
828 return (const char *)d;
829 }
830
831 static data_type ReadData(const internal_key_type, const unsigned char *d,
832 unsigned /*DataLen*/) {
833 using namespace clang::io;
834
835 if (*d++ == 1)
836 return data_type();
837
838 ino_t ino = (ino_t) ReadUnalignedLE32(d);
839 dev_t dev = (dev_t) ReadUnalignedLE32(d);
840 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000841 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000842 off_t size = (off_t) ReadUnalignedLE64(d);
843 return data_type(ino, dev, mode, mtime, size);
844 }
845};
846
847/// \brief stat() cache for precompiled headers.
848///
849/// This cache is very similar to the stat cache used by pretokenized
850/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000851class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000852 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
853 CacheTy *Cache;
854
855 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000856public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000857 PCHStatCache(const unsigned char *Buckets,
858 const unsigned char *Base,
859 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000860 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000861 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
862 Cache = CacheTy::Create(Buckets, Base);
863 }
864
865 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000866
Douglas Gregorc5046832009-04-27 18:38:38 +0000867 int stat(const char *path, struct stat *buf) {
868 // Do the lookup for the file's data in the PCH file.
869 CacheTy::iterator I = Cache->find(path);
870
871 // If we don't get a hit in the PCH file just forward to 'stat'.
872 if (I == Cache->end()) {
873 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000874 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000875 }
Mike Stump11289f42009-09-09 15:08:12 +0000876
Douglas Gregorc5046832009-04-27 18:38:38 +0000877 ++NumStatHits;
878 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000879
Douglas Gregorc5046832009-04-27 18:38:38 +0000880 if (!Data.hasStat)
881 return 1;
882
883 buf->st_ino = Data.ino;
884 buf->st_dev = Data.dev;
885 buf->st_mtime = Data.mtime;
886 buf->st_mode = Data.mode;
887 buf->st_size = Data.size;
888 return 0;
889 }
890};
891} // end anonymous namespace
892
893
Sebastian Redl393f8b72010-07-19 20:52:06 +0000894/// \brief Read a source manager block
895PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000896 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000897
Sebastian Redl393f8b72010-07-19 20:52:06 +0000898 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl34522812010-07-16 17:50:48 +0000899
Douglas Gregor258ae542009-04-27 06:38:32 +0000900 // Set the source-location entry cursor to the current position in
901 // the stream. This cursor will be used to read the contents of the
902 // source manager block initially, and then lazily read
903 // source-location entries as needed.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000904 SLocEntryCursor = F.Stream;
Douglas Gregor258ae542009-04-27 06:38:32 +0000905
906 // The stream itself is going to skip over the source manager block.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000907 if (F.Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000908 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000909 return Failure;
910 }
911
912 // Enter the source manager block.
913 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000914 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000915 return Failure;
916 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000917
Douglas Gregora7f71a92009-04-10 03:52:48 +0000918 RecordData Record;
919 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000920 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000921 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000922 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000923 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000924 return Failure;
925 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000926 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000927 }
Mike Stump11289f42009-09-09 15:08:12 +0000928
Douglas Gregora7f71a92009-04-10 03:52:48 +0000929 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
930 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000931 SLocEntryCursor.ReadSubBlockID();
932 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000933 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000934 return Failure;
935 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000936 continue;
937 }
Mike Stump11289f42009-09-09 15:08:12 +0000938
Douglas Gregora7f71a92009-04-10 03:52:48 +0000939 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000940 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000941 continue;
942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
Douglas Gregora7f71a92009-04-10 03:52:48 +0000944 // Read a record.
945 const char *BlobStart;
946 unsigned BlobLen;
947 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000948 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000949 default: // Default behavior: ignore.
950 break;
951
Chris Lattner184e65d2009-04-14 23:22:57 +0000952 case pch::SM_LINE_TABLE:
Sebastian Redlb293a452010-07-20 21:20:32 +0000953 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000954 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000955 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000956
Douglas Gregor258ae542009-04-27 06:38:32 +0000957 case pch::SM_SLOC_FILE_ENTRY:
958 case pch::SM_SLOC_BUFFER_ENTRY:
959 case pch::SM_SLOC_INSTANTIATION_ENTRY:
960 // Once we hit one of the source location entries, we're done.
961 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000962 }
963 }
964}
965
Sebastian Redl06750302010-07-20 21:50:20 +0000966/// \brief Get a cursor that's correctly positioned for reading the source
967/// location entry with the given ID.
968llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
969 assert(ID != 0 && ID <= TotalNumSLocEntries &&
970 "SLocCursorForID should only be called for real IDs.");
971
972 ID -= 1;
973 PerFileData *F = 0;
974 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
975 F = Chain[N - I - 1];
976 if (ID < F->LocalNumSLocEntries)
977 break;
978 ID -= F->LocalNumSLocEntries;
979 }
980 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
981
982 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
983 return F->SLocEntryCursor;
984}
985
Douglas Gregor258ae542009-04-27 06:38:32 +0000986/// \brief Read in the source location entry with the given ID.
987PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
988 if (ID == 0)
989 return Success;
990
991 if (ID > TotalNumSLocEntries) {
992 Error("source location entry ID out-of-range for PCH file");
993 return Failure;
994 }
995
Sebastian Redl06750302010-07-20 21:50:20 +0000996 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl34522812010-07-16 17:50:48 +0000997
Douglas Gregor258ae542009-04-27 06:38:32 +0000998 ++NumSLocEntriesRead;
Douglas Gregor258ae542009-04-27 06:38:32 +0000999 unsigned Code = SLocEntryCursor.ReadCode();
1000 if (Code == llvm::bitc::END_BLOCK ||
1001 Code == llvm::bitc::ENTER_SUBBLOCK ||
1002 Code == llvm::bitc::DEFINE_ABBREV) {
1003 Error("incorrectly-formatted source location entry in PCH file");
1004 return Failure;
1005 }
1006
Douglas Gregor258ae542009-04-27 06:38:32 +00001007 RecordData Record;
1008 const char *BlobStart;
1009 unsigned BlobLen;
1010 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1011 default:
1012 Error("incorrectly-formatted source location entry in PCH file");
1013 return Failure;
1014
1015 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001016 std::string Filename(BlobStart, BlobStart + BlobLen);
1017 MaybeAddSystemRootToFilename(Filename);
1018 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +00001019 if (File == 0) {
1020 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001021 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +00001022 ErrorStr += "' referenced by PCH file";
1023 Error(ErrorStr.c_str());
1024 return Failure;
1025 }
Mike Stump11289f42009-09-09 15:08:12 +00001026
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001027 if (Record.size() < 10) {
Ted Kremenekabb1ddd2010-03-18 21:23:05 +00001028 Error("source location entry is incorrect");
1029 return Failure;
1030 }
1031
Douglas Gregorce3a8292010-07-27 00:27:13 +00001032 if (!DisableValidation &&
1033 ((off_t)Record[4] != File->getSize()
Douglas Gregor08288f22010-04-09 15:54:22 +00001034#if !defined(LLVM_ON_WIN32)
1035 // In our regression testing, the Windows file system seems to
1036 // have inconsistent modification times that sometimes
1037 // erroneously trigger this error-handling path.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001038 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor08288f22010-04-09 15:54:22 +00001039#endif
Douglas Gregorce3a8292010-07-27 00:27:13 +00001040 )) {
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001041 Diag(diag::err_fe_pch_file_modified)
1042 << Filename;
1043 return Failure;
1044 }
1045
Douglas Gregor258ae542009-04-27 06:38:32 +00001046 FileID FID = SourceMgr.createFileID(File,
1047 SourceLocation::getFromRawEncoding(Record[1]),
1048 (SrcMgr::CharacteristicKind)Record[2],
1049 ID, Record[0]);
1050 if (Record[3])
1051 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1052 .setHasLineDirectives();
1053
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001054 // Reconstruct header-search information for this file.
1055 HeaderFileInfo HFI;
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001056 HFI.isImport = Record[6];
1057 HFI.DirInfo = Record[7];
1058 HFI.NumIncludes = Record[8];
1059 HFI.ControllingMacroID = Record[9];
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001060 if (Listener)
1061 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +00001062 break;
1063 }
1064
1065 case pch::SM_SLOC_BUFFER_ENTRY: {
1066 const char *Name = BlobStart;
1067 unsigned Offset = Record[0];
1068 unsigned Code = SLocEntryCursor.ReadCode();
1069 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001070 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +00001071 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001072
1073 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1074 Error("PCH record has invalid code");
1075 return Failure;
1076 }
1077
Douglas Gregor258ae542009-04-27 06:38:32 +00001078 llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001079 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1080 Name);
Douglas Gregor258ae542009-04-27 06:38:32 +00001081 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +00001082
Douglas Gregore6648fb2009-04-28 20:33:11 +00001083 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001084 PCHPredefinesBlock Block = {
1085 BufferID,
1086 llvm::StringRef(BlobStart, BlobLen - 1)
1087 };
1088 PCHPredefinesBuffers.push_back(Block);
Douglas Gregore6648fb2009-04-28 20:33:11 +00001089 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001090
1091 break;
1092 }
1093
1094 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +00001095 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +00001096 = SourceLocation::getFromRawEncoding(Record[1]);
1097 SourceMgr.createInstantiationLoc(SpellingLoc,
1098 SourceLocation::getFromRawEncoding(Record[2]),
1099 SourceLocation::getFromRawEncoding(Record[3]),
1100 Record[4],
1101 ID,
1102 Record[0]);
1103 break;
Mike Stump11289f42009-09-09 15:08:12 +00001104 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001105 }
1106
1107 return Success;
1108}
1109
Chris Lattnere78a6be2009-04-27 01:05:14 +00001110/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1111/// specified cursor. Read the abbreviations that are at the top of the block
1112/// and then leave the cursor pointing into the block.
1113bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1114 unsigned BlockID) {
1115 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001116 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001117 return Failure;
1118 }
Mike Stump11289f42009-09-09 15:08:12 +00001119
Chris Lattnere78a6be2009-04-27 01:05:14 +00001120 while (true) {
1121 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001122
Chris Lattnere78a6be2009-04-27 01:05:14 +00001123 // We expect all abbrevs to be at the start of the block.
1124 if (Code != llvm::bitc::DEFINE_ABBREV)
1125 return false;
1126 Cursor.ReadAbbrevRecord();
1127 }
1128}
1129
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001130void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001131 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregorc3366a52009-04-21 23:56:24 +00001133 // Keep track of where we are in the stream, then jump back there
1134 // after reading this macro.
1135 SavedStreamPosition SavedPosition(Stream);
1136
1137 Stream.JumpToBit(Offset);
1138 RecordData Record;
1139 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1140 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001141
Douglas Gregorc3366a52009-04-21 23:56:24 +00001142 while (true) {
1143 unsigned Code = Stream.ReadCode();
1144 switch (Code) {
1145 case llvm::bitc::END_BLOCK:
1146 return;
1147
1148 case llvm::bitc::ENTER_SUBBLOCK:
1149 // No known subblocks, always skip them.
1150 Stream.ReadSubBlockID();
1151 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001152 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001153 return;
1154 }
1155 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001156
Douglas Gregorc3366a52009-04-21 23:56:24 +00001157 case llvm::bitc::DEFINE_ABBREV:
1158 Stream.ReadAbbrevRecord();
1159 continue;
1160 default: break;
1161 }
1162
1163 // Read a record.
1164 Record.clear();
1165 pch::PreprocessorRecordTypes RecType =
1166 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1167 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001168 case pch::PP_MACRO_OBJECT_LIKE:
1169 case pch::PP_MACRO_FUNCTION_LIKE: {
1170 // If we already have a macro, that means that we've hit the end
1171 // of the definition of the macro we were looking for. We're
1172 // done.
1173 if (Macro)
1174 return;
1175
1176 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1177 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001178 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001179 return;
1180 }
1181 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1182 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001183
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001184 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001185 MI->setIsUsed(isUsed);
Sebastian Redl98912122010-07-27 23:01:28 +00001186 MI->setIsFromPCH();
Mike Stump11289f42009-09-09 15:08:12 +00001187
Douglas Gregoraae92242010-03-19 21:51:54 +00001188 unsigned NextIndex = 3;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001189 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1190 // Decode function-like macro info.
1191 bool isC99VarArgs = Record[3];
1192 bool isGNUVarArgs = Record[4];
1193 MacroArgs.clear();
1194 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001195 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001196 for (unsigned i = 0; i != NumArgs; ++i)
1197 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1198
1199 // Install function-like macro info.
1200 MI->setIsFunctionLike();
1201 if (isC99VarArgs) MI->setIsC99Varargs();
1202 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001203 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001204 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001205 }
1206
1207 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001208 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001209
1210 // Remember that we saw this macro last so that we add the tokens that
1211 // form its body to it.
1212 Macro = MI;
Douglas Gregoraae92242010-03-19 21:51:54 +00001213
1214 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1215 // We have a macro definition. Load it now.
1216 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1217 getMacroDefinition(Record[NextIndex]));
1218 }
1219
Douglas Gregorc3366a52009-04-21 23:56:24 +00001220 ++NumMacrosRead;
1221 break;
1222 }
Mike Stump11289f42009-09-09 15:08:12 +00001223
Douglas Gregorc3366a52009-04-21 23:56:24 +00001224 case pch::PP_TOKEN: {
1225 // If we see a TOKEN before a PP_MACRO_*, then the file is
1226 // erroneous, just pretend we didn't see this.
1227 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001228
Douglas Gregorc3366a52009-04-21 23:56:24 +00001229 Token Tok;
1230 Tok.startToken();
1231 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1232 Tok.setLength(Record[1]);
1233 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1234 Tok.setIdentifierInfo(II);
1235 Tok.setKind((tok::TokenKind)Record[3]);
1236 Tok.setFlag((Token::TokenFlags)Record[4]);
1237 Macro->AddTokenToBody(Tok);
1238 break;
1239 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001240
1241 case pch::PP_MACRO_INSTANTIATION: {
1242 // If we already have a macro, that means that we've hit the end
1243 // of the definition of the macro we were looking for. We're
1244 // done.
1245 if (Macro)
1246 return;
1247
1248 if (!PP->getPreprocessingRecord()) {
1249 Error("missing preprocessing record in PCH file");
1250 return;
1251 }
1252
1253 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1254 if (PPRec.getPreprocessedEntity(Record[0]))
1255 return;
1256
1257 MacroInstantiation *MI
1258 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1259 SourceRange(
1260 SourceLocation::getFromRawEncoding(Record[1]),
1261 SourceLocation::getFromRawEncoding(Record[2])),
1262 getMacroDefinition(Record[4]));
1263 PPRec.SetPreallocatedEntity(Record[0], MI);
1264 return;
1265 }
1266
1267 case pch::PP_MACRO_DEFINITION: {
1268 // If we already have a macro, that means that we've hit the end
1269 // of the definition of the macro we were looking for. We're
1270 // done.
1271 if (Macro)
1272 return;
1273
1274 if (!PP->getPreprocessingRecord()) {
1275 Error("missing preprocessing record in PCH file");
1276 return;
1277 }
1278
1279 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1280 if (PPRec.getPreprocessedEntity(Record[0]))
1281 return;
1282
1283 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1284 Error("out-of-bounds macro definition record");
1285 return;
1286 }
1287
1288 MacroDefinition *MD
1289 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1290 SourceLocation::getFromRawEncoding(Record[5]),
1291 SourceRange(
1292 SourceLocation::getFromRawEncoding(Record[2]),
1293 SourceLocation::getFromRawEncoding(Record[3])));
1294 PPRec.SetPreallocatedEntity(Record[0], MD);
1295 MacroDefinitionsLoaded[Record[1]] = MD;
1296 return;
1297 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001298 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001299 }
1300}
1301
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001302void PCHReader::ReadDefinedMacros() {
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001303 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1304 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl34522812010-07-16 17:50:48 +00001305
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001306 // If there was no preprocessor block, skip this file.
1307 if (!MacroCursor.getBitStreamReader())
1308 continue;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001309
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001310 llvm::BitstreamCursor Cursor = MacroCursor;
1311 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1312 Error("malformed preprocessor block record in PCH file");
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001313 return;
1314 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001315
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001316 RecordData Record;
1317 while (true) {
1318 unsigned Code = Cursor.ReadCode();
1319 if (Code == llvm::bitc::END_BLOCK) {
1320 if (Cursor.ReadBlockEnd()) {
1321 Error("error at end of preprocessor block in PCH file");
1322 return;
1323 }
1324 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001325 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001326
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001327 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1328 // No known subblocks, always skip them.
1329 Cursor.ReadSubBlockID();
1330 if (Cursor.SkipBlock()) {
1331 Error("malformed block record in PCH file");
1332 return;
1333 }
1334 continue;
1335 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001336
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001337 if (Code == llvm::bitc::DEFINE_ABBREV) {
1338 Cursor.ReadAbbrevRecord();
1339 continue;
1340 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001341
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001342 // Read a record.
1343 const char *BlobStart;
1344 unsigned BlobLen;
1345 Record.clear();
1346 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1347 default: // Default behavior: ignore.
1348 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001349
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001350 case pch::PP_MACRO_OBJECT_LIKE:
1351 case pch::PP_MACRO_FUNCTION_LIKE:
1352 DecodeIdentifierInfo(Record[0]);
1353 break;
1354
1355 case pch::PP_TOKEN:
1356 // Ignore tokens.
1357 break;
Douglas Gregoraae92242010-03-19 21:51:54 +00001358
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001359 case pch::PP_MACRO_INSTANTIATION:
1360 case pch::PP_MACRO_DEFINITION:
1361 // Read the macro record.
1362 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1363 break;
1364 }
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001365 }
1366 }
1367}
1368
Douglas Gregoraae92242010-03-19 21:51:54 +00001369MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1370 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1371 return 0;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001372
1373 if (!MacroDefinitionsLoaded[ID]) {
1374 unsigned Index = ID;
1375 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1376 PerFileData &F = *Chain[N - I - 1];
1377 if (Index < F.LocalNumMacroDefinitions) {
1378 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1379 break;
1380 }
1381 Index -= F.LocalNumMacroDefinitions;
1382 }
1383 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1384 }
1385
Douglas Gregoraae92242010-03-19 21:51:54 +00001386 return MacroDefinitionsLoaded[ID];
1387}
1388
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001389/// \brief If we are loading a relocatable PCH file, and the filename is
1390/// not an absolute path, add the system root to the beginning of the file
1391/// name.
1392void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1393 // If this is not a relocatable PCH file, there's nothing to do.
1394 if (!RelocatablePCH)
1395 return;
Mike Stump11289f42009-09-09 15:08:12 +00001396
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001397 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001398 return;
1399
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001400 if (isysroot == 0) {
1401 // If no system root was given, default to '/'
1402 Filename.insert(Filename.begin(), '/');
1403 return;
1404 }
Mike Stump11289f42009-09-09 15:08:12 +00001405
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001406 unsigned Length = strlen(isysroot);
1407 if (isysroot[Length - 1] != '/')
1408 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001409
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001410 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1411}
1412
Mike Stump11289f42009-09-09 15:08:12 +00001413PCHReader::PCHReadResult
Sebastian Redl2abc0382010-07-16 20:41:52 +00001414PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl34522812010-07-16 17:50:48 +00001415 llvm::BitstreamCursor &Stream = F.Stream;
1416
Douglas Gregor55abb232009-04-10 20:39:37 +00001417 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001418 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001419 return Failure;
1420 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001421
1422 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001423 RecordData Record;
Sebastian Redl393f8b72010-07-19 20:52:06 +00001424 bool First = true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001425 while (!Stream.AtEndOfStream()) {
1426 unsigned Code = Stream.ReadCode();
1427 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001428 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001429 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001430 return Failure;
1431 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001432
Douglas Gregor55abb232009-04-10 20:39:37 +00001433 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001434 }
1435
1436 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1437 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001438 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001439 // We lazily load the decls block, but we want to set up the
1440 // DeclsCursor cursor to point into it. Clone our current bitcode
1441 // cursor to it, enter the block and read the abbrevs in that block.
1442 // With the main cursor, we just skip over it.
Sebastian Redl34522812010-07-16 17:50:48 +00001443 F.DeclsCursor = Stream;
Chris Lattnere78a6be2009-04-27 01:05:14 +00001444 if (Stream.SkipBlock() || // Skip with the main cursor.
1445 // Read the abbrevs.
Sebastian Redl34522812010-07-16 17:50:48 +00001446 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001447 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001448 return Failure;
1449 }
1450 break;
Mike Stump11289f42009-09-09 15:08:12 +00001451
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001452 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl34522812010-07-16 17:50:48 +00001453 F.MacroCursor = Stream;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001454 if (PP)
1455 PP->setExternalSource(this);
1456
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001457 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001458 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001459 return Failure;
1460 }
1461 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001462
Douglas Gregora7f71a92009-04-10 03:52:48 +00001463 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001464 switch (ReadSourceManagerBlock(F)) {
Douglas Gregor92863e42009-04-10 23:10:45 +00001465 case Success:
1466 break;
1467
1468 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001469 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001470 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001471
1472 case IgnorePCH:
1473 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001474 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001475 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001476 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001477 First = false;
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001478 continue;
1479 }
1480
1481 if (Code == llvm::bitc::DEFINE_ABBREV) {
1482 Stream.ReadAbbrevRecord();
1483 continue;
1484 }
1485
1486 // Read and process a record.
1487 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001488 const char *BlobStart = 0;
1489 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001490 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001491 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001492 default: // Default behavior: ignore.
1493 break;
1494
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001495 case pch::METADATA: {
Douglas Gregorce3a8292010-07-27 00:27:13 +00001496 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001497 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1498 : diag::warn_pch_version_too_new);
1499 return IgnorePCH;
1500 }
1501
1502 RelocatablePCH = Record[4];
1503 if (Listener) {
1504 std::string TargetTriple(BlobStart, BlobLen);
1505 if (Listener->ReadTargetTriple(TargetTriple))
1506 return IgnorePCH;
1507 }
1508 break;
1509 }
1510
1511 case pch::CHAINED_METADATA: {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001512 if (!First) {
1513 Error("CHAINED_METADATA is not first record in block");
1514 return Failure;
1515 }
Douglas Gregorce3a8292010-07-27 00:27:13 +00001516 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001517 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1518 : diag::warn_pch_version_too_new);
1519 return IgnorePCH;
1520 }
1521
1522 // Load the chained file.
1523 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1524 case Failure: return Failure;
1525 // If we have to ignore the dependency, we'll have to ignore this too.
1526 case IgnorePCH: return IgnorePCH;
1527 case Success: break;
1528 }
1529 break;
1530 }
1531
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001532 case pch::TYPE_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001533 if (F.LocalNumTypes != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001534 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001535 return Failure;
1536 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001537 F.TypeOffsets = (const uint32_t *)BlobStart;
1538 F.LocalNumTypes = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001539 break;
1540
1541 case pch::DECL_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001542 if (F.LocalNumDecls != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001543 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001544 return Failure;
1545 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001546 F.DeclOffsets = (const uint32_t *)BlobStart;
1547 F.LocalNumDecls = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001548 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001549
Sebastian Redl4b1f4902010-07-27 18:24:41 +00001550 case pch::TU_UPDATE_LEXICAL: {
1551 DeclContextInfo Info = {
1552 /* No visible information */ 0, 0,
1553 reinterpret_cast<const pch::DeclID *>(BlobStart),
1554 BlobLen / sizeof(pch::DeclID)
1555 };
1556 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1557 break;
1558 }
1559
Douglas Gregor55abb232009-04-10 20:39:37 +00001560 case pch::LANGUAGE_OPTIONS:
Douglas Gregorce3a8292010-07-27 00:27:13 +00001561 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor55abb232009-04-10 20:39:37 +00001562 return IgnorePCH;
1563 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001564
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001565 case pch::IDENTIFIER_TABLE:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001566 F.IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001567 if (Record[0]) {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001568 F.IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001569 = PCHIdentifierLookupTable::Create(
Sebastian Redl393f8b72010-07-19 20:52:06 +00001570 (const unsigned char *)F.IdentifierTableData + Record[0],
1571 (const unsigned char *)F.IdentifierTableData,
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001572 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001573 if (PP)
1574 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001575 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001576 break;
1577
1578 case pch::IDENTIFIER_OFFSET:
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001579 if (F.LocalNumIdentifiers != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001580 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001581 return Failure;
1582 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001583 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1584 F.LocalNumIdentifiers = Record[0];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001585 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001586
1587 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001588 // Optimization for the first block.
1589 if (ExternalDefinitions.empty())
1590 ExternalDefinitions.swap(Record);
1591 else
1592 ExternalDefinitions.insert(ExternalDefinitions.end(),
1593 Record.begin(), Record.end());
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001594 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001595
Douglas Gregor652d82a2009-04-18 05:55:16 +00001596 case pch::SPECIAL_TYPES:
Sebastian Redlb293a452010-07-20 21:20:32 +00001597 // Optimization for the first block
1598 if (SpecialTypes.empty())
1599 SpecialTypes.swap(Record);
1600 else
1601 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregor652d82a2009-04-18 05:55:16 +00001602 break;
1603
Douglas Gregor08f01292009-04-17 22:13:46 +00001604 case pch::STATISTICS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001605 TotalNumStatements += Record[0];
1606 TotalNumMacros += Record[1];
1607 TotalLexicalDeclContexts += Record[2];
1608 TotalVisibleDeclContexts += Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001609 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001610
Douglas Gregord4df8652009-04-22 22:02:47 +00001611 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001612 // Optimization for the first block.
1613 if (TentativeDefinitions.empty())
1614 TentativeDefinitions.swap(Record);
1615 else
1616 TentativeDefinitions.insert(TentativeDefinitions.end(),
1617 Record.begin(), Record.end());
Douglas Gregord4df8652009-04-22 22:02:47 +00001618 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001619
Tanya Lattner90073802010-02-12 00:07:30 +00001620 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001621 // Optimization for the first block.
1622 if (UnusedStaticFuncs.empty())
1623 UnusedStaticFuncs.swap(Record);
1624 else
1625 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1626 Record.begin(), Record.end());
Tanya Lattner90073802010-02-12 00:07:30 +00001627 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001628
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001629 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001630 // Optimization for the first block.
1631 if (LocallyScopedExternalDecls.empty())
1632 LocallyScopedExternalDecls.swap(Record);
1633 else
1634 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1635 Record.begin(), Record.end());
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001636 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001637
Douglas Gregor95c13f52009-04-25 17:48:32 +00001638 case pch::SELECTOR_OFFSETS:
1639 SelectorOffsets = (const uint32_t *)BlobStart;
1640 TotalNumSelectors = Record[0];
1641 SelectorsLoaded.resize(TotalNumSelectors);
1642 break;
1643
Douglas Gregorc78d3462009-04-24 21:10:55 +00001644 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001645 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1646 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001647 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001648 = PCHMethodPoolLookupTable::Create(
1649 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001650 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001651 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001652 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001653 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001654
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001655 case pch::REFERENCED_SELECTOR_POOL: {
1656 unsigned int numEl = Record[0]*2;
1657 for (unsigned int i = 1; i <= numEl; i++)
1658 F.ReferencedSelectorsData.push_back(Record[i]);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001659 break;
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001660 }
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001661
Douglas Gregoreda6a892009-04-26 00:07:37 +00001662 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001663 if (!Record.empty() && Listener)
1664 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001665 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001666
1667 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001668 F.SLocOffsets = (const uint32_t *)BlobStart;
1669 F.LocalNumSLocEntries = Record[0];
1670 // We cannot delay this until all PCHs are loaded, because then source
1671 // location preloads would also have to be delayed.
1672 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001673 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001674 break;
1675
1676 case pch::SOURCE_LOCATION_PRELOADS:
1677 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1678 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1679 if (Result != Success)
1680 return Result;
1681 }
1682 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001683
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001684 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001685 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001686 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1687 (const unsigned char *)BlobStart,
1688 NumStatHits, NumStatMisses);
1689 FileMgr.addStatCache(MyStatCache);
Sebastian Redl34522812010-07-16 17:50:48 +00001690 F.StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001691 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001692 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001693
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001694 case pch::EXT_VECTOR_DECLS:
Sebastian Redl04f5c312010-07-28 21:38:49 +00001695 // Optimization for the first block.
1696 if (ExtVectorDecls.empty())
1697 ExtVectorDecls.swap(Record);
1698 else
1699 ExtVectorDecls.insert(ExtVectorDecls.end(),
1700 Record.begin(), Record.end());
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001701 break;
1702
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001703 case pch::VTABLE_USES:
1704 if (!VTableUses.empty()) {
1705 Error("duplicate VTABLE_USES record in PCH file");
1706 return Failure;
1707 }
1708 VTableUses.swap(Record);
1709 break;
1710
1711 case pch::DYNAMIC_CLASSES:
1712 if (!DynamicClasses.empty()) {
1713 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1714 return Failure;
1715 }
1716 DynamicClasses.swap(Record);
1717 break;
1718
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001719 case pch::SEMA_DECL_REFS:
1720 if (!SemaDeclRefs.empty()) {
1721 Error("duplicate SEMA_DECL_REFS record in PCH file");
1722 return Failure;
1723 }
1724 SemaDeclRefs.swap(Record);
1725 break;
1726
Douglas Gregor45fe0362009-05-12 01:31:05 +00001727 case pch::ORIGINAL_FILE_NAME:
Sebastian Redlb293a452010-07-20 21:20:32 +00001728 // The primary PCH will be the last to get here, so it will be the one
1729 // that's used.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001730 ActualOriginalFileName.assign(BlobStart, BlobLen);
1731 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001732 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001733 break;
Mike Stump11289f42009-09-09 15:08:12 +00001734
Ted Kremenek17437132010-01-22 20:59:36 +00001735 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001736 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001737 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001738 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001739 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1740 return IgnorePCH;
1741 }
1742 break;
1743 }
Sebastian Redlfa061442010-07-21 20:07:32 +00001744
Douglas Gregoraae92242010-03-19 21:51:54 +00001745 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redlfa061442010-07-21 20:07:32 +00001746 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1747 F.NumPreallocatedPreprocessingEntities = Record[0];
1748 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregoraae92242010-03-19 21:51:54 +00001749 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001750 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001751 First = false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001752 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001753 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001754 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001755}
1756
Douglas Gregor92863e42009-04-10 23:10:45 +00001757PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001758 switch(ReadPCHCore(FileName)) {
Sebastian Redl2abc0382010-07-16 20:41:52 +00001759 case Failure: return Failure;
1760 case IgnorePCH: return IgnorePCH;
1761 case Success: break;
1762 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001763
1764 // Here comes stuff that we only do once the entire chain is loaded.
1765
Sebastian Redlb293a452010-07-20 21:20:32 +00001766 // Allocate space for loaded identifiers, decls and types.
Sebastian Redlfa061442010-07-21 20:07:32 +00001767 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
1768 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0;
Sebastian Redl9e687992010-07-19 22:06:55 +00001769 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001770 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl9e687992010-07-19 22:06:55 +00001771 TotalNumTypes += Chain[I]->LocalNumTypes;
1772 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redlfa061442010-07-21 20:07:32 +00001773 TotalNumPreallocatedPreprocessingEntities +=
1774 Chain[I]->NumPreallocatedPreprocessingEntities;
1775 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redl9e687992010-07-19 22:06:55 +00001776 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001777 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl9e687992010-07-19 22:06:55 +00001778 TypesLoaded.resize(TotalNumTypes);
1779 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redlfa061442010-07-21 20:07:32 +00001780 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1781 if (PP) {
1782 if (TotalNumIdentifiers > 0)
1783 PP->getHeaderSearchInfo().SetExternalLookup(this);
1784 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1785 if (!PP->getPreprocessingRecord())
1786 PP->createPreprocessingRecord();
1787 PP->getPreprocessingRecord()->SetExternalSource(*this,
1788 TotalNumPreallocatedPreprocessingEntities);
1789 }
1790 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001791
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001792 // Check the predefines buffers.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001793 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001794 return IgnorePCH;
1795
1796 if (PP) {
1797 // Initialization of keywords and pragmas occurs before the
1798 // PCH file is read, so there may be some identifiers that were
1799 // loaded into the IdentifierTable before we intercepted the
1800 // creation of identifiers. Iterate through the list of known
1801 // identifiers and determine whether we have to establish
1802 // preprocessor definitions or top-level identifier declaration
1803 // chains for those identifiers.
1804 //
1805 // We copy the IdentifierInfo pointers to a small vector first,
1806 // since de-serializing declarations or macro definitions can add
1807 // new entries into the identifier table, invalidating the
1808 // iterators.
1809 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1810 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1811 IdEnd = PP->getIdentifierTable().end();
1812 Id != IdEnd; ++Id)
1813 Identifiers.push_back(Id->second);
Sebastian Redlfa061442010-07-21 20:07:32 +00001814 // We need to search the tables in all files.
Sebastian Redlfa061442010-07-21 20:07:32 +00001815 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1816 PCHIdentifierLookupTable *IdTable
1817 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl5c415f32010-07-22 17:01:13 +00001818 // Not all PCH files necessarily have identifier tables, only the useful
1819 // ones.
1820 if (!IdTable)
1821 continue;
Sebastian Redlfa061442010-07-21 20:07:32 +00001822 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1823 IdentifierInfo *II = Identifiers[I];
1824 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001825 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redlfa061442010-07-21 20:07:32 +00001826 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redlb293a452010-07-20 21:20:32 +00001827 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1828 if (Pos == IdTable->end())
1829 continue;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001830
Sebastian Redlb293a452010-07-20 21:20:32 +00001831 // Dereferencing the iterator has the effect of populating the
1832 // IdentifierInfo node with the various declarations it needs.
1833 (void)*Pos;
1834 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001835 }
1836 }
1837
1838 if (Context)
1839 InitializeContext(*Context);
1840
1841 return Success;
1842}
1843
1844PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1845 Chain.push_back(new PerFileData());
Sebastian Redl34522812010-07-16 17:50:48 +00001846 PerFileData &F = *Chain.back();
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001847
1848 // Set the PCH file name.
1849 F.FileName = FileName;
1850
1851 // Open the PCH file.
1852 //
1853 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1854 std::string ErrStr;
1855 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1856 if (!F.Buffer) {
1857 Error(ErrStr.c_str());
1858 return IgnorePCH;
1859 }
1860
1861 // Initialize the stream
1862 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1863 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl34522812010-07-16 17:50:48 +00001864 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001865 Stream.init(F.StreamFile);
Sebastian Redlfa061442010-07-21 20:07:32 +00001866 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001867
1868 // Sniff for the signature.
1869 if (Stream.Read(8) != 'C' ||
1870 Stream.Read(8) != 'P' ||
1871 Stream.Read(8) != 'C' ||
1872 Stream.Read(8) != 'H') {
1873 Diag(diag::err_not_a_pch_file) << FileName;
1874 return Failure;
1875 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001876
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001877 while (!Stream.AtEndOfStream()) {
1878 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001879
Douglas Gregor92863e42009-04-10 23:10:45 +00001880 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001881 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001882 return Failure;
1883 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001884
1885 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001886
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001887 // We only know the PCH subblock ID.
1888 switch (BlockID) {
1889 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001890 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001891 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001892 return Failure;
1893 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001894 break;
1895 case pch::PCH_BLOCK_ID:
Sebastian Redl2abc0382010-07-16 20:41:52 +00001896 switch (ReadPCHBlock(F)) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001897 case Success:
1898 break;
1899
1900 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001901 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001902
1903 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001904 // FIXME: We could consider reading through to the end of this
1905 // PCH block, skipping subblocks, to see if there are other
1906 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001907
1908 // Clear out any preallocated source location entries, so that
1909 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001910 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001911
1912 // Remove the stat cache.
Sebastian Redl34522812010-07-16 17:50:48 +00001913 if (F.StatCache)
1914 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001915
Douglas Gregor92863e42009-04-10 23:10:45 +00001916 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001917 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001918 break;
1919 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001920 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001921 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001922 return Failure;
1923 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001924 break;
1925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926 }
1927
Sebastian Redl2abc0382010-07-16 20:41:52 +00001928 return Success;
1929}
1930
Douglas Gregoraae92242010-03-19 21:51:54 +00001931void PCHReader::setPreprocessor(Preprocessor &pp) {
1932 PP = &pp;
Sebastian Redlfa061442010-07-21 20:07:32 +00001933
1934 unsigned TotalNum = 0;
1935 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1936 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1937 if (TotalNum) {
Douglas Gregoraae92242010-03-19 21:51:54 +00001938 if (!PP->getPreprocessingRecord())
1939 PP->createPreprocessingRecord();
Sebastian Redlfa061442010-07-21 20:07:32 +00001940 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregoraae92242010-03-19 21:51:54 +00001941 }
1942}
1943
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001944void PCHReader::InitializeContext(ASTContext &Ctx) {
1945 Context = &Ctx;
1946 assert(Context && "Passed null context!");
1947
1948 assert(PP && "Forgot to set Preprocessor ?");
1949 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1950 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001951 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001952
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001953 // Load the translation unit declaration
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00001954 GetTranslationUnitDecl();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001955
1956 // Load the special types.
1957 Context->setBuiltinVaListType(
1958 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1959 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1960 Context->setObjCIdType(GetType(Id));
1961 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1962 Context->setObjCSelType(GetType(Sel));
1963 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1964 Context->setObjCProtoType(GetType(Proto));
1965 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1966 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001967
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001968 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1969 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001970 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001971 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1972 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001973 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1974 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001975 if (FileType.isNull()) {
1976 Error("FILE type is NULL");
1977 return;
1978 }
John McCall9dd450b2009-09-21 23:43:11 +00001979 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001980 Context->setFILEDecl(Typedef->getDecl());
1981 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001982 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001983 if (!Tag) {
1984 Error("Invalid FILE type in PCH file");
1985 return;
1986 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00001987 Context->setFILEDecl(Tag->getDecl());
1988 }
1989 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001990 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1991 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001992 if (Jmp_bufType.isNull()) {
1993 Error("jmp_bug type is NULL");
1994 return;
1995 }
John McCall9dd450b2009-09-21 23:43:11 +00001996 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001997 Context->setjmp_bufDecl(Typedef->getDecl());
1998 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001999 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002000 if (!Tag) {
2001 Error("Invalid jmp_bug type in PCH file");
2002 return;
2003 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00002004 Context->setjmp_bufDecl(Tag->getDecl());
2005 }
2006 }
2007 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2008 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002009 if (Sigjmp_bufType.isNull()) {
2010 Error("sigjmp_buf type is NULL");
2011 return;
2012 }
John McCall9dd450b2009-09-21 23:43:11 +00002013 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00002014 Context->setsigjmp_bufDecl(Typedef->getDecl());
2015 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002016 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00002017 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2018 Context->setsigjmp_bufDecl(Tag->getDecl());
2019 }
2020 }
Mike Stump11289f42009-09-09 15:08:12 +00002021 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00002022 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2023 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00002024 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00002025 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2026 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00002027 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2028 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002029 if (unsigned String
2030 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2031 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002032 if (unsigned ObjCSelRedef
2033 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2034 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2035 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2036 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +00002037
2038 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2039 Context->setInt128Installed();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002040}
2041
Douglas Gregor45fe0362009-05-12 01:31:05 +00002042/// \brief Retrieve the name of the original source file name
2043/// directly from the PCH file, without actually loading the PCH
2044/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00002045std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2046 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00002047 // Open the PCH file.
2048 std::string ErrStr;
2049 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2050 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2051 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002052 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002053 return std::string();
2054 }
2055
2056 // Initialize the stream
2057 llvm::BitstreamReader StreamFile;
2058 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00002059 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00002060 (const unsigned char *)Buffer->getBufferEnd());
2061 Stream.init(StreamFile);
2062
2063 // Sniff for the signature.
2064 if (Stream.Read(8) != 'C' ||
2065 Stream.Read(8) != 'P' ||
2066 Stream.Read(8) != 'C' ||
2067 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002068 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002069 return std::string();
2070 }
2071
2072 RecordData Record;
2073 while (!Stream.AtEndOfStream()) {
2074 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00002075
Douglas Gregor45fe0362009-05-12 01:31:05 +00002076 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2077 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00002078
Douglas Gregor45fe0362009-05-12 01:31:05 +00002079 // We only know the PCH subblock ID.
2080 switch (BlockID) {
2081 case pch::PCH_BLOCK_ID:
2082 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002083 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002084 return std::string();
2085 }
2086 break;
Mike Stump11289f42009-09-09 15:08:12 +00002087
Douglas Gregor45fe0362009-05-12 01:31:05 +00002088 default:
2089 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002090 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002091 return std::string();
2092 }
2093 break;
2094 }
2095 continue;
2096 }
2097
2098 if (Code == llvm::bitc::END_BLOCK) {
2099 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002100 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002101 return std::string();
2102 }
2103 continue;
2104 }
2105
2106 if (Code == llvm::bitc::DEFINE_ABBREV) {
2107 Stream.ReadAbbrevRecord();
2108 continue;
2109 }
2110
2111 Record.clear();
2112 const char *BlobStart = 0;
2113 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002114 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00002115 == pch::ORIGINAL_FILE_NAME)
2116 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00002117 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00002118
2119 return std::string();
2120}
2121
Douglas Gregor55abb232009-04-10 20:39:37 +00002122/// \brief Parse the record that corresponds to a LangOptions data
2123/// structure.
2124///
2125/// This routine compares the language options used to generate the
2126/// PCH file against the language options set for the current
2127/// compilation. For each option, we classify differences between the
2128/// two compiler states as either "benign" or "important". Benign
2129/// differences don't matter, and we accept them without complaint
2130/// (and without modifying the language options). Differences between
2131/// the states for important options cause the PCH file to be
2132/// unusable, so we emit a warning and return true to indicate that
2133/// there was an error.
2134///
2135/// \returns true if the PCH file is unacceptable, false otherwise.
2136bool PCHReader::ParseLanguageOptions(
2137 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002138 if (Listener) {
2139 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00002140
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002141 #define PARSE_LANGOPT(Option) \
2142 LangOpts.Option = Record[Idx]; \
2143 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00002144
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002145 unsigned Idx = 0;
2146 PARSE_LANGOPT(Trigraphs);
2147 PARSE_LANGOPT(BCPLComment);
2148 PARSE_LANGOPT(DollarIdents);
2149 PARSE_LANGOPT(AsmPreprocessor);
2150 PARSE_LANGOPT(GNUMode);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002151 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002152 PARSE_LANGOPT(ImplicitInt);
2153 PARSE_LANGOPT(Digraphs);
2154 PARSE_LANGOPT(HexFloats);
2155 PARSE_LANGOPT(C99);
2156 PARSE_LANGOPT(Microsoft);
2157 PARSE_LANGOPT(CPlusPlus);
2158 PARSE_LANGOPT(CPlusPlus0x);
2159 PARSE_LANGOPT(CXXOperatorNames);
2160 PARSE_LANGOPT(ObjC1);
2161 PARSE_LANGOPT(ObjC2);
2162 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00002163 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +00002164 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002165 PARSE_LANGOPT(PascalStrings);
2166 PARSE_LANGOPT(WritableStrings);
2167 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00002168 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002169 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00002170 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002171 PARSE_LANGOPT(NeXTRuntime);
2172 PARSE_LANGOPT(Freestanding);
2173 PARSE_LANGOPT(NoBuiltin);
2174 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00002175 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002176 PARSE_LANGOPT(Blocks);
2177 PARSE_LANGOPT(EmitAllDecls);
2178 PARSE_LANGOPT(MathErrno);
Chris Lattner51924e512010-06-26 21:25:03 +00002179 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2180 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002181 PARSE_LANGOPT(HeinousExtensions);
2182 PARSE_LANGOPT(Optimize);
2183 PARSE_LANGOPT(OptimizeSize);
2184 PARSE_LANGOPT(Static);
2185 PARSE_LANGOPT(PICLevel);
2186 PARSE_LANGOPT(GNUInline);
2187 PARSE_LANGOPT(NoInline);
2188 PARSE_LANGOPT(AccessControl);
2189 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00002190 PARSE_LANGOPT(ShortWChar);
Chris Lattner51924e512010-06-26 21:25:03 +00002191 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2192 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbar143021e2009-09-21 04:16:19 +00002193 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattner51924e512010-06-26 21:25:03 +00002194 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002195 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00002196 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00002197 PARSE_LANGOPT(CatchUndefined);
2198 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002199 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00002200
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002201 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00002202 }
Douglas Gregor55abb232009-04-10 20:39:37 +00002203
2204 return false;
2205}
2206
Douglas Gregoraae92242010-03-19 21:51:54 +00002207void PCHReader::ReadPreprocessedEntities() {
2208 ReadDefinedMacros();
2209}
2210
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002211/// \brief Get the correct cursor and offset for loading a type.
2212PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2213 PerFileData *F = 0;
2214 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2215 F = Chain[N - I - 1];
2216 if (Index < F->LocalNumTypes)
2217 break;
2218 Index -= F->LocalNumTypes;
2219 }
2220 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redlb2831db2010-07-20 22:55:31 +00002221 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002222}
2223
2224/// \brief Read and return the type with the given index..
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002225///
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002226/// The index is the type ID, shifted and minus the number of predefs. This
2227/// routine actually reads the record corresponding to the type at the given
2228/// location. It is a helper routine for GetType, which deals with reading type
2229/// IDs.
2230QualType PCHReader::ReadTypeRecord(unsigned Index) {
2231 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redlb2831db2010-07-20 22:55:31 +00002232 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl34522812010-07-16 17:50:48 +00002233
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002234 // Keep track of where we are in the stream, then jump back there
2235 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00002236 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002237
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002238 ReadingKindTracker ReadingKind(Read_Type, *this);
2239
Douglas Gregor1342e842009-07-06 18:54:52 +00002240 // Note that we are loading a type record.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00002241 Deserializing AType(this);
Mike Stump11289f42009-09-09 15:08:12 +00002242
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002243 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002244 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00002245 unsigned Code = DeclsCursor.ReadCode();
2246 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00002247 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002248 if (Record.size() != 2) {
2249 Error("Incorrect encoding of extended qualifier type");
2250 return QualType();
2251 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00002252 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00002253 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2254 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00002255 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002256
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002257 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002258 if (Record.size() != 1) {
2259 Error("Incorrect encoding of complex type");
2260 return QualType();
2261 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002262 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002263 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002264 }
2265
2266 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002267 if (Record.size() != 1) {
2268 Error("Incorrect encoding of pointer type");
2269 return QualType();
2270 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002271 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002272 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002273 }
2274
2275 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002276 if (Record.size() != 1) {
2277 Error("Incorrect encoding of block pointer type");
2278 return QualType();
2279 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002280 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002281 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002282 }
2283
2284 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002285 if (Record.size() != 1) {
2286 Error("Incorrect encoding of lvalue reference type");
2287 return QualType();
2288 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002289 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002290 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002291 }
2292
2293 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002294 if (Record.size() != 1) {
2295 Error("Incorrect encoding of rvalue reference type");
2296 return QualType();
2297 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002298 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002299 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002300 }
2301
2302 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidisee776bc2010-07-02 11:55:15 +00002303 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002304 Error("Incorrect encoding of member pointer type");
2305 return QualType();
2306 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002307 QualType PointeeType = GetType(Record[0]);
2308 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002309 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002310 }
2311
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002312 case pch::TYPE_CONSTANT_ARRAY: {
2313 QualType ElementType = GetType(Record[0]);
2314 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2315 unsigned IndexTypeQuals = Record[2];
2316 unsigned Idx = 3;
2317 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00002318 return Context->getConstantArrayType(ElementType, Size,
2319 ASM, IndexTypeQuals);
2320 }
2321
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002322 case pch::TYPE_INCOMPLETE_ARRAY: {
2323 QualType ElementType = GetType(Record[0]);
2324 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2325 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00002326 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002327 }
2328
2329 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002330 QualType ElementType = GetType(Record[0]);
2331 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2332 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00002333 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2334 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redlc67764e2010-07-22 22:43:28 +00002335 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor04318252009-07-06 15:59:29 +00002336 ASM, IndexTypeQuals,
2337 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002338 }
2339
2340 case pch::TYPE_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002341 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002342 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002343 return QualType();
2344 }
2345
2346 QualType ElementType = GetType(Record[0]);
2347 unsigned NumElements = Record[1];
Chris Lattner37141f42010-06-23 06:00:24 +00002348 unsigned AltiVecSpec = Record[2];
2349 return Context->getVectorType(ElementType, NumElements,
2350 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002351 }
2352
2353 case pch::TYPE_EXT_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002354 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002355 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002356 return QualType();
2357 }
2358
2359 QualType ElementType = GetType(Record[0]);
2360 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00002361 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002362 }
2363
2364 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002365 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002366 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002367 return QualType();
2368 }
2369 QualType ResultType = GetType(Record[0]);
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002370 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002371 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002372 }
2373
2374 case pch::TYPE_FUNCTION_PROTO: {
2375 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00002376 bool NoReturn = Record[1];
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002377 unsigned RegParm = Record[2];
2378 CallingConv CallConv = (CallingConv)Record[3];
2379 unsigned Idx = 4;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002380 unsigned NumParams = Record[Idx++];
2381 llvm::SmallVector<QualType, 16> ParamTypes;
2382 for (unsigned I = 0; I != NumParams; ++I)
2383 ParamTypes.push_back(GetType(Record[Idx++]));
2384 bool isVariadic = Record[Idx++];
2385 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002386 bool hasExceptionSpec = Record[Idx++];
2387 bool hasAnyExceptionSpec = Record[Idx++];
2388 unsigned NumExceptions = Record[Idx++];
2389 llvm::SmallVector<QualType, 2> Exceptions;
2390 for (unsigned I = 0; I != NumExceptions; ++I)
2391 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00002392 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002393 isVariadic, Quals, hasExceptionSpec,
2394 hasAnyExceptionSpec, NumExceptions,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002395 Exceptions.data(),
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002396 FunctionType::ExtInfo(NoReturn, RegParm,
2397 CallConv));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002398 }
2399
John McCallb96ec562009-12-04 22:46:56 +00002400 case pch::TYPE_UNRESOLVED_USING:
2401 return Context->getTypeDeclType(
2402 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2403
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002404 case pch::TYPE_TYPEDEF: {
2405 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002406 Error("incorrect encoding of typedef type");
2407 return QualType();
2408 }
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002409 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2410 QualType Canonical = GetType(Record[1]);
2411 return Context->getTypedefType(Decl, Canonical);
2412 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002413
2414 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002415 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002416
2417 case pch::TYPE_TYPEOF: {
2418 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002419 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002420 return QualType();
2421 }
2422 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002423 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002424 }
Mike Stump11289f42009-09-09 15:08:12 +00002425
Anders Carlsson81df7b82009-06-24 19:06:50 +00002426 case pch::TYPE_DECLTYPE:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002427 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson81df7b82009-06-24 19:06:50 +00002428
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002429 case pch::TYPE_RECORD: {
2430 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002431 Error("incorrect encoding of record type");
2432 return QualType();
2433 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002434 bool IsDependent = Record[0];
2435 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2436 T->Dependent = IsDependent;
2437 return T;
2438 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002439
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002440 case pch::TYPE_ENUM: {
2441 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002442 Error("incorrect encoding of enum type");
2443 return QualType();
2444 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002445 bool IsDependent = Record[0];
2446 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2447 T->Dependent = IsDependent;
2448 return T;
2449 }
Douglas Gregor1daeb692009-04-13 18:14:40 +00002450
John McCallfcc33b02009-09-05 00:15:47 +00002451 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002452 unsigned Idx = 0;
2453 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2454 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2455 QualType NamedType = GetType(Record[Idx++]);
2456 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCallfcc33b02009-09-05 00:15:47 +00002457 }
2458
Steve Naroffc277ad12009-07-18 15:33:26 +00002459 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002460 unsigned Idx = 0;
2461 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002462 return Context->getObjCInterfaceType(ItfD);
2463 }
2464
2465 case pch::TYPE_OBJC_OBJECT: {
2466 unsigned Idx = 0;
2467 QualType Base = GetType(Record[Idx++]);
Chris Lattner587cbe12009-04-22 06:45:28 +00002468 unsigned NumProtos = Record[Idx++];
2469 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2470 for (unsigned I = 0; I != NumProtos; ++I)
2471 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCall8b07ec22010-05-15 11:32:37 +00002472 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002473 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002474
Steve Narofffb4330f2009-06-17 22:40:22 +00002475 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002476 unsigned Idx = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002477 QualType Pointee = GetType(Record[Idx++]);
2478 return Context->getObjCObjectPointerType(Pointee);
Chris Lattner6e054af2009-04-22 06:40:03 +00002479 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002480
John McCallcebee162009-10-18 09:09:24 +00002481 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2482 unsigned Idx = 0;
2483 QualType Parm = GetType(Record[Idx++]);
2484 QualType Replacement = GetType(Record[Idx++]);
2485 return
2486 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2487 Replacement);
2488 }
John McCalle78aac42010-03-10 03:28:59 +00002489
2490 case pch::TYPE_INJECTED_CLASS_NAME: {
2491 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2492 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00002493 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2494 // for PCH reading, too much interdependencies.
2495 return
2496 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCalle78aac42010-03-10 03:28:59 +00002497 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002498
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002499 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2500 unsigned Idx = 0;
2501 unsigned Depth = Record[Idx++];
2502 unsigned Index = Record[Idx++];
2503 bool Pack = Record[Idx++];
2504 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2505 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2506 }
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002507
2508 case pch::TYPE_DEPENDENT_NAME: {
2509 unsigned Idx = 0;
2510 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2511 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2512 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +00002513 QualType Canon = GetType(Record[Idx++]);
2514 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002515 }
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002516
2517 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2518 unsigned Idx = 0;
2519 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2520 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2521 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2522 unsigned NumArgs = Record[Idx++];
2523 llvm::SmallVector<TemplateArgument, 8> Args;
2524 Args.reserve(NumArgs);
2525 while (NumArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00002526 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002527 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2528 Args.size(), Args.data());
2529 }
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002530
2531 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2532 unsigned Idx = 0;
2533
2534 // ArrayType
2535 QualType ElementType = GetType(Record[Idx++]);
2536 ArrayType::ArraySizeModifier ASM
2537 = (ArrayType::ArraySizeModifier)Record[Idx++];
2538 unsigned IndexTypeQuals = Record[Idx++];
2539
2540 // DependentSizedArrayType
Sebastian Redlc67764e2010-07-22 22:43:28 +00002541 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002542 SourceRange Brackets = ReadSourceRange(Record, Idx);
2543
2544 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2545 IndexTypeQuals, Brackets);
2546 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002547
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002548 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2549 unsigned Idx = 0;
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002550 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002551 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002552 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redlc67764e2010-07-22 22:43:28 +00002553 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00002554 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002555 QualType T;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002556 if (Canon.isNull())
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002557 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2558 Args.size());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002559 else
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002560 T = Context->getTemplateSpecializationType(Name, Args.data(),
2561 Args.size(), Canon);
2562 T->Dependent = IsDependent;
2563 return T;
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002564 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002565 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002566 // Suppress a GCC warning
2567 return QualType();
2568}
2569
John McCall8f115c62009-10-16 21:56:05 +00002570namespace {
2571
2572class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2573 PCHReader &Reader;
Sebastian Redlc67764e2010-07-22 22:43:28 +00002574 llvm::BitstreamCursor &DeclsCursor;
John McCall8f115c62009-10-16 21:56:05 +00002575 const PCHReader::RecordData &Record;
2576 unsigned &Idx;
2577
2578public:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002579 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2580 const PCHReader::RecordData &Record, unsigned &Idx)
2581 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCall8f115c62009-10-16 21:56:05 +00002582
John McCall17001972009-10-18 01:05:36 +00002583 // We want compile-time assurance that we've enumerated all of
2584 // these, so unfortunately we have to declare them first, then
2585 // define them out-of-line.
2586#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002587#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002588 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002589#include "clang/AST/TypeLocNodes.def"
2590
John McCall17001972009-10-18 01:05:36 +00002591 void VisitFunctionTypeLoc(FunctionTypeLoc);
2592 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002593};
2594
2595}
2596
John McCall17001972009-10-18 01:05:36 +00002597void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002598 // nothing to do
2599}
John McCall17001972009-10-18 01:05:36 +00002600void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002601 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2602 if (TL.needsExtraLocalData()) {
2603 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2604 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2605 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2606 TL.setModeAttr(Record[Idx++]);
2607 }
John McCall8f115c62009-10-16 21:56:05 +00002608}
John McCall17001972009-10-18 01:05:36 +00002609void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2610 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002611}
John McCall17001972009-10-18 01:05:36 +00002612void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2613 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002614}
John McCall17001972009-10-18 01:05:36 +00002615void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2616 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002617}
John McCall17001972009-10-18 01:05:36 +00002618void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2619 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002620}
John McCall17001972009-10-18 01:05:36 +00002621void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2622 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002623}
John McCall17001972009-10-18 01:05:36 +00002624void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2625 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002626}
John McCall17001972009-10-18 01:05:36 +00002627void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2628 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2629 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002630 if (Record[Idx++])
Sebastian Redlc67764e2010-07-22 22:43:28 +00002631 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor12bfa382009-10-17 00:13:19 +00002632 else
John McCall17001972009-10-18 01:05:36 +00002633 TL.setSizeExpr(0);
2634}
2635void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2636 VisitArrayTypeLoc(TL);
2637}
2638void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2639 VisitArrayTypeLoc(TL);
2640}
2641void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2642 VisitArrayTypeLoc(TL);
2643}
2644void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2645 DependentSizedArrayTypeLoc TL) {
2646 VisitArrayTypeLoc(TL);
2647}
2648void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2649 DependentSizedExtVectorTypeLoc TL) {
2650 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2651}
2652void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2653 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2654}
2655void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2656 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2657}
2658void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2659 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2660 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2661 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002662 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002663 }
2664}
2665void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2666 VisitFunctionTypeLoc(TL);
2667}
2668void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2669 VisitFunctionTypeLoc(TL);
2670}
John McCallb96ec562009-12-04 22:46:56 +00002671void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2672 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2673}
John McCall17001972009-10-18 01:05:36 +00002674void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2675 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2676}
2677void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002678 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2679 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2680 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002681}
2682void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002683 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2684 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2685 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redlc67764e2010-07-22 22:43:28 +00002686 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002687}
2688void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2689 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2690}
2691void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2692 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2693}
2694void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2695 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2696}
John McCall17001972009-10-18 01:05:36 +00002697void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2698 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2699}
John McCallcebee162009-10-18 09:09:24 +00002700void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2701 SubstTemplateTypeParmTypeLoc TL) {
2702 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2703}
John McCall17001972009-10-18 01:05:36 +00002704void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2705 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002706 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2707 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2708 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2709 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2710 TL.setArgLocInfo(i,
2711 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002712 DeclsCursor, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002713}
Abramo Bagnara6150c882010-05-11 21:36:43 +00002714void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002715 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2716 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002717}
John McCalle78aac42010-03-10 03:28:59 +00002718void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2719 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2720}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002721void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002722 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2723 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002724 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2725}
John McCallc392f372010-06-11 00:33:02 +00002726void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2727 DependentTemplateSpecializationTypeLoc TL) {
2728 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2729 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2730 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2731 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2732 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2733 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2734 TL.setArgLocInfo(I,
2735 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002736 DeclsCursor, Record, Idx));
John McCallc392f372010-06-11 00:33:02 +00002737}
John McCall17001972009-10-18 01:05:36 +00002738void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2739 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002740}
2741void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2742 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall17001972009-10-18 01:05:36 +00002743 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2744 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2745 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2746 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002747}
John McCallfc93cf92009-10-22 22:37:11 +00002748void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2749 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallfc93cf92009-10-22 22:37:11 +00002750}
John McCall8f115c62009-10-16 21:56:05 +00002751
Sebastian Redlc67764e2010-07-22 22:43:28 +00002752TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2753 const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002754 unsigned &Idx) {
2755 QualType InfoTy = GetType(Record[Idx++]);
2756 if (InfoTy.isNull())
2757 return 0;
2758
John McCallbcd03502009-12-07 02:54:59 +00002759 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redlc67764e2010-07-22 22:43:28 +00002760 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002761 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002762 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002763 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002764}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002765
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002766QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002767 unsigned FastQuals = ID & Qualifiers::FastMask;
2768 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002769
2770 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2771 QualType T;
2772 switch ((pch::PredefinedTypeIDs)Index) {
2773 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002774 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2775 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002776
2777 case pch::PREDEF_TYPE_CHAR_U_ID:
2778 case pch::PREDEF_TYPE_CHAR_S_ID:
2779 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002780 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002781 break;
2782
Chris Lattner8575daa2009-04-27 21:45:14 +00002783 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2784 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2785 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2786 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2787 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002788 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002789 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2790 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2791 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2792 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2793 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2794 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002795 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002796 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2797 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2798 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2799 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2800 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002801 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002802 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2803 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002804 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2805 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002806 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002807 }
2808
2809 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002810 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002811 }
2812
2813 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002814 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl409183f2010-07-14 20:26:45 +00002815 if (TypesLoaded[Index].isNull()) {
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002816 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl409183f2010-07-14 20:26:45 +00002817 TypesLoaded[Index]->setFromPCH();
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002818 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002819 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2820 TypesLoaded[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002821 }
Mike Stump11289f42009-09-09 15:08:12 +00002822
John McCall8ccfcb52009-09-24 19:53:00 +00002823 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002824}
2825
John McCall0ad16662009-10-29 08:12:44 +00002826TemplateArgumentLocInfo
2827PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redlc67764e2010-07-22 22:43:28 +00002828 llvm::BitstreamCursor &DeclsCursor,
John McCall0ad16662009-10-29 08:12:44 +00002829 const RecordData &Record,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002830 unsigned &Index) {
John McCall0ad16662009-10-29 08:12:44 +00002831 switch (Kind) {
2832 case TemplateArgument::Expression:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002833 return ReadExpr(DeclsCursor);
John McCall0ad16662009-10-29 08:12:44 +00002834 case TemplateArgument::Type:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002835 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002836 case TemplateArgument::Template: {
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002837 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2838 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2839 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002840 }
John McCall0ad16662009-10-29 08:12:44 +00002841 case TemplateArgument::Null:
2842 case TemplateArgument::Integral:
2843 case TemplateArgument::Declaration:
2844 case TemplateArgument::Pack:
2845 return TemplateArgumentLocInfo();
2846 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002847 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002848 return TemplateArgumentLocInfo();
2849}
2850
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002851TemplateArgumentLoc
Sebastian Redlc67764e2010-07-22 22:43:28 +00002852PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2853 const RecordData &Record, unsigned &Index) {
2854 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002855
2856 if (Arg.getKind() == TemplateArgument::Expression) {
2857 if (Record[Index++]) // bool InfoHasSameExpr.
2858 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2859 }
2860 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002861 DeclsCursor,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002862 Record, Index));
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00002863}
2864
John McCall75b960e2010-06-01 09:23:16 +00002865Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2866 return GetDecl(ID);
2867}
2868
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002869TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002870 if (!DeclsLoaded[0]) {
Sebastian Redl34627792010-07-20 22:46:15 +00002871 ReadDeclRecord(0);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002872 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002873 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002874 }
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002875
2876 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2877}
2878
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002879Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002880 if (ID == 0)
2881 return 0;
2882
Douglas Gregor745ed142009-04-25 18:35:21 +00002883 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002884 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002885 return 0;
2886 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002887
Douglas Gregor745ed142009-04-25 18:35:21 +00002888 unsigned Index = ID - 1;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002889 if (!DeclsLoaded[Index]) {
Sebastian Redl34627792010-07-20 22:46:15 +00002890 ReadDeclRecord(Index);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002891 if (DeserializationListener)
2892 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2893 }
Douglas Gregor745ed142009-04-25 18:35:21 +00002894
2895 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002896}
2897
Chris Lattner9c28af02009-04-27 05:46:25 +00002898/// \brief Resolve the offset of a statement into a statement.
2899///
2900/// This operation will read a new statement from the external
2901/// source each time it is called, and is meant to be used via a
2902/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall75b960e2010-06-01 09:23:16 +00002903Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl5c415f32010-07-22 17:01:13 +00002904 // Offset here is a global offset across the entire chain.
2905 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2906 PerFileData &F = *Chain[N - I - 1];
2907 if (Offset < F.SizeInBits) {
2908 // Since we know that this statement is part of a decl, make sure to use
2909 // the decl cursor to read it.
2910 F.DeclsCursor.JumpToBit(Offset);
2911 return ReadStmtFromStream(F.DeclsCursor);
2912 }
2913 Offset -= F.SizeInBits;
2914 }
2915 llvm_unreachable("Broken chain");
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002916}
2917
John McCall75b960e2010-06-01 09:23:16 +00002918bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2919 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002920 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002921 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002922
Sebastian Redl5c415f32010-07-22 17:01:13 +00002923 // There might be lexical decls in multiple parts of the chain, for the TU
2924 // at least.
2925 DeclContextInfos &Infos = DeclContextOffsets[DC];
2926 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2927 I != E; ++I) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002928 // IDs can be 0 if this context doesn't contain declarations.
2929 if (!I->LexicalDecls)
Sebastian Redl5c415f32010-07-22 17:01:13 +00002930 continue;
Sebastian Redl5c415f32010-07-22 17:01:13 +00002931
2932 // Load all of the declaration IDs
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002933 for (const pch::DeclID *ID = I->LexicalDecls,
2934 *IDE = ID + I->NumLexicalDecls;
2935 ID != IDE; ++ID)
2936 Decls.push_back(GetDecl(*ID));
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002937 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002938
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002939 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002940 return false;
2941}
2942
John McCall75b960e2010-06-01 09:23:16 +00002943DeclContext::lookup_result
2944PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2945 DeclarationName Name) {
Mike Stump11289f42009-09-09 15:08:12 +00002946 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002947 "DeclContext has no visible decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002948
John McCall75b960e2010-06-01 09:23:16 +00002949 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl5c415f32010-07-22 17:01:13 +00002950 // There might be lexical decls in multiple parts of the chain, for the TU
2951 // and namespaces.
2952 DeclContextInfos &Infos = DeclContextOffsets[DC];
2953 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2954 I != E; ++I) {
2955 uint64_t Offset = I->OffsetToVisibleDecls;
2956 if (Offset == 0)
2957 continue;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002958
Sebastian Redl5c415f32010-07-22 17:01:13 +00002959 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002960
Sebastian Redl5c415f32010-07-22 17:01:13 +00002961 // Keep track of where we are in the stream, then jump back there
2962 // after reading this context.
2963 SavedStreamPosition SavedPosition(DeclsCursor);
2964
2965 // Load the record containing all of the declarations visible in
2966 // this context.
2967 DeclsCursor.JumpToBit(Offset);
2968 RecordData Record;
2969 unsigned Code = DeclsCursor.ReadCode();
2970 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2971 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2972 Error("Expected visible block");
2973 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2974 DeclContext::lookup_iterator());
2975 }
2976
2977 if (Record.empty())
2978 continue;
2979
2980 unsigned Idx = 0;
2981 while (Idx < Record.size()) {
2982 Decls.push_back(VisibleDeclaration());
2983 Decls.back().Name = ReadDeclarationName(Record, Idx);
2984
2985 unsigned Size = Record[Idx++];
2986 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
2987 LoadedDecls.reserve(Size);
2988 for (unsigned J = 0; J < Size; ++J)
2989 LoadedDecls.push_back(Record[Idx++]);
2990 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002991 }
2992
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002993 ++NumVisibleDeclContextsRead;
John McCall75b960e2010-06-01 09:23:16 +00002994
2995 SetExternalVisibleDecls(DC, Decls);
2996 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002997}
2998
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002999void PCHReader::PassInterestingDeclsToConsumer() {
3000 assert(Consumer);
3001 while (!InterestingDecls.empty()) {
3002 DeclGroupRef DG(InterestingDecls.front());
3003 InterestingDecls.pop_front();
3004 Consumer->HandleTopLevelDecl(DG);
3005 }
3006}
3007
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003008void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00003009 this->Consumer = Consumer;
3010
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003011 if (!Consumer)
3012 return;
3013
3014 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003015 // Force deserialization of this decl, which will cause it to be queued for
3016 // passing to the consumer.
Daniel Dunbar865c2a72009-09-17 03:06:44 +00003017 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003018 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00003019
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003020 PassInterestingDeclsToConsumer();
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003021}
3022
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003023void PCHReader::PrintStats() {
3024 std::fprintf(stderr, "*** PCH Statistics:\n");
3025
Mike Stump11289f42009-09-09 15:08:12 +00003026 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00003027 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00003028 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00003029 unsigned NumDeclsLoaded
3030 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3031 (Decl *)0);
3032 unsigned NumIdentifiersLoaded
3033 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3034 IdentifiersLoaded.end(),
3035 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00003036 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00003037 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3038 SelectorsLoaded.end(),
3039 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00003040
Douglas Gregorc5046832009-04-27 18:38:38 +00003041 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3042 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00003043 if (TotalNumSLocEntries)
3044 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3045 NumSLocEntriesRead, TotalNumSLocEntries,
3046 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00003047 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003048 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00003049 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3050 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3051 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003052 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00003053 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3054 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00003055 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003056 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00003057 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3058 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003059 if (TotalNumSelectors)
3060 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
3061 NumSelectorsLoaded, TotalNumSelectors,
3062 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
3063 if (TotalNumStatements)
3064 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3065 NumStatementsRead, TotalNumStatements,
3066 ((float)NumStatementsRead/TotalNumStatements * 100));
3067 if (TotalNumMacros)
3068 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3069 NumMacrosRead, TotalNumMacros,
3070 ((float)NumMacrosRead/TotalNumMacros * 100));
3071 if (TotalLexicalDeclContexts)
3072 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3073 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3074 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3075 * 100));
3076 if (TotalVisibleDeclContexts)
3077 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3078 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3079 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3080 * 100));
3081 if (TotalSelectorsInMethodPool) {
3082 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
3083 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
3084 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
3085 * 100));
3086 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
3087 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003088 std::fprintf(stderr, "\n");
3089}
3090
Douglas Gregora868bbd2009-04-21 22:25:48 +00003091void PCHReader::InitializeSema(Sema &S) {
3092 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003093 S.ExternalSource = this;
3094
Douglas Gregor7cd60f72009-04-22 21:15:06 +00003095 // Makes sure any declarations that were deserialized "too early"
3096 // still get added to the identifier's declaration chains.
3097 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3098 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3099 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003100 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00003101 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00003102
3103 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00003104 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00003105 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3106 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00003107 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00003108 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00003109
Tanya Lattner90073802010-02-12 00:07:30 +00003110 // If there were any unused static functions, deserialize them and add to
3111 // Sema's list of unused static functions.
3112 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3113 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3114 SemaObj->UnusedStaticFuncs.push_back(FD);
3115 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00003116
3117 // If there were any locally-scoped external declarations,
3118 // deserialize them and add them to Sema's table of locally-scoped
3119 // external declarations.
3120 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3121 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3122 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3123 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00003124
3125 // If there were any ext_vector type declarations, deserialize them
3126 // and add them to Sema's vector of such declarations.
3127 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3128 SemaObj->ExtVectorDecls.push_back(
3129 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00003130
3131 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3132 // Can we cut them down before writing them ?
3133
3134 // If there were any VTable uses, deserialize the information and add it
3135 // to Sema's vector and map of VTable uses.
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00003136 if (!VTableUses.empty()) {
3137 unsigned Idx = 0;
3138 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3139 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3140 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3141 bool DefinitionRequired = VTableUses[Idx++];
3142 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3143 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3144 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00003145 }
3146
3147 // If there were any dynamic classes declarations, deserialize them
3148 // and add them to Sema's vector of such declarations.
3149 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3150 SemaObj->DynamicClasses.push_back(
3151 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003152
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003153 // Load the offsets of the declarations that Sema references.
3154 // They will be lazily deserialized when needed.
3155 if (!SemaDeclRefs.empty()) {
3156 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3157 SemaObj->StdNamespace = SemaDeclRefs[0];
3158 SemaObj->StdBadAlloc = SemaDeclRefs[1];
3159 }
3160
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003161 // If there are @selector references added them to its pool. This is for
3162 // implementation of -Wselector.
3163 PerFileData &F = *Chain[0];
3164 if (!F.ReferencedSelectorsData.empty()) {
3165 unsigned int DataSize = F.ReferencedSelectorsData.size()-1;
3166 unsigned I = 0;
3167 while (I < DataSize) {
3168 Selector Sel = DecodeSelector(F.ReferencedSelectorsData[I++]);
3169 SourceLocation SelLoc =
3170 SourceLocation::getFromRawEncoding(F.ReferencedSelectorsData[I++]);
3171 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3172 }
3173 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00003174}
3175
3176IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redl78f51772010-08-02 18:30:12 +00003177 // Try to find this name within our on-disk hash tables. We start with the
3178 // most recent one, since that one contains the most up-to-date info.
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003179 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3180 PCHIdentifierLookupTable *IdTable
Sebastian Redl78f51772010-08-02 18:30:12 +00003181 = (PCHIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
Sebastian Redl5c415f32010-07-22 17:01:13 +00003182 if (!IdTable)
3183 continue;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003184 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3185 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3186 if (Pos == IdTable->end())
3187 continue;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003188
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003189 // Dereferencing the iterator has the effect of building the
3190 // IdentifierInfo node and populating it with the various
3191 // declarations it needs.
Sebastian Redl78f51772010-08-02 18:30:12 +00003192 return *Pos;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003193 }
Sebastian Redl78f51772010-08-02 18:30:12 +00003194 return 0;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003195}
3196
Mike Stump11289f42009-09-09 15:08:12 +00003197std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00003198PCHReader::ReadMethodPool(Selector Sel) {
3199 if (!MethodPoolLookupTable)
3200 return std::pair<ObjCMethodList, ObjCMethodList>();
3201
3202 // Try to find this selector within our on-disk hash table.
3203 PCHMethodPoolLookupTable *PoolTable
3204 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
3205 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003206 if (Pos == PoolTable->end()) {
3207 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003208 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00003209 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003210
Douglas Gregor95c13f52009-04-25 17:48:32 +00003211 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003212 return *Pos;
3213}
3214
Douglas Gregor0e149972009-04-25 19:10:14 +00003215void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00003216 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003217 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00003218 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlff4a2952010-07-23 23:49:55 +00003219 if (DeserializationListener)
3220 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003221}
3222
Douglas Gregor1342e842009-07-06 18:54:52 +00003223/// \brief Set the globally-visible declarations associated with the given
3224/// identifier.
3225///
3226/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00003227/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00003228/// them.
3229///
3230/// \param II an IdentifierInfo that refers to one or more globally-visible
3231/// declarations.
3232///
3233/// \param DeclIDs the set of declaration IDs with the name @p II that are
3234/// visible at global scope.
3235///
3236/// \param Nonrecursive should be true to indicate that the caller knows that
3237/// this call is non-recursive, and therefore the globally-visible declarations
3238/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00003239void
3240PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00003241 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3242 bool Nonrecursive) {
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003243 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregor1342e842009-07-06 18:54:52 +00003244 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3245 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3246 PII.II = II;
3247 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3248 PII.DeclIDs.push_back(DeclIDs[I]);
3249 return;
3250 }
Mike Stump11289f42009-09-09 15:08:12 +00003251
Douglas Gregor1342e842009-07-06 18:54:52 +00003252 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3253 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3254 if (SemaObj) {
3255 // Introduce this declaration into the translation-unit scope
3256 // and add it to the declaration chain for this identifier, so
3257 // that (unqualified) name lookup will find it.
3258 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3259 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3260 } else {
3261 // Queue this declaration so that it will be added to the
3262 // translation unit scope and identifier's declaration chain
3263 // once a Sema object is known.
3264 PreloadedDecls.push_back(D);
3265 }
3266 }
3267}
3268
Chris Lattnerc523d8e2009-04-11 21:15:38 +00003269IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003270 if (ID == 0)
3271 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003272
Sebastian Redlc713b962010-07-21 00:46:22 +00003273 if (IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003274 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003275 return 0;
3276 }
Mike Stump11289f42009-09-09 15:08:12 +00003277
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003278 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redlc713b962010-07-21 00:46:22 +00003279 ID -= 1;
3280 if (!IdentifiersLoaded[ID]) {
3281 unsigned Index = ID;
3282 const char *Str = 0;
3283 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3284 PerFileData *F = Chain[N - I - 1];
3285 if (Index < F->LocalNumIdentifiers) {
3286 uint32_t Offset = F->IdentifierOffsets[Index];
3287 Str = F->IdentifierTableData + Offset;
3288 break;
3289 }
3290 Index -= F->LocalNumIdentifiers;
3291 }
3292 assert(Str && "Broken Chain");
Douglas Gregor5287b4e2009-04-25 21:04:17 +00003293
Douglas Gregorab4df582009-04-28 20:01:51 +00003294 // All of the strings in the PCH file are preceded by a 16-bit
3295 // length. Extract that 16-bit length to avoid having to execute
3296 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00003297 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3298 // unsigned integers. This is important to avoid integer overflow when
3299 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00003300 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00003301 unsigned StrLen = (((unsigned) StrLenPtr[0])
3302 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redlc713b962010-07-21 00:46:22 +00003303 IdentifiersLoaded[ID]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00003304 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlff4a2952010-07-23 23:49:55 +00003305 if (DeserializationListener)
3306 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003307 }
Mike Stump11289f42009-09-09 15:08:12 +00003308
Sebastian Redlc713b962010-07-21 00:46:22 +00003309 return IdentifiersLoaded[ID];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003310}
3311
Douglas Gregor258ae542009-04-27 06:38:32 +00003312void PCHReader::ReadSLocEntry(unsigned ID) {
3313 ReadSLocEntryRecord(ID);
3314}
3315
Steve Naroff2ddea052009-04-23 10:39:46 +00003316Selector PCHReader::DecodeSelector(unsigned ID) {
3317 if (ID == 0)
3318 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00003319
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003320 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00003321 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003322
3323 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003324 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00003325 return Selector();
3326 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003327
3328 unsigned Index = ID - 1;
3329 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3330 // Load this selector from the selector table.
3331 // FIXME: endianness portability issues with SelectorOffsets table
3332 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003333 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00003334 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3335 }
3336
3337 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00003338}
3339
John McCall75b960e2010-06-01 09:23:16 +00003340Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003341 return DecodeSelector(ID);
3342}
3343
John McCall75b960e2010-06-01 09:23:16 +00003344uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregord720daf2010-04-06 17:30:22 +00003345 return TotalNumSelectors + 1;
3346}
3347
Mike Stump11289f42009-09-09 15:08:12 +00003348DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003349PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3350 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3351 switch (Kind) {
3352 case DeclarationName::Identifier:
3353 return DeclarationName(GetIdentifierInfo(Record, Idx));
3354
3355 case DeclarationName::ObjCZeroArgSelector:
3356 case DeclarationName::ObjCOneArgSelector:
3357 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00003358 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003359
3360 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003361 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003362 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003363
3364 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003365 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003366 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003367
3368 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003369 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003370 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003371
3372 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003373 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003374 (OverloadedOperatorKind)Record[Idx++]);
3375
Alexis Hunt3d221f22009-11-29 07:34:05 +00003376 case DeclarationName::CXXLiteralOperatorName:
3377 return Context->DeclarationNames.getCXXLiteralOperatorName(
3378 GetIdentifierInfo(Record, Idx));
3379
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003380 case DeclarationName::CXXUsingDirective:
3381 return DeclarationName::getUsingDirectiveName();
3382 }
3383
3384 // Required to silence GCC warning
3385 return DeclarationName();
3386}
Douglas Gregor55abb232009-04-10 20:39:37 +00003387
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003388TemplateName
3389PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3390 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3391 switch (Kind) {
3392 case TemplateName::Template:
3393 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3394
3395 case TemplateName::OverloadedTemplate: {
3396 unsigned size = Record[Idx++];
3397 UnresolvedSet<8> Decls;
3398 while (size--)
3399 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3400
3401 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3402 }
3403
3404 case TemplateName::QualifiedTemplate: {
3405 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3406 bool hasTemplKeyword = Record[Idx++];
3407 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3408 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3409 }
3410
3411 case TemplateName::DependentTemplate: {
3412 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3413 if (Record[Idx++]) // isIdentifier
3414 return Context->getDependentTemplateName(NNS,
3415 GetIdentifierInfo(Record, Idx));
3416 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00003417 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003418 }
3419 }
3420
3421 assert(0 && "Unhandled template name kind!");
3422 return TemplateName();
3423}
3424
3425TemplateArgument
Sebastian Redlc67764e2010-07-22 22:43:28 +00003426PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3427 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003428 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3429 case TemplateArgument::Null:
3430 return TemplateArgument();
3431 case TemplateArgument::Type:
3432 return TemplateArgument(GetType(Record[Idx++]));
3433 case TemplateArgument::Declaration:
3434 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00003435 case TemplateArgument::Integral: {
3436 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3437 QualType T = GetType(Record[Idx++]);
3438 return TemplateArgument(Value, T);
3439 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003440 case TemplateArgument::Template:
3441 return TemplateArgument(ReadTemplateName(Record, Idx));
3442 case TemplateArgument::Expression:
Sebastian Redlc67764e2010-07-22 22:43:28 +00003443 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003444 case TemplateArgument::Pack: {
3445 unsigned NumArgs = Record[Idx++];
3446 llvm::SmallVector<TemplateArgument, 8> Args;
3447 Args.reserve(NumArgs);
3448 while (NumArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00003449 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003450 TemplateArgument TemplArg;
3451 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3452 return TemplArg;
3453 }
3454 }
3455
3456 assert(0 && "Unhandled template argument kind!");
3457 return TemplateArgument();
3458}
3459
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003460TemplateParameterList *
3461PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3462 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3463 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3464 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3465
3466 unsigned NumParams = Record[Idx++];
3467 llvm::SmallVector<NamedDecl *, 16> Params;
3468 Params.reserve(NumParams);
3469 while (NumParams--)
3470 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3471
3472 TemplateParameterList* TemplateParams =
3473 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3474 Params.data(), Params.size(), RAngleLoc);
3475 return TemplateParams;
3476}
3477
3478void
3479PCHReader::
3480ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redlc67764e2010-07-22 22:43:28 +00003481 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003482 const RecordData &Record, unsigned &Idx) {
3483 unsigned NumTemplateArgs = Record[Idx++];
3484 TemplArgs.reserve(NumTemplateArgs);
3485 while (NumTemplateArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00003486 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003487}
3488
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00003489/// \brief Read a UnresolvedSet structure.
3490void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3491 const RecordData &Record, unsigned &Idx) {
3492 unsigned NumDecls = Record[Idx++];
3493 while (NumDecls--) {
3494 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3495 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3496 Set.addDecl(D, AS);
3497 }
3498}
3499
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003500CXXBaseSpecifier
Nick Lewycky19b9f952010-07-26 16:56:01 +00003501PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3502 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003503 bool isVirtual = static_cast<bool>(Record[Idx++]);
3504 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3505 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky19b9f952010-07-26 16:56:01 +00003506 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003507 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky19b9f952010-07-26 16:56:01 +00003508 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003509}
3510
Chris Lattnerca025db2010-05-07 21:43:38 +00003511NestedNameSpecifier *
3512PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3513 unsigned N = Record[Idx++];
3514 NestedNameSpecifier *NNS = 0, *Prev = 0;
3515 for (unsigned I = 0; I != N; ++I) {
3516 NestedNameSpecifier::SpecifierKind Kind
3517 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3518 switch (Kind) {
3519 case NestedNameSpecifier::Identifier: {
3520 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3521 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3522 break;
3523 }
3524
3525 case NestedNameSpecifier::Namespace: {
3526 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3527 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3528 break;
3529 }
3530
3531 case NestedNameSpecifier::TypeSpec:
3532 case NestedNameSpecifier::TypeSpecWithTemplate: {
3533 Type *T = GetType(Record[Idx++]).getTypePtr();
3534 bool Template = Record[Idx++];
3535 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3536 break;
3537 }
3538
3539 case NestedNameSpecifier::Global: {
3540 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3541 // No associated value, and there can't be a prefix.
3542 break;
3543 }
Chris Lattnerca025db2010-05-07 21:43:38 +00003544 }
Argyrios Kyrtzidisad65c692010-07-07 15:46:30 +00003545 Prev = NNS;
Chris Lattnerca025db2010-05-07 21:43:38 +00003546 }
3547 return NNS;
3548}
3549
3550SourceRange
3551PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar6d3bc082010-06-02 15:47:10 +00003552 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3553 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3554 return SourceRange(beg, end);
Chris Lattnerca025db2010-05-07 21:43:38 +00003555}
3556
Douglas Gregor1daeb692009-04-13 18:14:40 +00003557/// \brief Read an integral value
3558llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3559 unsigned BitWidth = Record[Idx++];
3560 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3561 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3562 Idx += NumWords;
3563 return Result;
3564}
3565
3566/// \brief Read a signed integral value
3567llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3568 bool isUnsigned = Record[Idx++];
3569 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3570}
3571
Douglas Gregore0a3a512009-04-14 21:55:33 +00003572/// \brief Read a floating-point value
3573llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00003574 return llvm::APFloat(ReadAPInt(Record, Idx));
3575}
3576
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003577// \brief Read a string
3578std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3579 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00003580 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003581 Idx += Len;
3582 return Result;
3583}
3584
Chris Lattnercba86142010-05-10 00:25:06 +00003585CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3586 unsigned &Idx) {
3587 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3588 return CXXTemporary::Create(*Context, Decl);
3589}
3590
Douglas Gregor55abb232009-04-10 20:39:37 +00003591DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00003592 return Diag(SourceLocation(), DiagID);
3593}
3594
3595DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003596 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00003597}
Douglas Gregora9af1d12009-04-17 00:04:06 +00003598
Douglas Gregora868bbd2009-04-21 22:25:48 +00003599/// \brief Retrieve the identifier table associated with the
3600/// preprocessor.
3601IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003602 assert(PP && "Forgot to set Preprocessor ?");
3603 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00003604}
3605
Douglas Gregora9af1d12009-04-17 00:04:06 +00003606/// \brief Record that the given ID maps to the given switch-case
3607/// statement.
3608void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3609 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3610 SwitchCaseStmts[ID] = SC;
3611}
3612
3613/// \brief Retrieve the switch-case statement with the given ID.
3614SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3615 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3616 return SwitchCaseStmts[ID];
3617}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003618
3619/// \brief Record that the given label statement has been
3620/// deserialized and has the given ID.
3621void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00003622 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003623 "Deserialized label twice");
3624 LabelStmts[ID] = S;
3625
3626 // If we've already seen any goto statements that point to this
3627 // label, resolve them now.
3628 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3629 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3630 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3631 Goto->second->setLabel(S);
3632 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00003633
3634 // If we've already seen any address-label statements that point to
3635 // this label, resolve them now.
3636 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00003637 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00003638 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00003639 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00003640 AddrLabel != AddrLabels.second; ++AddrLabel)
3641 AddrLabel->second->setLabel(S);
3642 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003643}
3644
3645/// \brief Set the label of the given statement to the label
3646/// identified by ID.
3647///
3648/// Depending on the order in which the label and other statements
3649/// referencing that label occur, this operation may complete
3650/// immediately (updating the statement) or it may queue the
3651/// statement to be back-patched later.
3652void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3653 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3654 if (Label != LabelStmts.end()) {
3655 // We've already seen this label, so set the label of the goto and
3656 // we're done.
3657 S->setLabel(Label->second);
3658 } else {
3659 // We haven't seen this label yet, so add this goto to the set of
3660 // unresolved goto statements.
3661 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3662 }
3663}
Douglas Gregor779d8652009-04-17 18:58:21 +00003664
3665/// \brief Set the label of the given expression to the label
3666/// identified by ID.
3667///
3668/// Depending on the order in which the label and other statements
3669/// referencing that label occur, this operation may complete
3670/// immediately (updating the statement) or it may queue the
3671/// statement to be back-patched later.
3672void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3673 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3674 if (Label != LabelStmts.end()) {
3675 // We've already seen this label, so set the label of the
3676 // label-address expression and we're done.
3677 S->setLabel(Label->second);
3678 } else {
3679 // We haven't seen this label yet, so add this label-address
3680 // expression to the set of unresolved label-address expressions.
3681 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3682 }
3683}
Douglas Gregor1342e842009-07-06 18:54:52 +00003684
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003685void PCHReader::FinishedDeserializing() {
3686 assert(NumCurrentElementsDeserializing &&
3687 "FinishedDeserializing not paired with StartedDeserializing");
3688 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregor1342e842009-07-06 18:54:52 +00003689 // If any identifiers with corresponding top-level declarations have
3690 // been loaded, load those declarations now.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003691 while (!PendingIdentifierInfos.empty()) {
3692 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3693 PendingIdentifierInfos.front().DeclIDs, true);
3694 PendingIdentifierInfos.pop_front();
Douglas Gregor1342e842009-07-06 18:54:52 +00003695 }
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003696
3697 // We are not in recursive loading, so it's safe to pass the "interesting"
3698 // decls to the consumer.
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003699 if (Consumer)
3700 PassInterestingDeclsToConsumer();
Douglas Gregor1342e842009-07-06 18:54:52 +00003701 }
Argyrios Kyrtzidisb24355a2010-07-30 10:03:16 +00003702 --NumCurrentElementsDeserializing;
Douglas Gregor1342e842009-07-06 18:54:52 +00003703}