blob: 86f1091a05d06568ea860b71fef20f526bc4e6c1 [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,
417 const char *isysroot)
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 Gregor6a5a23f2010-03-19 21:51:54 +0000423 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000424 NumPreallocatedPreprocessingEntities(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000425 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000426 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
427 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
428 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
429 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
430 TotalVisibleDeclContexts(0), CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000431 RelocatablePCH = false;
432}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000433
434PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000435 Diagnostic &Diags, const char *isysroot)
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 Gregor6a5a23f2010-03-19 21:51:54 +0000440 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000441 NumPreallocatedPreprocessingEntities(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000442 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000443 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
444 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
445 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
446 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
447 TotalVisibleDeclContexts(0), CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000448 RelocatablePCH = false;
449}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000450
Sebastian Redl9137a522010-07-16 17:50:48 +0000451PCHReader::~PCHReader() {
452 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
453 delete Chain[e - i - 1];
454}
455
456PCHReader::PerFileData::PerFileData()
Sebastian Redl12d6da02010-07-19 22:06:55 +0000457 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redl2da08f92010-07-19 22:28:42 +0000458 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
459 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0)
Sebastian Redl9137a522010-07-16 17:50:48 +0000460{}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000461
Chris Lattner4c6f9522009-04-27 05:14:47 +0000462
Douglas Gregor668c1a42009-04-21 22:25:48 +0000463namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000464class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000465 PCHReader &Reader;
466
467public:
468 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
469
470 typedef Selector external_key_type;
471 typedef external_key_type internal_key_type;
472
473 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000475 static bool EqualKey(const internal_key_type& a,
476 const internal_key_type& b) {
477 return a == b;
478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000480 static unsigned ComputeHash(Selector Sel) {
481 unsigned N = Sel.getNumArgs();
482 if (N == 0)
483 ++N;
484 unsigned R = 5381;
485 for (unsigned I = 0; I != N; ++I)
486 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000487 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000488 return R;
489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000491 // This hopefully will just get inlined and removed by the optimizer.
492 static const internal_key_type&
493 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000495 static std::pair<unsigned, unsigned>
496 ReadKeyDataLength(const unsigned char*& d) {
497 using namespace clang::io;
498 unsigned KeyLen = ReadUnalignedLE16(d);
499 unsigned DataLen = ReadUnalignedLE16(d);
500 return std::make_pair(KeyLen, DataLen);
501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Douglas Gregor83941df2009-04-25 17:48:32 +0000503 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000504 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000505 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000506 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000507 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000508 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
509 if (N == 0)
510 return SelTable.getNullarySelector(FirstII);
511 else if (N == 1)
512 return SelTable.getUnarySelector(FirstII);
513
514 llvm::SmallVector<IdentifierInfo *, 16> Args;
515 Args.push_back(FirstII);
516 for (unsigned I = 1; I != N; ++I)
517 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
518
Douglas Gregor75fdb232009-05-22 22:45:36 +0000519 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000520 }
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000522 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
523 using namespace clang::io;
524 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
525 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
526
527 data_type Result;
528
529 // Load instance methods
530 ObjCMethodList *Prev = 0;
531 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000532 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000533 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
534 if (!Result.first.Method) {
535 // This is the first method, which is the easy case.
536 Result.first.Method = Method;
537 Prev = &Result.first;
538 continue;
539 }
540
Ted Kremenek298ed872010-02-11 00:53:01 +0000541 ObjCMethodList *Mem =
542 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
543 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000544 Prev = Prev->Next;
545 }
546
547 // Load factory methods
548 Prev = 0;
549 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000550 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000551 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
552 if (!Result.second.Method) {
553 // This is the first method, which is the easy case.
554 Result.second.Method = Method;
555 Prev = &Result.second;
556 continue;
557 }
558
Ted Kremenek298ed872010-02-11 00:53:01 +0000559 ObjCMethodList *Mem =
560 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
561 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000562 Prev = Prev->Next;
563 }
564
565 return Result;
566 }
567};
Mike Stump1eb44332009-09-09 15:08:12 +0000568
569} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000570
571/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000572typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000573 PCHMethodPoolLookupTable;
574
575namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000576class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000577 PCHReader &Reader;
578
579 // If we know the IdentifierInfo in advance, it is here and we will
580 // not build a new one. Used when deserializing information about an
581 // identifier that was constructed before the PCH file was read.
582 IdentifierInfo *KnownII;
583
584public:
585 typedef IdentifierInfo * data_type;
586
587 typedef const std::pair<const char*, unsigned> external_key_type;
588
589 typedef external_key_type internal_key_type;
590
Mike Stump1eb44332009-09-09 15:08:12 +0000591 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000592 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Douglas Gregor668c1a42009-04-21 22:25:48 +0000594 static bool EqualKey(const internal_key_type& a,
595 const internal_key_type& b) {
596 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
597 : false;
598 }
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Douglas Gregor668c1a42009-04-21 22:25:48 +0000600 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000601 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000602 }
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Douglas Gregor668c1a42009-04-21 22:25:48 +0000604 // This hopefully will just get inlined and removed by the optimizer.
605 static const internal_key_type&
606 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Douglas Gregor668c1a42009-04-21 22:25:48 +0000608 static std::pair<unsigned, unsigned>
609 ReadKeyDataLength(const unsigned char*& d) {
610 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000611 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000612 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000613 return std::make_pair(KeyLen, DataLen);
614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Douglas Gregor668c1a42009-04-21 22:25:48 +0000616 static std::pair<const char*, unsigned>
617 ReadKey(const unsigned char* d, unsigned n) {
618 assert(n >= 2 && d[n-1] == '\0');
619 return std::make_pair((const char*) d, n-1);
620 }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
622 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000623 const unsigned char* d,
624 unsigned DataLen) {
625 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000626 pch::IdentID ID = ReadUnalignedLE32(d);
627 bool IsInteresting = ID & 0x01;
628
629 // Wipe out the "is interesting" bit.
630 ID = ID >> 1;
631
632 if (!IsInteresting) {
633 // For unintersting identifiers, just build the IdentifierInfo
634 // and associate it with the persistent ID.
635 IdentifierInfo *II = KnownII;
636 if (!II)
637 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
638 k.first, k.first + k.second);
639 Reader.SetIdentifierInfo(ID, II);
640 return II;
641 }
642
Douglas Gregor5998da52009-04-28 21:32:13 +0000643 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000644 bool CPlusPlusOperatorKeyword = Bits & 0x01;
645 Bits >>= 1;
646 bool Poisoned = Bits & 0x01;
647 Bits >>= 1;
648 bool ExtensionToken = Bits & 0x01;
649 Bits >>= 1;
650 bool hasMacroDefinition = Bits & 0x01;
651 Bits >>= 1;
652 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
653 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Douglas Gregor2deaea32009-04-22 18:49:13 +0000655 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000656 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000657
658 // Build the IdentifierInfo itself and link the identifier ID with
659 // the new IdentifierInfo.
660 IdentifierInfo *II = KnownII;
661 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000662 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
663 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000664 Reader.SetIdentifierInfo(ID, II);
665
Douglas Gregor2deaea32009-04-22 18:49:13 +0000666 // Set or check the various bits in the IdentifierInfo structure.
667 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000668 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000669 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000670 "Incorrect extension token flag");
671 (void)ExtensionToken;
672 II->setIsPoisoned(Poisoned);
673 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
674 "Incorrect C++ operator keyword flag");
675 (void)CPlusPlusOperatorKeyword;
676
Douglas Gregor37e26842009-04-21 23:56:24 +0000677 // If this identifier is a macro, deserialize the macro
678 // definition.
679 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000680 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000681 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000682 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000683 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000684
685 // Read all of the declarations visible at global scope with this
686 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000687 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000688 if (DataLen > 0) {
689 llvm::SmallVector<uint32_t, 4> DeclIDs;
690 for (; DataLen > 0; DataLen -= 4)
691 DeclIDs.push_back(ReadUnalignedLE32(d));
692 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000693 }
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Douglas Gregor668c1a42009-04-21 22:25:48 +0000695 return II;
696 }
697};
Mike Stump1eb44332009-09-09 15:08:12 +0000698
699} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000700
701/// \brief The on-disk hash table used to contain information about
702/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000703typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000704 PCHIdentifierLookupTable;
705
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000706void PCHReader::Error(const char *Msg) {
707 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000708}
709
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000710/// \brief Check the contents of the concatenation of all predefines buffers in
711/// the PCH chain against the contents of the predefines buffer of the current
712/// compiler invocation.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000713///
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000714/// The contents should be the same. If not, then some command-line option
715/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000716///
717/// \returns true if there was a mismatch (in which case the PCH file
718/// should be ignored), or false otherwise.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000719bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000720 if (Listener)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000721 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000722 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000723 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000724 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000725}
726
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000727//===----------------------------------------------------------------------===//
728// Source Manager Deserialization
729//===----------------------------------------------------------------------===//
730
Douglas Gregorbd945002009-04-13 16:31:14 +0000731/// \brief Read the line table in the source manager block.
732/// \returns true if ther was an error.
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000733bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000734 unsigned Idx = 0;
735 LineTableInfo &LineTable = SourceMgr.getLineTable();
736
737 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000738 std::map<int, int> FileIDs;
739 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000740 // Extract the file name
741 unsigned FilenameLen = Record[Idx++];
742 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
743 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000744 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000745 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000746 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000747 }
748
749 // Parse the line entries
750 std::vector<LineEntry> Entries;
751 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000752 int FID = Record[Idx++];
Douglas Gregorbd945002009-04-13 16:31:14 +0000753
754 // Extract the line entries
755 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000756 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +0000757 Entries.clear();
758 Entries.reserve(NumEntries);
759 for (unsigned I = 0; I != NumEntries; ++I) {
760 unsigned FileOffset = Record[Idx++];
761 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000762 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +0000763 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000764 = (SrcMgr::CharacteristicKind)Record[Idx++];
765 unsigned IncludeOffset = Record[Idx++];
766 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
767 FileKind, IncludeOffset));
768 }
769 LineTable.AddEntry(FID, Entries);
770 }
771
772 return false;
773}
774
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000775namespace {
776
Benjamin Kramerbd218282009-11-28 10:07:24 +0000777class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000778public:
779 const bool hasStat;
780 const ino_t ino;
781 const dev_t dev;
782 const mode_t mode;
783 const time_t mtime;
784 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000786 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000787 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
788
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000789 PCHStatData()
790 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
791};
792
Benjamin Kramerbd218282009-11-28 10:07:24 +0000793class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000794 public:
795 typedef const char *external_key_type;
796 typedef const char *internal_key_type;
797
798 typedef PCHStatData data_type;
799
800 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000801 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000802 }
803
804 static internal_key_type GetInternalKey(const char *path) { return path; }
805
806 static bool EqualKey(internal_key_type a, internal_key_type b) {
807 return strcmp(a, b) == 0;
808 }
809
810 static std::pair<unsigned, unsigned>
811 ReadKeyDataLength(const unsigned char*& d) {
812 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
813 unsigned DataLen = (unsigned) *d++;
814 return std::make_pair(KeyLen + 1, DataLen);
815 }
816
817 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
818 return (const char *)d;
819 }
820
821 static data_type ReadData(const internal_key_type, const unsigned char *d,
822 unsigned /*DataLen*/) {
823 using namespace clang::io;
824
825 if (*d++ == 1)
826 return data_type();
827
828 ino_t ino = (ino_t) ReadUnalignedLE32(d);
829 dev_t dev = (dev_t) ReadUnalignedLE32(d);
830 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000831 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000832 off_t size = (off_t) ReadUnalignedLE64(d);
833 return data_type(ino, dev, mode, mtime, size);
834 }
835};
836
837/// \brief stat() cache for precompiled headers.
838///
839/// This cache is very similar to the stat cache used by pretokenized
840/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000841class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000842 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
843 CacheTy *Cache;
844
845 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000846public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000847 PCHStatCache(const unsigned char *Buckets,
848 const unsigned char *Base,
849 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000850 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000851 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
852 Cache = CacheTy::Create(Buckets, Base);
853 }
854
855 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000857 int stat(const char *path, struct stat *buf) {
858 // Do the lookup for the file's data in the PCH file.
859 CacheTy::iterator I = Cache->find(path);
860
861 // If we don't get a hit in the PCH file just forward to 'stat'.
862 if (I == Cache->end()) {
863 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000864 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000867 ++NumStatHits;
868 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000870 if (!Data.hasStat)
871 return 1;
872
873 buf->st_ino = Data.ino;
874 buf->st_dev = Data.dev;
875 buf->st_mtime = Data.mtime;
876 buf->st_mode = Data.mode;
877 buf->st_size = Data.size;
878 return 0;
879 }
880};
881} // end anonymous namespace
882
883
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000884/// \brief Read a source manager block
885PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000886 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000887
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000888 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +0000889
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000890 // Set the source-location entry cursor to the current position in
891 // the stream. This cursor will be used to read the contents of the
892 // source manager block initially, and then lazily read
893 // source-location entries as needed.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000894 SLocEntryCursor = F.Stream;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000895
896 // The stream itself is going to skip over the source manager block.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000897 if (F.Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000898 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000899 return Failure;
900 }
901
902 // Enter the source manager block.
903 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000904 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000905 return Failure;
906 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000907
Douglas Gregor14f79002009-04-10 03:52:48 +0000908 RecordData Record;
909 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000910 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000911 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000912 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000913 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000914 return Failure;
915 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000916 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000917 }
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Douglas Gregor14f79002009-04-10 03:52:48 +0000919 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
920 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000921 SLocEntryCursor.ReadSubBlockID();
922 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000923 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000924 return Failure;
925 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000926 continue;
927 }
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Douglas Gregor14f79002009-04-10 03:52:48 +0000929 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000930 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000931 continue;
932 }
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Douglas Gregor14f79002009-04-10 03:52:48 +0000934 // Read a record.
935 const char *BlobStart;
936 unsigned BlobLen;
937 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000938 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000939 default: // Default behavior: ignore.
940 break;
941
Chris Lattner2c78b872009-04-14 23:22:57 +0000942 case pch::SM_LINE_TABLE:
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000943 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000944 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000945 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000946
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000947 case pch::SM_SLOC_FILE_ENTRY:
948 case pch::SM_SLOC_BUFFER_ENTRY:
949 case pch::SM_SLOC_INSTANTIATION_ENTRY:
950 // Once we hit one of the source location entries, we're done.
951 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000952 }
953 }
954}
955
Sebastian Redl190faf72010-07-20 21:50:20 +0000956/// \brief Get a cursor that's correctly positioned for reading the source
957/// location entry with the given ID.
958llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
959 assert(ID != 0 && ID <= TotalNumSLocEntries &&
960 "SLocCursorForID should only be called for real IDs.");
961
962 ID -= 1;
963 PerFileData *F = 0;
964 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
965 F = Chain[N - I - 1];
966 if (ID < F->LocalNumSLocEntries)
967 break;
968 ID -= F->LocalNumSLocEntries;
969 }
970 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
971
972 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
973 return F->SLocEntryCursor;
974}
975
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000976/// \brief Read in the source location entry with the given ID.
977PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
978 if (ID == 0)
979 return Success;
980
981 if (ID > TotalNumSLocEntries) {
982 Error("source location entry ID out-of-range for PCH file");
983 return Failure;
984 }
985
Sebastian Redl190faf72010-07-20 21:50:20 +0000986 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl9137a522010-07-16 17:50:48 +0000987
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000988 ++NumSLocEntriesRead;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000989 unsigned Code = SLocEntryCursor.ReadCode();
990 if (Code == llvm::bitc::END_BLOCK ||
991 Code == llvm::bitc::ENTER_SUBBLOCK ||
992 Code == llvm::bitc::DEFINE_ABBREV) {
993 Error("incorrectly-formatted source location entry in PCH file");
994 return Failure;
995 }
996
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000997 RecordData Record;
998 const char *BlobStart;
999 unsigned BlobLen;
1000 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1001 default:
1002 Error("incorrectly-formatted source location entry in PCH file");
1003 return Failure;
1004
1005 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001006 std::string Filename(BlobStart, BlobStart + BlobLen);
1007 MaybeAddSystemRootToFilename(Filename);
1008 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001009 if (File == 0) {
1010 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +00001011 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001012 ErrorStr += "' referenced by PCH file";
1013 Error(ErrorStr.c_str());
1014 return Failure;
1015 }
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Douglas Gregor2d52be52010-03-21 22:49:54 +00001017 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +00001018 Error("source location entry is incorrect");
1019 return Failure;
1020 }
1021
Douglas Gregor9f692a02010-04-09 15:54:22 +00001022 if ((off_t)Record[4] != File->getSize()
1023#if !defined(LLVM_ON_WIN32)
1024 // In our regression testing, the Windows file system seems to
1025 // have inconsistent modification times that sometimes
1026 // erroneously trigger this error-handling path.
1027 || (time_t)Record[5] != File->getModificationTime()
1028#endif
1029 ) {
Douglas Gregor2d52be52010-03-21 22:49:54 +00001030 Diag(diag::err_fe_pch_file_modified)
1031 << Filename;
1032 return Failure;
1033 }
1034
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001035 FileID FID = SourceMgr.createFileID(File,
1036 SourceLocation::getFromRawEncoding(Record[1]),
1037 (SrcMgr::CharacteristicKind)Record[2],
1038 ID, Record[0]);
1039 if (Record[3])
1040 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1041 .setHasLineDirectives();
1042
Douglas Gregor12fab312010-03-16 16:35:32 +00001043 // Reconstruct header-search information for this file.
1044 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001045 HFI.isImport = Record[6];
1046 HFI.DirInfo = Record[7];
1047 HFI.NumIncludes = Record[8];
1048 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +00001049 if (Listener)
1050 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001051 break;
1052 }
1053
1054 case pch::SM_SLOC_BUFFER_ENTRY: {
1055 const char *Name = BlobStart;
1056 unsigned Offset = Record[0];
1057 unsigned Code = SLocEntryCursor.ReadCode();
1058 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001059 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001060 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001061
1062 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1063 Error("PCH record has invalid code");
1064 return Failure;
1065 }
1066
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001067 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001068 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1069 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001070 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Douglas Gregor92b059e2009-04-28 20:33:11 +00001072 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001073 PCHPredefinesBlock Block = {
1074 BufferID,
1075 llvm::StringRef(BlobStart, BlobLen - 1)
1076 };
1077 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001078 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001079
1080 break;
1081 }
1082
1083 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +00001084 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001085 = SourceLocation::getFromRawEncoding(Record[1]);
1086 SourceMgr.createInstantiationLoc(SpellingLoc,
1087 SourceLocation::getFromRawEncoding(Record[2]),
1088 SourceLocation::getFromRawEncoding(Record[3]),
1089 Record[4],
1090 ID,
1091 Record[0]);
1092 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001093 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001094 }
1095
1096 return Success;
1097}
1098
Chris Lattner6367f6d2009-04-27 01:05:14 +00001099/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1100/// specified cursor. Read the abbreviations that are at the top of the block
1101/// and then leave the cursor pointing into the block.
1102bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1103 unsigned BlockID) {
1104 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001105 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001106 return Failure;
1107 }
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Chris Lattner6367f6d2009-04-27 01:05:14 +00001109 while (true) {
1110 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Chris Lattner6367f6d2009-04-27 01:05:14 +00001112 // We expect all abbrevs to be at the start of the block.
1113 if (Code != llvm::bitc::DEFINE_ABBREV)
1114 return false;
1115 Cursor.ReadAbbrevRecord();
1116 }
1117}
1118
Douglas Gregor37e26842009-04-21 23:56:24 +00001119void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001120 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Sebastian Redl9137a522010-07-16 17:50:48 +00001122 llvm::BitstreamCursor &Stream = Chain[0]->Stream;
1123
Douglas Gregor37e26842009-04-21 23:56:24 +00001124 // Keep track of where we are in the stream, then jump back there
1125 // after reading this macro.
1126 SavedStreamPosition SavedPosition(Stream);
1127
1128 Stream.JumpToBit(Offset);
1129 RecordData Record;
1130 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1131 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Douglas Gregor37e26842009-04-21 23:56:24 +00001133 while (true) {
1134 unsigned Code = Stream.ReadCode();
1135 switch (Code) {
1136 case llvm::bitc::END_BLOCK:
1137 return;
1138
1139 case llvm::bitc::ENTER_SUBBLOCK:
1140 // No known subblocks, always skip them.
1141 Stream.ReadSubBlockID();
1142 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001143 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001144 return;
1145 }
1146 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Douglas Gregor37e26842009-04-21 23:56:24 +00001148 case llvm::bitc::DEFINE_ABBREV:
1149 Stream.ReadAbbrevRecord();
1150 continue;
1151 default: break;
1152 }
1153
1154 // Read a record.
1155 Record.clear();
1156 pch::PreprocessorRecordTypes RecType =
1157 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1158 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001159 case pch::PP_MACRO_OBJECT_LIKE:
1160 case pch::PP_MACRO_FUNCTION_LIKE: {
1161 // If we already have a macro, that means that we've hit the end
1162 // of the definition of the macro we were looking for. We're
1163 // done.
1164 if (Macro)
1165 return;
1166
1167 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1168 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001169 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001170 return;
1171 }
1172 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1173 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001175 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001176 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001178 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001179 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1180 // Decode function-like macro info.
1181 bool isC99VarArgs = Record[3];
1182 bool isGNUVarArgs = Record[4];
1183 MacroArgs.clear();
1184 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001185 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001186 for (unsigned i = 0; i != NumArgs; ++i)
1187 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1188
1189 // Install function-like macro info.
1190 MI->setIsFunctionLike();
1191 if (isC99VarArgs) MI->setIsC99Varargs();
1192 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001193 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001194 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001195 }
1196
1197 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001198 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001199
1200 // Remember that we saw this macro last so that we add the tokens that
1201 // form its body to it.
1202 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001203
1204 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1205 // We have a macro definition. Load it now.
1206 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1207 getMacroDefinition(Record[NextIndex]));
1208 }
1209
Douglas Gregor37e26842009-04-21 23:56:24 +00001210 ++NumMacrosRead;
1211 break;
1212 }
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Douglas Gregor37e26842009-04-21 23:56:24 +00001214 case pch::PP_TOKEN: {
1215 // If we see a TOKEN before a PP_MACRO_*, then the file is
1216 // erroneous, just pretend we didn't see this.
1217 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Douglas Gregor37e26842009-04-21 23:56:24 +00001219 Token Tok;
1220 Tok.startToken();
1221 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1222 Tok.setLength(Record[1]);
1223 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1224 Tok.setIdentifierInfo(II);
1225 Tok.setKind((tok::TokenKind)Record[3]);
1226 Tok.setFlag((Token::TokenFlags)Record[4]);
1227 Macro->AddTokenToBody(Tok);
1228 break;
1229 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001230
1231 case pch::PP_MACRO_INSTANTIATION: {
1232 // If we already have a macro, that means that we've hit the end
1233 // of the definition of the macro we were looking for. We're
1234 // done.
1235 if (Macro)
1236 return;
1237
1238 if (!PP->getPreprocessingRecord()) {
1239 Error("missing preprocessing record in PCH file");
1240 return;
1241 }
1242
1243 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1244 if (PPRec.getPreprocessedEntity(Record[0]))
1245 return;
1246
1247 MacroInstantiation *MI
1248 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1249 SourceRange(
1250 SourceLocation::getFromRawEncoding(Record[1]),
1251 SourceLocation::getFromRawEncoding(Record[2])),
1252 getMacroDefinition(Record[4]));
1253 PPRec.SetPreallocatedEntity(Record[0], MI);
1254 return;
1255 }
1256
1257 case pch::PP_MACRO_DEFINITION: {
1258 // If we already have a macro, that means that we've hit the end
1259 // of the definition of the macro we were looking for. We're
1260 // done.
1261 if (Macro)
1262 return;
1263
1264 if (!PP->getPreprocessingRecord()) {
1265 Error("missing preprocessing record in PCH file");
1266 return;
1267 }
1268
1269 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1270 if (PPRec.getPreprocessedEntity(Record[0]))
1271 return;
1272
1273 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1274 Error("out-of-bounds macro definition record");
1275 return;
1276 }
1277
1278 MacroDefinition *MD
1279 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1280 SourceLocation::getFromRawEncoding(Record[5]),
1281 SourceRange(
1282 SourceLocation::getFromRawEncoding(Record[2]),
1283 SourceLocation::getFromRawEncoding(Record[3])));
1284 PPRec.SetPreallocatedEntity(Record[0], MD);
1285 MacroDefinitionsLoaded[Record[1]] = MD;
1286 return;
1287 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001288 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001289 }
1290}
1291
Douglas Gregor88a35862010-01-04 19:18:44 +00001292void PCHReader::ReadDefinedMacros() {
Sebastian Redl9137a522010-07-16 17:50:48 +00001293 llvm::BitstreamCursor &MacroCursor = Chain[0]->MacroCursor;
1294
Douglas Gregor88a35862010-01-04 19:18:44 +00001295 // If there was no preprocessor block, do nothing.
1296 if (!MacroCursor.getBitStreamReader())
1297 return;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001298
Douglas Gregor88a35862010-01-04 19:18:44 +00001299 llvm::BitstreamCursor Cursor = MacroCursor;
1300 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1301 Error("malformed preprocessor block record in PCH file");
1302 return;
1303 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001304
Douglas Gregor88a35862010-01-04 19:18:44 +00001305 RecordData Record;
1306 while (true) {
1307 unsigned Code = Cursor.ReadCode();
1308 if (Code == llvm::bitc::END_BLOCK) {
1309 if (Cursor.ReadBlockEnd())
1310 Error("error at end of preprocessor block in PCH file");
1311 return;
1312 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001313
Douglas Gregor88a35862010-01-04 19:18:44 +00001314 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1315 // No known subblocks, always skip them.
1316 Cursor.ReadSubBlockID();
1317 if (Cursor.SkipBlock()) {
1318 Error("malformed block record in PCH file");
1319 return;
1320 }
1321 continue;
1322 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001323
Douglas Gregor88a35862010-01-04 19:18:44 +00001324 if (Code == llvm::bitc::DEFINE_ABBREV) {
1325 Cursor.ReadAbbrevRecord();
1326 continue;
1327 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001328
Douglas Gregor88a35862010-01-04 19:18:44 +00001329 // Read a record.
1330 const char *BlobStart;
1331 unsigned BlobLen;
1332 Record.clear();
1333 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1334 default: // Default behavior: ignore.
1335 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001336
Douglas Gregor88a35862010-01-04 19:18:44 +00001337 case pch::PP_MACRO_OBJECT_LIKE:
1338 case pch::PP_MACRO_FUNCTION_LIKE:
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001339 DecodeIdentifierInfo(Record[0]);
Douglas Gregor88a35862010-01-04 19:18:44 +00001340 break;
1341
1342 case pch::PP_TOKEN:
1343 // Ignore tokens.
1344 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001345
1346 case pch::PP_MACRO_INSTANTIATION:
1347 case pch::PP_MACRO_DEFINITION:
1348 // Read the macro record.
1349 ReadMacroRecord(Cursor.GetCurrentBitNo());
1350 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001351 }
1352 }
1353}
1354
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001355MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1356 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1357 return 0;
1358
1359 if (!MacroDefinitionsLoaded[ID])
1360 ReadMacroRecord(MacroDefinitionOffsets[ID]);
1361
1362 return MacroDefinitionsLoaded[ID];
1363}
1364
Douglas Gregore650c8c2009-07-07 00:12:59 +00001365/// \brief If we are loading a relocatable PCH file, and the filename is
1366/// not an absolute path, add the system root to the beginning of the file
1367/// name.
1368void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1369 // If this is not a relocatable PCH file, there's nothing to do.
1370 if (!RelocatablePCH)
1371 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Daniel Dunbard5b21972009-11-18 19:50:41 +00001373 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001374 return;
1375
Douglas Gregore650c8c2009-07-07 00:12:59 +00001376 if (isysroot == 0) {
1377 // If no system root was given, default to '/'
1378 Filename.insert(Filename.begin(), '/');
1379 return;
1380 }
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Douglas Gregore650c8c2009-07-07 00:12:59 +00001382 unsigned Length = strlen(isysroot);
1383 if (isysroot[Length - 1] != '/')
1384 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Douglas Gregore650c8c2009-07-07 00:12:59 +00001386 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1387}
1388
Mike Stump1eb44332009-09-09 15:08:12 +00001389PCHReader::PCHReadResult
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001390PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00001391 llvm::BitstreamCursor &Stream = F.Stream;
1392
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001393 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001394 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001395 return Failure;
1396 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001397
1398 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001399 RecordData Record;
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001400 bool First = true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001401 while (!Stream.AtEndOfStream()) {
1402 unsigned Code = Stream.ReadCode();
1403 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001404 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001405 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001406 return Failure;
1407 }
Chris Lattner7356a312009-04-11 21:15:38 +00001408
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001409 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001410 }
1411
1412 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1413 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001414 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001415 // We lazily load the decls block, but we want to set up the
1416 // DeclsCursor cursor to point into it. Clone our current bitcode
1417 // cursor to it, enter the block and read the abbrevs in that block.
1418 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00001419 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00001420 if (Stream.SkipBlock() || // Skip with the main cursor.
1421 // Read the abbrevs.
Sebastian Redl9137a522010-07-16 17:50:48 +00001422 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001423 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001424 return Failure;
1425 }
1426 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Chris Lattner7356a312009-04-11 21:15:38 +00001428 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00001429 F.MacroCursor = Stream;
Douglas Gregor88a35862010-01-04 19:18:44 +00001430 if (PP)
1431 PP->setExternalSource(this);
1432
Chris Lattner7356a312009-04-11 21:15:38 +00001433 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001434 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001435 return Failure;
1436 }
1437 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001438
Douglas Gregor14f79002009-04-10 03:52:48 +00001439 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001440 switch (ReadSourceManagerBlock(F)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001441 case Success:
1442 break;
1443
1444 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001445 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001446 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001447
1448 case IgnorePCH:
1449 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001450 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001451 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001452 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001453 First = false;
Douglas Gregor8038d512009-04-10 17:25:41 +00001454 continue;
1455 }
1456
1457 if (Code == llvm::bitc::DEFINE_ABBREV) {
1458 Stream.ReadAbbrevRecord();
1459 continue;
1460 }
1461
1462 // Read and process a record.
1463 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001464 const char *BlobStart = 0;
1465 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001466 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001467 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001468 default: // Default behavior: ignore.
1469 break;
1470
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001471 case pch::METADATA: {
1472 if (Record[0] != pch::VERSION_MAJOR) {
1473 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1474 : diag::warn_pch_version_too_new);
1475 return IgnorePCH;
1476 }
1477
1478 RelocatablePCH = Record[4];
1479 if (Listener) {
1480 std::string TargetTriple(BlobStart, BlobLen);
1481 if (Listener->ReadTargetTriple(TargetTriple))
1482 return IgnorePCH;
1483 }
1484 break;
1485 }
1486
1487 case pch::CHAINED_METADATA: {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001488 if (!First) {
1489 Error("CHAINED_METADATA is not first record in block");
1490 return Failure;
1491 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001492 if (Record[0] != pch::VERSION_MAJOR) {
1493 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1494 : diag::warn_pch_version_too_new);
1495 return IgnorePCH;
1496 }
1497
1498 // Load the chained file.
1499 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1500 case Failure: return Failure;
1501 // If we have to ignore the dependency, we'll have to ignore this too.
1502 case IgnorePCH: return IgnorePCH;
1503 case Success: break;
1504 }
1505 break;
1506 }
1507
Douglas Gregor8038d512009-04-10 17:25:41 +00001508 case pch::TYPE_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001509 if (F.LocalNumTypes != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001510 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001511 return Failure;
1512 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001513 F.TypeOffsets = (const uint32_t *)BlobStart;
1514 F.LocalNumTypes = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001515 break;
1516
1517 case pch::DECL_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001518 if (F.LocalNumDecls != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001519 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001520 return Failure;
1521 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001522 F.DeclOffsets = (const uint32_t *)BlobStart;
1523 F.LocalNumDecls = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001524 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001525
1526 case pch::LANGUAGE_OPTIONS:
1527 if (ParseLanguageOptions(Record))
1528 return IgnorePCH;
1529 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001530
Douglas Gregorafaf3082009-04-11 00:14:32 +00001531 case pch::IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001532 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001533 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001534 F.IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001535 = PCHIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001536 (const unsigned char *)F.IdentifierTableData + Record[0],
1537 (const unsigned char *)F.IdentifierTableData,
1538 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001539 if (PP)
1540 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001541 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001542 break;
1543
1544 case pch::IDENTIFIER_OFFSET:
Sebastian Redl2da08f92010-07-19 22:28:42 +00001545 if (F.LocalNumIdentifiers != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001546 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001547 return Failure;
1548 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001549 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1550 F.LocalNumIdentifiers = Record[0];
Douglas Gregorafaf3082009-04-11 00:14:32 +00001551 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001552
1553 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001554 // Optimization for the first block.
1555 if (ExternalDefinitions.empty())
1556 ExternalDefinitions.swap(Record);
1557 else
1558 ExternalDefinitions.insert(ExternalDefinitions.end(),
1559 Record.begin(), Record.end());
Douglas Gregorfdd01722009-04-14 00:24:19 +00001560 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001561
Douglas Gregorad1de002009-04-18 05:55:16 +00001562 case pch::SPECIAL_TYPES:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001563 // Optimization for the first block
1564 if (SpecialTypes.empty())
1565 SpecialTypes.swap(Record);
1566 else
1567 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregorad1de002009-04-18 05:55:16 +00001568 break;
1569
Douglas Gregor3e1af842009-04-17 22:13:46 +00001570 case pch::STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001571 TotalNumStatements += Record[0];
1572 TotalNumMacros += Record[1];
1573 TotalLexicalDeclContexts += Record[2];
1574 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001575 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001576
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001577 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001578 // Optimization for the first block.
1579 if (TentativeDefinitions.empty())
1580 TentativeDefinitions.swap(Record);
1581 else
1582 TentativeDefinitions.insert(TentativeDefinitions.end(),
1583 Record.begin(), Record.end());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001584 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001585
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001586 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001587 // Optimization for the first block.
1588 if (UnusedStaticFuncs.empty())
1589 UnusedStaticFuncs.swap(Record);
1590 else
1591 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1592 Record.begin(), Record.end());
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001593 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001594
Douglas Gregor14c22f22009-04-22 22:18:58 +00001595 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001596 // Optimization for the first block.
1597 if (LocallyScopedExternalDecls.empty())
1598 LocallyScopedExternalDecls.swap(Record);
1599 else
1600 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1601 Record.begin(), Record.end());
Douglas Gregor14c22f22009-04-22 22:18:58 +00001602 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001603
Douglas Gregor83941df2009-04-25 17:48:32 +00001604 case pch::SELECTOR_OFFSETS:
1605 SelectorOffsets = (const uint32_t *)BlobStart;
1606 TotalNumSelectors = Record[0];
1607 SelectorsLoaded.resize(TotalNumSelectors);
1608 break;
1609
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001610 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001611 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1612 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001613 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001614 = PCHMethodPoolLookupTable::Create(
1615 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001616 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001617 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001618 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001619 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001620
1621 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001622 if (!Record.empty() && Listener)
1623 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001624 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001625
1626 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001627 F.SLocOffsets = (const uint32_t *)BlobStart;
1628 F.LocalNumSLocEntries = Record[0];
1629 // We cannot delay this until all PCHs are loaded, because then source
1630 // location preloads would also have to be delayed.
1631 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001632 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001633 break;
1634
1635 case pch::SOURCE_LOCATION_PRELOADS:
1636 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1637 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1638 if (Result != Success)
1639 return Result;
1640 }
1641 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001642
Douglas Gregor52e71082009-10-16 18:18:30 +00001643 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001644 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001645 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1646 (const unsigned char *)BlobStart,
1647 NumStatHits, NumStatMisses);
1648 FileMgr.addStatCache(MyStatCache);
Sebastian Redl9137a522010-07-16 17:50:48 +00001649 F.StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001650 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001651 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001652
Douglas Gregorb81c1702009-04-27 20:06:05 +00001653 case pch::EXT_VECTOR_DECLS:
1654 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001655 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001656 return Failure;
1657 }
1658 ExtVectorDecls.swap(Record);
1659 break;
1660
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001661 case pch::VTABLE_USES:
1662 if (!VTableUses.empty()) {
1663 Error("duplicate VTABLE_USES record in PCH file");
1664 return Failure;
1665 }
1666 VTableUses.swap(Record);
1667 break;
1668
1669 case pch::DYNAMIC_CLASSES:
1670 if (!DynamicClasses.empty()) {
1671 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1672 return Failure;
1673 }
1674 DynamicClasses.swap(Record);
1675 break;
1676
Douglas Gregorb64c1932009-05-12 01:31:05 +00001677 case pch::ORIGINAL_FILE_NAME:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001678 // The primary PCH will be the last to get here, so it will be the one
1679 // that's used.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001680 ActualOriginalFileName.assign(BlobStart, BlobLen);
1681 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001682 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001683 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001685 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001686 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001687 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek974be4d2010-02-12 23:31:14 +00001688 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001689 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1690 return IgnorePCH;
1691 }
1692 break;
1693 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001694
1695 case pch::MACRO_DEFINITION_OFFSETS:
1696 MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1697 if (PP) {
1698 if (!PP->getPreprocessingRecord())
1699 PP->createPreprocessingRecord();
1700 PP->getPreprocessingRecord()->SetExternalSource(*this, Record[0]);
1701 } else {
1702 NumPreallocatedPreprocessingEntities = Record[0];
1703 }
1704
1705 MacroDefinitionsLoaded.resize(Record[1]);
1706 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001707 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001708 First = false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001709 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001710 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001711 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001712}
1713
Douglas Gregore1d918e2009-04-10 23:10:45 +00001714PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001715 switch(ReadPCHCore(FileName)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001716 case Failure: return Failure;
1717 case IgnorePCH: return IgnorePCH;
1718 case Success: break;
1719 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001720
1721 // Here comes stuff that we only do once the entire chain is loaded.
1722
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001723 // Allocate space for loaded identifiers, decls and types.
Sebastian Redl2da08f92010-07-19 22:28:42 +00001724 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001725 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redl2da08f92010-07-19 22:28:42 +00001726 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001727 TotalNumTypes += Chain[I]->LocalNumTypes;
1728 TotalNumDecls += Chain[I]->LocalNumDecls;
1729 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001730 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001731 TypesLoaded.resize(TotalNumTypes);
1732 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redl2da08f92010-07-19 22:28:42 +00001733 if (PP && TotalNumIdentifiers > 0)
1734 PP->getHeaderSearchInfo().SetExternalLookup(this);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001735
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001736 // Check the predefines buffers.
1737 if (CheckPredefinesBuffers())
1738 return IgnorePCH;
1739
1740 if (PP) {
1741 // Initialization of keywords and pragmas occurs before the
1742 // PCH file is read, so there may be some identifiers that were
1743 // loaded into the IdentifierTable before we intercepted the
1744 // creation of identifiers. Iterate through the list of known
1745 // identifiers and determine whether we have to establish
1746 // preprocessor definitions or top-level identifier declaration
1747 // chains for those identifiers.
1748 //
1749 // We copy the IdentifierInfo pointers to a small vector first,
1750 // since de-serializing declarations or macro definitions can add
1751 // new entries into the identifier table, invalidating the
1752 // iterators.
1753 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1754 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1755 IdEnd = PP->getIdentifierTable().end();
1756 Id != IdEnd; ++Id)
1757 Identifiers.push_back(Id->second);
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001758 // FIXME: The loop order here is very cache-inefficient. Loop over files
1759 // should probably be the outer loop.
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001760 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1761 IdentifierInfo *II = Identifiers[I];
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001762 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001763 PCHIdentifierLookupTrait Info(*this, II);
1764 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001765 // We need to search the tables in all files.
1766 // FIXME: What happens if this stuff changes between files, e.g. the
1767 // dependent PCH undefs a macro from the core file?
1768 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1769 PCHIdentifierLookupTable *IdTable
1770 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
1771 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1772 if (Pos == IdTable->end())
1773 continue;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001774
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001775 // Dereferencing the iterator has the effect of populating the
1776 // IdentifierInfo node with the various declarations it needs.
1777 (void)*Pos;
1778 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001779 }
1780 }
1781
1782 if (Context)
1783 InitializeContext(*Context);
1784
1785 return Success;
1786}
1787
1788PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1789 Chain.push_back(new PerFileData());
Sebastian Redl9137a522010-07-16 17:50:48 +00001790 PerFileData &F = *Chain.back();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001791
1792 // Set the PCH file name.
1793 F.FileName = FileName;
1794
1795 // Open the PCH file.
1796 //
1797 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1798 std::string ErrStr;
1799 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1800 if (!F.Buffer) {
1801 Error(ErrStr.c_str());
1802 return IgnorePCH;
1803 }
1804
1805 // Initialize the stream
1806 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1807 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl9137a522010-07-16 17:50:48 +00001808 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001809 Stream.init(F.StreamFile);
1810
1811 // Sniff for the signature.
1812 if (Stream.Read(8) != 'C' ||
1813 Stream.Read(8) != 'P' ||
1814 Stream.Read(8) != 'C' ||
1815 Stream.Read(8) != 'H') {
1816 Diag(diag::err_not_a_pch_file) << FileName;
1817 return Failure;
1818 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001819
Douglas Gregor2cf26342009-04-09 22:27:44 +00001820 while (!Stream.AtEndOfStream()) {
1821 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Douglas Gregore1d918e2009-04-10 23:10:45 +00001823 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001824 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001825 return Failure;
1826 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001827
1828 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001829
Douglas Gregor2cf26342009-04-09 22:27:44 +00001830 // We only know the PCH subblock ID.
1831 switch (BlockID) {
1832 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001833 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001834 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001835 return Failure;
1836 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001837 break;
1838 case pch::PCH_BLOCK_ID:
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001839 switch (ReadPCHBlock(F)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001840 case Success:
1841 break;
1842
1843 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001844 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001845
1846 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001847 // FIXME: We could consider reading through to the end of this
1848 // PCH block, skipping subblocks, to see if there are other
1849 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001850
1851 // Clear out any preallocated source location entries, so that
1852 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001853 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001854
1855 // Remove the stat cache.
Sebastian Redl9137a522010-07-16 17:50:48 +00001856 if (F.StatCache)
1857 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001858
Douglas Gregore1d918e2009-04-10 23:10:45 +00001859 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001860 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001861 break;
1862 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001863 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001864 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001865 return Failure;
1866 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001867 break;
1868 }
Mike Stump1eb44332009-09-09 15:08:12 +00001869 }
1870
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001871 return Success;
1872}
1873
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001874void PCHReader::setPreprocessor(Preprocessor &pp) {
1875 PP = &pp;
1876
1877 if (NumPreallocatedPreprocessingEntities) {
1878 if (!PP->getPreprocessingRecord())
1879 PP->createPreprocessingRecord();
1880 PP->getPreprocessingRecord()->SetExternalSource(*this,
1881 NumPreallocatedPreprocessingEntities);
1882 NumPreallocatedPreprocessingEntities = 0;
1883 }
1884}
1885
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001886void PCHReader::InitializeContext(ASTContext &Ctx) {
1887 Context = &Ctx;
1888 assert(Context && "Passed null context!");
1889
1890 assert(PP && "Forgot to set Preprocessor ?");
1891 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1892 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001893 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001894
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001895 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001896 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001897
1898 // Load the special types.
1899 Context->setBuiltinVaListType(
1900 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1901 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1902 Context->setObjCIdType(GetType(Id));
1903 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1904 Context->setObjCSelType(GetType(Sel));
1905 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1906 Context->setObjCProtoType(GetType(Proto));
1907 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1908 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001909
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001910 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1911 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001912 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001913 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1914 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001915 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1916 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001917 if (FileType.isNull()) {
1918 Error("FILE type is NULL");
1919 return;
1920 }
John McCall183700f2009-09-21 23:43:11 +00001921 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001922 Context->setFILEDecl(Typedef->getDecl());
1923 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001924 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001925 if (!Tag) {
1926 Error("Invalid FILE type in PCH file");
1927 return;
1928 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001929 Context->setFILEDecl(Tag->getDecl());
1930 }
1931 }
Mike Stump782fa302009-07-28 02:25:19 +00001932 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1933 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001934 if (Jmp_bufType.isNull()) {
1935 Error("jmp_bug type is NULL");
1936 return;
1937 }
John McCall183700f2009-09-21 23:43:11 +00001938 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001939 Context->setjmp_bufDecl(Typedef->getDecl());
1940 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001941 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001942 if (!Tag) {
1943 Error("Invalid jmp_bug type in PCH file");
1944 return;
1945 }
Mike Stump782fa302009-07-28 02:25:19 +00001946 Context->setjmp_bufDecl(Tag->getDecl());
1947 }
1948 }
1949 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1950 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001951 if (Sigjmp_bufType.isNull()) {
1952 Error("sigjmp_buf type is NULL");
1953 return;
1954 }
John McCall183700f2009-09-21 23:43:11 +00001955 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001956 Context->setsigjmp_bufDecl(Typedef->getDecl());
1957 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001958 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001959 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1960 Context->setsigjmp_bufDecl(Tag->getDecl());
1961 }
1962 }
Mike Stump1eb44332009-09-09 15:08:12 +00001963 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001964 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1965 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001966 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001967 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1968 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00001969 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1970 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001971 if (unsigned String
1972 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1973 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001974 if (unsigned ObjCSelRedef
1975 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
1976 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
1977 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
1978 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00001979
1980 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
1981 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001982}
1983
Douglas Gregorb64c1932009-05-12 01:31:05 +00001984/// \brief Retrieve the name of the original source file name
1985/// directly from the PCH file, without actually loading the PCH
1986/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001987std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1988 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00001989 // Open the PCH file.
1990 std::string ErrStr;
1991 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1992 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1993 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001994 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001995 return std::string();
1996 }
1997
1998 // Initialize the stream
1999 llvm::BitstreamReader StreamFile;
2000 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00002001 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00002002 (const unsigned char *)Buffer->getBufferEnd());
2003 Stream.init(StreamFile);
2004
2005 // Sniff for the signature.
2006 if (Stream.Read(8) != 'C' ||
2007 Stream.Read(8) != 'P' ||
2008 Stream.Read(8) != 'C' ||
2009 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002010 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002011 return std::string();
2012 }
2013
2014 RecordData Record;
2015 while (!Stream.AtEndOfStream()) {
2016 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Douglas Gregorb64c1932009-05-12 01:31:05 +00002018 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2019 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Douglas Gregorb64c1932009-05-12 01:31:05 +00002021 // We only know the PCH subblock ID.
2022 switch (BlockID) {
2023 case pch::PCH_BLOCK_ID:
2024 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002025 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002026 return std::string();
2027 }
2028 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Douglas Gregorb64c1932009-05-12 01:31:05 +00002030 default:
2031 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002032 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002033 return std::string();
2034 }
2035 break;
2036 }
2037 continue;
2038 }
2039
2040 if (Code == llvm::bitc::END_BLOCK) {
2041 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002042 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002043 return std::string();
2044 }
2045 continue;
2046 }
2047
2048 if (Code == llvm::bitc::DEFINE_ABBREV) {
2049 Stream.ReadAbbrevRecord();
2050 continue;
2051 }
2052
2053 Record.clear();
2054 const char *BlobStart = 0;
2055 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002056 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00002057 == pch::ORIGINAL_FILE_NAME)
2058 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00002059 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00002060
2061 return std::string();
2062}
2063
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002064/// \brief Parse the record that corresponds to a LangOptions data
2065/// structure.
2066///
2067/// This routine compares the language options used to generate the
2068/// PCH file against the language options set for the current
2069/// compilation. For each option, we classify differences between the
2070/// two compiler states as either "benign" or "important". Benign
2071/// differences don't matter, and we accept them without complaint
2072/// (and without modifying the language options). Differences between
2073/// the states for important options cause the PCH file to be
2074/// unusable, so we emit a warning and return true to indicate that
2075/// there was an error.
2076///
2077/// \returns true if the PCH file is unacceptable, false otherwise.
2078bool PCHReader::ParseLanguageOptions(
2079 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002080 if (Listener) {
2081 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002083 #define PARSE_LANGOPT(Option) \
2084 LangOpts.Option = Record[Idx]; \
2085 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002087 unsigned Idx = 0;
2088 PARSE_LANGOPT(Trigraphs);
2089 PARSE_LANGOPT(BCPLComment);
2090 PARSE_LANGOPT(DollarIdents);
2091 PARSE_LANGOPT(AsmPreprocessor);
2092 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00002093 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002094 PARSE_LANGOPT(ImplicitInt);
2095 PARSE_LANGOPT(Digraphs);
2096 PARSE_LANGOPT(HexFloats);
2097 PARSE_LANGOPT(C99);
2098 PARSE_LANGOPT(Microsoft);
2099 PARSE_LANGOPT(CPlusPlus);
2100 PARSE_LANGOPT(CPlusPlus0x);
2101 PARSE_LANGOPT(CXXOperatorNames);
2102 PARSE_LANGOPT(ObjC1);
2103 PARSE_LANGOPT(ObjC2);
2104 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002105 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00002106 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002107 PARSE_LANGOPT(PascalStrings);
2108 PARSE_LANGOPT(WritableStrings);
2109 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002110 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002111 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002112 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002113 PARSE_LANGOPT(NeXTRuntime);
2114 PARSE_LANGOPT(Freestanding);
2115 PARSE_LANGOPT(NoBuiltin);
2116 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002117 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002118 PARSE_LANGOPT(Blocks);
2119 PARSE_LANGOPT(EmitAllDecls);
2120 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002121 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2122 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002123 PARSE_LANGOPT(HeinousExtensions);
2124 PARSE_LANGOPT(Optimize);
2125 PARSE_LANGOPT(OptimizeSize);
2126 PARSE_LANGOPT(Static);
2127 PARSE_LANGOPT(PICLevel);
2128 PARSE_LANGOPT(GNUInline);
2129 PARSE_LANGOPT(NoInline);
2130 PARSE_LANGOPT(AccessControl);
2131 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002132 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002133 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2134 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002135 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002136 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002137 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002138 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002139 PARSE_LANGOPT(CatchUndefined);
2140 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002141 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002142
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002143 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002144 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002145
2146 return false;
2147}
2148
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002149void PCHReader::ReadPreprocessedEntities() {
2150 ReadDefinedMacros();
2151}
2152
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002153/// \brief Get the correct cursor and offset for loading a type.
2154PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2155 PerFileData *F = 0;
2156 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2157 F = Chain[N - I - 1];
2158 if (Index < F->LocalNumTypes)
2159 break;
2160 Index -= F->LocalNumTypes;
2161 }
2162 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redl971dd442010-07-20 22:55:31 +00002163 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002164}
2165
2166/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00002167///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002168/// The index is the type ID, shifted and minus the number of predefs. This
2169/// routine actually reads the record corresponding to the type at the given
2170/// location. It is a helper routine for GetType, which deals with reading type
2171/// IDs.
2172QualType PCHReader::ReadTypeRecord(unsigned Index) {
2173 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redl971dd442010-07-20 22:55:31 +00002174 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl9137a522010-07-16 17:50:48 +00002175
Douglas Gregor0b748912009-04-14 21:18:50 +00002176 // Keep track of where we are in the stream, then jump back there
2177 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002178 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002179
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002180 ReadingKindTracker ReadingKind(Read_Type, *this);
2181
Douglas Gregord89275b2009-07-06 18:54:52 +00002182 // Note that we are loading a type record.
2183 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002185 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002186 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002187 unsigned Code = DeclsCursor.ReadCode();
2188 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002189 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002190 if (Record.size() != 2) {
2191 Error("Incorrect encoding of extended qualifier type");
2192 return QualType();
2193 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002194 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002195 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2196 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002197 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002198
Douglas Gregor2cf26342009-04-09 22:27:44 +00002199 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002200 if (Record.size() != 1) {
2201 Error("Incorrect encoding of complex type");
2202 return QualType();
2203 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002204 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002205 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002206 }
2207
2208 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002209 if (Record.size() != 1) {
2210 Error("Incorrect encoding of pointer type");
2211 return QualType();
2212 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002213 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002214 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002215 }
2216
2217 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002218 if (Record.size() != 1) {
2219 Error("Incorrect encoding of block pointer type");
2220 return QualType();
2221 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002222 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002223 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002224 }
2225
2226 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002227 if (Record.size() != 1) {
2228 Error("Incorrect encoding of lvalue reference type");
2229 return QualType();
2230 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002231 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002232 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002233 }
2234
2235 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002236 if (Record.size() != 1) {
2237 Error("Incorrect encoding of rvalue reference type");
2238 return QualType();
2239 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002240 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002241 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002242 }
2243
2244 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002245 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002246 Error("Incorrect encoding of member pointer type");
2247 return QualType();
2248 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002249 QualType PointeeType = GetType(Record[0]);
2250 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002251 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002252 }
2253
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002254 case pch::TYPE_CONSTANT_ARRAY: {
2255 QualType ElementType = GetType(Record[0]);
2256 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2257 unsigned IndexTypeQuals = Record[2];
2258 unsigned Idx = 3;
2259 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002260 return Context->getConstantArrayType(ElementType, Size,
2261 ASM, IndexTypeQuals);
2262 }
2263
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002264 case pch::TYPE_INCOMPLETE_ARRAY: {
2265 QualType ElementType = GetType(Record[0]);
2266 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2267 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002268 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002269 }
2270
2271 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002272 QualType ElementType = GetType(Record[0]);
2273 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2274 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002275 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2276 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002277 return Context->getVariableArrayType(ElementType, ReadExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002278 ASM, IndexTypeQuals,
2279 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002280 }
2281
2282 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002283 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002284 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002285 return QualType();
2286 }
2287
2288 QualType ElementType = GetType(Record[0]);
2289 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002290 unsigned AltiVecSpec = Record[2];
2291 return Context->getVectorType(ElementType, NumElements,
2292 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002293 }
2294
2295 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002296 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002297 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002298 return QualType();
2299 }
2300
2301 QualType ElementType = GetType(Record[0]);
2302 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002303 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002304 }
2305
2306 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002307 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002308 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002309 return QualType();
2310 }
2311 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002312 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002313 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002314 }
2315
2316 case pch::TYPE_FUNCTION_PROTO: {
2317 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002318 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002319 unsigned RegParm = Record[2];
2320 CallingConv CallConv = (CallingConv)Record[3];
2321 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002322 unsigned NumParams = Record[Idx++];
2323 llvm::SmallVector<QualType, 16> ParamTypes;
2324 for (unsigned I = 0; I != NumParams; ++I)
2325 ParamTypes.push_back(GetType(Record[Idx++]));
2326 bool isVariadic = Record[Idx++];
2327 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002328 bool hasExceptionSpec = Record[Idx++];
2329 bool hasAnyExceptionSpec = Record[Idx++];
2330 unsigned NumExceptions = Record[Idx++];
2331 llvm::SmallVector<QualType, 2> Exceptions;
2332 for (unsigned I = 0; I != NumExceptions; ++I)
2333 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002334 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002335 isVariadic, Quals, hasExceptionSpec,
2336 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002337 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002338 FunctionType::ExtInfo(NoReturn, RegParm,
2339 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002340 }
2341
John McCalled976492009-12-04 22:46:56 +00002342 case pch::TYPE_UNRESOLVED_USING:
2343 return Context->getTypeDeclType(
2344 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2345
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002346 case pch::TYPE_TYPEDEF: {
2347 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002348 Error("incorrect encoding of typedef type");
2349 return QualType();
2350 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002351 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2352 QualType Canonical = GetType(Record[1]);
2353 return Context->getTypedefType(Decl, Canonical);
2354 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002355
2356 case pch::TYPE_TYPEOF_EXPR:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002357 return Context->getTypeOfExprType(ReadExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002358
2359 case pch::TYPE_TYPEOF: {
2360 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002361 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002362 return QualType();
2363 }
2364 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002365 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002366 }
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Anders Carlsson395b4752009-06-24 19:06:50 +00002368 case pch::TYPE_DECLTYPE:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002369 return Context->getDecltypeType(ReadExpr());
Anders Carlsson395b4752009-06-24 19:06:50 +00002370
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002371 case pch::TYPE_RECORD: {
2372 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002373 Error("incorrect encoding of record type");
2374 return QualType();
2375 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002376 bool IsDependent = Record[0];
2377 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2378 T->Dependent = IsDependent;
2379 return T;
2380 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002381
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002382 case pch::TYPE_ENUM: {
2383 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002384 Error("incorrect encoding of enum type");
2385 return QualType();
2386 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002387 bool IsDependent = Record[0];
2388 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2389 T->Dependent = IsDependent;
2390 return T;
2391 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002392
John McCall7da24312009-09-05 00:15:47 +00002393 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002394 unsigned Idx = 0;
2395 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2396 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2397 QualType NamedType = GetType(Record[Idx++]);
2398 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002399 }
2400
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002401 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002402 unsigned Idx = 0;
2403 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002404 return Context->getObjCInterfaceType(ItfD);
2405 }
2406
2407 case pch::TYPE_OBJC_OBJECT: {
2408 unsigned Idx = 0;
2409 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002410 unsigned NumProtos = Record[Idx++];
2411 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2412 for (unsigned I = 0; I != NumProtos; ++I)
2413 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002414 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002415 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002416
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002417 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002418 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002419 QualType Pointee = GetType(Record[Idx++]);
2420 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002421 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002422
John McCall49a832b2009-10-18 09:09:24 +00002423 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2424 unsigned Idx = 0;
2425 QualType Parm = GetType(Record[Idx++]);
2426 QualType Replacement = GetType(Record[Idx++]);
2427 return
2428 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2429 Replacement);
2430 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002431
2432 case pch::TYPE_INJECTED_CLASS_NAME: {
2433 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2434 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002435 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2436 // for PCH reading, too much interdependencies.
2437 return
2438 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002439 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002440
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002441 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2442 unsigned Idx = 0;
2443 unsigned Depth = Record[Idx++];
2444 unsigned Index = Record[Idx++];
2445 bool Pack = Record[Idx++];
2446 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2447 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2448 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002449
2450 case pch::TYPE_DEPENDENT_NAME: {
2451 unsigned Idx = 0;
2452 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2453 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2454 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002455 QualType Canon = GetType(Record[Idx++]);
2456 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002457 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002458
2459 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2460 unsigned Idx = 0;
2461 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2462 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2463 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2464 unsigned NumArgs = Record[Idx++];
2465 llvm::SmallVector<TemplateArgument, 8> Args;
2466 Args.reserve(NumArgs);
2467 while (NumArgs--)
2468 Args.push_back(ReadTemplateArgument(Record, Idx));
2469 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2470 Args.size(), Args.data());
2471 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002472
2473 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2474 unsigned Idx = 0;
2475
2476 // ArrayType
2477 QualType ElementType = GetType(Record[Idx++]);
2478 ArrayType::ArraySizeModifier ASM
2479 = (ArrayType::ArraySizeModifier)Record[Idx++];
2480 unsigned IndexTypeQuals = Record[Idx++];
2481
2482 // DependentSizedArrayType
2483 Expr *NumElts = ReadExpr();
2484 SourceRange Brackets = ReadSourceRange(Record, Idx);
2485
2486 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2487 IndexTypeQuals, Brackets);
2488 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002489
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002490 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2491 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002492 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002493 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002494 llvm::SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002495 ReadTemplateArgumentList(Args, Record, Idx);
2496 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002497 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002498 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002499 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2500 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002501 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002502 T = Context->getTemplateSpecializationType(Name, Args.data(),
2503 Args.size(), Canon);
2504 T->Dependent = IsDependent;
2505 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002506 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002507 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002508 // Suppress a GCC warning
2509 return QualType();
2510}
2511
John McCalla1ee0c52009-10-16 21:56:05 +00002512namespace {
2513
2514class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2515 PCHReader &Reader;
2516 const PCHReader::RecordData &Record;
2517 unsigned &Idx;
2518
2519public:
2520 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2521 unsigned &Idx)
2522 : Reader(Reader), Record(Record), Idx(Idx) { }
2523
John McCall51bd8032009-10-18 01:05:36 +00002524 // We want compile-time assurance that we've enumerated all of
2525 // these, so unfortunately we have to declare them first, then
2526 // define them out-of-line.
2527#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002528#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002529 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002530#include "clang/AST/TypeLocNodes.def"
2531
John McCall51bd8032009-10-18 01:05:36 +00002532 void VisitFunctionTypeLoc(FunctionTypeLoc);
2533 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002534};
2535
2536}
2537
John McCall51bd8032009-10-18 01:05:36 +00002538void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002539 // nothing to do
2540}
John McCall51bd8032009-10-18 01:05:36 +00002541void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002542 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2543 if (TL.needsExtraLocalData()) {
2544 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2545 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2546 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2547 TL.setModeAttr(Record[Idx++]);
2548 }
John McCalla1ee0c52009-10-16 21:56:05 +00002549}
John McCall51bd8032009-10-18 01:05:36 +00002550void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2551 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002552}
John McCall51bd8032009-10-18 01:05:36 +00002553void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2554 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002555}
John McCall51bd8032009-10-18 01:05:36 +00002556void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2557 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002558}
John McCall51bd8032009-10-18 01:05:36 +00002559void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2560 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002561}
John McCall51bd8032009-10-18 01:05:36 +00002562void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2563 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002564}
John McCall51bd8032009-10-18 01:05:36 +00002565void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2566 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002567}
John McCall51bd8032009-10-18 01:05:36 +00002568void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2569 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2570 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002571 if (Record[Idx++])
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002572 TL.setSizeExpr(Reader.ReadExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002573 else
John McCall51bd8032009-10-18 01:05:36 +00002574 TL.setSizeExpr(0);
2575}
2576void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2577 VisitArrayTypeLoc(TL);
2578}
2579void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2580 VisitArrayTypeLoc(TL);
2581}
2582void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2583 VisitArrayTypeLoc(TL);
2584}
2585void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2586 DependentSizedArrayTypeLoc TL) {
2587 VisitArrayTypeLoc(TL);
2588}
2589void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2590 DependentSizedExtVectorTypeLoc TL) {
2591 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2592}
2593void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2594 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2595}
2596void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2597 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2598}
2599void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2600 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2601 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2602 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002603 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002604 }
2605}
2606void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2607 VisitFunctionTypeLoc(TL);
2608}
2609void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2610 VisitFunctionTypeLoc(TL);
2611}
John McCalled976492009-12-04 22:46:56 +00002612void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2613 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2614}
John McCall51bd8032009-10-18 01:05:36 +00002615void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2616 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2617}
2618void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002619 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2620 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2621 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002622}
2623void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002624 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2625 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2626 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2627 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002628}
2629void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2630 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2631}
2632void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2633 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2634}
2635void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2636 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2637}
John McCall51bd8032009-10-18 01:05:36 +00002638void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2639 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2640}
John McCall49a832b2009-10-18 09:09:24 +00002641void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2642 SubstTemplateTypeParmTypeLoc TL) {
2643 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2644}
John McCall51bd8032009-10-18 01:05:36 +00002645void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2646 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002647 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2648 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2649 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2650 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2651 TL.setArgLocInfo(i,
2652 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2653 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002654}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002655void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002656 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2657 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002658}
John McCall3cb0ebd2010-03-10 03:28:59 +00002659void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2660 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2661}
Douglas Gregor4714c122010-03-31 17:34:00 +00002662void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002663 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2664 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002665 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2666}
John McCall33500952010-06-11 00:33:02 +00002667void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2668 DependentTemplateSpecializationTypeLoc TL) {
2669 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2670 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2671 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2672 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2673 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2674 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2675 TL.setArgLocInfo(I,
2676 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
2677 Record, Idx));
2678}
John McCall51bd8032009-10-18 01:05:36 +00002679void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2680 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002681}
2682void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2683 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002684 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2685 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2686 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2687 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002688}
John McCall54e14c42009-10-22 22:37:11 +00002689void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2690 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002691}
John McCalla1ee0c52009-10-16 21:56:05 +00002692
John McCalla93c9342009-12-07 02:54:59 +00002693TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002694 unsigned &Idx) {
2695 QualType InfoTy = GetType(Record[Idx++]);
2696 if (InfoTy.isNull())
2697 return 0;
2698
John McCalla93c9342009-12-07 02:54:59 +00002699 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCalla1ee0c52009-10-16 21:56:05 +00002700 TypeLocReader TLR(*this, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002701 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002702 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002703 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002704}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002705
Douglas Gregor8038d512009-04-10 17:25:41 +00002706QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002707 unsigned FastQuals = ID & Qualifiers::FastMask;
2708 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002709
2710 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2711 QualType T;
2712 switch ((pch::PredefinedTypeIDs)Index) {
2713 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002714 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2715 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002716
2717 case pch::PREDEF_TYPE_CHAR_U_ID:
2718 case pch::PREDEF_TYPE_CHAR_S_ID:
2719 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002720 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002721 break;
2722
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002723 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2724 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2725 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2726 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2727 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002728 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002729 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2730 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2731 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2732 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2733 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2734 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002735 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002736 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2737 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2738 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2739 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2740 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002741 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002742 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2743 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002744 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2745 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002746 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002747 }
2748
2749 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002750 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002751 }
2752
2753 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002754 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002755 if (TypesLoaded[Index].isNull()) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002756 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002757 TypesLoaded[Index]->setFromPCH();
Sebastian Redl30c514c2010-07-14 23:45:08 +00002758 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002759 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2760 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002761 }
Mike Stump1eb44332009-09-09 15:08:12 +00002762
John McCall0953e762009-09-24 19:53:00 +00002763 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002764}
2765
John McCall833ca992009-10-29 08:12:44 +00002766TemplateArgumentLocInfo
2767PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2768 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002769 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002770 switch (Kind) {
2771 case TemplateArgument::Expression:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002772 return ReadExpr();
John McCall833ca992009-10-29 08:12:44 +00002773 case TemplateArgument::Type:
John McCalla93c9342009-12-07 02:54:59 +00002774 return GetTypeSourceInfo(Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002775 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002776 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2777 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2778 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002779 }
John McCall833ca992009-10-29 08:12:44 +00002780 case TemplateArgument::Null:
2781 case TemplateArgument::Integral:
2782 case TemplateArgument::Declaration:
2783 case TemplateArgument::Pack:
2784 return TemplateArgumentLocInfo();
2785 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002786 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002787 return TemplateArgumentLocInfo();
2788}
2789
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002790TemplateArgumentLoc
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002791PCHReader::ReadTemplateArgumentLoc(const RecordData &Record, unsigned &Index) {
2792 TemplateArgument Arg = ReadTemplateArgument(Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002793
2794 if (Arg.getKind() == TemplateArgument::Expression) {
2795 if (Record[Index++]) // bool InfoHasSameExpr.
2796 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2797 }
2798 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002799 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002800}
2801
John McCall76bd1f32010-06-01 09:23:16 +00002802Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2803 return GetDecl(ID);
2804}
2805
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002806TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl30c514c2010-07-14 23:45:08 +00002807 if (!DeclsLoaded[0]) {
Sebastian Redlcb526aa2010-07-20 22:46:15 +00002808 ReadDeclRecord(0);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002809 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002810 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002811 }
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002812
2813 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2814}
2815
Douglas Gregor8038d512009-04-10 17:25:41 +00002816Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002817 if (ID == 0)
2818 return 0;
2819
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002820 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002821 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002822 return 0;
2823 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002824
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002825 unsigned Index = ID - 1;
Sebastian Redl30c514c2010-07-14 23:45:08 +00002826 if (!DeclsLoaded[Index]) {
Sebastian Redlcb526aa2010-07-20 22:46:15 +00002827 ReadDeclRecord(Index);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002828 if (DeserializationListener)
2829 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2830 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002831
2832 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002833}
2834
Chris Lattner887e2b32009-04-27 05:46:25 +00002835/// \brief Resolve the offset of a statement into a statement.
2836///
2837/// This operation will read a new statement from the external
2838/// source each time it is called, and is meant to be used via a
2839/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002840Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002841 // Since we know tha this statement is part of a decl, make sure to use the
2842 // decl cursor to read it.
Sebastian Redl9137a522010-07-16 17:50:48 +00002843 Chain[0]->DeclsCursor.JumpToBit(Offset);
2844 return ReadStmtFromStream(Chain[0]->DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002845}
2846
John McCall76bd1f32010-06-01 09:23:16 +00002847bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2848 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002849 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002850 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002851
Douglas Gregor2cf26342009-04-09 22:27:44 +00002852 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002853 if (Offset == 0) {
2854 Error("DeclContext has no lexical decls in storage");
2855 return true;
2856 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002857
Sebastian Redl9137a522010-07-16 17:50:48 +00002858 llvm::BitstreamCursor &DeclsCursor = Chain[0]->DeclsCursor;
2859
Douglas Gregor0b748912009-04-14 21:18:50 +00002860 // Keep track of where we are in the stream, then jump back there
2861 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002862 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002863
Douglas Gregor2cf26342009-04-09 22:27:44 +00002864 // Load the record containing all of the declarations lexically in
2865 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002866 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002867 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002868 unsigned Code = DeclsCursor.ReadCode();
2869 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002870 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2871 Error("Expected lexical block");
2872 return true;
2873 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002874
2875 // Load all of the declaration IDs
John McCall76bd1f32010-06-01 09:23:16 +00002876 for (RecordData::iterator I = Record.begin(), E = Record.end(); I != E; ++I)
2877 Decls.push_back(GetDecl(*I));
Douglas Gregor25123082009-04-22 22:34:57 +00002878 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002879 return false;
2880}
2881
John McCall76bd1f32010-06-01 09:23:16 +00002882DeclContext::lookup_result
2883PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2884 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002885 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002886 "DeclContext has no visible decls in storage");
2887 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002888 if (Offset == 0) {
2889 Error("DeclContext has no visible decls in storage");
John McCall76bd1f32010-06-01 09:23:16 +00002890 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2891 DeclContext::lookup_iterator());
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002892 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002893
Sebastian Redl9137a522010-07-16 17:50:48 +00002894 llvm::BitstreamCursor &DeclsCursor = Chain[0]->DeclsCursor;
2895
Douglas Gregor0b748912009-04-14 21:18:50 +00002896 // Keep track of where we are in the stream, then jump back there
2897 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002898 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002899
Douglas Gregor2cf26342009-04-09 22:27:44 +00002900 // Load the record containing all of the declarations visible in
2901 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002902 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002903 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002904 unsigned Code = DeclsCursor.ReadCode();
2905 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002906 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2907 Error("Expected visible block");
John McCall76bd1f32010-06-01 09:23:16 +00002908 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2909 DeclContext::lookup_iterator());
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002910 }
2911
John McCall76bd1f32010-06-01 09:23:16 +00002912 llvm::SmallVector<VisibleDeclaration, 64> Decls;
2913 if (Record.empty()) {
2914 SetExternalVisibleDecls(DC, Decls);
2915 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2916 DeclContext::lookup_iterator());
2917 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002918
2919 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002920 while (Idx < Record.size()) {
2921 Decls.push_back(VisibleDeclaration());
2922 Decls.back().Name = ReadDeclarationName(Record, Idx);
2923
Douglas Gregor2cf26342009-04-09 22:27:44 +00002924 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002925 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002926 LoadedDecls.reserve(Size);
2927 for (unsigned I = 0; I < Size; ++I)
2928 LoadedDecls.push_back(Record[Idx++]);
2929 }
2930
Douglas Gregor25123082009-04-22 22:34:57 +00002931 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00002932
2933 SetExternalVisibleDecls(DC, Decls);
2934 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002935}
2936
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002937void PCHReader::PassInterestingDeclsToConsumer() {
2938 assert(Consumer);
2939 while (!InterestingDecls.empty()) {
2940 DeclGroupRef DG(InterestingDecls.front());
2941 InterestingDecls.pop_front();
2942 Consumer->HandleTopLevelDecl(DG);
2943 }
2944}
2945
Douglas Gregorfdd01722009-04-14 00:24:19 +00002946void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002947 this->Consumer = Consumer;
2948
Douglas Gregorfdd01722009-04-14 00:24:19 +00002949 if (!Consumer)
2950 return;
2951
2952 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002953 // Force deserialization of this decl, which will cause it to be queued for
2954 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002955 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002956 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002957
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002958 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00002959}
2960
Douglas Gregor2cf26342009-04-09 22:27:44 +00002961void PCHReader::PrintStats() {
2962 std::fprintf(stderr, "*** PCH Statistics:\n");
2963
Mike Stump1eb44332009-09-09 15:08:12 +00002964 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002965 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002966 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002967 unsigned NumDeclsLoaded
2968 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2969 (Decl *)0);
2970 unsigned NumIdentifiersLoaded
2971 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2972 IdentifiersLoaded.end(),
2973 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002974 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002975 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2976 SelectorsLoaded.end(),
2977 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002978
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002979 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2980 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002981 if (TotalNumSLocEntries)
2982 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2983 NumSLocEntriesRead, TotalNumSLocEntries,
2984 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002985 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002986 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002987 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2988 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2989 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002990 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002991 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2992 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002993 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002994 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002995 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2996 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002997 if (TotalNumSelectors)
2998 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2999 NumSelectorsLoaded, TotalNumSelectors,
3000 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
3001 if (TotalNumStatements)
3002 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3003 NumStatementsRead, TotalNumStatements,
3004 ((float)NumStatementsRead/TotalNumStatements * 100));
3005 if (TotalNumMacros)
3006 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3007 NumMacrosRead, TotalNumMacros,
3008 ((float)NumMacrosRead/TotalNumMacros * 100));
3009 if (TotalLexicalDeclContexts)
3010 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3011 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3012 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3013 * 100));
3014 if (TotalVisibleDeclContexts)
3015 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3016 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3017 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3018 * 100));
3019 if (TotalSelectorsInMethodPool) {
3020 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
3021 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
3022 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
3023 * 100));
3024 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
3025 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003026 std::fprintf(stderr, "\n");
3027}
3028
Douglas Gregor668c1a42009-04-21 22:25:48 +00003029void PCHReader::InitializeSema(Sema &S) {
3030 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003031 S.ExternalSource = this;
3032
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003033 // Makes sure any declarations that were deserialized "too early"
3034 // still get added to the identifier's declaration chains.
3035 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3036 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3037 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003038 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003039 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003040
3041 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00003042 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003043 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3044 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00003045 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003046 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00003047
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003048 // If there were any unused static functions, deserialize them and add to
3049 // Sema's list of unused static functions.
3050 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3051 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3052 SemaObj->UnusedStaticFuncs.push_back(FD);
3053 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00003054
3055 // If there were any locally-scoped external declarations,
3056 // deserialize them and add them to Sema's table of locally-scoped
3057 // external declarations.
3058 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3059 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3060 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3061 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00003062
3063 // If there were any ext_vector type declarations, deserialize them
3064 // and add them to Sema's vector of such declarations.
3065 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3066 SemaObj->ExtVectorDecls.push_back(
3067 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003068
3069 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3070 // Can we cut them down before writing them ?
3071
3072 // If there were any VTable uses, deserialize the information and add it
3073 // to Sema's vector and map of VTable uses.
3074 unsigned Idx = 0;
3075 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3076 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3077 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3078 bool DefinitionRequired = VTableUses[Idx++];
3079 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3080 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3081 }
3082
3083 // If there were any dynamic classes declarations, deserialize them
3084 // and add them to Sema's vector of such declarations.
3085 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3086 SemaObj->DynamicClasses.push_back(
3087 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00003088}
3089
3090IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
3091 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00003092 PCHIdentifierLookupTable *IdTable
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00003093 = (PCHIdentifierLookupTable *)Chain[0]->IdentifierLookupTable;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003094 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3095 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3096 if (Pos == IdTable->end())
3097 return 0;
3098
3099 // Dereferencing the iterator has the effect of building the
3100 // IdentifierInfo node and populating it with the various
3101 // declarations it needs.
3102 return *Pos;
3103}
3104
Mike Stump1eb44332009-09-09 15:08:12 +00003105std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003106PCHReader::ReadMethodPool(Selector Sel) {
3107 if (!MethodPoolLookupTable)
3108 return std::pair<ObjCMethodList, ObjCMethodList>();
3109
3110 // Try to find this selector within our on-disk hash table.
3111 PCHMethodPoolLookupTable *PoolTable
3112 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
3113 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00003114 if (Pos == PoolTable->end()) {
3115 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003116 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00003117 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003118
Douglas Gregor83941df2009-04-25 17:48:32 +00003119 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003120 return *Pos;
3121}
3122
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003123void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00003124 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00003125 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003126 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003127}
3128
Douglas Gregord89275b2009-07-06 18:54:52 +00003129/// \brief Set the globally-visible declarations associated with the given
3130/// identifier.
3131///
3132/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00003133/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00003134/// them.
3135///
3136/// \param II an IdentifierInfo that refers to one or more globally-visible
3137/// declarations.
3138///
3139/// \param DeclIDs the set of declaration IDs with the name @p II that are
3140/// visible at global scope.
3141///
3142/// \param Nonrecursive should be true to indicate that the caller knows that
3143/// this call is non-recursive, and therefore the globally-visible declarations
3144/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003145void
3146PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003147 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3148 bool Nonrecursive) {
3149 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
3150 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3151 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3152 PII.II = II;
3153 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3154 PII.DeclIDs.push_back(DeclIDs[I]);
3155 return;
3156 }
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Douglas Gregord89275b2009-07-06 18:54:52 +00003158 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3159 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3160 if (SemaObj) {
3161 // Introduce this declaration into the translation-unit scope
3162 // and add it to the declaration chain for this identifier, so
3163 // that (unqualified) name lookup will find it.
3164 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3165 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3166 } else {
3167 // Queue this declaration so that it will be added to the
3168 // translation unit scope and identifier's declaration chain
3169 // once a Sema object is known.
3170 PreloadedDecls.push_back(D);
3171 }
3172 }
3173}
3174
Chris Lattner7356a312009-04-11 21:15:38 +00003175IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003176 if (ID == 0)
3177 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003179 if (IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003180 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003181 return 0;
3182 }
Mike Stump1eb44332009-09-09 15:08:12 +00003183
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003184 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003185 ID -= 1;
3186 if (!IdentifiersLoaded[ID]) {
3187 unsigned Index = ID;
3188 const char *Str = 0;
3189 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3190 PerFileData *F = Chain[N - I - 1];
3191 if (Index < F->LocalNumIdentifiers) {
3192 uint32_t Offset = F->IdentifierOffsets[Index];
3193 Str = F->IdentifierTableData + Offset;
3194 break;
3195 }
3196 Index -= F->LocalNumIdentifiers;
3197 }
3198 assert(Str && "Broken Chain");
Douglas Gregord6595a42009-04-25 21:04:17 +00003199
Douglas Gregor02fc7512009-04-28 20:01:51 +00003200 // All of the strings in the PCH file are preceded by a 16-bit
3201 // length. Extract that 16-bit length to avoid having to execute
3202 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003203 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3204 // unsigned integers. This is important to avoid integer overflow when
3205 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003206 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003207 unsigned StrLen = (((unsigned) StrLenPtr[0])
3208 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003209 IdentifiersLoaded[ID]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003210 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003211 }
Mike Stump1eb44332009-09-09 15:08:12 +00003212
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003213 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003214}
3215
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003216void PCHReader::ReadSLocEntry(unsigned ID) {
3217 ReadSLocEntryRecord(ID);
3218}
3219
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003220Selector PCHReader::DecodeSelector(unsigned ID) {
3221 if (ID == 0)
3222 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003223
Douglas Gregora02b1472009-04-28 21:53:25 +00003224 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003225 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00003226
3227 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003228 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003229 return Selector();
3230 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003231
3232 unsigned Index = ID - 1;
3233 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3234 // Load this selector from the selector table.
3235 // FIXME: endianness portability issues with SelectorOffsets table
3236 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00003237 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00003238 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3239 }
3240
3241 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003242}
3243
John McCall76bd1f32010-06-01 09:23:16 +00003244Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003245 return DecodeSelector(ID);
3246}
3247
John McCall76bd1f32010-06-01 09:23:16 +00003248uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregor719770d2010-04-06 17:30:22 +00003249 return TotalNumSelectors + 1;
3250}
3251
Mike Stump1eb44332009-09-09 15:08:12 +00003252DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003253PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3254 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3255 switch (Kind) {
3256 case DeclarationName::Identifier:
3257 return DeclarationName(GetIdentifierInfo(Record, Idx));
3258
3259 case DeclarationName::ObjCZeroArgSelector:
3260 case DeclarationName::ObjCOneArgSelector:
3261 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003262 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003263
3264 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003265 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003266 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003267
3268 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003269 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003270 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003271
3272 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003273 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003274 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003275
3276 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003277 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003278 (OverloadedOperatorKind)Record[Idx++]);
3279
Sean Hunt3e518bd2009-11-29 07:34:05 +00003280 case DeclarationName::CXXLiteralOperatorName:
3281 return Context->DeclarationNames.getCXXLiteralOperatorName(
3282 GetIdentifierInfo(Record, Idx));
3283
Douglas Gregor2cf26342009-04-09 22:27:44 +00003284 case DeclarationName::CXXUsingDirective:
3285 return DeclarationName::getUsingDirectiveName();
3286 }
3287
3288 // Required to silence GCC warning
3289 return DeclarationName();
3290}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003291
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003292TemplateName
3293PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3294 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3295 switch (Kind) {
3296 case TemplateName::Template:
3297 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3298
3299 case TemplateName::OverloadedTemplate: {
3300 unsigned size = Record[Idx++];
3301 UnresolvedSet<8> Decls;
3302 while (size--)
3303 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3304
3305 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3306 }
3307
3308 case TemplateName::QualifiedTemplate: {
3309 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3310 bool hasTemplKeyword = Record[Idx++];
3311 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3312 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3313 }
3314
3315 case TemplateName::DependentTemplate: {
3316 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3317 if (Record[Idx++]) // isIdentifier
3318 return Context->getDependentTemplateName(NNS,
3319 GetIdentifierInfo(Record, Idx));
3320 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003321 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003322 }
3323 }
3324
3325 assert(0 && "Unhandled template name kind!");
3326 return TemplateName();
3327}
3328
3329TemplateArgument
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003330PCHReader::ReadTemplateArgument(const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003331 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3332 case TemplateArgument::Null:
3333 return TemplateArgument();
3334 case TemplateArgument::Type:
3335 return TemplateArgument(GetType(Record[Idx++]));
3336 case TemplateArgument::Declaration:
3337 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003338 case TemplateArgument::Integral: {
3339 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3340 QualType T = GetType(Record[Idx++]);
3341 return TemplateArgument(Value, T);
3342 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003343 case TemplateArgument::Template:
3344 return TemplateArgument(ReadTemplateName(Record, Idx));
3345 case TemplateArgument::Expression:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003346 return TemplateArgument(ReadExpr());
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003347 case TemplateArgument::Pack: {
3348 unsigned NumArgs = Record[Idx++];
3349 llvm::SmallVector<TemplateArgument, 8> Args;
3350 Args.reserve(NumArgs);
3351 while (NumArgs--)
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003352 Args.push_back(ReadTemplateArgument(Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003353 TemplateArgument TemplArg;
3354 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3355 return TemplArg;
3356 }
3357 }
3358
3359 assert(0 && "Unhandled template argument kind!");
3360 return TemplateArgument();
3361}
3362
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003363TemplateParameterList *
3364PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3365 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3366 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3367 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3368
3369 unsigned NumParams = Record[Idx++];
3370 llvm::SmallVector<NamedDecl *, 16> Params;
3371 Params.reserve(NumParams);
3372 while (NumParams--)
3373 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3374
3375 TemplateParameterList* TemplateParams =
3376 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3377 Params.data(), Params.size(), RAngleLoc);
3378 return TemplateParams;
3379}
3380
3381void
3382PCHReader::
3383ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
3384 const RecordData &Record, unsigned &Idx) {
3385 unsigned NumTemplateArgs = Record[Idx++];
3386 TemplArgs.reserve(NumTemplateArgs);
3387 while (NumTemplateArgs--)
3388 TemplArgs.push_back(ReadTemplateArgument(Record, Idx));
3389}
3390
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003391/// \brief Read a UnresolvedSet structure.
3392void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3393 const RecordData &Record, unsigned &Idx) {
3394 unsigned NumDecls = Record[Idx++];
3395 while (NumDecls--) {
3396 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3397 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3398 Set.addDecl(D, AS);
3399 }
3400}
3401
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003402CXXBaseSpecifier
3403PCHReader::ReadCXXBaseSpecifier(const RecordData &Record, unsigned &Idx) {
3404 bool isVirtual = static_cast<bool>(Record[Idx++]);
3405 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3406 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3407 QualType T = GetType(Record[Idx++]);
3408 SourceRange Range = ReadSourceRange(Record, Idx);
3409 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, T);
3410}
3411
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003412NestedNameSpecifier *
3413PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3414 unsigned N = Record[Idx++];
3415 NestedNameSpecifier *NNS = 0, *Prev = 0;
3416 for (unsigned I = 0; I != N; ++I) {
3417 NestedNameSpecifier::SpecifierKind Kind
3418 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3419 switch (Kind) {
3420 case NestedNameSpecifier::Identifier: {
3421 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3422 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3423 break;
3424 }
3425
3426 case NestedNameSpecifier::Namespace: {
3427 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3428 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3429 break;
3430 }
3431
3432 case NestedNameSpecifier::TypeSpec:
3433 case NestedNameSpecifier::TypeSpecWithTemplate: {
3434 Type *T = GetType(Record[Idx++]).getTypePtr();
3435 bool Template = Record[Idx++];
3436 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3437 break;
3438 }
3439
3440 case NestedNameSpecifier::Global: {
3441 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3442 // No associated value, and there can't be a prefix.
3443 break;
3444 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003445 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003446 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003447 }
3448 return NNS;
3449}
3450
3451SourceRange
3452PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003453 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3454 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3455 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003456}
3457
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003458/// \brief Read an integral value
3459llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3460 unsigned BitWidth = Record[Idx++];
3461 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3462 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3463 Idx += NumWords;
3464 return Result;
3465}
3466
3467/// \brief Read a signed integral value
3468llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3469 bool isUnsigned = Record[Idx++];
3470 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3471}
3472
Douglas Gregor17fc2232009-04-14 21:55:33 +00003473/// \brief Read a floating-point value
3474llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003475 return llvm::APFloat(ReadAPInt(Record, Idx));
3476}
3477
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003478// \brief Read a string
3479std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3480 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003481 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003482 Idx += Len;
3483 return Result;
3484}
3485
Chris Lattnerd2598362010-05-10 00:25:06 +00003486CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3487 unsigned &Idx) {
3488 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3489 return CXXTemporary::Create(*Context, Decl);
3490}
3491
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003492DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003493 return Diag(SourceLocation(), DiagID);
3494}
3495
3496DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003497 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003498}
Douglas Gregor025452f2009-04-17 00:04:06 +00003499
Douglas Gregor668c1a42009-04-21 22:25:48 +00003500/// \brief Retrieve the identifier table associated with the
3501/// preprocessor.
3502IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003503 assert(PP && "Forgot to set Preprocessor ?");
3504 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003505}
3506
Douglas Gregor025452f2009-04-17 00:04:06 +00003507/// \brief Record that the given ID maps to the given switch-case
3508/// statement.
3509void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3510 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3511 SwitchCaseStmts[ID] = SC;
3512}
3513
3514/// \brief Retrieve the switch-case statement with the given ID.
3515SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3516 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3517 return SwitchCaseStmts[ID];
3518}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003519
3520/// \brief Record that the given label statement has been
3521/// deserialized and has the given ID.
3522void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003523 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003524 "Deserialized label twice");
3525 LabelStmts[ID] = S;
3526
3527 // If we've already seen any goto statements that point to this
3528 // label, resolve them now.
3529 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3530 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3531 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3532 Goto->second->setLabel(S);
3533 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003534
3535 // If we've already seen any address-label statements that point to
3536 // this label, resolve them now.
3537 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003538 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003539 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003540 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003541 AddrLabel != AddrLabels.second; ++AddrLabel)
3542 AddrLabel->second->setLabel(S);
3543 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003544}
3545
3546/// \brief Set the label of the given statement to the label
3547/// identified by ID.
3548///
3549/// Depending on the order in which the label and other statements
3550/// referencing that label occur, this operation may complete
3551/// immediately (updating the statement) or it may queue the
3552/// statement to be back-patched later.
3553void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3554 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3555 if (Label != LabelStmts.end()) {
3556 // We've already seen this label, so set the label of the goto and
3557 // we're done.
3558 S->setLabel(Label->second);
3559 } else {
3560 // We haven't seen this label yet, so add this goto to the set of
3561 // unresolved goto statements.
3562 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3563 }
3564}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003565
3566/// \brief Set the label of the given expression to the label
3567/// identified by ID.
3568///
3569/// Depending on the order in which the label and other statements
3570/// referencing that label occur, this operation may complete
3571/// immediately (updating the statement) or it may queue the
3572/// statement to be back-patched later.
3573void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3574 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3575 if (Label != LabelStmts.end()) {
3576 // We've already seen this label, so set the label of the
3577 // label-address expression and we're done.
3578 S->setLabel(Label->second);
3579 } else {
3580 // We haven't seen this label yet, so add this label-address
3581 // expression to the set of unresolved label-address expressions.
3582 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3583 }
3584}
Douglas Gregord89275b2009-07-06 18:54:52 +00003585
3586
Mike Stump1eb44332009-09-09 15:08:12 +00003587PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00003588 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3589 Reader.CurrentlyLoadingTypeOrDecl = this;
3590}
3591
3592PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3593 if (!Parent) {
3594 // If any identifiers with corresponding top-level declarations have
3595 // been loaded, load those declarations now.
3596 while (!Reader.PendingIdentifierInfos.empty()) {
3597 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3598 Reader.PendingIdentifierInfos.front().DeclIDs,
3599 true);
3600 Reader.PendingIdentifierInfos.pop_front();
3601 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003602
3603 // We are not in recursive loading, so it's safe to pass the "interesting"
3604 // decls to the consumer.
3605 if (Reader.Consumer)
3606 Reader.PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003607 }
3608
Mike Stump1eb44332009-09-09 15:08:12 +00003609 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00003610}