blob: 5a239e4f045b12ee0d7b4cd9050be74cd08cc6ab [file] [log] [blame]
Douglas Gregor2cf26342009-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 Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Sebastian Redl30c514c2010-07-14 23:45:08 +000016#include "clang/Frontend/PCHDeserializationListener.h"
Daniel Dunbarc7162932009-11-11 23:58:53 +000017#include "clang/Frontend/Utils.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000018#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000021#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000023#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000024#include "clang/Lex/MacroInfo.h"
Douglas Gregor6a5a23f2010-03-19 21:51:54 +000025#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000026#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000027#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000028#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000029#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000030#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000031#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000032#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000033#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000036#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000037#include "llvm/Support/ErrorHandling.h"
Daniel Dunbard5b21972009-11-18 19:50:41 +000038#include "llvm/System/Path.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000039#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000040#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000041#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000042#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000043using namespace clang;
44
45//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-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 Carrutheb5d7b72010-04-17 20:17:31 +000066 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis11e51102009-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 Jahanian412e7982010-02-09 19:31:38 +000078 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +000079 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
80 diag::warn_pch_no_constant_cfstrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000081 PARSE_LANGOPT_BENIGN(PascalStrings);
82 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000084 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000085 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +000087 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis11e51102009-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 Stump1eb44332009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000092 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000093 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-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 Lattnera4d71452010-06-26 21:25:03 +000097 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
Mike Stump1eb44332009-09-09 15:08:12 +000098 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-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 Thompsona6fda122009-11-05 20:14:16 +0000115 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000116 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000117 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000118 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
119 return true;
120 }
121 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000122 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
123 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000124 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000125 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stump9c276ae2009-12-12 01:27:46 +0000126 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000127 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Douglas Gregora0068fc2010-07-09 17:35:33 +0000128 PARSE_LANGOPT_BENIGN(SpellChecking);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +0000129#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000130#undef PARSE_LANGOPT_BENIGN
131
132 return false;
133}
134
Daniel Dunbardc3c0d22009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000142}
143
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000144struct EmptyStringRef {
Benjamin Kramerec1b1cc2010-07-14 23:19:41 +0000145 bool operator ()(llvm::StringRef r) const { return r.empty(); }
Sebastian Redl7e9ad8b2010-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 Dunbarc76c9e02010-07-16 00:00:11 +0000173 (void) RN;
Sebastian Redl7e9ad8b2010-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 Dunbar7b5a1212009-11-11 05:29:04 +0000225 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000226 std::string &SuggestedPredefines) {
Daniel Dunbarc7162932009-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 Dunbar7b5a1212009-11-11 05:29:04 +0000231 llvm::SmallString<256> PCHInclude;
232 PCHInclude += "#include \"";
Daniel Dunbarc7162932009-11-11 23:58:53 +0000233 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar7b5a1212009-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 Kremenekd5d7b3f2010-03-18 00:56:54 +0000238 if (Left == PP.getPredefines()) {
239 Error("Missing PCH include entry!");
240 return true;
241 }
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000242
Sebastian Redl7e9ad8b2010-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000252 return false;
253
254 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Daniel Dunbar10014aa2009-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 Dunbare6750492009-11-13 16:46:11 +0000258 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
Sebastian Redl7e9ad8b2010-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 Dunbare6750492009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000265
Daniel Dunbar4d5936a2009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000268 std::sort(CmdLineLines.begin(), CmdLineLines.end());
269 std::sort(PCHLines.begin(), PCHLines.end());
270
Daniel Dunbar4d5936a2009-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 Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000281 llvm::StringRef Missing = MissingPredefines[I];
282 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000283 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
284 return true;
285 }
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000287 // This is a macro definition. Determine the name of the macro we're
288 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000289 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000290 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000294 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000295
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000296 // Determine whether this macro was given a different definition on the
297 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000298 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000299 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbare6750492009-11-13 16:46:11 +0000300 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000301 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
302 MacroDefStart);
303 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000304 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000305 // Different macro; we're done.
306 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000307 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000308 }
Mike Stump1eb44332009-09-09 15:08:12 +0000309
310 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000311 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000312 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000313 (*ConflictPos)[MacroDefLen] != '(')
314 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000316 // We found a conflicting macro definition.
317 break;
318 }
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Argyrios Kyrtzidis11e51102009-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 Redl7e9ad8b2010-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 Dunbar4d5936a2009-11-11 05:26:28 +0000331 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000332
333 ConflictingDefines = true;
334 continue;
335 }
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Daniel Dunbar10014aa2009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000339 if (ConflictingDefines)
340 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Argyrios Kyrtzidis11e51102009-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 Redl7e9ad8b2010-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000354 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
355 }
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000357 if (ConflictingDefines)
358 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Argyrios Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000364 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000365 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
366 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000367 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000368 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000369 llvm::StringRef &Extra = ExtraPredefines[I];
370 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-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 Stump1eb44332009-09-09 15:08:12 +0000378 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000382 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-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 Dunbar4d5936a2009-11-11 05:26:28 +0000387 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000388 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-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 Gregor12fab312010-03-16 16:35:32 +0000402void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
403 unsigned ID) {
404 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
405 ++NumHeaderInfos;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000406}
407
408void PCHValidator::ReadCounter(unsigned Value) {
409 PP.setCounterValue(Value);
410}
411
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000412//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000413// PCH reader implementation
414//===----------------------------------------------------------------------===//
415
Mike Stump1eb44332009-09-09 15:08:12 +0000416PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000417 const char *isysroot, bool DisableValidation)
Sebastian Redl30c514c2010-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 Redl2da08f92010-07-19 22:28:42 +0000421 Consumer(0), MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000422 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000423 TotalNumSelectors(0), isysroot(isysroot),
424 DisableValidation(DisableValidation), NumStatHits(0), NumStatMisses(0),
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000425 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
426 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
427 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
428 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +0000429 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000430 RelocatablePCH = false;
431}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000432
433PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000434 Diagnostic &Diags, const char *isysroot,
435 bool DisableValidation)
Sebastian Redl30c514c2010-07-14 23:45:08 +0000436 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl9137a522010-07-16 17:50:48 +0000437 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000438 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
439 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000440 TotalNumSelectors(0), isysroot(isysroot),
441 DisableValidation(DisableValidation), NumStatHits(0), NumStatMisses(0),
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000442 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
443 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
444 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
445 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +0000446 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000447 RelocatablePCH = false;
448}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000449
Sebastian Redl9137a522010-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 Redl12d6da02010-07-19 22:06:55 +0000456 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redl2da08f92010-07-19 22:28:42 +0000457 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
Sebastian Redl04e6fd42010-07-21 20:07:32 +0000458 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
459 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
460 NumPreallocatedPreprocessingEntities(0)
Sebastian Redl9137a522010-07-16 17:50:48 +0000461{}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000462
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000463void
464PCHReader::setDeserializationListener(PCHDeserializationListener *Listener) {
465 DeserializationListener = Listener;
466 if (DeserializationListener)
467 DeserializationListener->SetReader(this);
468}
469
Chris Lattner4c6f9522009-04-27 05:14:47 +0000470
Douglas Gregor668c1a42009-04-21 22:25:48 +0000471namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000472class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000473 PCHReader &Reader;
474
475public:
476 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
477
478 typedef Selector external_key_type;
479 typedef external_key_type internal_key_type;
480
481 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000483 static bool EqualKey(const internal_key_type& a,
484 const internal_key_type& b) {
485 return a == b;
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000488 static unsigned ComputeHash(Selector Sel) {
489 unsigned N = Sel.getNumArgs();
490 if (N == 0)
491 ++N;
492 unsigned R = 5381;
493 for (unsigned I = 0; I != N; ++I)
494 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000495 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000496 return R;
497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000499 // This hopefully will just get inlined and removed by the optimizer.
500 static const internal_key_type&
501 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000503 static std::pair<unsigned, unsigned>
504 ReadKeyDataLength(const unsigned char*& d) {
505 using namespace clang::io;
506 unsigned KeyLen = ReadUnalignedLE16(d);
507 unsigned DataLen = ReadUnalignedLE16(d);
508 return std::make_pair(KeyLen, DataLen);
509 }
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Douglas Gregor83941df2009-04-25 17:48:32 +0000511 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000512 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000513 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000514 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000515 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000516 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
517 if (N == 0)
518 return SelTable.getNullarySelector(FirstII);
519 else if (N == 1)
520 return SelTable.getUnarySelector(FirstII);
521
522 llvm::SmallVector<IdentifierInfo *, 16> Args;
523 Args.push_back(FirstII);
524 for (unsigned I = 1; I != N; ++I)
525 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
526
Douglas Gregor75fdb232009-05-22 22:45:36 +0000527 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000530 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
531 using namespace clang::io;
532 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
533 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
534
535 data_type Result;
536
537 // Load instance methods
538 ObjCMethodList *Prev = 0;
539 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000540 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000541 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
542 if (!Result.first.Method) {
543 // This is the first method, which is the easy case.
544 Result.first.Method = Method;
545 Prev = &Result.first;
546 continue;
547 }
548
Ted Kremenek298ed872010-02-11 00:53:01 +0000549 ObjCMethodList *Mem =
550 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
551 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000552 Prev = Prev->Next;
553 }
554
555 // Load factory methods
556 Prev = 0;
557 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000558 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000559 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
560 if (!Result.second.Method) {
561 // This is the first method, which is the easy case.
562 Result.second.Method = Method;
563 Prev = &Result.second;
564 continue;
565 }
566
Ted Kremenek298ed872010-02-11 00:53:01 +0000567 ObjCMethodList *Mem =
568 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
569 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000570 Prev = Prev->Next;
571 }
572
573 return Result;
574 }
575};
Mike Stump1eb44332009-09-09 15:08:12 +0000576
577} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000578
579/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000580typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000581 PCHMethodPoolLookupTable;
582
583namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000584class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000585 PCHReader &Reader;
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000586 llvm::BitstreamCursor &Stream;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000587
588 // If we know the IdentifierInfo in advance, it is here and we will
589 // not build a new one. Used when deserializing information about an
590 // identifier that was constructed before the PCH file was read.
591 IdentifierInfo *KnownII;
592
593public:
594 typedef IdentifierInfo * data_type;
595
596 typedef const std::pair<const char*, unsigned> external_key_type;
597
598 typedef external_key_type internal_key_type;
599
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000600 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
601 IdentifierInfo *II = 0)
602 : Reader(Reader), Stream(Stream), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Douglas Gregor668c1a42009-04-21 22:25:48 +0000604 static bool EqualKey(const internal_key_type& a,
605 const internal_key_type& b) {
606 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
607 : false;
608 }
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Douglas Gregor668c1a42009-04-21 22:25:48 +0000610 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000611 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Douglas Gregor668c1a42009-04-21 22:25:48 +0000614 // This hopefully will just get inlined and removed by the optimizer.
615 static const internal_key_type&
616 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregor668c1a42009-04-21 22:25:48 +0000618 static std::pair<unsigned, unsigned>
619 ReadKeyDataLength(const unsigned char*& d) {
620 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000621 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000622 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000623 return std::make_pair(KeyLen, DataLen);
624 }
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Douglas Gregor668c1a42009-04-21 22:25:48 +0000626 static std::pair<const char*, unsigned>
627 ReadKey(const unsigned char* d, unsigned n) {
628 assert(n >= 2 && d[n-1] == '\0');
629 return std::make_pair((const char*) d, n-1);
630 }
Mike Stump1eb44332009-09-09 15:08:12 +0000631
632 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000633 const unsigned char* d,
634 unsigned DataLen) {
635 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000636 pch::IdentID ID = ReadUnalignedLE32(d);
637 bool IsInteresting = ID & 0x01;
638
639 // Wipe out the "is interesting" bit.
640 ID = ID >> 1;
641
642 if (!IsInteresting) {
Sebastian Redl083abdf2010-07-27 23:01:28 +0000643 // For uninteresting identifiers, just build the IdentifierInfo
Douglas Gregora92193e2009-04-28 21:18:29 +0000644 // and associate it with the persistent ID.
645 IdentifierInfo *II = KnownII;
646 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000647 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregora92193e2009-04-28 21:18:29 +0000648 Reader.SetIdentifierInfo(ID, II);
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000649 II->setIsFromPCH();
Douglas Gregora92193e2009-04-28 21:18:29 +0000650 return II;
651 }
652
Douglas Gregor5998da52009-04-28 21:32:13 +0000653 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000654 bool CPlusPlusOperatorKeyword = Bits & 0x01;
655 Bits >>= 1;
656 bool Poisoned = Bits & 0x01;
657 Bits >>= 1;
658 bool ExtensionToken = Bits & 0x01;
659 Bits >>= 1;
660 bool hasMacroDefinition = Bits & 0x01;
661 Bits >>= 1;
662 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
663 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Douglas Gregor2deaea32009-04-22 18:49:13 +0000665 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000666 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000667
668 // Build the IdentifierInfo itself and link the identifier ID with
669 // the new IdentifierInfo.
670 IdentifierInfo *II = KnownII;
671 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000672 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000673 Reader.SetIdentifierInfo(ID, II);
674
Douglas Gregor2deaea32009-04-22 18:49:13 +0000675 // Set or check the various bits in the IdentifierInfo structure.
676 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000677 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000678 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000679 "Incorrect extension token flag");
680 (void)ExtensionToken;
681 II->setIsPoisoned(Poisoned);
682 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
683 "Incorrect C++ operator keyword flag");
684 (void)CPlusPlusOperatorKeyword;
685
Douglas Gregor37e26842009-04-21 23:56:24 +0000686 // If this identifier is a macro, deserialize the macro
687 // definition.
688 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000689 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000690 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000691 DataLen -= 4;
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000692 } else if (II->hasMacroDefinition() && !Reader.isBuiltinMacro(II)) {
693 // A previous part of the chain added a macro, but this part #undefed it.
694 Reader.EraseMacro(II);
Douglas Gregor37e26842009-04-21 23:56:24 +0000695 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000696
697 // Read all of the declarations visible at global scope with this
698 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000699 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000700 if (DataLen > 0) {
701 llvm::SmallVector<uint32_t, 4> DeclIDs;
702 for (; DataLen > 0; DataLen -= 4)
703 DeclIDs.push_back(ReadUnalignedLE32(d));
704 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000705 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000707 II->setIsFromPCH();
Douglas Gregor668c1a42009-04-21 22:25:48 +0000708 return II;
709 }
710};
Mike Stump1eb44332009-09-09 15:08:12 +0000711
712} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000713
714/// \brief The on-disk hash table used to contain information about
715/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000716typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000717 PCHIdentifierLookupTable;
718
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000719void PCHReader::Error(const char *Msg) {
720 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000721}
722
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000723/// \brief Check the contents of the concatenation of all predefines buffers in
724/// the PCH chain against the contents of the predefines buffer of the current
725/// compiler invocation.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000726///
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000727/// The contents should be the same. If not, then some command-line option
728/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000729///
730/// \returns true if there was a mismatch (in which case the PCH file
731/// should be ignored), or false otherwise.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000732bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000733 if (Listener)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000734 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000735 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000736 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000737 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000738}
739
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000740//===----------------------------------------------------------------------===//
741// Source Manager Deserialization
742//===----------------------------------------------------------------------===//
743
Douglas Gregorbd945002009-04-13 16:31:14 +0000744/// \brief Read the line table in the source manager block.
745/// \returns true if ther was an error.
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000746bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000747 unsigned Idx = 0;
748 LineTableInfo &LineTable = SourceMgr.getLineTable();
749
750 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000751 std::map<int, int> FileIDs;
752 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000753 // Extract the file name
754 unsigned FilenameLen = Record[Idx++];
755 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
756 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000757 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000758 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000759 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000760 }
761
762 // Parse the line entries
763 std::vector<LineEntry> Entries;
764 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000765 int FID = Record[Idx++];
Douglas Gregorbd945002009-04-13 16:31:14 +0000766
767 // Extract the line entries
768 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000769 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +0000770 Entries.clear();
771 Entries.reserve(NumEntries);
772 for (unsigned I = 0; I != NumEntries; ++I) {
773 unsigned FileOffset = Record[Idx++];
774 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000775 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +0000776 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000777 = (SrcMgr::CharacteristicKind)Record[Idx++];
778 unsigned IncludeOffset = Record[Idx++];
779 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
780 FileKind, IncludeOffset));
781 }
782 LineTable.AddEntry(FID, Entries);
783 }
784
785 return false;
786}
787
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000788namespace {
789
Benjamin Kramerbd218282009-11-28 10:07:24 +0000790class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000791public:
792 const bool hasStat;
793 const ino_t ino;
794 const dev_t dev;
795 const mode_t mode;
796 const time_t mtime;
797 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000799 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000800 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
801
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000802 PCHStatData()
803 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
804};
805
Benjamin Kramerbd218282009-11-28 10:07:24 +0000806class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000807 public:
808 typedef const char *external_key_type;
809 typedef const char *internal_key_type;
810
811 typedef PCHStatData data_type;
812
813 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000814 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000815 }
816
817 static internal_key_type GetInternalKey(const char *path) { return path; }
818
819 static bool EqualKey(internal_key_type a, internal_key_type b) {
820 return strcmp(a, b) == 0;
821 }
822
823 static std::pair<unsigned, unsigned>
824 ReadKeyDataLength(const unsigned char*& d) {
825 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
826 unsigned DataLen = (unsigned) *d++;
827 return std::make_pair(KeyLen + 1, DataLen);
828 }
829
830 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
831 return (const char *)d;
832 }
833
834 static data_type ReadData(const internal_key_type, const unsigned char *d,
835 unsigned /*DataLen*/) {
836 using namespace clang::io;
837
838 if (*d++ == 1)
839 return data_type();
840
841 ino_t ino = (ino_t) ReadUnalignedLE32(d);
842 dev_t dev = (dev_t) ReadUnalignedLE32(d);
843 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000844 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000845 off_t size = (off_t) ReadUnalignedLE64(d);
846 return data_type(ino, dev, mode, mtime, size);
847 }
848};
849
850/// \brief stat() cache for precompiled headers.
851///
852/// This cache is very similar to the stat cache used by pretokenized
853/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000854class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000855 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
856 CacheTy *Cache;
857
858 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000859public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000860 PCHStatCache(const unsigned char *Buckets,
861 const unsigned char *Base,
862 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000863 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000864 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
865 Cache = CacheTy::Create(Buckets, Base);
866 }
867
868 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000870 int stat(const char *path, struct stat *buf) {
871 // Do the lookup for the file's data in the PCH file.
872 CacheTy::iterator I = Cache->find(path);
873
874 // If we don't get a hit in the PCH file just forward to 'stat'.
875 if (I == Cache->end()) {
876 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000877 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000878 }
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000880 ++NumStatHits;
881 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000883 if (!Data.hasStat)
884 return 1;
885
886 buf->st_ino = Data.ino;
887 buf->st_dev = Data.dev;
888 buf->st_mtime = Data.mtime;
889 buf->st_mode = Data.mode;
890 buf->st_size = Data.size;
891 return 0;
892 }
893};
894} // end anonymous namespace
895
896
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000897/// \brief Read a source manager block
898PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000899 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000900
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000901 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +0000902
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000903 // Set the source-location entry cursor to the current position in
904 // the stream. This cursor will be used to read the contents of the
905 // source manager block initially, and then lazily read
906 // source-location entries as needed.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000907 SLocEntryCursor = F.Stream;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000908
909 // The stream itself is going to skip over the source manager block.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000910 if (F.Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000911 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000912 return Failure;
913 }
914
915 // Enter the source manager block.
916 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000917 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000918 return Failure;
919 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000920
Douglas Gregor14f79002009-04-10 03:52:48 +0000921 RecordData Record;
922 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000923 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000924 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000925 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000926 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000927 return Failure;
928 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000929 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000930 }
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Douglas Gregor14f79002009-04-10 03:52:48 +0000932 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
933 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000934 SLocEntryCursor.ReadSubBlockID();
935 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000936 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000937 return Failure;
938 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000939 continue;
940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Douglas Gregor14f79002009-04-10 03:52:48 +0000942 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000943 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000944 continue;
945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Douglas Gregor14f79002009-04-10 03:52:48 +0000947 // Read a record.
948 const char *BlobStart;
949 unsigned BlobLen;
950 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000951 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000952 default: // Default behavior: ignore.
953 break;
954
Chris Lattner2c78b872009-04-14 23:22:57 +0000955 case pch::SM_LINE_TABLE:
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000956 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000957 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000958 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000959
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000960 case pch::SM_SLOC_FILE_ENTRY:
961 case pch::SM_SLOC_BUFFER_ENTRY:
962 case pch::SM_SLOC_INSTANTIATION_ENTRY:
963 // Once we hit one of the source location entries, we're done.
964 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000965 }
966 }
967}
968
Sebastian Redl190faf72010-07-20 21:50:20 +0000969/// \brief Get a cursor that's correctly positioned for reading the source
970/// location entry with the given ID.
971llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
972 assert(ID != 0 && ID <= TotalNumSLocEntries &&
973 "SLocCursorForID should only be called for real IDs.");
974
975 ID -= 1;
976 PerFileData *F = 0;
977 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
978 F = Chain[N - I - 1];
979 if (ID < F->LocalNumSLocEntries)
980 break;
981 ID -= F->LocalNumSLocEntries;
982 }
983 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
984
985 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
986 return F->SLocEntryCursor;
987}
988
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000989/// \brief Read in the source location entry with the given ID.
990PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
991 if (ID == 0)
992 return Success;
993
994 if (ID > TotalNumSLocEntries) {
995 Error("source location entry ID out-of-range for PCH file");
996 return Failure;
997 }
998
Sebastian Redl190faf72010-07-20 21:50:20 +0000999 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl9137a522010-07-16 17:50:48 +00001000
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001001 ++NumSLocEntriesRead;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001002 unsigned Code = SLocEntryCursor.ReadCode();
1003 if (Code == llvm::bitc::END_BLOCK ||
1004 Code == llvm::bitc::ENTER_SUBBLOCK ||
1005 Code == llvm::bitc::DEFINE_ABBREV) {
1006 Error("incorrectly-formatted source location entry in PCH file");
1007 return Failure;
1008 }
1009
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001010 RecordData Record;
1011 const char *BlobStart;
1012 unsigned BlobLen;
1013 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1014 default:
1015 Error("incorrectly-formatted source location entry in PCH file");
1016 return Failure;
1017
1018 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001019 std::string Filename(BlobStart, BlobStart + BlobLen);
1020 MaybeAddSystemRootToFilename(Filename);
1021 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001022 if (File == 0) {
1023 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +00001024 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001025 ErrorStr += "' referenced by PCH file";
1026 Error(ErrorStr.c_str());
1027 return Failure;
1028 }
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Douglas Gregor2d52be52010-03-21 22:49:54 +00001030 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +00001031 Error("source location entry is incorrect");
1032 return Failure;
1033 }
1034
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001035 if (!DisableValidation &&
1036 ((off_t)Record[4] != File->getSize()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001037#if !defined(LLVM_ON_WIN32)
1038 // In our regression testing, the Windows file system seems to
1039 // have inconsistent modification times that sometimes
1040 // erroneously trigger this error-handling path.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001041 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001042#endif
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001043 )) {
Douglas Gregor2d52be52010-03-21 22:49:54 +00001044 Diag(diag::err_fe_pch_file_modified)
1045 << Filename;
1046 return Failure;
1047 }
1048
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001049 FileID FID = SourceMgr.createFileID(File,
1050 SourceLocation::getFromRawEncoding(Record[1]),
1051 (SrcMgr::CharacteristicKind)Record[2],
1052 ID, Record[0]);
1053 if (Record[3])
1054 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1055 .setHasLineDirectives();
1056
Douglas Gregor12fab312010-03-16 16:35:32 +00001057 // Reconstruct header-search information for this file.
1058 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001059 HFI.isImport = Record[6];
1060 HFI.DirInfo = Record[7];
1061 HFI.NumIncludes = Record[8];
1062 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +00001063 if (Listener)
1064 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001065 break;
1066 }
1067
1068 case pch::SM_SLOC_BUFFER_ENTRY: {
1069 const char *Name = BlobStart;
1070 unsigned Offset = Record[0];
1071 unsigned Code = SLocEntryCursor.ReadCode();
1072 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001073 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001074 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001075
1076 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1077 Error("PCH record has invalid code");
1078 return Failure;
1079 }
1080
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001081 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001082 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1083 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001084 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Douglas Gregor92b059e2009-04-28 20:33:11 +00001086 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001087 PCHPredefinesBlock Block = {
1088 BufferID,
1089 llvm::StringRef(BlobStart, BlobLen - 1)
1090 };
1091 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001092 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001093
1094 break;
1095 }
1096
1097 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +00001098 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001099 = SourceLocation::getFromRawEncoding(Record[1]);
1100 SourceMgr.createInstantiationLoc(SpellingLoc,
1101 SourceLocation::getFromRawEncoding(Record[2]),
1102 SourceLocation::getFromRawEncoding(Record[3]),
1103 Record[4],
1104 ID,
1105 Record[0]);
1106 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001107 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001108 }
1109
1110 return Success;
1111}
1112
Chris Lattner6367f6d2009-04-27 01:05:14 +00001113/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1114/// specified cursor. Read the abbreviations that are at the top of the block
1115/// and then leave the cursor pointing into the block.
1116bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1117 unsigned BlockID) {
1118 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001119 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001120 return Failure;
1121 }
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Chris Lattner6367f6d2009-04-27 01:05:14 +00001123 while (true) {
1124 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Chris Lattner6367f6d2009-04-27 01:05:14 +00001126 // We expect all abbrevs to be at the start of the block.
1127 if (Code != llvm::bitc::DEFINE_ABBREV)
1128 return false;
1129 Cursor.ReadAbbrevRecord();
1130 }
1131}
1132
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001133void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001134 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Douglas Gregor37e26842009-04-21 23:56:24 +00001136 // Keep track of where we are in the stream, then jump back there
1137 // after reading this macro.
1138 SavedStreamPosition SavedPosition(Stream);
1139
1140 Stream.JumpToBit(Offset);
1141 RecordData Record;
1142 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1143 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Douglas Gregor37e26842009-04-21 23:56:24 +00001145 while (true) {
1146 unsigned Code = Stream.ReadCode();
1147 switch (Code) {
1148 case llvm::bitc::END_BLOCK:
1149 return;
1150
1151 case llvm::bitc::ENTER_SUBBLOCK:
1152 // No known subblocks, always skip them.
1153 Stream.ReadSubBlockID();
1154 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001155 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001156 return;
1157 }
1158 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Douglas Gregor37e26842009-04-21 23:56:24 +00001160 case llvm::bitc::DEFINE_ABBREV:
1161 Stream.ReadAbbrevRecord();
1162 continue;
1163 default: break;
1164 }
1165
1166 // Read a record.
1167 Record.clear();
1168 pch::PreprocessorRecordTypes RecType =
1169 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1170 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001171 case pch::PP_MACRO_OBJECT_LIKE:
1172 case pch::PP_MACRO_FUNCTION_LIKE: {
1173 // If we already have a macro, that means that we've hit the end
1174 // of the definition of the macro we were looking for. We're
1175 // done.
1176 if (Macro)
1177 return;
1178
1179 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1180 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001181 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001182 return;
1183 }
1184 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1185 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001187 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001188 MI->setIsUsed(isUsed);
Sebastian Redl083abdf2010-07-27 23:01:28 +00001189 MI->setIsFromPCH();
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001191 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001192 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1193 // Decode function-like macro info.
1194 bool isC99VarArgs = Record[3];
1195 bool isGNUVarArgs = Record[4];
1196 MacroArgs.clear();
1197 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001198 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001199 for (unsigned i = 0; i != NumArgs; ++i)
1200 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1201
1202 // Install function-like macro info.
1203 MI->setIsFunctionLike();
1204 if (isC99VarArgs) MI->setIsC99Varargs();
1205 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001206 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001207 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001208 }
1209
1210 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001211 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001212
1213 // Remember that we saw this macro last so that we add the tokens that
1214 // form its body to it.
1215 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001216
1217 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1218 // We have a macro definition. Load it now.
1219 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1220 getMacroDefinition(Record[NextIndex]));
1221 }
1222
Douglas Gregor37e26842009-04-21 23:56:24 +00001223 ++NumMacrosRead;
1224 break;
1225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Douglas Gregor37e26842009-04-21 23:56:24 +00001227 case pch::PP_TOKEN: {
1228 // If we see a TOKEN before a PP_MACRO_*, then the file is
1229 // erroneous, just pretend we didn't see this.
1230 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Douglas Gregor37e26842009-04-21 23:56:24 +00001232 Token Tok;
1233 Tok.startToken();
1234 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1235 Tok.setLength(Record[1]);
1236 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1237 Tok.setIdentifierInfo(II);
1238 Tok.setKind((tok::TokenKind)Record[3]);
1239 Tok.setFlag((Token::TokenFlags)Record[4]);
1240 Macro->AddTokenToBody(Tok);
1241 break;
1242 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001243
1244 case pch::PP_MACRO_INSTANTIATION: {
1245 // If we already have a macro, that means that we've hit the end
1246 // of the definition of the macro we were looking for. We're
1247 // done.
1248 if (Macro)
1249 return;
1250
1251 if (!PP->getPreprocessingRecord()) {
1252 Error("missing preprocessing record in PCH file");
1253 return;
1254 }
1255
1256 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1257 if (PPRec.getPreprocessedEntity(Record[0]))
1258 return;
1259
1260 MacroInstantiation *MI
1261 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1262 SourceRange(
1263 SourceLocation::getFromRawEncoding(Record[1]),
1264 SourceLocation::getFromRawEncoding(Record[2])),
1265 getMacroDefinition(Record[4]));
1266 PPRec.SetPreallocatedEntity(Record[0], MI);
1267 return;
1268 }
1269
1270 case pch::PP_MACRO_DEFINITION: {
1271 // If we already have a macro, that means that we've hit the end
1272 // of the definition of the macro we were looking for. We're
1273 // done.
1274 if (Macro)
1275 return;
1276
1277 if (!PP->getPreprocessingRecord()) {
1278 Error("missing preprocessing record in PCH file");
1279 return;
1280 }
1281
1282 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1283 if (PPRec.getPreprocessedEntity(Record[0]))
1284 return;
1285
1286 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1287 Error("out-of-bounds macro definition record");
1288 return;
1289 }
1290
1291 MacroDefinition *MD
1292 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1293 SourceLocation::getFromRawEncoding(Record[5]),
1294 SourceRange(
1295 SourceLocation::getFromRawEncoding(Record[2]),
1296 SourceLocation::getFromRawEncoding(Record[3])));
1297 PPRec.SetPreallocatedEntity(Record[0], MD);
1298 MacroDefinitionsLoaded[Record[1]] = MD;
1299 return;
1300 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001301 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001302 }
1303}
1304
Douglas Gregor88a35862010-01-04 19:18:44 +00001305void PCHReader::ReadDefinedMacros() {
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001306 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1307 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001308
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001309 // If there was no preprocessor block, skip this file.
1310 if (!MacroCursor.getBitStreamReader())
1311 continue;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001312
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001313 llvm::BitstreamCursor Cursor = MacroCursor;
1314 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1315 Error("malformed preprocessor block record in PCH file");
Douglas Gregor88a35862010-01-04 19:18:44 +00001316 return;
1317 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001318
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001319 RecordData Record;
1320 while (true) {
1321 unsigned Code = Cursor.ReadCode();
1322 if (Code == llvm::bitc::END_BLOCK) {
1323 if (Cursor.ReadBlockEnd()) {
1324 Error("error at end of preprocessor block in PCH file");
1325 return;
1326 }
1327 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001328 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001329
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001330 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1331 // No known subblocks, always skip them.
1332 Cursor.ReadSubBlockID();
1333 if (Cursor.SkipBlock()) {
1334 Error("malformed block record in PCH file");
1335 return;
1336 }
1337 continue;
1338 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001339
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001340 if (Code == llvm::bitc::DEFINE_ABBREV) {
1341 Cursor.ReadAbbrevRecord();
1342 continue;
1343 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001344
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001345 // Read a record.
1346 const char *BlobStart;
1347 unsigned BlobLen;
1348 Record.clear();
1349 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1350 default: // Default behavior: ignore.
1351 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001352
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001353 case pch::PP_MACRO_OBJECT_LIKE:
1354 case pch::PP_MACRO_FUNCTION_LIKE:
1355 DecodeIdentifierInfo(Record[0]);
1356 break;
1357
1358 case pch::PP_TOKEN:
1359 // Ignore tokens.
1360 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001361
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001362 case pch::PP_MACRO_INSTANTIATION:
1363 case pch::PP_MACRO_DEFINITION:
1364 // Read the macro record.
1365 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1366 break;
1367 }
Douglas Gregor88a35862010-01-04 19:18:44 +00001368 }
1369 }
1370}
1371
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001372MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1373 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1374 return 0;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001375
1376 if (!MacroDefinitionsLoaded[ID]) {
1377 unsigned Index = ID;
1378 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1379 PerFileData &F = *Chain[N - I - 1];
1380 if (Index < F.LocalNumMacroDefinitions) {
1381 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1382 break;
1383 }
1384 Index -= F.LocalNumMacroDefinitions;
1385 }
1386 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1387 }
1388
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001389 return MacroDefinitionsLoaded[ID];
1390}
1391
Sebastian Redlffaab3e2010-07-30 00:29:29 +00001392void PCHReader::EraseMacro(IdentifierInfo *II) {
1393 PP->setMacroInfo(II, 0);
1394}
1395
1396bool PCHReader::isBuiltinMacro(IdentifierInfo *II) {
1397 assert(II->hasMacroDefinition() && "Identifier is not a macro");
1398 return PP->getMacroInfo(II)->isBuiltinMacro();
1399}
1400
Douglas Gregore650c8c2009-07-07 00:12:59 +00001401/// \brief If we are loading a relocatable PCH file, and the filename is
1402/// not an absolute path, add the system root to the beginning of the file
1403/// name.
1404void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1405 // If this is not a relocatable PCH file, there's nothing to do.
1406 if (!RelocatablePCH)
1407 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Daniel Dunbard5b21972009-11-18 19:50:41 +00001409 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001410 return;
1411
Douglas Gregore650c8c2009-07-07 00:12:59 +00001412 if (isysroot == 0) {
1413 // If no system root was given, default to '/'
1414 Filename.insert(Filename.begin(), '/');
1415 return;
1416 }
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Douglas Gregore650c8c2009-07-07 00:12:59 +00001418 unsigned Length = strlen(isysroot);
1419 if (isysroot[Length - 1] != '/')
1420 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Douglas Gregore650c8c2009-07-07 00:12:59 +00001422 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1423}
1424
Mike Stump1eb44332009-09-09 15:08:12 +00001425PCHReader::PCHReadResult
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001426PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00001427 llvm::BitstreamCursor &Stream = F.Stream;
1428
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001429 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001430 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001431 return Failure;
1432 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001433
1434 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001435 RecordData Record;
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001436 bool First = true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001437 while (!Stream.AtEndOfStream()) {
1438 unsigned Code = Stream.ReadCode();
1439 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001440 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001441 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001442 return Failure;
1443 }
Chris Lattner7356a312009-04-11 21:15:38 +00001444
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001445 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001446 }
1447
1448 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1449 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001450 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001451 // We lazily load the decls block, but we want to set up the
1452 // DeclsCursor cursor to point into it. Clone our current bitcode
1453 // cursor to it, enter the block and read the abbrevs in that block.
1454 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00001455 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00001456 if (Stream.SkipBlock() || // Skip with the main cursor.
1457 // Read the abbrevs.
Sebastian Redl9137a522010-07-16 17:50:48 +00001458 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001459 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001460 return Failure;
1461 }
1462 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Chris Lattner7356a312009-04-11 21:15:38 +00001464 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00001465 F.MacroCursor = Stream;
Douglas Gregor88a35862010-01-04 19:18:44 +00001466 if (PP)
1467 PP->setExternalSource(this);
1468
Chris Lattner7356a312009-04-11 21:15:38 +00001469 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001470 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001471 return Failure;
1472 }
1473 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001474
Douglas Gregor14f79002009-04-10 03:52:48 +00001475 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001476 switch (ReadSourceManagerBlock(F)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001477 case Success:
1478 break;
1479
1480 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001481 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001482 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001483
1484 case IgnorePCH:
1485 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001486 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001487 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001488 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001489 First = false;
Douglas Gregor8038d512009-04-10 17:25:41 +00001490 continue;
1491 }
1492
1493 if (Code == llvm::bitc::DEFINE_ABBREV) {
1494 Stream.ReadAbbrevRecord();
1495 continue;
1496 }
1497
1498 // Read and process a record.
1499 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001500 const char *BlobStart = 0;
1501 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001502 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001503 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001504 default: // Default behavior: ignore.
1505 break;
1506
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001507 case pch::METADATA: {
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001508 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-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 RelocatablePCH = Record[4];
1515 if (Listener) {
1516 std::string TargetTriple(BlobStart, BlobLen);
1517 if (Listener->ReadTargetTriple(TargetTriple))
1518 return IgnorePCH;
1519 }
1520 break;
1521 }
1522
1523 case pch::CHAINED_METADATA: {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001524 if (!First) {
1525 Error("CHAINED_METADATA is not first record in block");
1526 return Failure;
1527 }
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001528 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001529 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1530 : diag::warn_pch_version_too_new);
1531 return IgnorePCH;
1532 }
1533
1534 // Load the chained file.
1535 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1536 case Failure: return Failure;
1537 // If we have to ignore the dependency, we'll have to ignore this too.
1538 case IgnorePCH: return IgnorePCH;
1539 case Success: break;
1540 }
1541 break;
1542 }
1543
Douglas Gregor8038d512009-04-10 17:25:41 +00001544 case pch::TYPE_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001545 if (F.LocalNumTypes != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001546 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001547 return Failure;
1548 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001549 F.TypeOffsets = (const uint32_t *)BlobStart;
1550 F.LocalNumTypes = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001551 break;
1552
1553 case pch::DECL_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001554 if (F.LocalNumDecls != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001555 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001556 return Failure;
1557 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001558 F.DeclOffsets = (const uint32_t *)BlobStart;
1559 F.LocalNumDecls = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001560 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001561
Sebastian Redld692af72010-07-27 18:24:41 +00001562 case pch::TU_UPDATE_LEXICAL: {
1563 DeclContextInfo Info = {
1564 /* No visible information */ 0, 0,
1565 reinterpret_cast<const pch::DeclID *>(BlobStart),
1566 BlobLen / sizeof(pch::DeclID)
1567 };
1568 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1569 break;
1570 }
1571
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001572 case pch::LANGUAGE_OPTIONS:
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001573 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001574 return IgnorePCH;
1575 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001576
Douglas Gregorafaf3082009-04-11 00:14:32 +00001577 case pch::IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001578 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001579 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001580 F.IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001581 = PCHIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001582 (const unsigned char *)F.IdentifierTableData + Record[0],
1583 (const unsigned char *)F.IdentifierTableData,
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001584 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001585 if (PP)
1586 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001587 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001588 break;
1589
1590 case pch::IDENTIFIER_OFFSET:
Sebastian Redl2da08f92010-07-19 22:28:42 +00001591 if (F.LocalNumIdentifiers != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001592 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001593 return Failure;
1594 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001595 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1596 F.LocalNumIdentifiers = Record[0];
Douglas Gregorafaf3082009-04-11 00:14:32 +00001597 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001598
1599 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001600 // Optimization for the first block.
1601 if (ExternalDefinitions.empty())
1602 ExternalDefinitions.swap(Record);
1603 else
1604 ExternalDefinitions.insert(ExternalDefinitions.end(),
1605 Record.begin(), Record.end());
Douglas Gregorfdd01722009-04-14 00:24:19 +00001606 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001607
Douglas Gregorad1de002009-04-18 05:55:16 +00001608 case pch::SPECIAL_TYPES:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001609 // Optimization for the first block
1610 if (SpecialTypes.empty())
1611 SpecialTypes.swap(Record);
1612 else
1613 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregorad1de002009-04-18 05:55:16 +00001614 break;
1615
Douglas Gregor3e1af842009-04-17 22:13:46 +00001616 case pch::STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001617 TotalNumStatements += Record[0];
1618 TotalNumMacros += Record[1];
1619 TotalLexicalDeclContexts += Record[2];
1620 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001621 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001622
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001623 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001624 // Optimization for the first block.
1625 if (TentativeDefinitions.empty())
1626 TentativeDefinitions.swap(Record);
1627 else
1628 TentativeDefinitions.insert(TentativeDefinitions.end(),
1629 Record.begin(), Record.end());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001630 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001631
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001632 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001633 // Optimization for the first block.
1634 if (UnusedStaticFuncs.empty())
1635 UnusedStaticFuncs.swap(Record);
1636 else
1637 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1638 Record.begin(), Record.end());
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001639 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001640
Douglas Gregor14c22f22009-04-22 22:18:58 +00001641 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001642 // Optimization for the first block.
1643 if (LocallyScopedExternalDecls.empty())
1644 LocallyScopedExternalDecls.swap(Record);
1645 else
1646 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1647 Record.begin(), Record.end());
Douglas Gregor14c22f22009-04-22 22:18:58 +00001648 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001649
Douglas Gregor83941df2009-04-25 17:48:32 +00001650 case pch::SELECTOR_OFFSETS:
1651 SelectorOffsets = (const uint32_t *)BlobStart;
1652 TotalNumSelectors = Record[0];
1653 SelectorsLoaded.resize(TotalNumSelectors);
1654 break;
1655
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001656 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001657 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1658 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001659 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001660 = PCHMethodPoolLookupTable::Create(
1661 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001662 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001663 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001664 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001665 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001666
Fariborz Jahanian32019832010-07-23 19:11:11 +00001667 case pch::REFERENCED_SELECTOR_POOL: {
1668 unsigned int numEl = Record[0]*2;
1669 for (unsigned int i = 1; i <= numEl; i++)
1670 F.ReferencedSelectorsData.push_back(Record[i]);
Fariborz Jahanian32019832010-07-23 19:11:11 +00001671 break;
Sebastian Redl681d7232010-07-27 00:17:23 +00001672 }
Fariborz Jahanian32019832010-07-23 19:11:11 +00001673
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001674 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001675 if (!Record.empty() && Listener)
1676 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001677 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001678
1679 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001680 F.SLocOffsets = (const uint32_t *)BlobStart;
1681 F.LocalNumSLocEntries = Record[0];
1682 // We cannot delay this until all PCHs are loaded, because then source
1683 // location preloads would also have to be delayed.
1684 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001685 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001686 break;
1687
1688 case pch::SOURCE_LOCATION_PRELOADS:
1689 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1690 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1691 if (Result != Success)
1692 return Result;
1693 }
1694 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001695
Douglas Gregor52e71082009-10-16 18:18:30 +00001696 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001697 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001698 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1699 (const unsigned char *)BlobStart,
1700 NumStatHits, NumStatMisses);
1701 FileMgr.addStatCache(MyStatCache);
Sebastian Redl9137a522010-07-16 17:50:48 +00001702 F.StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001703 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001704 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001705
Douglas Gregorb81c1702009-04-27 20:06:05 +00001706 case pch::EXT_VECTOR_DECLS:
Sebastian Redla9f23682010-07-28 21:38:49 +00001707 // Optimization for the first block.
1708 if (ExtVectorDecls.empty())
1709 ExtVectorDecls.swap(Record);
1710 else
1711 ExtVectorDecls.insert(ExtVectorDecls.end(),
1712 Record.begin(), Record.end());
Douglas Gregorb81c1702009-04-27 20:06:05 +00001713 break;
1714
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001715 case pch::VTABLE_USES:
1716 if (!VTableUses.empty()) {
1717 Error("duplicate VTABLE_USES record in PCH file");
1718 return Failure;
1719 }
1720 VTableUses.swap(Record);
1721 break;
1722
1723 case pch::DYNAMIC_CLASSES:
1724 if (!DynamicClasses.empty()) {
1725 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1726 return Failure;
1727 }
1728 DynamicClasses.swap(Record);
1729 break;
1730
Douglas Gregorb64c1932009-05-12 01:31:05 +00001731 case pch::ORIGINAL_FILE_NAME:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001732 // The primary PCH will be the last to get here, so it will be the one
1733 // that's used.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001734 ActualOriginalFileName.assign(BlobStart, BlobLen);
1735 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001736 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001737 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001739 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001740 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001741 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001742 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001743 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1744 return IgnorePCH;
1745 }
1746 break;
1747 }
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001748
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001749 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001750 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1751 F.NumPreallocatedPreprocessingEntities = Record[0];
1752 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001753 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001754 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001755 First = false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001756 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001757 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001758 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001759}
1760
Douglas Gregore1d918e2009-04-10 23:10:45 +00001761PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001762 switch(ReadPCHCore(FileName)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001763 case Failure: return Failure;
1764 case IgnorePCH: return IgnorePCH;
1765 case Success: break;
1766 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001767
1768 // Here comes stuff that we only do once the entire chain is loaded.
1769
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001770 // Allocate space for loaded identifiers, decls and types.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001771 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
1772 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001773 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redl2da08f92010-07-19 22:28:42 +00001774 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001775 TotalNumTypes += Chain[I]->LocalNumTypes;
1776 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001777 TotalNumPreallocatedPreprocessingEntities +=
1778 Chain[I]->NumPreallocatedPreprocessingEntities;
1779 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001780 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001781 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001782 TypesLoaded.resize(TotalNumTypes);
1783 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001784 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1785 if (PP) {
1786 if (TotalNumIdentifiers > 0)
1787 PP->getHeaderSearchInfo().SetExternalLookup(this);
1788 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1789 if (!PP->getPreprocessingRecord())
1790 PP->createPreprocessingRecord();
1791 PP->getPreprocessingRecord()->SetExternalSource(*this,
1792 TotalNumPreallocatedPreprocessingEntities);
1793 }
1794 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001795
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001796 // Check the predefines buffers.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001797 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001798 return IgnorePCH;
1799
1800 if (PP) {
1801 // Initialization of keywords and pragmas occurs before the
1802 // PCH file is read, so there may be some identifiers that were
1803 // loaded into the IdentifierTable before we intercepted the
1804 // creation of identifiers. Iterate through the list of known
1805 // identifiers and determine whether we have to establish
1806 // preprocessor definitions or top-level identifier declaration
1807 // chains for those identifiers.
1808 //
1809 // We copy the IdentifierInfo pointers to a small vector first,
1810 // since de-serializing declarations or macro definitions can add
1811 // new entries into the identifier table, invalidating the
1812 // iterators.
1813 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1814 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1815 IdEnd = PP->getIdentifierTable().end();
1816 Id != IdEnd; ++Id)
1817 Identifiers.push_back(Id->second);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001818 // We need to search the tables in all files.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001819 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1820 PCHIdentifierLookupTable *IdTable
1821 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00001822 // Not all PCH files necessarily have identifier tables, only the useful
1823 // ones.
1824 if (!IdTable)
1825 continue;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001826 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1827 IdentifierInfo *II = Identifiers[I];
1828 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001829 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001830 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001831 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1832 if (Pos == IdTable->end())
1833 continue;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001834
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001835 // Dereferencing the iterator has the effect of populating the
1836 // IdentifierInfo node with the various declarations it needs.
1837 (void)*Pos;
1838 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001839 }
1840 }
1841
1842 if (Context)
1843 InitializeContext(*Context);
1844
1845 return Success;
1846}
1847
1848PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1849 Chain.push_back(new PerFileData());
Sebastian Redl9137a522010-07-16 17:50:48 +00001850 PerFileData &F = *Chain.back();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001851
1852 // Set the PCH file name.
1853 F.FileName = FileName;
1854
1855 // Open the PCH file.
1856 //
1857 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1858 std::string ErrStr;
1859 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1860 if (!F.Buffer) {
1861 Error(ErrStr.c_str());
1862 return IgnorePCH;
1863 }
1864
1865 // Initialize the stream
1866 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1867 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl9137a522010-07-16 17:50:48 +00001868 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001869 Stream.init(F.StreamFile);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001870 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001871
1872 // Sniff for the signature.
1873 if (Stream.Read(8) != 'C' ||
1874 Stream.Read(8) != 'P' ||
1875 Stream.Read(8) != 'C' ||
1876 Stream.Read(8) != 'H') {
1877 Diag(diag::err_not_a_pch_file) << FileName;
1878 return Failure;
1879 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001880
Douglas Gregor2cf26342009-04-09 22:27:44 +00001881 while (!Stream.AtEndOfStream()) {
1882 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Douglas Gregore1d918e2009-04-10 23:10:45 +00001884 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001885 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001886 return Failure;
1887 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001888
1889 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001890
Douglas Gregor2cf26342009-04-09 22:27:44 +00001891 // We only know the PCH subblock ID.
1892 switch (BlockID) {
1893 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001894 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001895 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001896 return Failure;
1897 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001898 break;
1899 case pch::PCH_BLOCK_ID:
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001900 switch (ReadPCHBlock(F)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001901 case Success:
1902 break;
1903
1904 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001905 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001906
1907 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001908 // FIXME: We could consider reading through to the end of this
1909 // PCH block, skipping subblocks, to see if there are other
1910 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001911
1912 // Clear out any preallocated source location entries, so that
1913 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001914 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001915
1916 // Remove the stat cache.
Sebastian Redl9137a522010-07-16 17:50:48 +00001917 if (F.StatCache)
1918 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001919
Douglas Gregore1d918e2009-04-10 23:10:45 +00001920 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001921 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001922 break;
1923 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001924 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001925 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001926 return Failure;
1927 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001928 break;
1929 }
Mike Stump1eb44332009-09-09 15:08:12 +00001930 }
1931
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001932 return Success;
1933}
1934
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001935void PCHReader::setPreprocessor(Preprocessor &pp) {
1936 PP = &pp;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001937
1938 unsigned TotalNum = 0;
1939 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1940 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1941 if (TotalNum) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001942 if (!PP->getPreprocessingRecord())
1943 PP->createPreprocessingRecord();
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001944 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001945 }
1946}
1947
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001948void PCHReader::InitializeContext(ASTContext &Ctx) {
1949 Context = &Ctx;
1950 assert(Context && "Passed null context!");
1951
1952 assert(PP && "Forgot to set Preprocessor ?");
1953 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1954 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001955 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001956
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001957 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001958 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001959
1960 // Load the special types.
1961 Context->setBuiltinVaListType(
1962 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1963 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1964 Context->setObjCIdType(GetType(Id));
1965 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1966 Context->setObjCSelType(GetType(Sel));
1967 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1968 Context->setObjCProtoType(GetType(Proto));
1969 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1970 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001971
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001972 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1973 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001974 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001975 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1976 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001977 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1978 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001979 if (FileType.isNull()) {
1980 Error("FILE type is NULL");
1981 return;
1982 }
John McCall183700f2009-09-21 23:43:11 +00001983 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001984 Context->setFILEDecl(Typedef->getDecl());
1985 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001986 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001987 if (!Tag) {
1988 Error("Invalid FILE type in PCH file");
1989 return;
1990 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001991 Context->setFILEDecl(Tag->getDecl());
1992 }
1993 }
Mike Stump782fa302009-07-28 02:25:19 +00001994 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1995 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001996 if (Jmp_bufType.isNull()) {
1997 Error("jmp_bug type is NULL");
1998 return;
1999 }
John McCall183700f2009-09-21 23:43:11 +00002000 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002001 Context->setjmp_bufDecl(Typedef->getDecl());
2002 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002003 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002004 if (!Tag) {
2005 Error("Invalid jmp_bug type in PCH file");
2006 return;
2007 }
Mike Stump782fa302009-07-28 02:25:19 +00002008 Context->setjmp_bufDecl(Tag->getDecl());
2009 }
2010 }
2011 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2012 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002013 if (Sigjmp_bufType.isNull()) {
2014 Error("sigjmp_buf type is NULL");
2015 return;
2016 }
John McCall183700f2009-09-21 23:43:11 +00002017 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002018 Context->setsigjmp_bufDecl(Typedef->getDecl());
2019 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002020 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00002021 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2022 Context->setsigjmp_bufDecl(Tag->getDecl());
2023 }
2024 }
Mike Stump1eb44332009-09-09 15:08:12 +00002025 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002026 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2027 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00002028 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002029 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2030 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00002031 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2032 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00002033 if (unsigned String
2034 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2035 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002036 if (unsigned ObjCSelRedef
2037 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2038 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2039 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2040 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00002041
2042 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2043 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002044}
2045
Douglas Gregorb64c1932009-05-12 01:31:05 +00002046/// \brief Retrieve the name of the original source file name
2047/// directly from the PCH file, without actually loading the PCH
2048/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002049std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2050 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00002051 // Open the PCH file.
2052 std::string ErrStr;
2053 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2054 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2055 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002056 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002057 return std::string();
2058 }
2059
2060 // Initialize the stream
2061 llvm::BitstreamReader StreamFile;
2062 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00002063 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00002064 (const unsigned char *)Buffer->getBufferEnd());
2065 Stream.init(StreamFile);
2066
2067 // Sniff for the signature.
2068 if (Stream.Read(8) != 'C' ||
2069 Stream.Read(8) != 'P' ||
2070 Stream.Read(8) != 'C' ||
2071 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002072 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002073 return std::string();
2074 }
2075
2076 RecordData Record;
2077 while (!Stream.AtEndOfStream()) {
2078 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Douglas Gregorb64c1932009-05-12 01:31:05 +00002080 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2081 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Douglas Gregorb64c1932009-05-12 01:31:05 +00002083 // We only know the PCH subblock ID.
2084 switch (BlockID) {
2085 case pch::PCH_BLOCK_ID:
2086 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002087 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002088 return std::string();
2089 }
2090 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Douglas Gregorb64c1932009-05-12 01:31:05 +00002092 default:
2093 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002094 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002095 return std::string();
2096 }
2097 break;
2098 }
2099 continue;
2100 }
2101
2102 if (Code == llvm::bitc::END_BLOCK) {
2103 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002104 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002105 return std::string();
2106 }
2107 continue;
2108 }
2109
2110 if (Code == llvm::bitc::DEFINE_ABBREV) {
2111 Stream.ReadAbbrevRecord();
2112 continue;
2113 }
2114
2115 Record.clear();
2116 const char *BlobStart = 0;
2117 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002118 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00002119 == pch::ORIGINAL_FILE_NAME)
2120 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00002121 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00002122
2123 return std::string();
2124}
2125
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002126/// \brief Parse the record that corresponds to a LangOptions data
2127/// structure.
2128///
2129/// This routine compares the language options used to generate the
2130/// PCH file against the language options set for the current
2131/// compilation. For each option, we classify differences between the
2132/// two compiler states as either "benign" or "important". Benign
2133/// differences don't matter, and we accept them without complaint
2134/// (and without modifying the language options). Differences between
2135/// the states for important options cause the PCH file to be
2136/// unusable, so we emit a warning and return true to indicate that
2137/// there was an error.
2138///
2139/// \returns true if the PCH file is unacceptable, false otherwise.
2140bool PCHReader::ParseLanguageOptions(
2141 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002142 if (Listener) {
2143 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002145 #define PARSE_LANGOPT(Option) \
2146 LangOpts.Option = Record[Idx]; \
2147 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002149 unsigned Idx = 0;
2150 PARSE_LANGOPT(Trigraphs);
2151 PARSE_LANGOPT(BCPLComment);
2152 PARSE_LANGOPT(DollarIdents);
2153 PARSE_LANGOPT(AsmPreprocessor);
2154 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00002155 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002156 PARSE_LANGOPT(ImplicitInt);
2157 PARSE_LANGOPT(Digraphs);
2158 PARSE_LANGOPT(HexFloats);
2159 PARSE_LANGOPT(C99);
2160 PARSE_LANGOPT(Microsoft);
2161 PARSE_LANGOPT(CPlusPlus);
2162 PARSE_LANGOPT(CPlusPlus0x);
2163 PARSE_LANGOPT(CXXOperatorNames);
2164 PARSE_LANGOPT(ObjC1);
2165 PARSE_LANGOPT(ObjC2);
2166 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002167 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00002168 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002169 PARSE_LANGOPT(PascalStrings);
2170 PARSE_LANGOPT(WritableStrings);
2171 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002172 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002173 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002174 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002175 PARSE_LANGOPT(NeXTRuntime);
2176 PARSE_LANGOPT(Freestanding);
2177 PARSE_LANGOPT(NoBuiltin);
2178 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002179 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002180 PARSE_LANGOPT(Blocks);
2181 PARSE_LANGOPT(EmitAllDecls);
2182 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002183 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2184 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002185 PARSE_LANGOPT(HeinousExtensions);
2186 PARSE_LANGOPT(Optimize);
2187 PARSE_LANGOPT(OptimizeSize);
2188 PARSE_LANGOPT(Static);
2189 PARSE_LANGOPT(PICLevel);
2190 PARSE_LANGOPT(GNUInline);
2191 PARSE_LANGOPT(NoInline);
2192 PARSE_LANGOPT(AccessControl);
2193 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002194 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002195 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2196 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002197 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002198 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002199 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002200 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002201 PARSE_LANGOPT(CatchUndefined);
2202 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002203 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002204
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002205 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002206 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002207
2208 return false;
2209}
2210
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002211void PCHReader::ReadPreprocessedEntities() {
2212 ReadDefinedMacros();
2213}
2214
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002215/// \brief Get the correct cursor and offset for loading a type.
2216PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2217 PerFileData *F = 0;
2218 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2219 F = Chain[N - I - 1];
2220 if (Index < F->LocalNumTypes)
2221 break;
2222 Index -= F->LocalNumTypes;
2223 }
2224 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redl971dd442010-07-20 22:55:31 +00002225 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002226}
2227
2228/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00002229///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002230/// The index is the type ID, shifted and minus the number of predefs. This
2231/// routine actually reads the record corresponding to the type at the given
2232/// location. It is a helper routine for GetType, which deals with reading type
2233/// IDs.
2234QualType PCHReader::ReadTypeRecord(unsigned Index) {
2235 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redl971dd442010-07-20 22:55:31 +00002236 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl9137a522010-07-16 17:50:48 +00002237
Douglas Gregor0b748912009-04-14 21:18:50 +00002238 // Keep track of where we are in the stream, then jump back there
2239 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002240 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002241
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002242 ReadingKindTracker ReadingKind(Read_Type, *this);
2243
Douglas Gregord89275b2009-07-06 18:54:52 +00002244 // Note that we are loading a type record.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00002245 Deserializing AType(this);
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002247 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002248 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002249 unsigned Code = DeclsCursor.ReadCode();
2250 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002251 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002252 if (Record.size() != 2) {
2253 Error("Incorrect encoding of extended qualifier type");
2254 return QualType();
2255 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002256 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002257 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2258 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002259 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002260
Douglas Gregor2cf26342009-04-09 22:27:44 +00002261 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002262 if (Record.size() != 1) {
2263 Error("Incorrect encoding of complex type");
2264 return QualType();
2265 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002266 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002267 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002268 }
2269
2270 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002271 if (Record.size() != 1) {
2272 Error("Incorrect encoding of pointer type");
2273 return QualType();
2274 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002275 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002276 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002277 }
2278
2279 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002280 if (Record.size() != 1) {
2281 Error("Incorrect encoding of block pointer type");
2282 return QualType();
2283 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002284 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002285 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002286 }
2287
2288 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002289 if (Record.size() != 1) {
2290 Error("Incorrect encoding of lvalue reference type");
2291 return QualType();
2292 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002293 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002294 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002295 }
2296
2297 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002298 if (Record.size() != 1) {
2299 Error("Incorrect encoding of rvalue reference type");
2300 return QualType();
2301 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002302 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002303 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002304 }
2305
2306 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002307 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002308 Error("Incorrect encoding of member pointer type");
2309 return QualType();
2310 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002311 QualType PointeeType = GetType(Record[0]);
2312 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002313 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002314 }
2315
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002316 case pch::TYPE_CONSTANT_ARRAY: {
2317 QualType ElementType = GetType(Record[0]);
2318 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2319 unsigned IndexTypeQuals = Record[2];
2320 unsigned Idx = 3;
2321 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002322 return Context->getConstantArrayType(ElementType, Size,
2323 ASM, IndexTypeQuals);
2324 }
2325
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002326 case pch::TYPE_INCOMPLETE_ARRAY: {
2327 QualType ElementType = GetType(Record[0]);
2328 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2329 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002330 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002331 }
2332
2333 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002334 QualType ElementType = GetType(Record[0]);
2335 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2336 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002337 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2338 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redl577d4792010-07-22 22:43:28 +00002339 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002340 ASM, IndexTypeQuals,
2341 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002342 }
2343
2344 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002345 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002346 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002347 return QualType();
2348 }
2349
2350 QualType ElementType = GetType(Record[0]);
2351 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002352 unsigned AltiVecSpec = Record[2];
2353 return Context->getVectorType(ElementType, NumElements,
2354 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002355 }
2356
2357 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002358 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002359 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002360 return QualType();
2361 }
2362
2363 QualType ElementType = GetType(Record[0]);
2364 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002365 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002366 }
2367
2368 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002369 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002370 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002371 return QualType();
2372 }
2373 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002374 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002375 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002376 }
2377
2378 case pch::TYPE_FUNCTION_PROTO: {
2379 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002380 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002381 unsigned RegParm = Record[2];
2382 CallingConv CallConv = (CallingConv)Record[3];
2383 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002384 unsigned NumParams = Record[Idx++];
2385 llvm::SmallVector<QualType, 16> ParamTypes;
2386 for (unsigned I = 0; I != NumParams; ++I)
2387 ParamTypes.push_back(GetType(Record[Idx++]));
2388 bool isVariadic = Record[Idx++];
2389 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002390 bool hasExceptionSpec = Record[Idx++];
2391 bool hasAnyExceptionSpec = Record[Idx++];
2392 unsigned NumExceptions = Record[Idx++];
2393 llvm::SmallVector<QualType, 2> Exceptions;
2394 for (unsigned I = 0; I != NumExceptions; ++I)
2395 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002396 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002397 isVariadic, Quals, hasExceptionSpec,
2398 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002399 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002400 FunctionType::ExtInfo(NoReturn, RegParm,
2401 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002402 }
2403
John McCalled976492009-12-04 22:46:56 +00002404 case pch::TYPE_UNRESOLVED_USING:
2405 return Context->getTypeDeclType(
2406 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2407
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002408 case pch::TYPE_TYPEDEF: {
2409 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002410 Error("incorrect encoding of typedef type");
2411 return QualType();
2412 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002413 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2414 QualType Canonical = GetType(Record[1]);
2415 return Context->getTypedefType(Decl, Canonical);
2416 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002417
2418 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redl577d4792010-07-22 22:43:28 +00002419 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002420
2421 case pch::TYPE_TYPEOF: {
2422 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002423 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002424 return QualType();
2425 }
2426 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002427 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002428 }
Mike Stump1eb44332009-09-09 15:08:12 +00002429
Anders Carlsson395b4752009-06-24 19:06:50 +00002430 case pch::TYPE_DECLTYPE:
Sebastian Redl577d4792010-07-22 22:43:28 +00002431 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson395b4752009-06-24 19:06:50 +00002432
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002433 case pch::TYPE_RECORD: {
2434 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002435 Error("incorrect encoding of record type");
2436 return QualType();
2437 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002438 bool IsDependent = Record[0];
2439 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2440 T->Dependent = IsDependent;
2441 return T;
2442 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002443
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002444 case pch::TYPE_ENUM: {
2445 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002446 Error("incorrect encoding of enum type");
2447 return QualType();
2448 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002449 bool IsDependent = Record[0];
2450 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2451 T->Dependent = IsDependent;
2452 return T;
2453 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002454
John McCall7da24312009-09-05 00:15:47 +00002455 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002456 unsigned Idx = 0;
2457 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2458 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2459 QualType NamedType = GetType(Record[Idx++]);
2460 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002461 }
2462
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002463 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002464 unsigned Idx = 0;
2465 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002466 return Context->getObjCInterfaceType(ItfD);
2467 }
2468
2469 case pch::TYPE_OBJC_OBJECT: {
2470 unsigned Idx = 0;
2471 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002472 unsigned NumProtos = Record[Idx++];
2473 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2474 for (unsigned I = 0; I != NumProtos; ++I)
2475 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002476 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002477 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002478
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002479 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002480 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002481 QualType Pointee = GetType(Record[Idx++]);
2482 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002483 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002484
John McCall49a832b2009-10-18 09:09:24 +00002485 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2486 unsigned Idx = 0;
2487 QualType Parm = GetType(Record[Idx++]);
2488 QualType Replacement = GetType(Record[Idx++]);
2489 return
2490 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2491 Replacement);
2492 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002493
2494 case pch::TYPE_INJECTED_CLASS_NAME: {
2495 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2496 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002497 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2498 // for PCH reading, too much interdependencies.
2499 return
2500 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002501 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002502
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002503 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2504 unsigned Idx = 0;
2505 unsigned Depth = Record[Idx++];
2506 unsigned Index = Record[Idx++];
2507 bool Pack = Record[Idx++];
2508 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2509 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2510 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002511
2512 case pch::TYPE_DEPENDENT_NAME: {
2513 unsigned Idx = 0;
2514 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2515 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2516 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002517 QualType Canon = GetType(Record[Idx++]);
2518 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002519 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002520
2521 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2522 unsigned Idx = 0;
2523 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2524 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2525 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2526 unsigned NumArgs = Record[Idx++];
2527 llvm::SmallVector<TemplateArgument, 8> Args;
2528 Args.reserve(NumArgs);
2529 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00002530 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002531 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2532 Args.size(), Args.data());
2533 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002534
2535 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2536 unsigned Idx = 0;
2537
2538 // ArrayType
2539 QualType ElementType = GetType(Record[Idx++]);
2540 ArrayType::ArraySizeModifier ASM
2541 = (ArrayType::ArraySizeModifier)Record[Idx++];
2542 unsigned IndexTypeQuals = Record[Idx++];
2543
2544 // DependentSizedArrayType
Sebastian Redl577d4792010-07-22 22:43:28 +00002545 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002546 SourceRange Brackets = ReadSourceRange(Record, Idx);
2547
2548 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2549 IndexTypeQuals, Brackets);
2550 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002551
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002552 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2553 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002554 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002555 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002556 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redl577d4792010-07-22 22:43:28 +00002557 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002558 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002559 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002560 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002561 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2562 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002563 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002564 T = Context->getTemplateSpecializationType(Name, Args.data(),
2565 Args.size(), Canon);
2566 T->Dependent = IsDependent;
2567 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002568 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002569 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002570 // Suppress a GCC warning
2571 return QualType();
2572}
2573
John McCalla1ee0c52009-10-16 21:56:05 +00002574namespace {
2575
2576class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2577 PCHReader &Reader;
Sebastian Redl577d4792010-07-22 22:43:28 +00002578 llvm::BitstreamCursor &DeclsCursor;
John McCalla1ee0c52009-10-16 21:56:05 +00002579 const PCHReader::RecordData &Record;
2580 unsigned &Idx;
2581
2582public:
Sebastian Redl577d4792010-07-22 22:43:28 +00002583 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2584 const PCHReader::RecordData &Record, unsigned &Idx)
2585 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCalla1ee0c52009-10-16 21:56:05 +00002586
John McCall51bd8032009-10-18 01:05:36 +00002587 // We want compile-time assurance that we've enumerated all of
2588 // these, so unfortunately we have to declare them first, then
2589 // define them out-of-line.
2590#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002591#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002592 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002593#include "clang/AST/TypeLocNodes.def"
2594
John McCall51bd8032009-10-18 01:05:36 +00002595 void VisitFunctionTypeLoc(FunctionTypeLoc);
2596 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002597};
2598
2599}
2600
John McCall51bd8032009-10-18 01:05:36 +00002601void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002602 // nothing to do
2603}
John McCall51bd8032009-10-18 01:05:36 +00002604void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002605 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2606 if (TL.needsExtraLocalData()) {
2607 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2608 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2609 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2610 TL.setModeAttr(Record[Idx++]);
2611 }
John McCalla1ee0c52009-10-16 21:56:05 +00002612}
John McCall51bd8032009-10-18 01:05:36 +00002613void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2614 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002615}
John McCall51bd8032009-10-18 01:05:36 +00002616void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2617 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002618}
John McCall51bd8032009-10-18 01:05:36 +00002619void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2620 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002621}
John McCall51bd8032009-10-18 01:05:36 +00002622void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2623 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002624}
John McCall51bd8032009-10-18 01:05:36 +00002625void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2626 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002627}
John McCall51bd8032009-10-18 01:05:36 +00002628void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2629 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002630}
John McCall51bd8032009-10-18 01:05:36 +00002631void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2632 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2633 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002634 if (Record[Idx++])
Sebastian Redl577d4792010-07-22 22:43:28 +00002635 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002636 else
John McCall51bd8032009-10-18 01:05:36 +00002637 TL.setSizeExpr(0);
2638}
2639void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2640 VisitArrayTypeLoc(TL);
2641}
2642void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2643 VisitArrayTypeLoc(TL);
2644}
2645void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2646 VisitArrayTypeLoc(TL);
2647}
2648void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2649 DependentSizedArrayTypeLoc TL) {
2650 VisitArrayTypeLoc(TL);
2651}
2652void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2653 DependentSizedExtVectorTypeLoc TL) {
2654 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2655}
2656void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2657 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2658}
2659void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2660 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2661}
2662void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2663 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2664 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2665 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002666 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002667 }
2668}
2669void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2670 VisitFunctionTypeLoc(TL);
2671}
2672void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2673 VisitFunctionTypeLoc(TL);
2674}
John McCalled976492009-12-04 22:46:56 +00002675void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2676 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2677}
John McCall51bd8032009-10-18 01:05:36 +00002678void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2679 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2680}
2681void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002682 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2683 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2684 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002685}
2686void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002687 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2688 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2689 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redl577d4792010-07-22 22:43:28 +00002690 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002691}
2692void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2693 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2694}
2695void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2696 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2697}
2698void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2699 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2700}
John McCall51bd8032009-10-18 01:05:36 +00002701void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2702 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2703}
John McCall49a832b2009-10-18 09:09:24 +00002704void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2705 SubstTemplateTypeParmTypeLoc TL) {
2706 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2707}
John McCall51bd8032009-10-18 01:05:36 +00002708void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2709 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002710 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2711 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2712 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2713 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2714 TL.setArgLocInfo(i,
2715 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002716 DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002717}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002718void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002719 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2720 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002721}
John McCall3cb0ebd2010-03-10 03:28:59 +00002722void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2723 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2724}
Douglas Gregor4714c122010-03-31 17:34:00 +00002725void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002726 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2727 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002728 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2729}
John McCall33500952010-06-11 00:33:02 +00002730void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2731 DependentTemplateSpecializationTypeLoc TL) {
2732 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2733 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2734 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2735 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2736 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2737 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2738 TL.setArgLocInfo(I,
2739 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002740 DeclsCursor, Record, Idx));
John McCall33500952010-06-11 00:33:02 +00002741}
John McCall51bd8032009-10-18 01:05:36 +00002742void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2743 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002744}
2745void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2746 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002747 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2748 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2749 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2750 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002751}
John McCall54e14c42009-10-22 22:37:11 +00002752void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2753 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002754}
John McCalla1ee0c52009-10-16 21:56:05 +00002755
Sebastian Redl577d4792010-07-22 22:43:28 +00002756TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2757 const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002758 unsigned &Idx) {
2759 QualType InfoTy = GetType(Record[Idx++]);
2760 if (InfoTy.isNull())
2761 return 0;
2762
John McCalla93c9342009-12-07 02:54:59 +00002763 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redl577d4792010-07-22 22:43:28 +00002764 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002765 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002766 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002767 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002768}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002769
Douglas Gregor8038d512009-04-10 17:25:41 +00002770QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002771 unsigned FastQuals = ID & Qualifiers::FastMask;
2772 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002773
2774 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2775 QualType T;
2776 switch ((pch::PredefinedTypeIDs)Index) {
2777 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002778 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2779 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002780
2781 case pch::PREDEF_TYPE_CHAR_U_ID:
2782 case pch::PREDEF_TYPE_CHAR_S_ID:
2783 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002784 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002785 break;
2786
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002787 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2788 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2789 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2790 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2791 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002792 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002793 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2794 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2795 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2796 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2797 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2798 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002799 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002800 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2801 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2802 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2803 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2804 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002805 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002806 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2807 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002808 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2809 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002810 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002811 }
2812
2813 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002814 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002815 }
2816
2817 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002818 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002819 if (TypesLoaded[Index].isNull()) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002820 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002821 TypesLoaded[Index]->setFromPCH();
Sebastian Redl30c514c2010-07-14 23:45:08 +00002822 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002823 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2824 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002825 }
Mike Stump1eb44332009-09-09 15:08:12 +00002826
John McCall0953e762009-09-24 19:53:00 +00002827 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002828}
2829
John McCall833ca992009-10-29 08:12:44 +00002830TemplateArgumentLocInfo
2831PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redl577d4792010-07-22 22:43:28 +00002832 llvm::BitstreamCursor &DeclsCursor,
John McCall833ca992009-10-29 08:12:44 +00002833 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002834 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002835 switch (Kind) {
2836 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00002837 return ReadExpr(DeclsCursor);
John McCall833ca992009-10-29 08:12:44 +00002838 case TemplateArgument::Type:
Sebastian Redl577d4792010-07-22 22:43:28 +00002839 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002840 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002841 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2842 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2843 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002844 }
John McCall833ca992009-10-29 08:12:44 +00002845 case TemplateArgument::Null:
2846 case TemplateArgument::Integral:
2847 case TemplateArgument::Declaration:
2848 case TemplateArgument::Pack:
2849 return TemplateArgumentLocInfo();
2850 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002851 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002852 return TemplateArgumentLocInfo();
2853}
2854
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002855TemplateArgumentLoc
Sebastian Redl577d4792010-07-22 22:43:28 +00002856PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2857 const RecordData &Record, unsigned &Index) {
2858 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002859
2860 if (Arg.getKind() == TemplateArgument::Expression) {
2861 if (Record[Index++]) // bool InfoHasSameExpr.
2862 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2863 }
2864 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002865 DeclsCursor,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002866 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002867}
2868
John McCall76bd1f32010-06-01 09:23:16 +00002869Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2870 return GetDecl(ID);
2871}
2872
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002873TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl30c514c2010-07-14 23:45:08 +00002874 if (!DeclsLoaded[0]) {
Sebastian Redlcb526aa2010-07-20 22:46:15 +00002875 ReadDeclRecord(0);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002876 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002877 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002878 }
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002879
2880 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2881}
2882
Douglas Gregor8038d512009-04-10 17:25:41 +00002883Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002884 if (ID == 0)
2885 return 0;
2886
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002887 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002888 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002889 return 0;
2890 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002891
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002892 unsigned Index = ID - 1;
Sebastian Redl30c514c2010-07-14 23:45:08 +00002893 if (!DeclsLoaded[Index]) {
Sebastian Redlcb526aa2010-07-20 22:46:15 +00002894 ReadDeclRecord(Index);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002895 if (DeserializationListener)
2896 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2897 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002898
2899 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002900}
2901
Chris Lattner887e2b32009-04-27 05:46:25 +00002902/// \brief Resolve the offset of a statement into a statement.
2903///
2904/// This operation will read a new statement from the external
2905/// source each time it is called, and is meant to be used via a
2906/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002907Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002908 // Offset here is a global offset across the entire chain.
2909 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2910 PerFileData &F = *Chain[N - I - 1];
2911 if (Offset < F.SizeInBits) {
2912 // Since we know that this statement is part of a decl, make sure to use
2913 // the decl cursor to read it.
2914 F.DeclsCursor.JumpToBit(Offset);
2915 return ReadStmtFromStream(F.DeclsCursor);
2916 }
2917 Offset -= F.SizeInBits;
2918 }
2919 llvm_unreachable("Broken chain");
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002920}
2921
John McCall76bd1f32010-06-01 09:23:16 +00002922bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2923 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002924 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002925 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002926
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002927 // There might be lexical decls in multiple parts of the chain, for the TU
2928 // at least.
2929 DeclContextInfos &Infos = DeclContextOffsets[DC];
2930 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2931 I != E; ++I) {
Sebastian Redl681d7232010-07-27 00:17:23 +00002932 // IDs can be 0 if this context doesn't contain declarations.
2933 if (!I->LexicalDecls)
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002934 continue;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002935
2936 // Load all of the declaration IDs
Sebastian Redl681d7232010-07-27 00:17:23 +00002937 for (const pch::DeclID *ID = I->LexicalDecls,
2938 *IDE = ID + I->NumLexicalDecls;
2939 ID != IDE; ++ID)
2940 Decls.push_back(GetDecl(*ID));
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002941 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002942
Douglas Gregor25123082009-04-22 22:34:57 +00002943 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002944 return false;
2945}
2946
John McCall76bd1f32010-06-01 09:23:16 +00002947DeclContext::lookup_result
2948PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2949 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002950 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002951 "DeclContext has no visible decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002952
John McCall76bd1f32010-06-01 09:23:16 +00002953 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002954 // There might be lexical decls in multiple parts of the chain, for the TU
2955 // and namespaces.
2956 DeclContextInfos &Infos = DeclContextOffsets[DC];
2957 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2958 I != E; ++I) {
2959 uint64_t Offset = I->OffsetToVisibleDecls;
2960 if (Offset == 0)
2961 continue;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002962
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002963 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002964
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002965 // Keep track of where we are in the stream, then jump back there
2966 // after reading this context.
2967 SavedStreamPosition SavedPosition(DeclsCursor);
2968
2969 // Load the record containing all of the declarations visible in
2970 // this context.
2971 DeclsCursor.JumpToBit(Offset);
2972 RecordData Record;
2973 unsigned Code = DeclsCursor.ReadCode();
2974 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2975 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2976 Error("Expected visible block");
2977 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2978 DeclContext::lookup_iterator());
2979 }
2980
2981 if (Record.empty())
2982 continue;
2983
2984 unsigned Idx = 0;
2985 while (Idx < Record.size()) {
2986 Decls.push_back(VisibleDeclaration());
2987 Decls.back().Name = ReadDeclarationName(Record, Idx);
2988
2989 unsigned Size = Record[Idx++];
2990 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
2991 LoadedDecls.reserve(Size);
2992 for (unsigned J = 0; J < Size; ++J)
2993 LoadedDecls.push_back(Record[Idx++]);
2994 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002995 }
2996
Douglas Gregor25123082009-04-22 22:34:57 +00002997 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00002998
2999 SetExternalVisibleDecls(DC, Decls);
3000 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00003001}
3002
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003003void PCHReader::PassInterestingDeclsToConsumer() {
3004 assert(Consumer);
3005 while (!InterestingDecls.empty()) {
3006 DeclGroupRef DG(InterestingDecls.front());
3007 InterestingDecls.pop_front();
3008 Consumer->HandleTopLevelDecl(DG);
3009 }
3010}
3011
Douglas Gregorfdd01722009-04-14 00:24:19 +00003012void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00003013 this->Consumer = Consumer;
3014
Douglas Gregorfdd01722009-04-14 00:24:19 +00003015 if (!Consumer)
3016 return;
3017
3018 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003019 // Force deserialization of this decl, which will cause it to be queued for
3020 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00003021 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00003022 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00003023
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003024 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00003025}
3026
Douglas Gregor2cf26342009-04-09 22:27:44 +00003027void PCHReader::PrintStats() {
3028 std::fprintf(stderr, "*** PCH Statistics:\n");
3029
Mike Stump1eb44332009-09-09 15:08:12 +00003030 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003031 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00003032 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003033 unsigned NumDeclsLoaded
3034 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3035 (Decl *)0);
3036 unsigned NumIdentifiersLoaded
3037 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3038 IdentifiersLoaded.end(),
3039 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00003040 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003041 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3042 SelectorsLoaded.end(),
3043 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00003044
Douglas Gregor4fed3f42009-04-27 18:38:38 +00003045 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3046 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003047 if (TotalNumSLocEntries)
3048 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3049 NumSLocEntriesRead, TotalNumSLocEntries,
3050 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003051 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003052 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003053 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3054 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3055 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003056 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003057 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3058 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003059 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003060 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003061 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3062 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00003063 if (TotalNumSelectors)
3064 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
3065 NumSelectorsLoaded, TotalNumSelectors,
3066 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
3067 if (TotalNumStatements)
3068 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3069 NumStatementsRead, TotalNumStatements,
3070 ((float)NumStatementsRead/TotalNumStatements * 100));
3071 if (TotalNumMacros)
3072 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3073 NumMacrosRead, TotalNumMacros,
3074 ((float)NumMacrosRead/TotalNumMacros * 100));
3075 if (TotalLexicalDeclContexts)
3076 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3077 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3078 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3079 * 100));
3080 if (TotalVisibleDeclContexts)
3081 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3082 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3083 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3084 * 100));
3085 if (TotalSelectorsInMethodPool) {
3086 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
3087 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
3088 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
3089 * 100));
3090 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
3091 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003092 std::fprintf(stderr, "\n");
3093}
3094
Douglas Gregor668c1a42009-04-21 22:25:48 +00003095void PCHReader::InitializeSema(Sema &S) {
3096 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003097 S.ExternalSource = this;
3098
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003099 // Makes sure any declarations that were deserialized "too early"
3100 // still get added to the identifier's declaration chains.
3101 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3102 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3103 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003104 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003105 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003106
3107 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00003108 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003109 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3110 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00003111 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003112 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00003113
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003114 // If there were any unused static functions, deserialize them and add to
3115 // Sema's list of unused static functions.
3116 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3117 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3118 SemaObj->UnusedStaticFuncs.push_back(FD);
3119 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00003120
3121 // If there were any locally-scoped external declarations,
3122 // deserialize them and add them to Sema's table of locally-scoped
3123 // external declarations.
3124 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3125 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3126 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3127 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00003128
3129 // If there were any ext_vector type declarations, deserialize them
3130 // and add them to Sema's vector of such declarations.
3131 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3132 SemaObj->ExtVectorDecls.push_back(
3133 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003134
3135 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3136 // Can we cut them down before writing them ?
3137
3138 // If there were any VTable uses, deserialize the information and add it
3139 // to Sema's vector and map of VTable uses.
3140 unsigned Idx = 0;
3141 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3142 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3143 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3144 bool DefinitionRequired = VTableUses[Idx++];
3145 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3146 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3147 }
3148
3149 // If there were any dynamic classes declarations, deserialize them
3150 // and add them to Sema's vector of such declarations.
3151 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3152 SemaObj->DynamicClasses.push_back(
3153 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanian32019832010-07-23 19:11:11 +00003154
3155 // If there are @selector references added them to its pool. This is for
3156 // implementation of -Wselector.
3157 PerFileData &F = *Chain[0];
3158 if (!F.ReferencedSelectorsData.empty()) {
3159 unsigned int DataSize = F.ReferencedSelectorsData.size()-1;
3160 unsigned I = 0;
3161 while (I < DataSize) {
3162 Selector Sel = DecodeSelector(F.ReferencedSelectorsData[I++]);
3163 SourceLocation SelLoc =
3164 SourceLocation::getFromRawEncoding(F.ReferencedSelectorsData[I++]);
3165 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3166 }
3167 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00003168}
3169
3170IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003171 // Try to find this name within our on-disk hash tables. We need to aggregate
3172 // the info from all of them.
3173 IdentifierInfo *II = 0;
3174 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3175 PCHIdentifierLookupTable *IdTable
3176 = (PCHIdentifierLookupTable *)Chain[N - I - 1]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00003177 if (!IdTable)
3178 continue;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003179 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3180 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3181 if (Pos == IdTable->end())
3182 continue;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003183
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003184 // Dereferencing the iterator has the effect of building the
3185 // IdentifierInfo node and populating it with the various
3186 // declarations it needs.
3187 II = *Pos;
3188 }
3189 return II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003190}
3191
Mike Stump1eb44332009-09-09 15:08:12 +00003192std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003193PCHReader::ReadMethodPool(Selector Sel) {
3194 if (!MethodPoolLookupTable)
3195 return std::pair<ObjCMethodList, ObjCMethodList>();
3196
3197 // Try to find this selector within our on-disk hash table.
3198 PCHMethodPoolLookupTable *PoolTable
3199 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
3200 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00003201 if (Pos == PoolTable->end()) {
3202 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003203 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00003204 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003205
Douglas Gregor83941df2009-04-25 17:48:32 +00003206 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003207 return *Pos;
3208}
3209
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003210void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00003211 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00003212 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003213 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003214 if (DeserializationListener)
3215 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003216}
3217
Douglas Gregord89275b2009-07-06 18:54:52 +00003218/// \brief Set the globally-visible declarations associated with the given
3219/// identifier.
3220///
3221/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00003222/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00003223/// them.
3224///
3225/// \param II an IdentifierInfo that refers to one or more globally-visible
3226/// declarations.
3227///
3228/// \param DeclIDs the set of declaration IDs with the name @p II that are
3229/// visible at global scope.
3230///
3231/// \param Nonrecursive should be true to indicate that the caller knows that
3232/// this call is non-recursive, and therefore the globally-visible declarations
3233/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003234void
3235PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003236 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3237 bool Nonrecursive) {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003238 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003239 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3240 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3241 PII.II = II;
3242 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3243 PII.DeclIDs.push_back(DeclIDs[I]);
3244 return;
3245 }
Mike Stump1eb44332009-09-09 15:08:12 +00003246
Douglas Gregord89275b2009-07-06 18:54:52 +00003247 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3248 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3249 if (SemaObj) {
3250 // Introduce this declaration into the translation-unit scope
3251 // and add it to the declaration chain for this identifier, so
3252 // that (unqualified) name lookup will find it.
3253 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3254 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3255 } else {
3256 // Queue this declaration so that it will be added to the
3257 // translation unit scope and identifier's declaration chain
3258 // once a Sema object is known.
3259 PreloadedDecls.push_back(D);
3260 }
3261 }
3262}
3263
Chris Lattner7356a312009-04-11 21:15:38 +00003264IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003265 if (ID == 0)
3266 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003268 if (IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003269 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003270 return 0;
3271 }
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003273 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003274 ID -= 1;
3275 if (!IdentifiersLoaded[ID]) {
3276 unsigned Index = ID;
3277 const char *Str = 0;
3278 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3279 PerFileData *F = Chain[N - I - 1];
3280 if (Index < F->LocalNumIdentifiers) {
3281 uint32_t Offset = F->IdentifierOffsets[Index];
3282 Str = F->IdentifierTableData + Offset;
3283 break;
3284 }
3285 Index -= F->LocalNumIdentifiers;
3286 }
3287 assert(Str && "Broken Chain");
Douglas Gregord6595a42009-04-25 21:04:17 +00003288
Douglas Gregor02fc7512009-04-28 20:01:51 +00003289 // All of the strings in the PCH file are preceded by a 16-bit
3290 // length. Extract that 16-bit length to avoid having to execute
3291 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003292 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3293 // unsigned integers. This is important to avoid integer overflow when
3294 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003295 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003296 unsigned StrLen = (((unsigned) StrLenPtr[0])
3297 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003298 IdentifiersLoaded[ID]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003299 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003300 if (DeserializationListener)
3301 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003302 }
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003304 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003305}
3306
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003307void PCHReader::ReadSLocEntry(unsigned ID) {
3308 ReadSLocEntryRecord(ID);
3309}
3310
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003311Selector PCHReader::DecodeSelector(unsigned ID) {
3312 if (ID == 0)
3313 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Douglas Gregora02b1472009-04-28 21:53:25 +00003315 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003316 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00003317
3318 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003319 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003320 return Selector();
3321 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003322
3323 unsigned Index = ID - 1;
3324 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3325 // Load this selector from the selector table.
3326 // FIXME: endianness portability issues with SelectorOffsets table
3327 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00003328 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00003329 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3330 }
3331
3332 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003333}
3334
John McCall76bd1f32010-06-01 09:23:16 +00003335Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003336 return DecodeSelector(ID);
3337}
3338
John McCall76bd1f32010-06-01 09:23:16 +00003339uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregor719770d2010-04-06 17:30:22 +00003340 return TotalNumSelectors + 1;
3341}
3342
Mike Stump1eb44332009-09-09 15:08:12 +00003343DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003344PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3345 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3346 switch (Kind) {
3347 case DeclarationName::Identifier:
3348 return DeclarationName(GetIdentifierInfo(Record, Idx));
3349
3350 case DeclarationName::ObjCZeroArgSelector:
3351 case DeclarationName::ObjCOneArgSelector:
3352 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003353 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003354
3355 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003356 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003357 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003358
3359 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003360 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003361 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003362
3363 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003364 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003365 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003366
3367 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003368 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003369 (OverloadedOperatorKind)Record[Idx++]);
3370
Sean Hunt3e518bd2009-11-29 07:34:05 +00003371 case DeclarationName::CXXLiteralOperatorName:
3372 return Context->DeclarationNames.getCXXLiteralOperatorName(
3373 GetIdentifierInfo(Record, Idx));
3374
Douglas Gregor2cf26342009-04-09 22:27:44 +00003375 case DeclarationName::CXXUsingDirective:
3376 return DeclarationName::getUsingDirectiveName();
3377 }
3378
3379 // Required to silence GCC warning
3380 return DeclarationName();
3381}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003382
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003383TemplateName
3384PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3385 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3386 switch (Kind) {
3387 case TemplateName::Template:
3388 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3389
3390 case TemplateName::OverloadedTemplate: {
3391 unsigned size = Record[Idx++];
3392 UnresolvedSet<8> Decls;
3393 while (size--)
3394 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3395
3396 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3397 }
3398
3399 case TemplateName::QualifiedTemplate: {
3400 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3401 bool hasTemplKeyword = Record[Idx++];
3402 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3403 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3404 }
3405
3406 case TemplateName::DependentTemplate: {
3407 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3408 if (Record[Idx++]) // isIdentifier
3409 return Context->getDependentTemplateName(NNS,
3410 GetIdentifierInfo(Record, Idx));
3411 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003412 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003413 }
3414 }
3415
3416 assert(0 && "Unhandled template name kind!");
3417 return TemplateName();
3418}
3419
3420TemplateArgument
Sebastian Redl577d4792010-07-22 22:43:28 +00003421PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3422 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003423 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3424 case TemplateArgument::Null:
3425 return TemplateArgument();
3426 case TemplateArgument::Type:
3427 return TemplateArgument(GetType(Record[Idx++]));
3428 case TemplateArgument::Declaration:
3429 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003430 case TemplateArgument::Integral: {
3431 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3432 QualType T = GetType(Record[Idx++]);
3433 return TemplateArgument(Value, T);
3434 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003435 case TemplateArgument::Template:
3436 return TemplateArgument(ReadTemplateName(Record, Idx));
3437 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00003438 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003439 case TemplateArgument::Pack: {
3440 unsigned NumArgs = Record[Idx++];
3441 llvm::SmallVector<TemplateArgument, 8> Args;
3442 Args.reserve(NumArgs);
3443 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003444 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003445 TemplateArgument TemplArg;
3446 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3447 return TemplArg;
3448 }
3449 }
3450
3451 assert(0 && "Unhandled template argument kind!");
3452 return TemplateArgument();
3453}
3454
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003455TemplateParameterList *
3456PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3457 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3458 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3459 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3460
3461 unsigned NumParams = Record[Idx++];
3462 llvm::SmallVector<NamedDecl *, 16> Params;
3463 Params.reserve(NumParams);
3464 while (NumParams--)
3465 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3466
3467 TemplateParameterList* TemplateParams =
3468 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3469 Params.data(), Params.size(), RAngleLoc);
3470 return TemplateParams;
3471}
3472
3473void
3474PCHReader::
3475ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redl577d4792010-07-22 22:43:28 +00003476 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003477 const RecordData &Record, unsigned &Idx) {
3478 unsigned NumTemplateArgs = Record[Idx++];
3479 TemplArgs.reserve(NumTemplateArgs);
3480 while (NumTemplateArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003481 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003482}
3483
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003484/// \brief Read a UnresolvedSet structure.
3485void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3486 const RecordData &Record, unsigned &Idx) {
3487 unsigned NumDecls = Record[Idx++];
3488 while (NumDecls--) {
3489 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3490 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3491 Set.addDecl(D, AS);
3492 }
3493}
3494
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003495CXXBaseSpecifier
Nick Lewycky56062202010-07-26 16:56:01 +00003496PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3497 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003498 bool isVirtual = static_cast<bool>(Record[Idx++]);
3499 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3500 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky56062202010-07-26 16:56:01 +00003501 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003502 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky56062202010-07-26 16:56:01 +00003503 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003504}
3505
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003506NestedNameSpecifier *
3507PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3508 unsigned N = Record[Idx++];
3509 NestedNameSpecifier *NNS = 0, *Prev = 0;
3510 for (unsigned I = 0; I != N; ++I) {
3511 NestedNameSpecifier::SpecifierKind Kind
3512 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3513 switch (Kind) {
3514 case NestedNameSpecifier::Identifier: {
3515 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3516 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3517 break;
3518 }
3519
3520 case NestedNameSpecifier::Namespace: {
3521 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3522 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3523 break;
3524 }
3525
3526 case NestedNameSpecifier::TypeSpec:
3527 case NestedNameSpecifier::TypeSpecWithTemplate: {
3528 Type *T = GetType(Record[Idx++]).getTypePtr();
3529 bool Template = Record[Idx++];
3530 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3531 break;
3532 }
3533
3534 case NestedNameSpecifier::Global: {
3535 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3536 // No associated value, and there can't be a prefix.
3537 break;
3538 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003539 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003540 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003541 }
3542 return NNS;
3543}
3544
3545SourceRange
3546PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003547 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3548 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3549 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003550}
3551
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003552/// \brief Read an integral value
3553llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3554 unsigned BitWidth = Record[Idx++];
3555 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3556 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3557 Idx += NumWords;
3558 return Result;
3559}
3560
3561/// \brief Read a signed integral value
3562llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3563 bool isUnsigned = Record[Idx++];
3564 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3565}
3566
Douglas Gregor17fc2232009-04-14 21:55:33 +00003567/// \brief Read a floating-point value
3568llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003569 return llvm::APFloat(ReadAPInt(Record, Idx));
3570}
3571
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003572// \brief Read a string
3573std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3574 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003575 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003576 Idx += Len;
3577 return Result;
3578}
3579
Chris Lattnerd2598362010-05-10 00:25:06 +00003580CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3581 unsigned &Idx) {
3582 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3583 return CXXTemporary::Create(*Context, Decl);
3584}
3585
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003586DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003587 return Diag(SourceLocation(), DiagID);
3588}
3589
3590DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003591 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003592}
Douglas Gregor025452f2009-04-17 00:04:06 +00003593
Douglas Gregor668c1a42009-04-21 22:25:48 +00003594/// \brief Retrieve the identifier table associated with the
3595/// preprocessor.
3596IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003597 assert(PP && "Forgot to set Preprocessor ?");
3598 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003599}
3600
Douglas Gregor025452f2009-04-17 00:04:06 +00003601/// \brief Record that the given ID maps to the given switch-case
3602/// statement.
3603void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3604 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3605 SwitchCaseStmts[ID] = SC;
3606}
3607
3608/// \brief Retrieve the switch-case statement with the given ID.
3609SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3610 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3611 return SwitchCaseStmts[ID];
3612}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003613
3614/// \brief Record that the given label statement has been
3615/// deserialized and has the given ID.
3616void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003617 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003618 "Deserialized label twice");
3619 LabelStmts[ID] = S;
3620
3621 // If we've already seen any goto statements that point to this
3622 // label, resolve them now.
3623 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3624 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3625 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3626 Goto->second->setLabel(S);
3627 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003628
3629 // If we've already seen any address-label statements that point to
3630 // this label, resolve them now.
3631 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003632 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003633 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003634 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003635 AddrLabel != AddrLabels.second; ++AddrLabel)
3636 AddrLabel->second->setLabel(S);
3637 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003638}
3639
3640/// \brief Set the label of the given statement to the label
3641/// identified by ID.
3642///
3643/// Depending on the order in which the label and other statements
3644/// referencing that label occur, this operation may complete
3645/// immediately (updating the statement) or it may queue the
3646/// statement to be back-patched later.
3647void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3648 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3649 if (Label != LabelStmts.end()) {
3650 // We've already seen this label, so set the label of the goto and
3651 // we're done.
3652 S->setLabel(Label->second);
3653 } else {
3654 // We haven't seen this label yet, so add this goto to the set of
3655 // unresolved goto statements.
3656 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3657 }
3658}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003659
3660/// \brief Set the label of the given expression to the label
3661/// identified by ID.
3662///
3663/// Depending on the order in which the label and other statements
3664/// referencing that label occur, this operation may complete
3665/// immediately (updating the statement) or it may queue the
3666/// statement to be back-patched later.
3667void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3668 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3669 if (Label != LabelStmts.end()) {
3670 // We've already seen this label, so set the label of the
3671 // label-address expression and we're done.
3672 S->setLabel(Label->second);
3673 } else {
3674 // We haven't seen this label yet, so add this label-address
3675 // expression to the set of unresolved label-address expressions.
3676 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3677 }
3678}
Douglas Gregord89275b2009-07-06 18:54:52 +00003679
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003680void PCHReader::FinishedDeserializing() {
3681 assert(NumCurrentElementsDeserializing &&
3682 "FinishedDeserializing not paired with StartedDeserializing");
3683 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003684 // If any identifiers with corresponding top-level declarations have
3685 // been loaded, load those declarations now.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003686 while (!PendingIdentifierInfos.empty()) {
3687 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3688 PendingIdentifierInfos.front().DeclIDs, true);
3689 PendingIdentifierInfos.pop_front();
Douglas Gregord89275b2009-07-06 18:54:52 +00003690 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003691
3692 // We are not in recursive loading, so it's safe to pass the "interesting"
3693 // decls to the consumer.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003694 if (Consumer)
3695 PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003696 }
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003697 --NumCurrentElementsDeserializing;
Douglas Gregord89275b2009-07-06 18:54:52 +00003698}