blob: a0e3148bc73e1141b3b2f0058d3b1152b46dced5 [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),
429 TotalVisibleDeclContexts(0), CurrentlyLoadingTypeOrDecl(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),
446 TotalVisibleDeclContexts(0), CurrentlyLoadingTypeOrDecl(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
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000463
Douglas Gregora868bbd2009-04-21 22:25:48 +0000464namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000465class PCHMethodPoolLookupTrait {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000466 PCHReader &Reader;
467
468public:
469 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
470
471 typedef Selector external_key_type;
472 typedef external_key_type internal_key_type;
473
474 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000475
Douglas Gregorc78d3462009-04-24 21:10:55 +0000476 static bool EqualKey(const internal_key_type& a,
477 const internal_key_type& b) {
478 return a == b;
479 }
Mike Stump11289f42009-09-09 15:08:12 +0000480
Douglas Gregorc78d3462009-04-24 21:10:55 +0000481 static unsigned ComputeHash(Selector Sel) {
482 unsigned N = Sel.getNumArgs();
483 if (N == 0)
484 ++N;
485 unsigned R = 5381;
486 for (unsigned I = 0; I != N; ++I)
487 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000488 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000489 return R;
490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregorc78d3462009-04-24 21:10:55 +0000492 // This hopefully will just get inlined and removed by the optimizer.
493 static const internal_key_type&
494 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000495
Douglas Gregorc78d3462009-04-24 21:10:55 +0000496 static std::pair<unsigned, unsigned>
497 ReadKeyDataLength(const unsigned char*& d) {
498 using namespace clang::io;
499 unsigned KeyLen = ReadUnalignedLE16(d);
500 unsigned DataLen = ReadUnalignedLE16(d);
501 return std::make_pair(KeyLen, DataLen);
502 }
Mike Stump11289f42009-09-09 15:08:12 +0000503
Douglas Gregor95c13f52009-04-25 17:48:32 +0000504 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000505 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000506 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000507 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000508 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000509 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
510 if (N == 0)
511 return SelTable.getNullarySelector(FirstII);
512 else if (N == 1)
513 return SelTable.getUnarySelector(FirstII);
514
515 llvm::SmallVector<IdentifierInfo *, 16> Args;
516 Args.push_back(FirstII);
517 for (unsigned I = 1; I != N; ++I)
518 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
519
Douglas Gregor038c3382009-05-22 22:45:36 +0000520 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000521 }
Mike Stump11289f42009-09-09 15:08:12 +0000522
Douglas Gregorc78d3462009-04-24 21:10:55 +0000523 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
524 using namespace clang::io;
525 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
526 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
527
528 data_type Result;
529
530 // Load instance methods
531 ObjCMethodList *Prev = 0;
532 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000533 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000534 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
535 if (!Result.first.Method) {
536 // This is the first method, which is the easy case.
537 Result.first.Method = Method;
538 Prev = &Result.first;
539 continue;
540 }
541
Ted Kremenekda4abf12010-02-11 00:53:01 +0000542 ObjCMethodList *Mem =
543 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
544 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000545 Prev = Prev->Next;
546 }
547
548 // Load factory methods
549 Prev = 0;
550 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000551 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000552 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
553 if (!Result.second.Method) {
554 // This is the first method, which is the easy case.
555 Result.second.Method = Method;
556 Prev = &Result.second;
557 continue;
558 }
559
Ted Kremenekda4abf12010-02-11 00:53:01 +0000560 ObjCMethodList *Mem =
561 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
562 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000563 Prev = Prev->Next;
564 }
565
566 return Result;
567 }
568};
Mike Stump11289f42009-09-09 15:08:12 +0000569
570} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000571
572/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000573typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000574 PCHMethodPoolLookupTable;
575
576namespace {
Benjamin Kramer16634c22009-11-28 10:07:24 +0000577class PCHIdentifierLookupTrait {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000578 PCHReader &Reader;
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000579 llvm::BitstreamCursor &Stream;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000580
581 // If we know the IdentifierInfo in advance, it is here and we will
582 // not build a new one. Used when deserializing information about an
583 // identifier that was constructed before the PCH file was read.
584 IdentifierInfo *KnownII;
585
586public:
587 typedef IdentifierInfo * data_type;
588
589 typedef const std::pair<const char*, unsigned> external_key_type;
590
591 typedef external_key_type internal_key_type;
592
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000593 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
594 IdentifierInfo *II = 0)
595 : Reader(Reader), Stream(Stream), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000596
Douglas Gregora868bbd2009-04-21 22:25:48 +0000597 static bool EqualKey(const internal_key_type& a,
598 const internal_key_type& b) {
599 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
600 : false;
601 }
Mike Stump11289f42009-09-09 15:08:12 +0000602
Douglas Gregora868bbd2009-04-21 22:25:48 +0000603 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000604 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000605 }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Douglas Gregora868bbd2009-04-21 22:25:48 +0000607 // This hopefully will just get inlined and removed by the optimizer.
608 static const internal_key_type&
609 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000610
Douglas Gregora868bbd2009-04-21 22:25:48 +0000611 static std::pair<unsigned, unsigned>
612 ReadKeyDataLength(const unsigned char*& d) {
613 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000614 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000615 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000616 return std::make_pair(KeyLen, DataLen);
617 }
Mike Stump11289f42009-09-09 15:08:12 +0000618
Douglas Gregora868bbd2009-04-21 22:25:48 +0000619 static std::pair<const char*, unsigned>
620 ReadKey(const unsigned char* d, unsigned n) {
621 assert(n >= 2 && d[n-1] == '\0');
622 return std::make_pair((const char*) d, n-1);
623 }
Mike Stump11289f42009-09-09 15:08:12 +0000624
625 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000626 const unsigned char* d,
627 unsigned DataLen) {
628 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000629 pch::IdentID ID = ReadUnalignedLE32(d);
630 bool IsInteresting = ID & 0x01;
631
632 // Wipe out the "is interesting" bit.
633 ID = ID >> 1;
634
635 if (!IsInteresting) {
636 // For unintersting identifiers, just build the IdentifierInfo
637 // and associate it with the persistent ID.
638 IdentifierInfo *II = KnownII;
639 if (!II)
640 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
641 k.first, k.first + k.second);
642 Reader.SetIdentifierInfo(ID, II);
643 return II;
644 }
645
Douglas Gregorb9256522009-04-28 21:32:13 +0000646 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000647 bool CPlusPlusOperatorKeyword = Bits & 0x01;
648 Bits >>= 1;
649 bool Poisoned = Bits & 0x01;
650 Bits >>= 1;
651 bool ExtensionToken = Bits & 0x01;
652 Bits >>= 1;
653 bool hasMacroDefinition = Bits & 0x01;
654 Bits >>= 1;
655 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
656 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000657
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000658 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000659 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000660
661 // Build the IdentifierInfo itself and link the identifier ID with
662 // the new IdentifierInfo.
663 IdentifierInfo *II = KnownII;
664 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000665 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
666 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000667 Reader.SetIdentifierInfo(ID, II);
668
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000669 // Set or check the various bits in the IdentifierInfo structure.
670 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000671 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000672 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000673 "Incorrect extension token flag");
674 (void)ExtensionToken;
675 II->setIsPoisoned(Poisoned);
676 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
677 "Incorrect C++ operator keyword flag");
678 (void)CPlusPlusOperatorKeyword;
679
Douglas Gregorc3366a52009-04-21 23:56:24 +0000680 // If this identifier is a macro, deserialize the macro
681 // definition.
682 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000683 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redl4e6c5672010-07-21 22:31:37 +0000684 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000685 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000686 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000687
688 // Read all of the declarations visible at global scope with this
689 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000690 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000691 if (DataLen > 0) {
692 llvm::SmallVector<uint32_t, 4> DeclIDs;
693 for (; DataLen > 0; DataLen -= 4)
694 DeclIDs.push_back(ReadUnalignedLE32(d));
695 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000696 }
Mike Stump11289f42009-09-09 15:08:12 +0000697
Douglas Gregora868bbd2009-04-21 22:25:48 +0000698 return II;
699 }
700};
Mike Stump11289f42009-09-09 15:08:12 +0000701
702} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000703
704/// \brief The on-disk hash table used to contain information about
705/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000706typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000707 PCHIdentifierLookupTable;
708
Ted Kremenek1ff615c2010-03-18 00:56:54 +0000709void PCHReader::Error(const char *Msg) {
710 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000711}
712
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000713/// \brief Check the contents of the concatenation of all predefines buffers in
714/// the PCH chain against the contents of the predefines buffer of the current
715/// compiler invocation.
Douglas Gregor92863e42009-04-10 23:10:45 +0000716///
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000717/// The contents should be the same. If not, then some command-line option
718/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregor92863e42009-04-10 23:10:45 +0000719///
720/// \returns true if there was a mismatch (in which case the PCH file
721/// should be ignored), or false otherwise.
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000722bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000723 if (Listener)
Sebastian Redl75fbb3b2010-07-14 17:49:11 +0000724 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000725 ActualOriginalFileName,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000726 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000727 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000728}
729
Douglas Gregorc5046832009-04-27 18:38:38 +0000730//===----------------------------------------------------------------------===//
731// Source Manager Deserialization
732//===----------------------------------------------------------------------===//
733
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000734/// \brief Read the line table in the source manager block.
735/// \returns true if ther was an error.
Sebastian Redlb293a452010-07-20 21:20:32 +0000736bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000737 unsigned Idx = 0;
738 LineTableInfo &LineTable = SourceMgr.getLineTable();
739
740 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000741 std::map<int, int> FileIDs;
742 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000743 // Extract the file name
744 unsigned FilenameLen = Record[Idx++];
745 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
746 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000747 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000748 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000749 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000750 }
751
752 // Parse the line entries
753 std::vector<LineEntry> Entries;
754 while (Idx < Record.size()) {
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000755 int FID = Record[Idx++];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000756
757 // Extract the line entries
758 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000759 assert(NumEntries && "Numentries is 00000");
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000760 Entries.clear();
761 Entries.reserve(NumEntries);
762 for (unsigned I = 0; I != NumEntries; ++I) {
763 unsigned FileOffset = Record[Idx++];
764 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidise3029a72010-07-02 11:55:05 +0000765 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump11289f42009-09-09 15:08:12 +0000766 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000767 = (SrcMgr::CharacteristicKind)Record[Idx++];
768 unsigned IncludeOffset = Record[Idx++];
769 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
770 FileKind, IncludeOffset));
771 }
772 LineTable.AddEntry(FID, Entries);
773 }
774
775 return false;
776}
777
Douglas Gregorc5046832009-04-27 18:38:38 +0000778namespace {
779
Benjamin Kramer16634c22009-11-28 10:07:24 +0000780class PCHStatData {
Douglas Gregorc5046832009-04-27 18:38:38 +0000781public:
782 const bool hasStat;
783 const ino_t ino;
784 const dev_t dev;
785 const mode_t mode;
786 const time_t mtime;
787 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregorc5046832009-04-27 18:38:38 +0000789 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000790 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
791
Douglas Gregorc5046832009-04-27 18:38:38 +0000792 PCHStatData()
793 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
794};
795
Benjamin Kramer16634c22009-11-28 10:07:24 +0000796class PCHStatLookupTrait {
Douglas Gregorc5046832009-04-27 18:38:38 +0000797 public:
798 typedef const char *external_key_type;
799 typedef const char *internal_key_type;
800
801 typedef PCHStatData data_type;
802
803 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000804 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000805 }
806
807 static internal_key_type GetInternalKey(const char *path) { return path; }
808
809 static bool EqualKey(internal_key_type a, internal_key_type b) {
810 return strcmp(a, b) == 0;
811 }
812
813 static std::pair<unsigned, unsigned>
814 ReadKeyDataLength(const unsigned char*& d) {
815 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
816 unsigned DataLen = (unsigned) *d++;
817 return std::make_pair(KeyLen + 1, DataLen);
818 }
819
820 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
821 return (const char *)d;
822 }
823
824 static data_type ReadData(const internal_key_type, const unsigned char *d,
825 unsigned /*DataLen*/) {
826 using namespace clang::io;
827
828 if (*d++ == 1)
829 return data_type();
830
831 ino_t ino = (ino_t) ReadUnalignedLE32(d);
832 dev_t dev = (dev_t) ReadUnalignedLE32(d);
833 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000834 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000835 off_t size = (off_t) ReadUnalignedLE64(d);
836 return data_type(ino, dev, mode, mtime, size);
837 }
838};
839
840/// \brief stat() cache for precompiled headers.
841///
842/// This cache is very similar to the stat cache used by pretokenized
843/// headers.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000844class PCHStatCache : public StatSysCallCache {
Douglas Gregorc5046832009-04-27 18:38:38 +0000845 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
846 CacheTy *Cache;
847
848 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000849public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000850 PCHStatCache(const unsigned char *Buckets,
851 const unsigned char *Base,
852 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000853 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000854 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
855 Cache = CacheTy::Create(Buckets, Base);
856 }
857
858 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregorc5046832009-04-27 18:38:38 +0000860 int stat(const char *path, struct stat *buf) {
861 // Do the lookup for the file's data in the PCH file.
862 CacheTy::iterator I = Cache->find(path);
863
864 // If we don't get a hit in the PCH file just forward to 'stat'.
865 if (I == Cache->end()) {
866 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000867 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000868 }
Mike Stump11289f42009-09-09 15:08:12 +0000869
Douglas Gregorc5046832009-04-27 18:38:38 +0000870 ++NumStatHits;
871 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000872
Douglas Gregorc5046832009-04-27 18:38:38 +0000873 if (!Data.hasStat)
874 return 1;
875
876 buf->st_ino = Data.ino;
877 buf->st_dev = Data.dev;
878 buf->st_mtime = Data.mtime;
879 buf->st_mode = Data.mode;
880 buf->st_size = Data.size;
881 return 0;
882 }
883};
884} // end anonymous namespace
885
886
Sebastian Redl393f8b72010-07-19 20:52:06 +0000887/// \brief Read a source manager block
888PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000889 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000890
Sebastian Redl393f8b72010-07-19 20:52:06 +0000891 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl34522812010-07-16 17:50:48 +0000892
Douglas Gregor258ae542009-04-27 06:38:32 +0000893 // Set the source-location entry cursor to the current position in
894 // the stream. This cursor will be used to read the contents of the
895 // source manager block initially, and then lazily read
896 // source-location entries as needed.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000897 SLocEntryCursor = F.Stream;
Douglas Gregor258ae542009-04-27 06:38:32 +0000898
899 // The stream itself is going to skip over the source manager block.
Sebastian Redl393f8b72010-07-19 20:52:06 +0000900 if (F.Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000901 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000902 return Failure;
903 }
904
905 // Enter the source manager block.
906 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000907 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000908 return Failure;
909 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000910
Douglas Gregora7f71a92009-04-10 03:52:48 +0000911 RecordData Record;
912 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000913 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000914 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000915 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000916 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000917 return Failure;
918 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000919 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000920 }
Mike Stump11289f42009-09-09 15:08:12 +0000921
Douglas Gregora7f71a92009-04-10 03:52:48 +0000922 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
923 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000924 SLocEntryCursor.ReadSubBlockID();
925 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000926 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000927 return Failure;
928 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000929 continue;
930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
Douglas Gregora7f71a92009-04-10 03:52:48 +0000932 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000933 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000934 continue;
935 }
Mike Stump11289f42009-09-09 15:08:12 +0000936
Douglas Gregora7f71a92009-04-10 03:52:48 +0000937 // Read a record.
938 const char *BlobStart;
939 unsigned BlobLen;
940 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000941 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000942 default: // Default behavior: ignore.
943 break;
944
Chris Lattner184e65d2009-04-14 23:22:57 +0000945 case pch::SM_LINE_TABLE:
Sebastian Redlb293a452010-07-20 21:20:32 +0000946 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000947 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000948 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000949
Douglas Gregor258ae542009-04-27 06:38:32 +0000950 case pch::SM_SLOC_FILE_ENTRY:
951 case pch::SM_SLOC_BUFFER_ENTRY:
952 case pch::SM_SLOC_INSTANTIATION_ENTRY:
953 // Once we hit one of the source location entries, we're done.
954 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000955 }
956 }
957}
958
Sebastian Redl06750302010-07-20 21:50:20 +0000959/// \brief Get a cursor that's correctly positioned for reading the source
960/// location entry with the given ID.
961llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
962 assert(ID != 0 && ID <= TotalNumSLocEntries &&
963 "SLocCursorForID should only be called for real IDs.");
964
965 ID -= 1;
966 PerFileData *F = 0;
967 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
968 F = Chain[N - I - 1];
969 if (ID < F->LocalNumSLocEntries)
970 break;
971 ID -= F->LocalNumSLocEntries;
972 }
973 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
974
975 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
976 return F->SLocEntryCursor;
977}
978
Douglas Gregor258ae542009-04-27 06:38:32 +0000979/// \brief Read in the source location entry with the given ID.
980PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
981 if (ID == 0)
982 return Success;
983
984 if (ID > TotalNumSLocEntries) {
985 Error("source location entry ID out-of-range for PCH file");
986 return Failure;
987 }
988
Sebastian Redl06750302010-07-20 21:50:20 +0000989 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl34522812010-07-16 17:50:48 +0000990
Douglas Gregor258ae542009-04-27 06:38:32 +0000991 ++NumSLocEntriesRead;
Douglas Gregor258ae542009-04-27 06:38:32 +0000992 unsigned Code = SLocEntryCursor.ReadCode();
993 if (Code == llvm::bitc::END_BLOCK ||
994 Code == llvm::bitc::ENTER_SUBBLOCK ||
995 Code == llvm::bitc::DEFINE_ABBREV) {
996 Error("incorrectly-formatted source location entry in PCH file");
997 return Failure;
998 }
999
Douglas Gregor258ae542009-04-27 06:38:32 +00001000 RecordData Record;
1001 const char *BlobStart;
1002 unsigned BlobLen;
1003 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1004 default:
1005 Error("incorrectly-formatted source location entry in PCH file");
1006 return Failure;
1007
1008 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001009 std::string Filename(BlobStart, BlobStart + BlobLen);
1010 MaybeAddSystemRootToFilename(Filename);
1011 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +00001012 if (File == 0) {
1013 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001014 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +00001015 ErrorStr += "' referenced by PCH file";
1016 Error(ErrorStr.c_str());
1017 return Failure;
1018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001020 if (Record.size() < 10) {
Ted Kremenekabb1ddd2010-03-18 21:23:05 +00001021 Error("source location entry is incorrect");
1022 return Failure;
1023 }
1024
Douglas Gregorce3a8292010-07-27 00:27:13 +00001025 if (!DisableValidation &&
1026 ((off_t)Record[4] != File->getSize()
Douglas Gregor08288f22010-04-09 15:54:22 +00001027#if !defined(LLVM_ON_WIN32)
1028 // In our regression testing, the Windows file system seems to
1029 // have inconsistent modification times that sometimes
1030 // erroneously trigger this error-handling path.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001031 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor08288f22010-04-09 15:54:22 +00001032#endif
Douglas Gregorce3a8292010-07-27 00:27:13 +00001033 )) {
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001034 Diag(diag::err_fe_pch_file_modified)
1035 << Filename;
1036 return Failure;
1037 }
1038
Douglas Gregor258ae542009-04-27 06:38:32 +00001039 FileID FID = SourceMgr.createFileID(File,
1040 SourceLocation::getFromRawEncoding(Record[1]),
1041 (SrcMgr::CharacteristicKind)Record[2],
1042 ID, Record[0]);
1043 if (Record[3])
1044 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1045 .setHasLineDirectives();
1046
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001047 // Reconstruct header-search information for this file.
1048 HeaderFileInfo HFI;
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001049 HFI.isImport = Record[6];
1050 HFI.DirInfo = Record[7];
1051 HFI.NumIncludes = Record[8];
1052 HFI.ControllingMacroID = Record[9];
Douglas Gregor5712ebc2010-03-16 16:35:32 +00001053 if (Listener)
1054 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor258ae542009-04-27 06:38:32 +00001055 break;
1056 }
1057
1058 case pch::SM_SLOC_BUFFER_ENTRY: {
1059 const char *Name = BlobStart;
1060 unsigned Offset = Record[0];
1061 unsigned Code = SLocEntryCursor.ReadCode();
1062 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +00001063 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +00001064 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001065
1066 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1067 Error("PCH record has invalid code");
1068 return Failure;
1069 }
1070
Douglas Gregor258ae542009-04-27 06:38:32 +00001071 llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001072 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1073 Name);
Douglas Gregor258ae542009-04-27 06:38:32 +00001074 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +00001075
Douglas Gregore6648fb2009-04-28 20:33:11 +00001076 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl75fbb3b2010-07-14 17:49:11 +00001077 PCHPredefinesBlock Block = {
1078 BufferID,
1079 llvm::StringRef(BlobStart, BlobLen - 1)
1080 };
1081 PCHPredefinesBuffers.push_back(Block);
Douglas Gregore6648fb2009-04-28 20:33:11 +00001082 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001083
1084 break;
1085 }
1086
1087 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +00001088 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +00001089 = SourceLocation::getFromRawEncoding(Record[1]);
1090 SourceMgr.createInstantiationLoc(SpellingLoc,
1091 SourceLocation::getFromRawEncoding(Record[2]),
1092 SourceLocation::getFromRawEncoding(Record[3]),
1093 Record[4],
1094 ID,
1095 Record[0]);
1096 break;
Mike Stump11289f42009-09-09 15:08:12 +00001097 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001098 }
1099
1100 return Success;
1101}
1102
Chris Lattnere78a6be2009-04-27 01:05:14 +00001103/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1104/// specified cursor. Read the abbreviations that are at the top of the block
1105/// and then leave the cursor pointing into the block.
1106bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1107 unsigned BlockID) {
1108 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001109 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001110 return Failure;
1111 }
Mike Stump11289f42009-09-09 15:08:12 +00001112
Chris Lattnere78a6be2009-04-27 01:05:14 +00001113 while (true) {
1114 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattnere78a6be2009-04-27 01:05:14 +00001116 // We expect all abbrevs to be at the start of the block.
1117 if (Code != llvm::bitc::DEFINE_ABBREV)
1118 return false;
1119 Cursor.ReadAbbrevRecord();
1120 }
1121}
1122
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001123void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001124 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001125
Douglas Gregorc3366a52009-04-21 23:56:24 +00001126 // Keep track of where we are in the stream, then jump back there
1127 // after reading this macro.
1128 SavedStreamPosition SavedPosition(Stream);
1129
1130 Stream.JumpToBit(Offset);
1131 RecordData Record;
1132 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1133 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001134
Douglas Gregorc3366a52009-04-21 23:56:24 +00001135 while (true) {
1136 unsigned Code = Stream.ReadCode();
1137 switch (Code) {
1138 case llvm::bitc::END_BLOCK:
1139 return;
1140
1141 case llvm::bitc::ENTER_SUBBLOCK:
1142 // No known subblocks, always skip them.
1143 Stream.ReadSubBlockID();
1144 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001145 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001146 return;
1147 }
1148 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregorc3366a52009-04-21 23:56:24 +00001150 case llvm::bitc::DEFINE_ABBREV:
1151 Stream.ReadAbbrevRecord();
1152 continue;
1153 default: break;
1154 }
1155
1156 // Read a record.
1157 Record.clear();
1158 pch::PreprocessorRecordTypes RecType =
1159 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1160 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001161 case pch::PP_MACRO_OBJECT_LIKE:
1162 case pch::PP_MACRO_FUNCTION_LIKE: {
1163 // If we already have a macro, that means that we've hit the end
1164 // of the definition of the macro we were looking for. We're
1165 // done.
1166 if (Macro)
1167 return;
1168
1169 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1170 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001171 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001172 return;
1173 }
1174 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1175 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001176
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001177 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001178 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001179
Douglas Gregoraae92242010-03-19 21:51:54 +00001180 unsigned NextIndex = 3;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001181 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1182 // Decode function-like macro info.
1183 bool isC99VarArgs = Record[3];
1184 bool isGNUVarArgs = Record[4];
1185 MacroArgs.clear();
1186 unsigned NumArgs = Record[5];
Douglas Gregoraae92242010-03-19 21:51:54 +00001187 NextIndex = 6 + NumArgs;
Douglas Gregorc3366a52009-04-21 23:56:24 +00001188 for (unsigned i = 0; i != NumArgs; ++i)
1189 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1190
1191 // Install function-like macro info.
1192 MI->setIsFunctionLike();
1193 if (isC99VarArgs) MI->setIsC99Varargs();
1194 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001195 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001196 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001197 }
1198
1199 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001200 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001201
1202 // Remember that we saw this macro last so that we add the tokens that
1203 // form its body to it.
1204 Macro = MI;
Douglas Gregoraae92242010-03-19 21:51:54 +00001205
1206 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1207 // We have a macro definition. Load it now.
1208 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1209 getMacroDefinition(Record[NextIndex]));
1210 }
1211
Douglas Gregorc3366a52009-04-21 23:56:24 +00001212 ++NumMacrosRead;
1213 break;
1214 }
Mike Stump11289f42009-09-09 15:08:12 +00001215
Douglas Gregorc3366a52009-04-21 23:56:24 +00001216 case pch::PP_TOKEN: {
1217 // If we see a TOKEN before a PP_MACRO_*, then the file is
1218 // erroneous, just pretend we didn't see this.
1219 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001220
Douglas Gregorc3366a52009-04-21 23:56:24 +00001221 Token Tok;
1222 Tok.startToken();
1223 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1224 Tok.setLength(Record[1]);
1225 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1226 Tok.setIdentifierInfo(II);
1227 Tok.setKind((tok::TokenKind)Record[3]);
1228 Tok.setFlag((Token::TokenFlags)Record[4]);
1229 Macro->AddTokenToBody(Tok);
1230 break;
1231 }
Douglas Gregoraae92242010-03-19 21:51:54 +00001232
1233 case pch::PP_MACRO_INSTANTIATION: {
1234 // If we already have a macro, that means that we've hit the end
1235 // of the definition of the macro we were looking for. We're
1236 // done.
1237 if (Macro)
1238 return;
1239
1240 if (!PP->getPreprocessingRecord()) {
1241 Error("missing preprocessing record in PCH file");
1242 return;
1243 }
1244
1245 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1246 if (PPRec.getPreprocessedEntity(Record[0]))
1247 return;
1248
1249 MacroInstantiation *MI
1250 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1251 SourceRange(
1252 SourceLocation::getFromRawEncoding(Record[1]),
1253 SourceLocation::getFromRawEncoding(Record[2])),
1254 getMacroDefinition(Record[4]));
1255 PPRec.SetPreallocatedEntity(Record[0], MI);
1256 return;
1257 }
1258
1259 case pch::PP_MACRO_DEFINITION: {
1260 // If we already have a macro, that means that we've hit the end
1261 // of the definition of the macro we were looking for. We're
1262 // done.
1263 if (Macro)
1264 return;
1265
1266 if (!PP->getPreprocessingRecord()) {
1267 Error("missing preprocessing record in PCH file");
1268 return;
1269 }
1270
1271 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1272 if (PPRec.getPreprocessedEntity(Record[0]))
1273 return;
1274
1275 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1276 Error("out-of-bounds macro definition record");
1277 return;
1278 }
1279
1280 MacroDefinition *MD
1281 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1282 SourceLocation::getFromRawEncoding(Record[5]),
1283 SourceRange(
1284 SourceLocation::getFromRawEncoding(Record[2]),
1285 SourceLocation::getFromRawEncoding(Record[3])));
1286 PPRec.SetPreallocatedEntity(Record[0], MD);
1287 MacroDefinitionsLoaded[Record[1]] = MD;
1288 return;
1289 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001290 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001291 }
1292}
1293
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001294void PCHReader::ReadDefinedMacros() {
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001295 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1296 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl34522812010-07-16 17:50:48 +00001297
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001298 // If there was no preprocessor block, skip this file.
1299 if (!MacroCursor.getBitStreamReader())
1300 continue;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001301
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001302 llvm::BitstreamCursor Cursor = MacroCursor;
1303 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1304 Error("malformed preprocessor block record in PCH file");
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001305 return;
1306 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001307
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001308 RecordData Record;
1309 while (true) {
1310 unsigned Code = Cursor.ReadCode();
1311 if (Code == llvm::bitc::END_BLOCK) {
1312 if (Cursor.ReadBlockEnd()) {
1313 Error("error at end of preprocessor block in PCH file");
1314 return;
1315 }
1316 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001317 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001318
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001319 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1320 // No known subblocks, always skip them.
1321 Cursor.ReadSubBlockID();
1322 if (Cursor.SkipBlock()) {
1323 Error("malformed block record in PCH file");
1324 return;
1325 }
1326 continue;
1327 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001328
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001329 if (Code == llvm::bitc::DEFINE_ABBREV) {
1330 Cursor.ReadAbbrevRecord();
1331 continue;
1332 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001333
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001334 // Read a record.
1335 const char *BlobStart;
1336 unsigned BlobLen;
1337 Record.clear();
1338 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1339 default: // Default behavior: ignore.
1340 break;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001341
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001342 case pch::PP_MACRO_OBJECT_LIKE:
1343 case pch::PP_MACRO_FUNCTION_LIKE:
1344 DecodeIdentifierInfo(Record[0]);
1345 break;
1346
1347 case pch::PP_TOKEN:
1348 // Ignore tokens.
1349 break;
Douglas Gregoraae92242010-03-19 21:51:54 +00001350
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001351 case pch::PP_MACRO_INSTANTIATION:
1352 case pch::PP_MACRO_DEFINITION:
1353 // Read the macro record.
1354 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1355 break;
1356 }
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001357 }
1358 }
1359}
1360
Douglas Gregoraae92242010-03-19 21:51:54 +00001361MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1362 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1363 return 0;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001364
1365 if (!MacroDefinitionsLoaded[ID]) {
1366 unsigned Index = ID;
1367 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1368 PerFileData &F = *Chain[N - I - 1];
1369 if (Index < F.LocalNumMacroDefinitions) {
1370 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1371 break;
1372 }
1373 Index -= F.LocalNumMacroDefinitions;
1374 }
1375 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1376 }
1377
Douglas Gregoraae92242010-03-19 21:51:54 +00001378 return MacroDefinitionsLoaded[ID];
1379}
1380
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001381/// \brief If we are loading a relocatable PCH file, and the filename is
1382/// not an absolute path, add the system root to the beginning of the file
1383/// name.
1384void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1385 // If this is not a relocatable PCH file, there's nothing to do.
1386 if (!RelocatablePCH)
1387 return;
Mike Stump11289f42009-09-09 15:08:12 +00001388
Daniel Dunbarf2ce9a22009-11-18 19:50:41 +00001389 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001390 return;
1391
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001392 if (isysroot == 0) {
1393 // If no system root was given, default to '/'
1394 Filename.insert(Filename.begin(), '/');
1395 return;
1396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001398 unsigned Length = strlen(isysroot);
1399 if (isysroot[Length - 1] != '/')
1400 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001401
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001402 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1403}
1404
Mike Stump11289f42009-09-09 15:08:12 +00001405PCHReader::PCHReadResult
Sebastian Redl2abc0382010-07-16 20:41:52 +00001406PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl34522812010-07-16 17:50:48 +00001407 llvm::BitstreamCursor &Stream = F.Stream;
1408
Douglas Gregor55abb232009-04-10 20:39:37 +00001409 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001410 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001411 return Failure;
1412 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001413
1414 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001415 RecordData Record;
Sebastian Redl393f8b72010-07-19 20:52:06 +00001416 bool First = true;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001417 while (!Stream.AtEndOfStream()) {
1418 unsigned Code = Stream.ReadCode();
1419 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001420 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001421 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001422 return Failure;
1423 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001424
Douglas Gregor55abb232009-04-10 20:39:37 +00001425 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001426 }
1427
1428 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1429 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001430 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001431 // We lazily load the decls block, but we want to set up the
1432 // DeclsCursor cursor to point into it. Clone our current bitcode
1433 // cursor to it, enter the block and read the abbrevs in that block.
1434 // With the main cursor, we just skip over it.
Sebastian Redl34522812010-07-16 17:50:48 +00001435 F.DeclsCursor = Stream;
Chris Lattnere78a6be2009-04-27 01:05:14 +00001436 if (Stream.SkipBlock() || // Skip with the main cursor.
1437 // Read the abbrevs.
Sebastian Redl34522812010-07-16 17:50:48 +00001438 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001439 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001440 return Failure;
1441 }
1442 break;
Mike Stump11289f42009-09-09 15:08:12 +00001443
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001444 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl34522812010-07-16 17:50:48 +00001445 F.MacroCursor = Stream;
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001446 if (PP)
1447 PP->setExternalSource(this);
1448
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001449 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001450 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001451 return Failure;
1452 }
1453 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001454
Douglas Gregora7f71a92009-04-10 03:52:48 +00001455 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001456 switch (ReadSourceManagerBlock(F)) {
Douglas Gregor92863e42009-04-10 23:10:45 +00001457 case Success:
1458 break;
1459
1460 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001461 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001462 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001463
1464 case IgnorePCH:
1465 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001466 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001467 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001468 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001469 First = false;
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001470 continue;
1471 }
1472
1473 if (Code == llvm::bitc::DEFINE_ABBREV) {
1474 Stream.ReadAbbrevRecord();
1475 continue;
1476 }
1477
1478 // Read and process a record.
1479 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001480 const char *BlobStart = 0;
1481 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001482 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001483 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001484 default: // Default behavior: ignore.
1485 break;
1486
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001487 case pch::METADATA: {
Douglas Gregorce3a8292010-07-27 00:27:13 +00001488 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001489 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1490 : diag::warn_pch_version_too_new);
1491 return IgnorePCH;
1492 }
1493
1494 RelocatablePCH = Record[4];
1495 if (Listener) {
1496 std::string TargetTriple(BlobStart, BlobLen);
1497 if (Listener->ReadTargetTriple(TargetTriple))
1498 return IgnorePCH;
1499 }
1500 break;
1501 }
1502
1503 case pch::CHAINED_METADATA: {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001504 if (!First) {
1505 Error("CHAINED_METADATA is not first record in block");
1506 return Failure;
1507 }
Douglas Gregorce3a8292010-07-27 00:27:13 +00001508 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001509 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1510 : diag::warn_pch_version_too_new);
1511 return IgnorePCH;
1512 }
1513
1514 // Load the chained file.
1515 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1516 case Failure: return Failure;
1517 // If we have to ignore the dependency, we'll have to ignore this too.
1518 case IgnorePCH: return IgnorePCH;
1519 case Success: break;
1520 }
1521 break;
1522 }
1523
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001524 case pch::TYPE_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001525 if (F.LocalNumTypes != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001526 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001527 return Failure;
1528 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001529 F.TypeOffsets = (const uint32_t *)BlobStart;
1530 F.LocalNumTypes = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001531 break;
1532
1533 case pch::DECL_OFFSET:
Sebastian Redl9e687992010-07-19 22:06:55 +00001534 if (F.LocalNumDecls != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001535 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001536 return Failure;
1537 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001538 F.DeclOffsets = (const uint32_t *)BlobStart;
1539 F.LocalNumDecls = Record[0];
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001540 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001541
Sebastian Redl4b1f4902010-07-27 18:24:41 +00001542 case pch::TU_UPDATE_LEXICAL: {
1543 DeclContextInfo Info = {
1544 /* No visible information */ 0, 0,
1545 reinterpret_cast<const pch::DeclID *>(BlobStart),
1546 BlobLen / sizeof(pch::DeclID)
1547 };
1548 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1549 break;
1550 }
1551
Douglas Gregor55abb232009-04-10 20:39:37 +00001552 case pch::LANGUAGE_OPTIONS:
Douglas Gregorce3a8292010-07-27 00:27:13 +00001553 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor55abb232009-04-10 20:39:37 +00001554 return IgnorePCH;
1555 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001556
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001557 case pch::IDENTIFIER_TABLE:
Sebastian Redl393f8b72010-07-19 20:52:06 +00001558 F.IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001559 if (Record[0]) {
Sebastian Redl393f8b72010-07-19 20:52:06 +00001560 F.IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001561 = PCHIdentifierLookupTable::Create(
Sebastian Redl393f8b72010-07-19 20:52:06 +00001562 (const unsigned char *)F.IdentifierTableData + Record[0],
1563 (const unsigned char *)F.IdentifierTableData,
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001564 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001565 if (PP)
1566 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001567 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001568 break;
1569
1570 case pch::IDENTIFIER_OFFSET:
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001571 if (F.LocalNumIdentifiers != 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001572 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001573 return Failure;
1574 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001575 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1576 F.LocalNumIdentifiers = Record[0];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001577 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001578
1579 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001580 // Optimization for the first block.
1581 if (ExternalDefinitions.empty())
1582 ExternalDefinitions.swap(Record);
1583 else
1584 ExternalDefinitions.insert(ExternalDefinitions.end(),
1585 Record.begin(), Record.end());
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001586 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001587
Douglas Gregor652d82a2009-04-18 05:55:16 +00001588 case pch::SPECIAL_TYPES:
Sebastian Redlb293a452010-07-20 21:20:32 +00001589 // Optimization for the first block
1590 if (SpecialTypes.empty())
1591 SpecialTypes.swap(Record);
1592 else
1593 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregor652d82a2009-04-18 05:55:16 +00001594 break;
1595
Douglas Gregor08f01292009-04-17 22:13:46 +00001596 case pch::STATISTICS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001597 TotalNumStatements += Record[0];
1598 TotalNumMacros += Record[1];
1599 TotalLexicalDeclContexts += Record[2];
1600 TotalVisibleDeclContexts += Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001601 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001602
Douglas Gregord4df8652009-04-22 22:02:47 +00001603 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001604 // Optimization for the first block.
1605 if (TentativeDefinitions.empty())
1606 TentativeDefinitions.swap(Record);
1607 else
1608 TentativeDefinitions.insert(TentativeDefinitions.end(),
1609 Record.begin(), Record.end());
Douglas Gregord4df8652009-04-22 22:02:47 +00001610 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001611
Tanya Lattner90073802010-02-12 00:07:30 +00001612 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001613 // Optimization for the first block.
1614 if (UnusedStaticFuncs.empty())
1615 UnusedStaticFuncs.swap(Record);
1616 else
1617 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1618 Record.begin(), Record.end());
Tanya Lattner90073802010-02-12 00:07:30 +00001619 break;
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001620
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001621 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001622 // Optimization for the first block.
1623 if (LocallyScopedExternalDecls.empty())
1624 LocallyScopedExternalDecls.swap(Record);
1625 else
1626 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1627 Record.begin(), Record.end());
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001628 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001629
Douglas Gregor95c13f52009-04-25 17:48:32 +00001630 case pch::SELECTOR_OFFSETS:
1631 SelectorOffsets = (const uint32_t *)BlobStart;
1632 TotalNumSelectors = Record[0];
1633 SelectorsLoaded.resize(TotalNumSelectors);
1634 break;
1635
Douglas Gregorc78d3462009-04-24 21:10:55 +00001636 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001637 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1638 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001639 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001640 = PCHMethodPoolLookupTable::Create(
1641 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001642 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001643 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001644 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001645 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001646
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001647 case pch::REFERENCED_SELECTOR_POOL: {
1648 unsigned int numEl = Record[0]*2;
1649 for (unsigned int i = 1; i <= numEl; i++)
1650 F.ReferencedSelectorsData.push_back(Record[i]);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001651 break;
Sebastian Redl66c5eef2010-07-27 00:17:23 +00001652 }
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001653
Douglas Gregoreda6a892009-04-26 00:07:37 +00001654 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001655 if (!Record.empty() && Listener)
1656 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001657 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001658
1659 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redlb293a452010-07-20 21:20:32 +00001660 F.SLocOffsets = (const uint32_t *)BlobStart;
1661 F.LocalNumSLocEntries = Record[0];
1662 // We cannot delay this until all PCHs are loaded, because then source
1663 // location preloads would also have to be delayed.
1664 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001665 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001666 break;
1667
1668 case pch::SOURCE_LOCATION_PRELOADS:
1669 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1670 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1671 if (Result != Success)
1672 return Result;
1673 }
1674 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001675
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001676 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001677 PCHStatCache *MyStatCache =
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001678 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1679 (const unsigned char *)BlobStart,
1680 NumStatHits, NumStatMisses);
1681 FileMgr.addStatCache(MyStatCache);
Sebastian Redl34522812010-07-16 17:50:48 +00001682 F.StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001683 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001684 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001685
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001686 case pch::EXT_VECTOR_DECLS:
1687 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001688 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001689 return Failure;
1690 }
1691 ExtVectorDecls.swap(Record);
1692 break;
1693
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00001694 case pch::VTABLE_USES:
1695 if (!VTableUses.empty()) {
1696 Error("duplicate VTABLE_USES record in PCH file");
1697 return Failure;
1698 }
1699 VTableUses.swap(Record);
1700 break;
1701
1702 case pch::DYNAMIC_CLASSES:
1703 if (!DynamicClasses.empty()) {
1704 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1705 return Failure;
1706 }
1707 DynamicClasses.swap(Record);
1708 break;
1709
Douglas Gregor45fe0362009-05-12 01:31:05 +00001710 case pch::ORIGINAL_FILE_NAME:
Sebastian Redlb293a452010-07-20 21:20:32 +00001711 // The primary PCH will be the last to get here, so it will be the one
1712 // that's used.
Daniel Dunbar000c4ff2009-11-11 05:29:04 +00001713 ActualOriginalFileName.assign(BlobStart, BlobLen);
1714 OriginalFileName = ActualOriginalFileName;
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001715 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001716 break;
Mike Stump11289f42009-09-09 15:08:12 +00001717
Ted Kremenek17437132010-01-22 20:59:36 +00001718 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek8bd09292010-02-12 23:31:14 +00001719 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek2377a0e2010-01-22 20:55:35 +00001720 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001721 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregord54f3a12009-10-05 21:07:28 +00001722 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1723 return IgnorePCH;
1724 }
1725 break;
1726 }
Sebastian Redlfa061442010-07-21 20:07:32 +00001727
Douglas Gregoraae92242010-03-19 21:51:54 +00001728 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redlfa061442010-07-21 20:07:32 +00001729 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1730 F.NumPreallocatedPreprocessingEntities = Record[0];
1731 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregoraae92242010-03-19 21:51:54 +00001732 break;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001733 }
Sebastian Redl393f8b72010-07-19 20:52:06 +00001734 First = false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001735 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001736 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001737 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001738}
1739
Douglas Gregor92863e42009-04-10 23:10:45 +00001740PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001741 switch(ReadPCHCore(FileName)) {
Sebastian Redl2abc0382010-07-16 20:41:52 +00001742 case Failure: return Failure;
1743 case IgnorePCH: return IgnorePCH;
1744 case Success: break;
1745 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001746
1747 // Here comes stuff that we only do once the entire chain is loaded.
1748
Sebastian Redlb293a452010-07-20 21:20:32 +00001749 // Allocate space for loaded identifiers, decls and types.
Sebastian Redlfa061442010-07-21 20:07:32 +00001750 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
1751 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0;
Sebastian Redl9e687992010-07-19 22:06:55 +00001752 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001753 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl9e687992010-07-19 22:06:55 +00001754 TotalNumTypes += Chain[I]->LocalNumTypes;
1755 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redlfa061442010-07-21 20:07:32 +00001756 TotalNumPreallocatedPreprocessingEntities +=
1757 Chain[I]->NumPreallocatedPreprocessingEntities;
1758 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redl9e687992010-07-19 22:06:55 +00001759 }
Sebastian Redlbd1b5be2010-07-19 22:28:42 +00001760 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl9e687992010-07-19 22:06:55 +00001761 TypesLoaded.resize(TotalNumTypes);
1762 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redlfa061442010-07-21 20:07:32 +00001763 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1764 if (PP) {
1765 if (TotalNumIdentifiers > 0)
1766 PP->getHeaderSearchInfo().SetExternalLookup(this);
1767 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1768 if (!PP->getPreprocessingRecord())
1769 PP->createPreprocessingRecord();
1770 PP->getPreprocessingRecord()->SetExternalSource(*this,
1771 TotalNumPreallocatedPreprocessingEntities);
1772 }
1773 }
Sebastian Redl9e687992010-07-19 22:06:55 +00001774
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001775 // Check the predefines buffers.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001776 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001777 return IgnorePCH;
1778
1779 if (PP) {
1780 // Initialization of keywords and pragmas occurs before the
1781 // PCH file is read, so there may be some identifiers that were
1782 // loaded into the IdentifierTable before we intercepted the
1783 // creation of identifiers. Iterate through the list of known
1784 // identifiers and determine whether we have to establish
1785 // preprocessor definitions or top-level identifier declaration
1786 // chains for those identifiers.
1787 //
1788 // We copy the IdentifierInfo pointers to a small vector first,
1789 // since de-serializing declarations or macro definitions can add
1790 // new entries into the identifier table, invalidating the
1791 // iterators.
1792 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1793 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1794 IdEnd = PP->getIdentifierTable().end();
1795 Id != IdEnd; ++Id)
1796 Identifiers.push_back(Id->second);
Sebastian Redlfa061442010-07-21 20:07:32 +00001797 // We need to search the tables in all files.
1798 // FIXME: What happens if this stuff changes between files, e.g. the
1799 // dependent PCH undefs a macro from the core file?
1800 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1801 PCHIdentifierLookupTable *IdTable
1802 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl5c415f32010-07-22 17:01:13 +00001803 // Not all PCH files necessarily have identifier tables, only the useful
1804 // ones.
1805 if (!IdTable)
1806 continue;
Sebastian Redlfa061442010-07-21 20:07:32 +00001807 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1808 IdentifierInfo *II = Identifiers[I];
1809 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redl4e6c5672010-07-21 22:31:37 +00001810 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redlfa061442010-07-21 20:07:32 +00001811 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redlb293a452010-07-20 21:20:32 +00001812 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1813 if (Pos == IdTable->end())
1814 continue;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001815
Sebastian Redlb293a452010-07-20 21:20:32 +00001816 // Dereferencing the iterator has the effect of populating the
1817 // IdentifierInfo node with the various declarations it needs.
1818 (void)*Pos;
1819 }
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001820 }
1821 }
1822
1823 if (Context)
1824 InitializeContext(*Context);
1825
1826 return Success;
1827}
1828
1829PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1830 Chain.push_back(new PerFileData());
Sebastian Redl34522812010-07-16 17:50:48 +00001831 PerFileData &F = *Chain.back();
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001832
1833 // Set the PCH file name.
1834 F.FileName = FileName;
1835
1836 // Open the PCH file.
1837 //
1838 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1839 std::string ErrStr;
1840 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1841 if (!F.Buffer) {
1842 Error(ErrStr.c_str());
1843 return IgnorePCH;
1844 }
1845
1846 // Initialize the stream
1847 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1848 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl34522812010-07-16 17:50:48 +00001849 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001850 Stream.init(F.StreamFile);
Sebastian Redlfa061442010-07-21 20:07:32 +00001851 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlc2e6dbf2010-07-17 00:12:06 +00001852
1853 // Sniff for the signature.
1854 if (Stream.Read(8) != 'C' ||
1855 Stream.Read(8) != 'P' ||
1856 Stream.Read(8) != 'C' ||
1857 Stream.Read(8) != 'H') {
1858 Diag(diag::err_not_a_pch_file) << FileName;
1859 return Failure;
1860 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001861
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001862 while (!Stream.AtEndOfStream()) {
1863 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001864
Douglas Gregor92863e42009-04-10 23:10:45 +00001865 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001866 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001867 return Failure;
1868 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001869
1870 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001871
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001872 // We only know the PCH subblock ID.
1873 switch (BlockID) {
1874 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001875 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001876 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001877 return Failure;
1878 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001879 break;
1880 case pch::PCH_BLOCK_ID:
Sebastian Redl2abc0382010-07-16 20:41:52 +00001881 switch (ReadPCHBlock(F)) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001882 case Success:
1883 break;
1884
1885 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001886 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001887
1888 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001889 // FIXME: We could consider reading through to the end of this
1890 // PCH block, skipping subblocks, to see if there are other
1891 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001892
1893 // Clear out any preallocated source location entries, so that
1894 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001895 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001896
1897 // Remove the stat cache.
Sebastian Redl34522812010-07-16 17:50:48 +00001898 if (F.StatCache)
1899 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001900
Douglas Gregor92863e42009-04-10 23:10:45 +00001901 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001902 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001903 break;
1904 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001905 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001906 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001907 return Failure;
1908 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001909 break;
1910 }
Mike Stump11289f42009-09-09 15:08:12 +00001911 }
1912
Sebastian Redl2abc0382010-07-16 20:41:52 +00001913 return Success;
1914}
1915
Douglas Gregoraae92242010-03-19 21:51:54 +00001916void PCHReader::setPreprocessor(Preprocessor &pp) {
1917 PP = &pp;
Sebastian Redlfa061442010-07-21 20:07:32 +00001918
1919 unsigned TotalNum = 0;
1920 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1921 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1922 if (TotalNum) {
Douglas Gregoraae92242010-03-19 21:51:54 +00001923 if (!PP->getPreprocessingRecord())
1924 PP->createPreprocessingRecord();
Sebastian Redlfa061442010-07-21 20:07:32 +00001925 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregoraae92242010-03-19 21:51:54 +00001926 }
1927}
1928
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001929void PCHReader::InitializeContext(ASTContext &Ctx) {
1930 Context = &Ctx;
1931 assert(Context && "Passed null context!");
1932
1933 assert(PP && "Forgot to set Preprocessor ?");
1934 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1935 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor9882a5a2010-01-04 19:18:44 +00001936 PP->setExternalSource(this);
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00001937
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001938 // Load the translation unit declaration
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00001939 GetTranslationUnitDecl();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001940
1941 // Load the special types.
1942 Context->setBuiltinVaListType(
1943 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1944 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1945 Context->setObjCIdType(GetType(Id));
1946 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1947 Context->setObjCSelType(GetType(Sel));
1948 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1949 Context->setObjCProtoType(GetType(Proto));
1950 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1951 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001952
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001953 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1954 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001955 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001956 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1957 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001958 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1959 QualType FileType = GetType(File);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001960 if (FileType.isNull()) {
1961 Error("FILE type is NULL");
1962 return;
1963 }
John McCall9dd450b2009-09-21 23:43:11 +00001964 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001965 Context->setFILEDecl(Typedef->getDecl());
1966 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001967 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001968 if (!Tag) {
1969 Error("Invalid FILE type in PCH file");
1970 return;
1971 }
Douglas Gregor27821ce2009-07-07 16:35:42 +00001972 Context->setFILEDecl(Tag->getDecl());
1973 }
1974 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001975 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1976 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001977 if (Jmp_bufType.isNull()) {
1978 Error("jmp_bug type is NULL");
1979 return;
1980 }
John McCall9dd450b2009-09-21 23:43:11 +00001981 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001982 Context->setjmp_bufDecl(Typedef->getDecl());
1983 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001984 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001985 if (!Tag) {
1986 Error("Invalid jmp_bug type in PCH file");
1987 return;
1988 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001989 Context->setjmp_bufDecl(Tag->getDecl());
1990 }
1991 }
1992 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1993 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenek1ff615c2010-03-18 00:56:54 +00001994 if (Sigjmp_bufType.isNull()) {
1995 Error("sigjmp_buf type is NULL");
1996 return;
1997 }
John McCall9dd450b2009-09-21 23:43:11 +00001998 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001999 Context->setsigjmp_bufDecl(Typedef->getDecl());
2000 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002001 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00002002 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2003 Context->setsigjmp_bufDecl(Tag->getDecl());
2004 }
2005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00002007 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2008 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00002009 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00002010 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2011 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00002012 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2013 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00002014 if (unsigned String
2015 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2016 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002017 if (unsigned ObjCSelRedef
2018 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2019 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2020 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2021 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +00002022
2023 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2024 Context->setInt128Installed();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002025}
2026
Douglas Gregor45fe0362009-05-12 01:31:05 +00002027/// \brief Retrieve the name of the original source file name
2028/// directly from the PCH file, without actually loading the PCH
2029/// file.
Daniel Dunbar3b951482009-12-03 09:13:06 +00002030std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2031 Diagnostic &Diags) {
Douglas Gregor45fe0362009-05-12 01:31:05 +00002032 // Open the PCH file.
2033 std::string ErrStr;
2034 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2035 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2036 if (!Buffer) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002037 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002038 return std::string();
2039 }
2040
2041 // Initialize the stream
2042 llvm::BitstreamReader StreamFile;
2043 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00002044 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00002045 (const unsigned char *)Buffer->getBufferEnd());
2046 Stream.init(StreamFile);
2047
2048 // Sniff for the signature.
2049 if (Stream.Read(8) != 'C' ||
2050 Stream.Read(8) != 'P' ||
2051 Stream.Read(8) != 'C' ||
2052 Stream.Read(8) != 'H') {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002053 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002054 return std::string();
2055 }
2056
2057 RecordData Record;
2058 while (!Stream.AtEndOfStream()) {
2059 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00002060
Douglas Gregor45fe0362009-05-12 01:31:05 +00002061 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2062 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00002063
Douglas Gregor45fe0362009-05-12 01:31:05 +00002064 // We only know the PCH subblock ID.
2065 switch (BlockID) {
2066 case pch::PCH_BLOCK_ID:
2067 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002068 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002069 return std::string();
2070 }
2071 break;
Mike Stump11289f42009-09-09 15:08:12 +00002072
Douglas Gregor45fe0362009-05-12 01:31:05 +00002073 default:
2074 if (Stream.SkipBlock()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002075 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002076 return std::string();
2077 }
2078 break;
2079 }
2080 continue;
2081 }
2082
2083 if (Code == llvm::bitc::END_BLOCK) {
2084 if (Stream.ReadBlockEnd()) {
Daniel Dunbar3b951482009-12-03 09:13:06 +00002085 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregor45fe0362009-05-12 01:31:05 +00002086 return std::string();
2087 }
2088 continue;
2089 }
2090
2091 if (Code == llvm::bitc::DEFINE_ABBREV) {
2092 Stream.ReadAbbrevRecord();
2093 continue;
2094 }
2095
2096 Record.clear();
2097 const char *BlobStart = 0;
2098 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002099 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00002100 == pch::ORIGINAL_FILE_NAME)
2101 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00002102 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00002103
2104 return std::string();
2105}
2106
Douglas Gregor55abb232009-04-10 20:39:37 +00002107/// \brief Parse the record that corresponds to a LangOptions data
2108/// structure.
2109///
2110/// This routine compares the language options used to generate the
2111/// PCH file against the language options set for the current
2112/// compilation. For each option, we classify differences between the
2113/// two compiler states as either "benign" or "important". Benign
2114/// differences don't matter, and we accept them without complaint
2115/// (and without modifying the language options). Differences between
2116/// the states for important options cause the PCH file to be
2117/// unusable, so we emit a warning and return true to indicate that
2118/// there was an error.
2119///
2120/// \returns true if the PCH file is unacceptable, false otherwise.
2121bool PCHReader::ParseLanguageOptions(
2122 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002123 if (Listener) {
2124 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00002125
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002126 #define PARSE_LANGOPT(Option) \
2127 LangOpts.Option = Record[Idx]; \
2128 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00002129
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002130 unsigned Idx = 0;
2131 PARSE_LANGOPT(Trigraphs);
2132 PARSE_LANGOPT(BCPLComment);
2133 PARSE_LANGOPT(DollarIdents);
2134 PARSE_LANGOPT(AsmPreprocessor);
2135 PARSE_LANGOPT(GNUMode);
Chandler Carruthe03aa552010-04-17 20:17:31 +00002136 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002137 PARSE_LANGOPT(ImplicitInt);
2138 PARSE_LANGOPT(Digraphs);
2139 PARSE_LANGOPT(HexFloats);
2140 PARSE_LANGOPT(C99);
2141 PARSE_LANGOPT(Microsoft);
2142 PARSE_LANGOPT(CPlusPlus);
2143 PARSE_LANGOPT(CPlusPlus0x);
2144 PARSE_LANGOPT(CXXOperatorNames);
2145 PARSE_LANGOPT(ObjC1);
2146 PARSE_LANGOPT(ObjC2);
2147 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian45878032010-02-09 19:31:38 +00002148 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian62c56022010-04-22 21:01:59 +00002149 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002150 PARSE_LANGOPT(PascalStrings);
2151 PARSE_LANGOPT(WritableStrings);
2152 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00002153 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002154 PARSE_LANGOPT(Exceptions);
Daniel Dunbar925152c2010-02-10 18:48:44 +00002155 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002156 PARSE_LANGOPT(NeXTRuntime);
2157 PARSE_LANGOPT(Freestanding);
2158 PARSE_LANGOPT(NoBuiltin);
2159 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00002160 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002161 PARSE_LANGOPT(Blocks);
2162 PARSE_LANGOPT(EmitAllDecls);
2163 PARSE_LANGOPT(MathErrno);
Chris Lattner51924e512010-06-26 21:25:03 +00002164 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2165 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002166 PARSE_LANGOPT(HeinousExtensions);
2167 PARSE_LANGOPT(Optimize);
2168 PARSE_LANGOPT(OptimizeSize);
2169 PARSE_LANGOPT(Static);
2170 PARSE_LANGOPT(PICLevel);
2171 PARSE_LANGOPT(GNUInline);
2172 PARSE_LANGOPT(NoInline);
2173 PARSE_LANGOPT(AccessControl);
2174 PARSE_LANGOPT(CharIsSigned);
John Thompsoned4e2952009-11-05 20:14:16 +00002175 PARSE_LANGOPT(ShortWChar);
Chris Lattner51924e512010-06-26 21:25:03 +00002176 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2177 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbar143021e2009-09-21 04:16:19 +00002178 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattner51924e512010-06-26 21:25:03 +00002179 Record[Idx++]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002180 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00002181 PARSE_LANGOPT(OpenCL);
Mike Stumpd9546382009-12-12 01:27:46 +00002182 PARSE_LANGOPT(CatchUndefined);
2183 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002184 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00002185
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002186 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00002187 }
Douglas Gregor55abb232009-04-10 20:39:37 +00002188
2189 return false;
2190}
2191
Douglas Gregoraae92242010-03-19 21:51:54 +00002192void PCHReader::ReadPreprocessedEntities() {
2193 ReadDefinedMacros();
2194}
2195
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002196/// \brief Get the correct cursor and offset for loading a type.
2197PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2198 PerFileData *F = 0;
2199 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2200 F = Chain[N - I - 1];
2201 if (Index < F->LocalNumTypes)
2202 break;
2203 Index -= F->LocalNumTypes;
2204 }
2205 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redlb2831db2010-07-20 22:55:31 +00002206 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002207}
2208
2209/// \brief Read and return the type with the given index..
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002210///
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002211/// The index is the type ID, shifted and minus the number of predefs. This
2212/// routine actually reads the record corresponding to the type at the given
2213/// location. It is a helper routine for GetType, which deals with reading type
2214/// IDs.
2215QualType PCHReader::ReadTypeRecord(unsigned Index) {
2216 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redlb2831db2010-07-20 22:55:31 +00002217 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl34522812010-07-16 17:50:48 +00002218
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002219 // Keep track of where we are in the stream, then jump back there
2220 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00002221 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002222
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002223 ReadingKindTracker ReadingKind(Read_Type, *this);
2224
Douglas Gregor1342e842009-07-06 18:54:52 +00002225 // Note that we are loading a type record.
2226 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002227
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002228 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002229 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00002230 unsigned Code = DeclsCursor.ReadCode();
2231 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00002232 case pch::TYPE_EXT_QUAL: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002233 if (Record.size() != 2) {
2234 Error("Incorrect encoding of extended qualifier type");
2235 return QualType();
2236 }
Douglas Gregor455b8f42009-04-15 22:00:08 +00002237 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00002238 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2239 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00002240 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002241
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002242 case pch::TYPE_COMPLEX: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002243 if (Record.size() != 1) {
2244 Error("Incorrect encoding of complex type");
2245 return QualType();
2246 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002247 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002248 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002249 }
2250
2251 case pch::TYPE_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002252 if (Record.size() != 1) {
2253 Error("Incorrect encoding of pointer type");
2254 return QualType();
2255 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002256 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002257 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002258 }
2259
2260 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002261 if (Record.size() != 1) {
2262 Error("Incorrect encoding of block pointer type");
2263 return QualType();
2264 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002265 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002266 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002267 }
2268
2269 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002270 if (Record.size() != 1) {
2271 Error("Incorrect encoding of lvalue reference type");
2272 return QualType();
2273 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002274 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002275 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002276 }
2277
2278 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002279 if (Record.size() != 1) {
2280 Error("Incorrect encoding of rvalue reference type");
2281 return QualType();
2282 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002283 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002284 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002285 }
2286
2287 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidisee776bc2010-07-02 11:55:15 +00002288 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002289 Error("Incorrect encoding of member pointer type");
2290 return QualType();
2291 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002292 QualType PointeeType = GetType(Record[0]);
2293 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002294 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002295 }
2296
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002297 case pch::TYPE_CONSTANT_ARRAY: {
2298 QualType ElementType = GetType(Record[0]);
2299 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2300 unsigned IndexTypeQuals = Record[2];
2301 unsigned Idx = 3;
2302 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00002303 return Context->getConstantArrayType(ElementType, Size,
2304 ASM, IndexTypeQuals);
2305 }
2306
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002307 case pch::TYPE_INCOMPLETE_ARRAY: {
2308 QualType ElementType = GetType(Record[0]);
2309 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2310 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00002311 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002312 }
2313
2314 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002315 QualType ElementType = GetType(Record[0]);
2316 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2317 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00002318 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2319 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redlc67764e2010-07-22 22:43:28 +00002320 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor04318252009-07-06 15:59:29 +00002321 ASM, IndexTypeQuals,
2322 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002323 }
2324
2325 case pch::TYPE_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002326 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002327 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002328 return QualType();
2329 }
2330
2331 QualType ElementType = GetType(Record[0]);
2332 unsigned NumElements = Record[1];
Chris Lattner37141f42010-06-23 06:00:24 +00002333 unsigned AltiVecSpec = Record[2];
2334 return Context->getVectorType(ElementType, NumElements,
2335 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002336 }
2337
2338 case pch::TYPE_EXT_VECTOR: {
Chris Lattner37141f42010-06-23 06:00:24 +00002339 if (Record.size() != 3) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002340 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002341 return QualType();
2342 }
2343
2344 QualType ElementType = GetType(Record[0]);
2345 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00002346 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002347 }
2348
2349 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002350 if (Record.size() != 4) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002351 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002352 return QualType();
2353 }
2354 QualType ResultType = GetType(Record[0]);
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002355 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002356 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002357 }
2358
2359 case pch::TYPE_FUNCTION_PROTO: {
2360 QualType ResultType = GetType(Record[0]);
Douglas Gregordc728752009-12-22 18:11:50 +00002361 bool NoReturn = Record[1];
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002362 unsigned RegParm = Record[2];
2363 CallingConv CallConv = (CallingConv)Record[3];
2364 unsigned Idx = 4;
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002365 unsigned NumParams = Record[Idx++];
2366 llvm::SmallVector<QualType, 16> ParamTypes;
2367 for (unsigned I = 0; I != NumParams; ++I)
2368 ParamTypes.push_back(GetType(Record[Idx++]));
2369 bool isVariadic = Record[Idx++];
2370 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002371 bool hasExceptionSpec = Record[Idx++];
2372 bool hasAnyExceptionSpec = Record[Idx++];
2373 unsigned NumExceptions = Record[Idx++];
2374 llvm::SmallVector<QualType, 2> Exceptions;
2375 for (unsigned I = 0; I != NumExceptions; ++I)
2376 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00002377 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002378 isVariadic, Quals, hasExceptionSpec,
2379 hasAnyExceptionSpec, NumExceptions,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002380 Exceptions.data(),
Rafael Espindola49b85ab2010-03-30 22:15:11 +00002381 FunctionType::ExtInfo(NoReturn, RegParm,
2382 CallConv));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002383 }
2384
John McCallb96ec562009-12-04 22:46:56 +00002385 case pch::TYPE_UNRESOLVED_USING:
2386 return Context->getTypeDeclType(
2387 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2388
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002389 case pch::TYPE_TYPEDEF: {
2390 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002391 Error("incorrect encoding of typedef type");
2392 return QualType();
2393 }
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002394 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2395 QualType Canonical = GetType(Record[1]);
2396 return Context->getTypedefType(Decl, Canonical);
2397 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002398
2399 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002400 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002401
2402 case pch::TYPE_TYPEOF: {
2403 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002404 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002405 return QualType();
2406 }
2407 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00002408 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002409 }
Mike Stump11289f42009-09-09 15:08:12 +00002410
Anders Carlsson81df7b82009-06-24 19:06:50 +00002411 case pch::TYPE_DECLTYPE:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002412 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson81df7b82009-06-24 19:06:50 +00002413
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002414 case pch::TYPE_RECORD: {
2415 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002416 Error("incorrect encoding of record type");
2417 return QualType();
2418 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002419 bool IsDependent = Record[0];
2420 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2421 T->Dependent = IsDependent;
2422 return T;
2423 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002424
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002425 case pch::TYPE_ENUM: {
2426 if (Record.size() != 2) {
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002427 Error("incorrect encoding of enum type");
2428 return QualType();
2429 }
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002430 bool IsDependent = Record[0];
2431 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2432 T->Dependent = IsDependent;
2433 return T;
2434 }
Douglas Gregor1daeb692009-04-13 18:14:40 +00002435
John McCallfcc33b02009-09-05 00:15:47 +00002436 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002437 unsigned Idx = 0;
2438 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2439 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2440 QualType NamedType = GetType(Record[Idx++]);
2441 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCallfcc33b02009-09-05 00:15:47 +00002442 }
2443
Steve Naroffc277ad12009-07-18 15:33:26 +00002444 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00002445 unsigned Idx = 0;
2446 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002447 return Context->getObjCInterfaceType(ItfD);
2448 }
2449
2450 case pch::TYPE_OBJC_OBJECT: {
2451 unsigned Idx = 0;
2452 QualType Base = GetType(Record[Idx++]);
Chris Lattner587cbe12009-04-22 06:45:28 +00002453 unsigned NumProtos = Record[Idx++];
2454 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2455 for (unsigned I = 0; I != NumProtos; ++I)
2456 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCall8b07ec22010-05-15 11:32:37 +00002457 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00002458 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00002459
Steve Narofffb4330f2009-06-17 22:40:22 +00002460 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00002461 unsigned Idx = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002462 QualType Pointee = GetType(Record[Idx++]);
2463 return Context->getObjCObjectPointerType(Pointee);
Chris Lattner6e054af2009-04-22 06:40:03 +00002464 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00002465
John McCallcebee162009-10-18 09:09:24 +00002466 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2467 unsigned Idx = 0;
2468 QualType Parm = GetType(Record[Idx++]);
2469 QualType Replacement = GetType(Record[Idx++]);
2470 return
2471 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2472 Replacement);
2473 }
John McCalle78aac42010-03-10 03:28:59 +00002474
2475 case pch::TYPE_INJECTED_CLASS_NAME: {
2476 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2477 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidisdab33c52010-07-02 11:55:20 +00002478 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2479 // for PCH reading, too much interdependencies.
2480 return
2481 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCalle78aac42010-03-10 03:28:59 +00002482 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002483
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002484 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2485 unsigned Idx = 0;
2486 unsigned Depth = Record[Idx++];
2487 unsigned Index = Record[Idx++];
2488 bool Pack = Record[Idx++];
2489 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2490 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2491 }
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002492
2493 case pch::TYPE_DEPENDENT_NAME: {
2494 unsigned Idx = 0;
2495 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2496 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2497 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +00002498 QualType Canon = GetType(Record[Idx++]);
2499 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +00002500 }
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002501
2502 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2503 unsigned Idx = 0;
2504 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2505 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2506 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2507 unsigned NumArgs = Record[Idx++];
2508 llvm::SmallVector<TemplateArgument, 8> Args;
2509 Args.reserve(NumArgs);
2510 while (NumArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00002511 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +00002512 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2513 Args.size(), Args.data());
2514 }
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002515
2516 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2517 unsigned Idx = 0;
2518
2519 // ArrayType
2520 QualType ElementType = GetType(Record[Idx++]);
2521 ArrayType::ArraySizeModifier ASM
2522 = (ArrayType::ArraySizeModifier)Record[Idx++];
2523 unsigned IndexTypeQuals = Record[Idx++];
2524
2525 // DependentSizedArrayType
Sebastian Redlc67764e2010-07-22 22:43:28 +00002526 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +00002527 SourceRange Brackets = ReadSourceRange(Record, Idx);
2528
2529 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2530 IndexTypeQuals, Brackets);
2531 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00002532
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002533 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2534 unsigned Idx = 0;
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002535 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002536 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002537 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redlc67764e2010-07-22 22:43:28 +00002538 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00002539 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002540 QualType T;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002541 if (Canon.isNull())
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002542 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2543 Args.size());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002544 else
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +00002545 T = Context->getTemplateSpecializationType(Name, Args.data(),
2546 Args.size(), Canon);
2547 T->Dependent = IsDependent;
2548 return T;
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00002549 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002550 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002551 // Suppress a GCC warning
2552 return QualType();
2553}
2554
John McCall8f115c62009-10-16 21:56:05 +00002555namespace {
2556
2557class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2558 PCHReader &Reader;
Sebastian Redlc67764e2010-07-22 22:43:28 +00002559 llvm::BitstreamCursor &DeclsCursor;
John McCall8f115c62009-10-16 21:56:05 +00002560 const PCHReader::RecordData &Record;
2561 unsigned &Idx;
2562
2563public:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002564 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2565 const PCHReader::RecordData &Record, unsigned &Idx)
2566 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCall8f115c62009-10-16 21:56:05 +00002567
John McCall17001972009-10-18 01:05:36 +00002568 // We want compile-time assurance that we've enumerated all of
2569 // these, so unfortunately we have to declare them first, then
2570 // define them out-of-line.
2571#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002572#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002573 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002574#include "clang/AST/TypeLocNodes.def"
2575
John McCall17001972009-10-18 01:05:36 +00002576 void VisitFunctionTypeLoc(FunctionTypeLoc);
2577 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002578};
2579
2580}
2581
John McCall17001972009-10-18 01:05:36 +00002582void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002583 // nothing to do
2584}
John McCall17001972009-10-18 01:05:36 +00002585void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +00002586 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2587 if (TL.needsExtraLocalData()) {
2588 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2589 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2590 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2591 TL.setModeAttr(Record[Idx++]);
2592 }
John McCall8f115c62009-10-16 21:56:05 +00002593}
John McCall17001972009-10-18 01:05:36 +00002594void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2595 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002596}
John McCall17001972009-10-18 01:05:36 +00002597void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2598 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002599}
John McCall17001972009-10-18 01:05:36 +00002600void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2601 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002602}
John McCall17001972009-10-18 01:05:36 +00002603void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2604 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002605}
John McCall17001972009-10-18 01:05:36 +00002606void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2607 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002608}
John McCall17001972009-10-18 01:05:36 +00002609void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2610 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002611}
John McCall17001972009-10-18 01:05:36 +00002612void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2613 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2614 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002615 if (Record[Idx++])
Sebastian Redlc67764e2010-07-22 22:43:28 +00002616 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor12bfa382009-10-17 00:13:19 +00002617 else
John McCall17001972009-10-18 01:05:36 +00002618 TL.setSizeExpr(0);
2619}
2620void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2621 VisitArrayTypeLoc(TL);
2622}
2623void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2624 VisitArrayTypeLoc(TL);
2625}
2626void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2627 VisitArrayTypeLoc(TL);
2628}
2629void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2630 DependentSizedArrayTypeLoc TL) {
2631 VisitArrayTypeLoc(TL);
2632}
2633void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2634 DependentSizedExtVectorTypeLoc TL) {
2635 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2636}
2637void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2638 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2639}
2640void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2641 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2642}
2643void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2644 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2645 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2646 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCalle6347002009-10-23 01:28:53 +00002647 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall17001972009-10-18 01:05:36 +00002648 }
2649}
2650void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2651 VisitFunctionTypeLoc(TL);
2652}
2653void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2654 VisitFunctionTypeLoc(TL);
2655}
John McCallb96ec562009-12-04 22:46:56 +00002656void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2657 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2658}
John McCall17001972009-10-18 01:05:36 +00002659void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2660 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2661}
2662void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002663 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2664 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2665 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall17001972009-10-18 01:05:36 +00002666}
2667void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +00002668 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2669 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2670 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redlc67764e2010-07-22 22:43:28 +00002671 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002672}
2673void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2674 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2675}
2676void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2677 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2678}
2679void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2680 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2681}
John McCall17001972009-10-18 01:05:36 +00002682void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2683 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2684}
John McCallcebee162009-10-18 09:09:24 +00002685void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2686 SubstTemplateTypeParmTypeLoc TL) {
2687 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2688}
John McCall17001972009-10-18 01:05:36 +00002689void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2690 TemplateSpecializationTypeLoc TL) {
John McCall0ad16662009-10-29 08:12:44 +00002691 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2692 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2693 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2694 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2695 TL.setArgLocInfo(i,
2696 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002697 DeclsCursor, Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002698}
Abramo Bagnara6150c882010-05-11 21:36:43 +00002699void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002700 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2701 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002702}
John McCalle78aac42010-03-10 03:28:59 +00002703void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2704 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2705}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002706void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarad7548482010-05-19 21:37:53 +00002707 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2708 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall17001972009-10-18 01:05:36 +00002709 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2710}
John McCallc392f372010-06-11 00:33:02 +00002711void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2712 DependentTemplateSpecializationTypeLoc TL) {
2713 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2714 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2715 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2716 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2717 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2718 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2719 TL.setArgLocInfo(I,
2720 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002721 DeclsCursor, Record, Idx));
John McCallc392f372010-06-11 00:33:02 +00002722}
John McCall17001972009-10-18 01:05:36 +00002723void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2724 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8b07ec22010-05-15 11:32:37 +00002725}
2726void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2727 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall17001972009-10-18 01:05:36 +00002728 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2729 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2730 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2731 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002732}
John McCallfc93cf92009-10-22 22:37:11 +00002733void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2734 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallfc93cf92009-10-22 22:37:11 +00002735}
John McCall8f115c62009-10-16 21:56:05 +00002736
Sebastian Redlc67764e2010-07-22 22:43:28 +00002737TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2738 const RecordData &Record,
John McCall8f115c62009-10-16 21:56:05 +00002739 unsigned &Idx) {
2740 QualType InfoTy = GetType(Record[Idx++]);
2741 if (InfoTy.isNull())
2742 return 0;
2743
John McCallbcd03502009-12-07 02:54:59 +00002744 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redlc67764e2010-07-22 22:43:28 +00002745 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCallbcd03502009-12-07 02:54:59 +00002746 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCall8f115c62009-10-16 21:56:05 +00002747 TLR.Visit(TL);
John McCallbcd03502009-12-07 02:54:59 +00002748 return TInfo;
John McCall8f115c62009-10-16 21:56:05 +00002749}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002750
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002751QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002752 unsigned FastQuals = ID & Qualifiers::FastMask;
2753 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002754
2755 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2756 QualType T;
2757 switch ((pch::PredefinedTypeIDs)Index) {
2758 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002759 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2760 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002761
2762 case pch::PREDEF_TYPE_CHAR_U_ID:
2763 case pch::PREDEF_TYPE_CHAR_S_ID:
2764 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002765 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002766 break;
2767
Chris Lattner8575daa2009-04-27 21:45:14 +00002768 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2769 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2770 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2771 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2772 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002773 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002774 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2775 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2776 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2777 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2778 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2779 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002780 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002781 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2782 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2783 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2784 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2785 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002786 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002787 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2788 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002789 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2790 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00002791 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002792 }
2793
2794 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002795 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002796 }
2797
2798 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002799 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl409183f2010-07-14 20:26:45 +00002800 if (TypesLoaded[Index].isNull()) {
Sebastian Redl837a6cb2010-07-20 22:37:49 +00002801 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl409183f2010-07-14 20:26:45 +00002802 TypesLoaded[Index]->setFromPCH();
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002803 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002804 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2805 TypesLoaded[Index]);
Sebastian Redl409183f2010-07-14 20:26:45 +00002806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
John McCall8ccfcb52009-09-24 19:53:00 +00002808 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002809}
2810
John McCall0ad16662009-10-29 08:12:44 +00002811TemplateArgumentLocInfo
2812PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redlc67764e2010-07-22 22:43:28 +00002813 llvm::BitstreamCursor &DeclsCursor,
John McCall0ad16662009-10-29 08:12:44 +00002814 const RecordData &Record,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002815 unsigned &Index) {
John McCall0ad16662009-10-29 08:12:44 +00002816 switch (Kind) {
2817 case TemplateArgument::Expression:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002818 return ReadExpr(DeclsCursor);
John McCall0ad16662009-10-29 08:12:44 +00002819 case TemplateArgument::Type:
Sebastian Redlc67764e2010-07-22 22:43:28 +00002820 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002821 case TemplateArgument::Template: {
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002822 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2823 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2824 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002825 }
John McCall0ad16662009-10-29 08:12:44 +00002826 case TemplateArgument::Null:
2827 case TemplateArgument::Integral:
2828 case TemplateArgument::Declaration:
2829 case TemplateArgument::Pack:
2830 return TemplateArgumentLocInfo();
2831 }
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002832 llvm_unreachable("unexpected template argument loc");
John McCall0ad16662009-10-29 08:12:44 +00002833 return TemplateArgumentLocInfo();
2834}
2835
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002836TemplateArgumentLoc
Sebastian Redlc67764e2010-07-22 22:43:28 +00002837PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2838 const RecordData &Record, unsigned &Index) {
2839 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00002840
2841 if (Arg.getKind() == TemplateArgument::Expression) {
2842 if (Record[Index++]) // bool InfoHasSameExpr.
2843 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2844 }
2845 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redlc67764e2010-07-22 22:43:28 +00002846 DeclsCursor,
Argyrios Kyrtzidisd0795b22010-06-28 22:28:35 +00002847 Record, Index));
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00002848}
2849
John McCall75b960e2010-06-01 09:23:16 +00002850Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2851 return GetDecl(ID);
2852}
2853
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002854TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002855 if (!DeclsLoaded[0]) {
Sebastian Redl34627792010-07-20 22:46:15 +00002856 ReadDeclRecord(0);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002857 if (DeserializationListener)
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002858 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002859 }
Argyrios Kyrtzidis7e8996c2010-07-08 17:13:02 +00002860
2861 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2862}
2863
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002864Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002865 if (ID == 0)
2866 return 0;
2867
Douglas Gregor745ed142009-04-25 18:35:21 +00002868 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002869 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002870 return 0;
2871 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002872
Douglas Gregor745ed142009-04-25 18:35:21 +00002873 unsigned Index = ID - 1;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002874 if (!DeclsLoaded[Index]) {
Sebastian Redl34627792010-07-20 22:46:15 +00002875 ReadDeclRecord(Index);
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00002876 if (DeserializationListener)
2877 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2878 }
Douglas Gregor745ed142009-04-25 18:35:21 +00002879
2880 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002881}
2882
Chris Lattner9c28af02009-04-27 05:46:25 +00002883/// \brief Resolve the offset of a statement into a statement.
2884///
2885/// This operation will read a new statement from the external
2886/// source each time it is called, and is meant to be used via a
2887/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall75b960e2010-06-01 09:23:16 +00002888Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl5c415f32010-07-22 17:01:13 +00002889 // Offset here is a global offset across the entire chain.
2890 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2891 PerFileData &F = *Chain[N - I - 1];
2892 if (Offset < F.SizeInBits) {
2893 // Since we know that this statement is part of a decl, make sure to use
2894 // the decl cursor to read it.
2895 F.DeclsCursor.JumpToBit(Offset);
2896 return ReadStmtFromStream(F.DeclsCursor);
2897 }
2898 Offset -= F.SizeInBits;
2899 }
2900 llvm_unreachable("Broken chain");
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002901}
2902
John McCall75b960e2010-06-01 09:23:16 +00002903bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2904 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002905 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002906 "DeclContext has no lexical decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002907
Sebastian Redl5c415f32010-07-22 17:01:13 +00002908 // There might be lexical decls in multiple parts of the chain, for the TU
2909 // at least.
2910 DeclContextInfos &Infos = DeclContextOffsets[DC];
2911 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2912 I != E; ++I) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002913 // IDs can be 0 if this context doesn't contain declarations.
2914 if (!I->LexicalDecls)
Sebastian Redl5c415f32010-07-22 17:01:13 +00002915 continue;
Sebastian Redl5c415f32010-07-22 17:01:13 +00002916
2917 // Load all of the declaration IDs
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002918 for (const pch::DeclID *ID = I->LexicalDecls,
2919 *IDE = ID + I->NumLexicalDecls;
2920 ID != IDE; ++ID)
2921 Decls.push_back(GetDecl(*ID));
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002922 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002923
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002924 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002925 return false;
2926}
2927
John McCall75b960e2010-06-01 09:23:16 +00002928DeclContext::lookup_result
2929PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2930 DeclarationName Name) {
Mike Stump11289f42009-09-09 15:08:12 +00002931 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002932 "DeclContext has no visible decls in storage");
Ted Kremenek1ff615c2010-03-18 00:56:54 +00002933
John McCall75b960e2010-06-01 09:23:16 +00002934 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl5c415f32010-07-22 17:01:13 +00002935 // There might be lexical decls in multiple parts of the chain, for the TU
2936 // and namespaces.
2937 DeclContextInfos &Infos = DeclContextOffsets[DC];
2938 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2939 I != E; ++I) {
2940 uint64_t Offset = I->OffsetToVisibleDecls;
2941 if (Offset == 0)
2942 continue;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002943
Sebastian Redl5c415f32010-07-22 17:01:13 +00002944 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002945
Sebastian Redl5c415f32010-07-22 17:01:13 +00002946 // Keep track of where we are in the stream, then jump back there
2947 // after reading this context.
2948 SavedStreamPosition SavedPosition(DeclsCursor);
2949
2950 // Load the record containing all of the declarations visible in
2951 // this context.
2952 DeclsCursor.JumpToBit(Offset);
2953 RecordData Record;
2954 unsigned Code = DeclsCursor.ReadCode();
2955 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2956 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2957 Error("Expected visible block");
2958 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2959 DeclContext::lookup_iterator());
2960 }
2961
2962 if (Record.empty())
2963 continue;
2964
2965 unsigned Idx = 0;
2966 while (Idx < Record.size()) {
2967 Decls.push_back(VisibleDeclaration());
2968 Decls.back().Name = ReadDeclarationName(Record, Idx);
2969
2970 unsigned Size = Record[Idx++];
2971 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
2972 LoadedDecls.reserve(Size);
2973 for (unsigned J = 0; J < Size; ++J)
2974 LoadedDecls.push_back(Record[Idx++]);
2975 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002976 }
2977
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002978 ++NumVisibleDeclContextsRead;
John McCall75b960e2010-06-01 09:23:16 +00002979
2980 SetExternalVisibleDecls(DC, Decls);
2981 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002982}
2983
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00002984void PCHReader::PassInterestingDeclsToConsumer() {
2985 assert(Consumer);
2986 while (!InterestingDecls.empty()) {
2987 DeclGroupRef DG(InterestingDecls.front());
2988 InterestingDecls.pop_front();
2989 Consumer->HandleTopLevelDecl(DG);
2990 }
2991}
2992
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002993void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002994 this->Consumer = Consumer;
2995
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002996 if (!Consumer)
2997 return;
2998
2999 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003000 // Force deserialization of this decl, which will cause it to be queued for
3001 // passing to the consumer.
Daniel Dunbar865c2a72009-09-17 03:06:44 +00003002 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003003 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00003004
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003005 PassInterestingDeclsToConsumer();
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00003006}
3007
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003008void PCHReader::PrintStats() {
3009 std::fprintf(stderr, "*** PCH Statistics:\n");
3010
Mike Stump11289f42009-09-09 15:08:12 +00003011 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00003012 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00003013 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00003014 unsigned NumDeclsLoaded
3015 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3016 (Decl *)0);
3017 unsigned NumIdentifiersLoaded
3018 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3019 IdentifiersLoaded.end(),
3020 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00003021 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00003022 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3023 SelectorsLoaded.end(),
3024 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00003025
Douglas Gregorc5046832009-04-27 18:38:38 +00003026 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3027 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00003028 if (TotalNumSLocEntries)
3029 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3030 NumSLocEntriesRead, TotalNumSLocEntries,
3031 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00003032 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003033 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00003034 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3035 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3036 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003037 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00003038 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3039 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00003040 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00003041 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00003042 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3043 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003044 if (TotalNumSelectors)
3045 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
3046 NumSelectorsLoaded, TotalNumSelectors,
3047 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
3048 if (TotalNumStatements)
3049 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3050 NumStatementsRead, TotalNumStatements,
3051 ((float)NumStatementsRead/TotalNumStatements * 100));
3052 if (TotalNumMacros)
3053 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3054 NumMacrosRead, TotalNumMacros,
3055 ((float)NumMacrosRead/TotalNumMacros * 100));
3056 if (TotalLexicalDeclContexts)
3057 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3058 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3059 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3060 * 100));
3061 if (TotalVisibleDeclContexts)
3062 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3063 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3064 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3065 * 100));
3066 if (TotalSelectorsInMethodPool) {
3067 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
3068 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
3069 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
3070 * 100));
3071 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
3072 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003073 std::fprintf(stderr, "\n");
3074}
3075
Douglas Gregora868bbd2009-04-21 22:25:48 +00003076void PCHReader::InitializeSema(Sema &S) {
3077 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003078 S.ExternalSource = this;
3079
Douglas Gregor7cd60f72009-04-22 21:15:06 +00003080 // Makes sure any declarations that were deserialized "too early"
3081 // still get added to the identifier's declaration chains.
3082 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3083 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3084 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003085 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00003086 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00003087
3088 // If there were any tentative definitions, deserialize them and add
Sebastian Redl35351a92010-01-31 22:27:38 +00003089 // them to Sema's list of tentative definitions.
Douglas Gregord4df8652009-04-22 22:02:47 +00003090 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3091 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redl35351a92010-01-31 22:27:38 +00003092 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregord4df8652009-04-22 22:02:47 +00003093 }
Kovarththanan Rajaratnam39f2fbd12010-03-07 19:10:13 +00003094
Tanya Lattner90073802010-02-12 00:07:30 +00003095 // If there were any unused static functions, deserialize them and add to
3096 // Sema's list of unused static functions.
3097 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3098 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3099 SemaObj->UnusedStaticFuncs.push_back(FD);
3100 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00003101
3102 // If there were any locally-scoped external declarations,
3103 // deserialize them and add them to Sema's table of locally-scoped
3104 // external declarations.
3105 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3106 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3107 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3108 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00003109
3110 // If there were any ext_vector type declarations, deserialize them
3111 // and add them to Sema's vector of such declarations.
3112 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3113 SemaObj->ExtVectorDecls.push_back(
3114 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00003115
3116 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3117 // Can we cut them down before writing them ?
3118
3119 // If there were any VTable uses, deserialize the information and add it
3120 // to Sema's vector and map of VTable uses.
3121 unsigned Idx = 0;
3122 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3123 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3124 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3125 bool DefinitionRequired = VTableUses[Idx++];
3126 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3127 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3128 }
3129
3130 // If there were any dynamic classes declarations, deserialize them
3131 // and add them to Sema's vector of such declarations.
3132 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3133 SemaObj->DynamicClasses.push_back(
3134 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003135
3136 // If there are @selector references added them to its pool. This is for
3137 // implementation of -Wselector.
3138 PerFileData &F = *Chain[0];
3139 if (!F.ReferencedSelectorsData.empty()) {
3140 unsigned int DataSize = F.ReferencedSelectorsData.size()-1;
3141 unsigned I = 0;
3142 while (I < DataSize) {
3143 Selector Sel = DecodeSelector(F.ReferencedSelectorsData[I++]);
3144 SourceLocation SelLoc =
3145 SourceLocation::getFromRawEncoding(F.ReferencedSelectorsData[I++]);
3146 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3147 }
3148 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00003149}
3150
3151IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003152 // Try to find this name within our on-disk hash tables. We need to aggregate
3153 // the info from all of them.
3154 IdentifierInfo *II = 0;
3155 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3156 PCHIdentifierLookupTable *IdTable
3157 = (PCHIdentifierLookupTable *)Chain[N - I - 1]->IdentifierLookupTable;
Sebastian Redl5c415f32010-07-22 17:01:13 +00003158 if (!IdTable)
3159 continue;
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003160 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3161 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3162 if (Pos == IdTable->end())
3163 continue;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003164
Sebastian Redl4e6c5672010-07-21 22:31:37 +00003165 // Dereferencing the iterator has the effect of building the
3166 // IdentifierInfo node and populating it with the various
3167 // declarations it needs.
3168 II = *Pos;
3169 }
3170 return II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003171}
3172
Mike Stump11289f42009-09-09 15:08:12 +00003173std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00003174PCHReader::ReadMethodPool(Selector Sel) {
3175 if (!MethodPoolLookupTable)
3176 return std::pair<ObjCMethodList, ObjCMethodList>();
3177
3178 // Try to find this selector within our on-disk hash table.
3179 PCHMethodPoolLookupTable *PoolTable
3180 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
3181 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00003182 if (Pos == PoolTable->end()) {
3183 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003184 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00003185 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003186
Douglas Gregor95c13f52009-04-25 17:48:32 +00003187 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003188 return *Pos;
3189}
3190
Douglas Gregor0e149972009-04-25 19:10:14 +00003191void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00003192 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003193 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00003194 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlff4a2952010-07-23 23:49:55 +00003195 if (DeserializationListener)
3196 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003197}
3198
Douglas Gregor1342e842009-07-06 18:54:52 +00003199/// \brief Set the globally-visible declarations associated with the given
3200/// identifier.
3201///
3202/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00003203/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00003204/// them.
3205///
3206/// \param II an IdentifierInfo that refers to one or more globally-visible
3207/// declarations.
3208///
3209/// \param DeclIDs the set of declaration IDs with the name @p II that are
3210/// visible at global scope.
3211///
3212/// \param Nonrecursive should be true to indicate that the caller knows that
3213/// this call is non-recursive, and therefore the globally-visible declarations
3214/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00003215void
3216PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00003217 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3218 bool Nonrecursive) {
3219 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
3220 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3221 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3222 PII.II = II;
3223 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3224 PII.DeclIDs.push_back(DeclIDs[I]);
3225 return;
3226 }
Mike Stump11289f42009-09-09 15:08:12 +00003227
Douglas Gregor1342e842009-07-06 18:54:52 +00003228 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3229 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3230 if (SemaObj) {
3231 // Introduce this declaration into the translation-unit scope
3232 // and add it to the declaration chain for this identifier, so
3233 // that (unqualified) name lookup will find it.
3234 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3235 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3236 } else {
3237 // Queue this declaration so that it will be added to the
3238 // translation unit scope and identifier's declaration chain
3239 // once a Sema object is known.
3240 PreloadedDecls.push_back(D);
3241 }
3242 }
3243}
3244
Chris Lattnerc523d8e2009-04-11 21:15:38 +00003245IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003246 if (ID == 0)
3247 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003248
Sebastian Redlc713b962010-07-21 00:46:22 +00003249 if (IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003250 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003251 return 0;
3252 }
Mike Stump11289f42009-09-09 15:08:12 +00003253
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003254 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redlc713b962010-07-21 00:46:22 +00003255 ID -= 1;
3256 if (!IdentifiersLoaded[ID]) {
3257 unsigned Index = ID;
3258 const char *Str = 0;
3259 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3260 PerFileData *F = Chain[N - I - 1];
3261 if (Index < F->LocalNumIdentifiers) {
3262 uint32_t Offset = F->IdentifierOffsets[Index];
3263 Str = F->IdentifierTableData + Offset;
3264 break;
3265 }
3266 Index -= F->LocalNumIdentifiers;
3267 }
3268 assert(Str && "Broken Chain");
Douglas Gregor5287b4e2009-04-25 21:04:17 +00003269
Douglas Gregorab4df582009-04-28 20:01:51 +00003270 // All of the strings in the PCH file are preceded by a 16-bit
3271 // length. Extract that 16-bit length to avoid having to execute
3272 // strlen().
Ted Kremenekca42a512009-10-23 04:45:31 +00003273 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3274 // unsigned integers. This is important to avoid integer overflow when
3275 // we cast them to 'unsigned'.
Ted Kremenek49c52322009-10-23 03:57:22 +00003276 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregorab4df582009-04-28 20:01:51 +00003277 unsigned StrLen = (((unsigned) StrLenPtr[0])
3278 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redlc713b962010-07-21 00:46:22 +00003279 IdentifiersLoaded[ID]
Kovarththanan Rajaratnama3b09592010-03-12 10:32:27 +00003280 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlff4a2952010-07-23 23:49:55 +00003281 if (DeserializationListener)
3282 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003283 }
Mike Stump11289f42009-09-09 15:08:12 +00003284
Sebastian Redlc713b962010-07-21 00:46:22 +00003285 return IdentifiersLoaded[ID];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003286}
3287
Douglas Gregor258ae542009-04-27 06:38:32 +00003288void PCHReader::ReadSLocEntry(unsigned ID) {
3289 ReadSLocEntryRecord(ID);
3290}
3291
Steve Naroff2ddea052009-04-23 10:39:46 +00003292Selector PCHReader::DecodeSelector(unsigned ID) {
3293 if (ID == 0)
3294 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00003295
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003296 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00003297 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003298
3299 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00003300 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00003301 return Selector();
3302 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003303
3304 unsigned Index = ID - 1;
3305 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3306 // Load this selector from the selector table.
3307 // FIXME: endianness portability issues with SelectorOffsets table
3308 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003309 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00003310 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3311 }
3312
3313 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00003314}
3315
John McCall75b960e2010-06-01 09:23:16 +00003316Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregord720daf2010-04-06 17:30:22 +00003317 return DecodeSelector(ID);
3318}
3319
John McCall75b960e2010-06-01 09:23:16 +00003320uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregord720daf2010-04-06 17:30:22 +00003321 return TotalNumSelectors + 1;
3322}
3323
Mike Stump11289f42009-09-09 15:08:12 +00003324DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003325PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3326 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3327 switch (Kind) {
3328 case DeclarationName::Identifier:
3329 return DeclarationName(GetIdentifierInfo(Record, Idx));
3330
3331 case DeclarationName::ObjCZeroArgSelector:
3332 case DeclarationName::ObjCOneArgSelector:
3333 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00003334 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003335
3336 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003337 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003338 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003339
3340 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003341 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003342 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003343
3344 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003345 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00003346 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003347
3348 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00003349 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003350 (OverloadedOperatorKind)Record[Idx++]);
3351
Alexis Hunt3d221f22009-11-29 07:34:05 +00003352 case DeclarationName::CXXLiteralOperatorName:
3353 return Context->DeclarationNames.getCXXLiteralOperatorName(
3354 GetIdentifierInfo(Record, Idx));
3355
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003356 case DeclarationName::CXXUsingDirective:
3357 return DeclarationName::getUsingDirectiveName();
3358 }
3359
3360 // Required to silence GCC warning
3361 return DeclarationName();
3362}
Douglas Gregor55abb232009-04-10 20:39:37 +00003363
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003364TemplateName
3365PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3366 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3367 switch (Kind) {
3368 case TemplateName::Template:
3369 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3370
3371 case TemplateName::OverloadedTemplate: {
3372 unsigned size = Record[Idx++];
3373 UnresolvedSet<8> Decls;
3374 while (size--)
3375 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3376
3377 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3378 }
3379
3380 case TemplateName::QualifiedTemplate: {
3381 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3382 bool hasTemplKeyword = Record[Idx++];
3383 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3384 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3385 }
3386
3387 case TemplateName::DependentTemplate: {
3388 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3389 if (Record[Idx++]) // isIdentifier
3390 return Context->getDependentTemplateName(NNS,
3391 GetIdentifierInfo(Record, Idx));
3392 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00003393 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003394 }
3395 }
3396
3397 assert(0 && "Unhandled template name kind!");
3398 return TemplateName();
3399}
3400
3401TemplateArgument
Sebastian Redlc67764e2010-07-22 22:43:28 +00003402PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3403 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003404 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3405 case TemplateArgument::Null:
3406 return TemplateArgument();
3407 case TemplateArgument::Type:
3408 return TemplateArgument(GetType(Record[Idx++]));
3409 case TemplateArgument::Declaration:
3410 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidis0b0369a2010-06-28 09:31:34 +00003411 case TemplateArgument::Integral: {
3412 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3413 QualType T = GetType(Record[Idx++]);
3414 return TemplateArgument(Value, T);
3415 }
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003416 case TemplateArgument::Template:
3417 return TemplateArgument(ReadTemplateName(Record, Idx));
3418 case TemplateArgument::Expression:
Sebastian Redlc67764e2010-07-22 22:43:28 +00003419 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003420 case TemplateArgument::Pack: {
3421 unsigned NumArgs = Record[Idx++];
3422 llvm::SmallVector<TemplateArgument, 8> Args;
3423 Args.reserve(NumArgs);
3424 while (NumArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00003425 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis95c04ca2010-06-19 19:29:09 +00003426 TemplateArgument TemplArg;
3427 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3428 return TemplArg;
3429 }
3430 }
3431
3432 assert(0 && "Unhandled template argument kind!");
3433 return TemplateArgument();
3434}
3435
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003436TemplateParameterList *
3437PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3438 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3439 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3440 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3441
3442 unsigned NumParams = Record[Idx++];
3443 llvm::SmallVector<NamedDecl *, 16> Params;
3444 Params.reserve(NumParams);
3445 while (NumParams--)
3446 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3447
3448 TemplateParameterList* TemplateParams =
3449 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3450 Params.data(), Params.size(), RAngleLoc);
3451 return TemplateParams;
3452}
3453
3454void
3455PCHReader::
3456ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redlc67764e2010-07-22 22:43:28 +00003457 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003458 const RecordData &Record, unsigned &Idx) {
3459 unsigned NumTemplateArgs = Record[Idx++];
3460 TemplArgs.reserve(NumTemplateArgs);
3461 while (NumTemplateArgs--)
Sebastian Redlc67764e2010-07-22 22:43:28 +00003462 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00003463}
3464
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00003465/// \brief Read a UnresolvedSet structure.
3466void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3467 const RecordData &Record, unsigned &Idx) {
3468 unsigned NumDecls = Record[Idx++];
3469 while (NumDecls--) {
3470 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3471 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3472 Set.addDecl(D, AS);
3473 }
3474}
3475
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003476CXXBaseSpecifier
Nick Lewycky19b9f952010-07-26 16:56:01 +00003477PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3478 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003479 bool isVirtual = static_cast<bool>(Record[Idx++]);
3480 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3481 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky19b9f952010-07-26 16:56:01 +00003482 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003483 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky19b9f952010-07-26 16:56:01 +00003484 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00003485}
3486
Chris Lattnerca025db2010-05-07 21:43:38 +00003487NestedNameSpecifier *
3488PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3489 unsigned N = Record[Idx++];
3490 NestedNameSpecifier *NNS = 0, *Prev = 0;
3491 for (unsigned I = 0; I != N; ++I) {
3492 NestedNameSpecifier::SpecifierKind Kind
3493 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3494 switch (Kind) {
3495 case NestedNameSpecifier::Identifier: {
3496 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3497 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3498 break;
3499 }
3500
3501 case NestedNameSpecifier::Namespace: {
3502 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3503 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3504 break;
3505 }
3506
3507 case NestedNameSpecifier::TypeSpec:
3508 case NestedNameSpecifier::TypeSpecWithTemplate: {
3509 Type *T = GetType(Record[Idx++]).getTypePtr();
3510 bool Template = Record[Idx++];
3511 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3512 break;
3513 }
3514
3515 case NestedNameSpecifier::Global: {
3516 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3517 // No associated value, and there can't be a prefix.
3518 break;
3519 }
Chris Lattnerca025db2010-05-07 21:43:38 +00003520 }
Argyrios Kyrtzidisad65c692010-07-07 15:46:30 +00003521 Prev = NNS;
Chris Lattnerca025db2010-05-07 21:43:38 +00003522 }
3523 return NNS;
3524}
3525
3526SourceRange
3527PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar6d3bc082010-06-02 15:47:10 +00003528 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3529 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3530 return SourceRange(beg, end);
Chris Lattnerca025db2010-05-07 21:43:38 +00003531}
3532
Douglas Gregor1daeb692009-04-13 18:14:40 +00003533/// \brief Read an integral value
3534llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3535 unsigned BitWidth = Record[Idx++];
3536 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3537 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3538 Idx += NumWords;
3539 return Result;
3540}
3541
3542/// \brief Read a signed integral value
3543llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3544 bool isUnsigned = Record[Idx++];
3545 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3546}
3547
Douglas Gregore0a3a512009-04-14 21:55:33 +00003548/// \brief Read a floating-point value
3549llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00003550 return llvm::APFloat(ReadAPInt(Record, Idx));
3551}
3552
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003553// \brief Read a string
3554std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3555 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00003556 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003557 Idx += Len;
3558 return Result;
3559}
3560
Chris Lattnercba86142010-05-10 00:25:06 +00003561CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3562 unsigned &Idx) {
3563 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3564 return CXXTemporary::Create(*Context, Decl);
3565}
3566
Douglas Gregor55abb232009-04-10 20:39:37 +00003567DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00003568 return Diag(SourceLocation(), DiagID);
3569}
3570
3571DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003572 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00003573}
Douglas Gregora9af1d12009-04-17 00:04:06 +00003574
Douglas Gregora868bbd2009-04-21 22:25:48 +00003575/// \brief Retrieve the identifier table associated with the
3576/// preprocessor.
3577IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00003578 assert(PP && "Forgot to set Preprocessor ?");
3579 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00003580}
3581
Douglas Gregora9af1d12009-04-17 00:04:06 +00003582/// \brief Record that the given ID maps to the given switch-case
3583/// statement.
3584void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3585 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3586 SwitchCaseStmts[ID] = SC;
3587}
3588
3589/// \brief Retrieve the switch-case statement with the given ID.
3590SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3591 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3592 return SwitchCaseStmts[ID];
3593}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003594
3595/// \brief Record that the given label statement has been
3596/// deserialized and has the given ID.
3597void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00003598 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003599 "Deserialized label twice");
3600 LabelStmts[ID] = S;
3601
3602 // If we've already seen any goto statements that point to this
3603 // label, resolve them now.
3604 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3605 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3606 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3607 Goto->second->setLabel(S);
3608 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00003609
3610 // If we've already seen any address-label statements that point to
3611 // this label, resolve them now.
3612 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00003613 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00003614 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00003615 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00003616 AddrLabel != AddrLabels.second; ++AddrLabel)
3617 AddrLabel->second->setLabel(S);
3618 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00003619}
3620
3621/// \brief Set the label of the given statement to the label
3622/// identified by ID.
3623///
3624/// Depending on the order in which the label and other statements
3625/// referencing that label occur, this operation may complete
3626/// immediately (updating the statement) or it may queue the
3627/// statement to be back-patched later.
3628void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3629 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3630 if (Label != LabelStmts.end()) {
3631 // We've already seen this label, so set the label of the goto and
3632 // we're done.
3633 S->setLabel(Label->second);
3634 } else {
3635 // We haven't seen this label yet, so add this goto to the set of
3636 // unresolved goto statements.
3637 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3638 }
3639}
Douglas Gregor779d8652009-04-17 18:58:21 +00003640
3641/// \brief Set the label of the given expression to the label
3642/// identified by ID.
3643///
3644/// Depending on the order in which the label and other statements
3645/// referencing that label occur, this operation may complete
3646/// immediately (updating the statement) or it may queue the
3647/// statement to be back-patched later.
3648void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3649 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3650 if (Label != LabelStmts.end()) {
3651 // We've already seen this label, so set the label of the
3652 // label-address expression and we're done.
3653 S->setLabel(Label->second);
3654 } else {
3655 // We haven't seen this label yet, so add this label-address
3656 // expression to the set of unresolved label-address expressions.
3657 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3658 }
3659}
Douglas Gregor1342e842009-07-06 18:54:52 +00003660
3661
Mike Stump11289f42009-09-09 15:08:12 +00003662PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00003663 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3664 Reader.CurrentlyLoadingTypeOrDecl = this;
3665}
3666
3667PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3668 if (!Parent) {
3669 // If any identifiers with corresponding top-level declarations have
3670 // been loaded, load those declarations now.
3671 while (!Reader.PendingIdentifierInfos.empty()) {
3672 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3673 Reader.PendingIdentifierInfos.front().DeclIDs,
3674 true);
3675 Reader.PendingIdentifierInfos.pop_front();
3676 }
Argyrios Kyrtzidis903ccd62010-07-07 15:46:26 +00003677
3678 // We are not in recursive loading, so it's safe to pass the "interesting"
3679 // decls to the consumer.
3680 if (Reader.Consumer)
3681 Reader.PassInterestingDeclsToConsumer();
Douglas Gregor1342e842009-07-06 18:54:52 +00003682 }
3683
Mike Stump11289f42009-09-09 15:08:12 +00003684 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00003685}