blob: 48d05ba826c3543126120b943d4219f1d1f69981 [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),
Sebastian Redl04e6fd42010-07-21 20:07:32 +0000423 TotalNumSelectors(0), isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000424 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
425 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
426 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
427 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
428 TotalVisibleDeclContexts(0), CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000429 RelocatablePCH = false;
430}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000431
432PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000433 Diagnostic &Diags, const char *isysroot)
Sebastian Redl30c514c2010-07-14 23:45:08 +0000434 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl9137a522010-07-16 17:50:48 +0000435 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000436 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
437 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Sebastian Redl04e6fd42010-07-21 20:07:32 +0000438 TotalNumSelectors(0), isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000439 NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
440 TotalNumStatements(0), NumMacrosRead(0), NumMethodPoolSelectorsRead(0),
441 NumMethodPoolMisses(0), TotalNumMacros(0), NumLexicalDeclContextsRead(0),
442 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
443 TotalVisibleDeclContexts(0), CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000444 RelocatablePCH = false;
445}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000446
Sebastian Redl9137a522010-07-16 17:50:48 +0000447PCHReader::~PCHReader() {
448 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
449 delete Chain[e - i - 1];
450}
451
452PCHReader::PerFileData::PerFileData()
Sebastian Redl12d6da02010-07-19 22:06:55 +0000453 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redl2da08f92010-07-19 22:28:42 +0000454 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
Sebastian Redl04e6fd42010-07-21 20:07:32 +0000455 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
456 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
457 NumPreallocatedPreprocessingEntities(0)
Sebastian Redl9137a522010-07-16 17:50:48 +0000458{}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000459
Chris Lattner4c6f9522009-04-27 05:14:47 +0000460
Douglas Gregor668c1a42009-04-21 22:25:48 +0000461namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000462class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000463 PCHReader &Reader;
464
465public:
466 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
467
468 typedef Selector external_key_type;
469 typedef external_key_type internal_key_type;
470
471 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000473 static bool EqualKey(const internal_key_type& a,
474 const internal_key_type& b) {
475 return a == b;
476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000478 static unsigned ComputeHash(Selector Sel) {
479 unsigned N = Sel.getNumArgs();
480 if (N == 0)
481 ++N;
482 unsigned R = 5381;
483 for (unsigned I = 0; I != N; ++I)
484 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000485 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000486 return R;
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000489 // This hopefully will just get inlined and removed by the optimizer.
490 static const internal_key_type&
491 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000493 static std::pair<unsigned, unsigned>
494 ReadKeyDataLength(const unsigned char*& d) {
495 using namespace clang::io;
496 unsigned KeyLen = ReadUnalignedLE16(d);
497 unsigned DataLen = ReadUnalignedLE16(d);
498 return std::make_pair(KeyLen, DataLen);
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregor83941df2009-04-25 17:48:32 +0000501 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000502 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000503 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000504 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000505 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000506 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
507 if (N == 0)
508 return SelTable.getNullarySelector(FirstII);
509 else if (N == 1)
510 return SelTable.getUnarySelector(FirstII);
511
512 llvm::SmallVector<IdentifierInfo *, 16> Args;
513 Args.push_back(FirstII);
514 for (unsigned I = 1; I != N; ++I)
515 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
516
Douglas Gregor75fdb232009-05-22 22:45:36 +0000517 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000518 }
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000520 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
521 using namespace clang::io;
522 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
523 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
524
525 data_type Result;
526
527 // Load instance methods
528 ObjCMethodList *Prev = 0;
529 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000530 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000531 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
532 if (!Result.first.Method) {
533 // This is the first method, which is the easy case.
534 Result.first.Method = Method;
535 Prev = &Result.first;
536 continue;
537 }
538
Ted Kremenek298ed872010-02-11 00:53:01 +0000539 ObjCMethodList *Mem =
540 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
541 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000542 Prev = Prev->Next;
543 }
544
545 // Load factory methods
546 Prev = 0;
547 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000548 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000549 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
550 if (!Result.second.Method) {
551 // This is the first method, which is the easy case.
552 Result.second.Method = Method;
553 Prev = &Result.second;
554 continue;
555 }
556
Ted Kremenek298ed872010-02-11 00:53:01 +0000557 ObjCMethodList *Mem =
558 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
559 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000560 Prev = Prev->Next;
561 }
562
563 return Result;
564 }
565};
Mike Stump1eb44332009-09-09 15:08:12 +0000566
567} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000568
569/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000570typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000571 PCHMethodPoolLookupTable;
572
573namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000574class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000575 PCHReader &Reader;
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000576 llvm::BitstreamCursor &Stream;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000577
578 // If we know the IdentifierInfo in advance, it is here and we will
579 // not build a new one. Used when deserializing information about an
580 // identifier that was constructed before the PCH file was read.
581 IdentifierInfo *KnownII;
582
583public:
584 typedef IdentifierInfo * data_type;
585
586 typedef const std::pair<const char*, unsigned> external_key_type;
587
588 typedef external_key_type internal_key_type;
589
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000590 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
591 IdentifierInfo *II = 0)
592 : Reader(Reader), Stream(Stream), 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);
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000681 Reader.ReadMacroRecord(Stream, 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
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001119void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, 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
Douglas Gregor37e26842009-04-21 23:56:24 +00001122 // Keep track of where we are in the stream, then jump back there
1123 // after reading this macro.
1124 SavedStreamPosition SavedPosition(Stream);
1125
1126 Stream.JumpToBit(Offset);
1127 RecordData Record;
1128 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1129 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Douglas Gregor37e26842009-04-21 23:56:24 +00001131 while (true) {
1132 unsigned Code = Stream.ReadCode();
1133 switch (Code) {
1134 case llvm::bitc::END_BLOCK:
1135 return;
1136
1137 case llvm::bitc::ENTER_SUBBLOCK:
1138 // No known subblocks, always skip them.
1139 Stream.ReadSubBlockID();
1140 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001141 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001142 return;
1143 }
1144 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Douglas Gregor37e26842009-04-21 23:56:24 +00001146 case llvm::bitc::DEFINE_ABBREV:
1147 Stream.ReadAbbrevRecord();
1148 continue;
1149 default: break;
1150 }
1151
1152 // Read a record.
1153 Record.clear();
1154 pch::PreprocessorRecordTypes RecType =
1155 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1156 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001157 case pch::PP_MACRO_OBJECT_LIKE:
1158 case pch::PP_MACRO_FUNCTION_LIKE: {
1159 // If we already have a macro, that means that we've hit the end
1160 // of the definition of the macro we were looking for. We're
1161 // done.
1162 if (Macro)
1163 return;
1164
1165 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1166 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001167 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001168 return;
1169 }
1170 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1171 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001173 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001174 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001176 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001177 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1178 // Decode function-like macro info.
1179 bool isC99VarArgs = Record[3];
1180 bool isGNUVarArgs = Record[4];
1181 MacroArgs.clear();
1182 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001183 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001184 for (unsigned i = 0; i != NumArgs; ++i)
1185 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1186
1187 // Install function-like macro info.
1188 MI->setIsFunctionLike();
1189 if (isC99VarArgs) MI->setIsC99Varargs();
1190 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001191 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001192 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001193 }
1194
1195 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001196 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001197
1198 // Remember that we saw this macro last so that we add the tokens that
1199 // form its body to it.
1200 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001201
1202 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1203 // We have a macro definition. Load it now.
1204 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1205 getMacroDefinition(Record[NextIndex]));
1206 }
1207
Douglas Gregor37e26842009-04-21 23:56:24 +00001208 ++NumMacrosRead;
1209 break;
1210 }
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Douglas Gregor37e26842009-04-21 23:56:24 +00001212 case pch::PP_TOKEN: {
1213 // If we see a TOKEN before a PP_MACRO_*, then the file is
1214 // erroneous, just pretend we didn't see this.
1215 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Douglas Gregor37e26842009-04-21 23:56:24 +00001217 Token Tok;
1218 Tok.startToken();
1219 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1220 Tok.setLength(Record[1]);
1221 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1222 Tok.setIdentifierInfo(II);
1223 Tok.setKind((tok::TokenKind)Record[3]);
1224 Tok.setFlag((Token::TokenFlags)Record[4]);
1225 Macro->AddTokenToBody(Tok);
1226 break;
1227 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001228
1229 case pch::PP_MACRO_INSTANTIATION: {
1230 // If we already have a macro, that means that we've hit the end
1231 // of the definition of the macro we were looking for. We're
1232 // done.
1233 if (Macro)
1234 return;
1235
1236 if (!PP->getPreprocessingRecord()) {
1237 Error("missing preprocessing record in PCH file");
1238 return;
1239 }
1240
1241 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1242 if (PPRec.getPreprocessedEntity(Record[0]))
1243 return;
1244
1245 MacroInstantiation *MI
1246 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1247 SourceRange(
1248 SourceLocation::getFromRawEncoding(Record[1]),
1249 SourceLocation::getFromRawEncoding(Record[2])),
1250 getMacroDefinition(Record[4]));
1251 PPRec.SetPreallocatedEntity(Record[0], MI);
1252 return;
1253 }
1254
1255 case pch::PP_MACRO_DEFINITION: {
1256 // If we already have a macro, that means that we've hit the end
1257 // of the definition of the macro we were looking for. We're
1258 // done.
1259 if (Macro)
1260 return;
1261
1262 if (!PP->getPreprocessingRecord()) {
1263 Error("missing preprocessing record in PCH file");
1264 return;
1265 }
1266
1267 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1268 if (PPRec.getPreprocessedEntity(Record[0]))
1269 return;
1270
1271 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1272 Error("out-of-bounds macro definition record");
1273 return;
1274 }
1275
1276 MacroDefinition *MD
1277 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1278 SourceLocation::getFromRawEncoding(Record[5]),
1279 SourceRange(
1280 SourceLocation::getFromRawEncoding(Record[2]),
1281 SourceLocation::getFromRawEncoding(Record[3])));
1282 PPRec.SetPreallocatedEntity(Record[0], MD);
1283 MacroDefinitionsLoaded[Record[1]] = MD;
1284 return;
1285 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001286 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001287 }
1288}
1289
Douglas Gregor88a35862010-01-04 19:18:44 +00001290void PCHReader::ReadDefinedMacros() {
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001291 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1292 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001293
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001294 // If there was no preprocessor block, skip this file.
1295 if (!MacroCursor.getBitStreamReader())
1296 continue;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001297
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001298 llvm::BitstreamCursor Cursor = MacroCursor;
1299 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1300 Error("malformed preprocessor block record in PCH file");
Douglas Gregor88a35862010-01-04 19:18:44 +00001301 return;
1302 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001303
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001304 RecordData Record;
1305 while (true) {
1306 unsigned Code = Cursor.ReadCode();
1307 if (Code == llvm::bitc::END_BLOCK) {
1308 if (Cursor.ReadBlockEnd()) {
1309 Error("error at end of preprocessor block in PCH file");
1310 return;
1311 }
1312 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001313 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001314
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001315 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1316 // No known subblocks, always skip them.
1317 Cursor.ReadSubBlockID();
1318 if (Cursor.SkipBlock()) {
1319 Error("malformed block record in PCH file");
1320 return;
1321 }
1322 continue;
1323 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001324
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001325 if (Code == llvm::bitc::DEFINE_ABBREV) {
1326 Cursor.ReadAbbrevRecord();
1327 continue;
1328 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001329
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001330 // Read a record.
1331 const char *BlobStart;
1332 unsigned BlobLen;
1333 Record.clear();
1334 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1335 default: // Default behavior: ignore.
1336 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001337
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001338 case pch::PP_MACRO_OBJECT_LIKE:
1339 case pch::PP_MACRO_FUNCTION_LIKE:
1340 DecodeIdentifierInfo(Record[0]);
1341 break;
1342
1343 case pch::PP_TOKEN:
1344 // Ignore tokens.
1345 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001346
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001347 case pch::PP_MACRO_INSTANTIATION:
1348 case pch::PP_MACRO_DEFINITION:
1349 // Read the macro record.
1350 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1351 break;
1352 }
Douglas Gregor88a35862010-01-04 19:18:44 +00001353 }
1354 }
1355}
1356
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001357MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1358 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1359 return 0;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001360
1361 if (!MacroDefinitionsLoaded[ID]) {
1362 unsigned Index = ID;
1363 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1364 PerFileData &F = *Chain[N - I - 1];
1365 if (Index < F.LocalNumMacroDefinitions) {
1366 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1367 break;
1368 }
1369 Index -= F.LocalNumMacroDefinitions;
1370 }
1371 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1372 }
1373
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001374 return MacroDefinitionsLoaded[ID];
1375}
1376
Douglas Gregore650c8c2009-07-07 00:12:59 +00001377/// \brief If we are loading a relocatable PCH file, and the filename is
1378/// not an absolute path, add the system root to the beginning of the file
1379/// name.
1380void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1381 // If this is not a relocatable PCH file, there's nothing to do.
1382 if (!RelocatablePCH)
1383 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Daniel Dunbard5b21972009-11-18 19:50:41 +00001385 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001386 return;
1387
Douglas Gregore650c8c2009-07-07 00:12:59 +00001388 if (isysroot == 0) {
1389 // If no system root was given, default to '/'
1390 Filename.insert(Filename.begin(), '/');
1391 return;
1392 }
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Douglas Gregore650c8c2009-07-07 00:12:59 +00001394 unsigned Length = strlen(isysroot);
1395 if (isysroot[Length - 1] != '/')
1396 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Douglas Gregore650c8c2009-07-07 00:12:59 +00001398 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1399}
1400
Mike Stump1eb44332009-09-09 15:08:12 +00001401PCHReader::PCHReadResult
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001402PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00001403 llvm::BitstreamCursor &Stream = F.Stream;
1404
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001405 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001406 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001407 return Failure;
1408 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001409
1410 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001411 RecordData Record;
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001412 bool First = true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001413 while (!Stream.AtEndOfStream()) {
1414 unsigned Code = Stream.ReadCode();
1415 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001416 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001417 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001418 return Failure;
1419 }
Chris Lattner7356a312009-04-11 21:15:38 +00001420
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001421 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001422 }
1423
1424 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1425 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001426 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001427 // We lazily load the decls block, but we want to set up the
1428 // DeclsCursor cursor to point into it. Clone our current bitcode
1429 // cursor to it, enter the block and read the abbrevs in that block.
1430 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00001431 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00001432 if (Stream.SkipBlock() || // Skip with the main cursor.
1433 // Read the abbrevs.
Sebastian Redl9137a522010-07-16 17:50:48 +00001434 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001435 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001436 return Failure;
1437 }
1438 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Chris Lattner7356a312009-04-11 21:15:38 +00001440 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00001441 F.MacroCursor = Stream;
Douglas Gregor88a35862010-01-04 19:18:44 +00001442 if (PP)
1443 PP->setExternalSource(this);
1444
Chris Lattner7356a312009-04-11 21:15:38 +00001445 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001446 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001447 return Failure;
1448 }
1449 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001450
Douglas Gregor14f79002009-04-10 03:52:48 +00001451 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001452 switch (ReadSourceManagerBlock(F)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001453 case Success:
1454 break;
1455
1456 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001457 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001458 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001459
1460 case IgnorePCH:
1461 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001462 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001463 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001464 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001465 First = false;
Douglas Gregor8038d512009-04-10 17:25:41 +00001466 continue;
1467 }
1468
1469 if (Code == llvm::bitc::DEFINE_ABBREV) {
1470 Stream.ReadAbbrevRecord();
1471 continue;
1472 }
1473
1474 // Read and process a record.
1475 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001476 const char *BlobStart = 0;
1477 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001478 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001479 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001480 default: // Default behavior: ignore.
1481 break;
1482
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001483 case pch::METADATA: {
1484 if (Record[0] != pch::VERSION_MAJOR) {
1485 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1486 : diag::warn_pch_version_too_new);
1487 return IgnorePCH;
1488 }
1489
1490 RelocatablePCH = Record[4];
1491 if (Listener) {
1492 std::string TargetTriple(BlobStart, BlobLen);
1493 if (Listener->ReadTargetTriple(TargetTriple))
1494 return IgnorePCH;
1495 }
1496 break;
1497 }
1498
1499 case pch::CHAINED_METADATA: {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001500 if (!First) {
1501 Error("CHAINED_METADATA is not first record in block");
1502 return Failure;
1503 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001504 if (Record[0] != pch::VERSION_MAJOR) {
1505 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1506 : diag::warn_pch_version_too_new);
1507 return IgnorePCH;
1508 }
1509
1510 // Load the chained file.
1511 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1512 case Failure: return Failure;
1513 // If we have to ignore the dependency, we'll have to ignore this too.
1514 case IgnorePCH: return IgnorePCH;
1515 case Success: break;
1516 }
1517 break;
1518 }
1519
Douglas Gregor8038d512009-04-10 17:25:41 +00001520 case pch::TYPE_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001521 if (F.LocalNumTypes != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001522 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001523 return Failure;
1524 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001525 F.TypeOffsets = (const uint32_t *)BlobStart;
1526 F.LocalNumTypes = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001527 break;
1528
1529 case pch::DECL_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001530 if (F.LocalNumDecls != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001531 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001532 return Failure;
1533 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001534 F.DeclOffsets = (const uint32_t *)BlobStart;
1535 F.LocalNumDecls = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001536 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001537
1538 case pch::LANGUAGE_OPTIONS:
1539 if (ParseLanguageOptions(Record))
1540 return IgnorePCH;
1541 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001542
Douglas Gregorafaf3082009-04-11 00:14:32 +00001543 case pch::IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001544 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001545 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001546 F.IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001547 = PCHIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001548 (const unsigned char *)F.IdentifierTableData + Record[0],
1549 (const unsigned char *)F.IdentifierTableData,
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001550 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001551 if (PP)
1552 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001553 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001554 break;
1555
1556 case pch::IDENTIFIER_OFFSET:
Sebastian Redl2da08f92010-07-19 22:28:42 +00001557 if (F.LocalNumIdentifiers != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001558 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001559 return Failure;
1560 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001561 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1562 F.LocalNumIdentifiers = Record[0];
Douglas Gregorafaf3082009-04-11 00:14:32 +00001563 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001564
1565 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001566 // Optimization for the first block.
1567 if (ExternalDefinitions.empty())
1568 ExternalDefinitions.swap(Record);
1569 else
1570 ExternalDefinitions.insert(ExternalDefinitions.end(),
1571 Record.begin(), Record.end());
Douglas Gregorfdd01722009-04-14 00:24:19 +00001572 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001573
Douglas Gregorad1de002009-04-18 05:55:16 +00001574 case pch::SPECIAL_TYPES:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001575 // Optimization for the first block
1576 if (SpecialTypes.empty())
1577 SpecialTypes.swap(Record);
1578 else
1579 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregorad1de002009-04-18 05:55:16 +00001580 break;
1581
Douglas Gregor3e1af842009-04-17 22:13:46 +00001582 case pch::STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001583 TotalNumStatements += Record[0];
1584 TotalNumMacros += Record[1];
1585 TotalLexicalDeclContexts += Record[2];
1586 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001587 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001588
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001589 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001590 // Optimization for the first block.
1591 if (TentativeDefinitions.empty())
1592 TentativeDefinitions.swap(Record);
1593 else
1594 TentativeDefinitions.insert(TentativeDefinitions.end(),
1595 Record.begin(), Record.end());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001596 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001597
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001598 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001599 // Optimization for the first block.
1600 if (UnusedStaticFuncs.empty())
1601 UnusedStaticFuncs.swap(Record);
1602 else
1603 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1604 Record.begin(), Record.end());
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001605 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001606
Douglas Gregor14c22f22009-04-22 22:18:58 +00001607 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001608 // Optimization for the first block.
1609 if (LocallyScopedExternalDecls.empty())
1610 LocallyScopedExternalDecls.swap(Record);
1611 else
1612 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1613 Record.begin(), Record.end());
Douglas Gregor14c22f22009-04-22 22:18:58 +00001614 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001615
Douglas Gregor83941df2009-04-25 17:48:32 +00001616 case pch::SELECTOR_OFFSETS:
1617 SelectorOffsets = (const uint32_t *)BlobStart;
1618 TotalNumSelectors = Record[0];
1619 SelectorsLoaded.resize(TotalNumSelectors);
1620 break;
1621
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001622 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001623 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1624 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001625 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001626 = PCHMethodPoolLookupTable::Create(
1627 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001628 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001629 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001630 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001631 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001632
Fariborz Jahanian32019832010-07-23 19:11:11 +00001633 case pch::REFERENCED_SELECTOR_POOL: {
1634 unsigned int numEl = Record[0]*2;
1635 for (unsigned int i = 1; i <= numEl; i++)
1636 F.ReferencedSelectorsData.push_back(Record[i]);
1637 }
1638 break;
1639
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001640 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001641 if (!Record.empty() && Listener)
1642 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001643 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001644
1645 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001646 F.SLocOffsets = (const uint32_t *)BlobStart;
1647 F.LocalNumSLocEntries = Record[0];
1648 // We cannot delay this until all PCHs are loaded, because then source
1649 // location preloads would also have to be delayed.
1650 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001651 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001652 break;
1653
1654 case pch::SOURCE_LOCATION_PRELOADS:
1655 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1656 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1657 if (Result != Success)
1658 return Result;
1659 }
1660 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001661
Douglas Gregor52e71082009-10-16 18:18:30 +00001662 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001663 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001664 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1665 (const unsigned char *)BlobStart,
1666 NumStatHits, NumStatMisses);
1667 FileMgr.addStatCache(MyStatCache);
Sebastian Redl9137a522010-07-16 17:50:48 +00001668 F.StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001669 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001670 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001671
Douglas Gregorb81c1702009-04-27 20:06:05 +00001672 case pch::EXT_VECTOR_DECLS:
1673 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001674 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001675 return Failure;
1676 }
1677 ExtVectorDecls.swap(Record);
1678 break;
1679
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001680 case pch::VTABLE_USES:
1681 if (!VTableUses.empty()) {
1682 Error("duplicate VTABLE_USES record in PCH file");
1683 return Failure;
1684 }
1685 VTableUses.swap(Record);
1686 break;
1687
1688 case pch::DYNAMIC_CLASSES:
1689 if (!DynamicClasses.empty()) {
1690 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1691 return Failure;
1692 }
1693 DynamicClasses.swap(Record);
1694 break;
1695
Douglas Gregorb64c1932009-05-12 01:31:05 +00001696 case pch::ORIGINAL_FILE_NAME:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001697 // The primary PCH will be the last to get here, so it will be the one
1698 // that's used.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001699 ActualOriginalFileName.assign(BlobStart, BlobLen);
1700 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001701 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001702 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001704 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001705 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001706 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek974be4d2010-02-12 23:31:14 +00001707 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001708 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1709 return IgnorePCH;
1710 }
1711 break;
1712 }
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001713
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001714 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001715 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1716 F.NumPreallocatedPreprocessingEntities = Record[0];
1717 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001718 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001719 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001720 First = false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001721 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001722 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001723 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001724}
1725
Douglas Gregore1d918e2009-04-10 23:10:45 +00001726PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001727 switch(ReadPCHCore(FileName)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001728 case Failure: return Failure;
1729 case IgnorePCH: return IgnorePCH;
1730 case Success: break;
1731 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001732
1733 // Here comes stuff that we only do once the entire chain is loaded.
1734
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001735 // Allocate space for loaded identifiers, decls and types.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001736 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
1737 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001738 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redl2da08f92010-07-19 22:28:42 +00001739 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001740 TotalNumTypes += Chain[I]->LocalNumTypes;
1741 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001742 TotalNumPreallocatedPreprocessingEntities +=
1743 Chain[I]->NumPreallocatedPreprocessingEntities;
1744 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001745 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001746 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001747 TypesLoaded.resize(TotalNumTypes);
1748 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001749 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1750 if (PP) {
1751 if (TotalNumIdentifiers > 0)
1752 PP->getHeaderSearchInfo().SetExternalLookup(this);
1753 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1754 if (!PP->getPreprocessingRecord())
1755 PP->createPreprocessingRecord();
1756 PP->getPreprocessingRecord()->SetExternalSource(*this,
1757 TotalNumPreallocatedPreprocessingEntities);
1758 }
1759 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001760
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001761 // Check the predefines buffers.
1762 if (CheckPredefinesBuffers())
1763 return IgnorePCH;
1764
1765 if (PP) {
1766 // Initialization of keywords and pragmas occurs before the
1767 // PCH file is read, so there may be some identifiers that were
1768 // loaded into the IdentifierTable before we intercepted the
1769 // creation of identifiers. Iterate through the list of known
1770 // identifiers and determine whether we have to establish
1771 // preprocessor definitions or top-level identifier declaration
1772 // chains for those identifiers.
1773 //
1774 // We copy the IdentifierInfo pointers to a small vector first,
1775 // since de-serializing declarations or macro definitions can add
1776 // new entries into the identifier table, invalidating the
1777 // iterators.
1778 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1779 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1780 IdEnd = PP->getIdentifierTable().end();
1781 Id != IdEnd; ++Id)
1782 Identifiers.push_back(Id->second);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001783 // We need to search the tables in all files.
1784 // FIXME: What happens if this stuff changes between files, e.g. the
1785 // dependent PCH undefs a macro from the core file?
1786 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1787 PCHIdentifierLookupTable *IdTable
1788 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00001789 // Not all PCH files necessarily have identifier tables, only the useful
1790 // ones.
1791 if (!IdTable)
1792 continue;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001793 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1794 IdentifierInfo *II = Identifiers[I];
1795 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001796 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001797 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001798 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1799 if (Pos == IdTable->end())
1800 continue;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001801
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001802 // Dereferencing the iterator has the effect of populating the
1803 // IdentifierInfo node with the various declarations it needs.
1804 (void)*Pos;
1805 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001806 }
1807 }
1808
1809 if (Context)
1810 InitializeContext(*Context);
1811
1812 return Success;
1813}
1814
1815PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1816 Chain.push_back(new PerFileData());
Sebastian Redl9137a522010-07-16 17:50:48 +00001817 PerFileData &F = *Chain.back();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001818
1819 // Set the PCH file name.
1820 F.FileName = FileName;
1821
1822 // Open the PCH file.
1823 //
1824 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1825 std::string ErrStr;
1826 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1827 if (!F.Buffer) {
1828 Error(ErrStr.c_str());
1829 return IgnorePCH;
1830 }
1831
1832 // Initialize the stream
1833 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1834 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl9137a522010-07-16 17:50:48 +00001835 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001836 Stream.init(F.StreamFile);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001837 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001838
1839 // Sniff for the signature.
1840 if (Stream.Read(8) != 'C' ||
1841 Stream.Read(8) != 'P' ||
1842 Stream.Read(8) != 'C' ||
1843 Stream.Read(8) != 'H') {
1844 Diag(diag::err_not_a_pch_file) << FileName;
1845 return Failure;
1846 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001847
Douglas Gregor2cf26342009-04-09 22:27:44 +00001848 while (!Stream.AtEndOfStream()) {
1849 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Douglas Gregore1d918e2009-04-10 23:10:45 +00001851 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001852 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001853 return Failure;
1854 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001855
1856 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001857
Douglas Gregor2cf26342009-04-09 22:27:44 +00001858 // We only know the PCH subblock ID.
1859 switch (BlockID) {
1860 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001861 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001862 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001863 return Failure;
1864 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001865 break;
1866 case pch::PCH_BLOCK_ID:
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001867 switch (ReadPCHBlock(F)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001868 case Success:
1869 break;
1870
1871 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001872 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001873
1874 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001875 // FIXME: We could consider reading through to the end of this
1876 // PCH block, skipping subblocks, to see if there are other
1877 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001878
1879 // Clear out any preallocated source location entries, so that
1880 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001881 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001882
1883 // Remove the stat cache.
Sebastian Redl9137a522010-07-16 17:50:48 +00001884 if (F.StatCache)
1885 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001886
Douglas Gregore1d918e2009-04-10 23:10:45 +00001887 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001888 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001889 break;
1890 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001891 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001892 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001893 return Failure;
1894 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001895 break;
1896 }
Mike Stump1eb44332009-09-09 15:08:12 +00001897 }
1898
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001899 return Success;
1900}
1901
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001902void PCHReader::setPreprocessor(Preprocessor &pp) {
1903 PP = &pp;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001904
1905 unsigned TotalNum = 0;
1906 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1907 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1908 if (TotalNum) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001909 if (!PP->getPreprocessingRecord())
1910 PP->createPreprocessingRecord();
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001911 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001912 }
1913}
1914
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001915void PCHReader::InitializeContext(ASTContext &Ctx) {
1916 Context = &Ctx;
1917 assert(Context && "Passed null context!");
1918
1919 assert(PP && "Forgot to set Preprocessor ?");
1920 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1921 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001922 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001923
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001924 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001925 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001926
1927 // Load the special types.
1928 Context->setBuiltinVaListType(
1929 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1930 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1931 Context->setObjCIdType(GetType(Id));
1932 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1933 Context->setObjCSelType(GetType(Sel));
1934 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1935 Context->setObjCProtoType(GetType(Proto));
1936 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1937 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001938
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001939 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1940 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001941 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001942 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1943 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001944 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1945 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001946 if (FileType.isNull()) {
1947 Error("FILE type is NULL");
1948 return;
1949 }
John McCall183700f2009-09-21 23:43:11 +00001950 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001951 Context->setFILEDecl(Typedef->getDecl());
1952 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001953 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001954 if (!Tag) {
1955 Error("Invalid FILE type in PCH file");
1956 return;
1957 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001958 Context->setFILEDecl(Tag->getDecl());
1959 }
1960 }
Mike Stump782fa302009-07-28 02:25:19 +00001961 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1962 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001963 if (Jmp_bufType.isNull()) {
1964 Error("jmp_bug type is NULL");
1965 return;
1966 }
John McCall183700f2009-09-21 23:43:11 +00001967 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001968 Context->setjmp_bufDecl(Typedef->getDecl());
1969 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001970 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001971 if (!Tag) {
1972 Error("Invalid jmp_bug type in PCH file");
1973 return;
1974 }
Mike Stump782fa302009-07-28 02:25:19 +00001975 Context->setjmp_bufDecl(Tag->getDecl());
1976 }
1977 }
1978 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1979 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001980 if (Sigjmp_bufType.isNull()) {
1981 Error("sigjmp_buf type is NULL");
1982 return;
1983 }
John McCall183700f2009-09-21 23:43:11 +00001984 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001985 Context->setsigjmp_bufDecl(Typedef->getDecl());
1986 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001987 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001988 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1989 Context->setsigjmp_bufDecl(Tag->getDecl());
1990 }
1991 }
Mike Stump1eb44332009-09-09 15:08:12 +00001992 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001993 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1994 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001995 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001996 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1997 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00001998 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1999 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00002000 if (unsigned String
2001 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2002 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002003 if (unsigned ObjCSelRedef
2004 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2005 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2006 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2007 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00002008
2009 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2010 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002011}
2012
Douglas Gregorb64c1932009-05-12 01:31:05 +00002013/// \brief Retrieve the name of the original source file name
2014/// directly from the PCH file, without actually loading the PCH
2015/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002016std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2017 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00002018 // Open the PCH file.
2019 std::string ErrStr;
2020 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2021 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2022 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002023 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002024 return std::string();
2025 }
2026
2027 // Initialize the stream
2028 llvm::BitstreamReader StreamFile;
2029 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00002030 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00002031 (const unsigned char *)Buffer->getBufferEnd());
2032 Stream.init(StreamFile);
2033
2034 // Sniff for the signature.
2035 if (Stream.Read(8) != 'C' ||
2036 Stream.Read(8) != 'P' ||
2037 Stream.Read(8) != 'C' ||
2038 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002039 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002040 return std::string();
2041 }
2042
2043 RecordData Record;
2044 while (!Stream.AtEndOfStream()) {
2045 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Douglas Gregorb64c1932009-05-12 01:31:05 +00002047 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2048 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Douglas Gregorb64c1932009-05-12 01:31:05 +00002050 // We only know the PCH subblock ID.
2051 switch (BlockID) {
2052 case pch::PCH_BLOCK_ID:
2053 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002054 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002055 return std::string();
2056 }
2057 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Douglas Gregorb64c1932009-05-12 01:31:05 +00002059 default:
2060 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002061 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002062 return std::string();
2063 }
2064 break;
2065 }
2066 continue;
2067 }
2068
2069 if (Code == llvm::bitc::END_BLOCK) {
2070 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002071 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002072 return std::string();
2073 }
2074 continue;
2075 }
2076
2077 if (Code == llvm::bitc::DEFINE_ABBREV) {
2078 Stream.ReadAbbrevRecord();
2079 continue;
2080 }
2081
2082 Record.clear();
2083 const char *BlobStart = 0;
2084 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002085 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00002086 == pch::ORIGINAL_FILE_NAME)
2087 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00002088 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00002089
2090 return std::string();
2091}
2092
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002093/// \brief Parse the record that corresponds to a LangOptions data
2094/// structure.
2095///
2096/// This routine compares the language options used to generate the
2097/// PCH file against the language options set for the current
2098/// compilation. For each option, we classify differences between the
2099/// two compiler states as either "benign" or "important". Benign
2100/// differences don't matter, and we accept them without complaint
2101/// (and without modifying the language options). Differences between
2102/// the states for important options cause the PCH file to be
2103/// unusable, so we emit a warning and return true to indicate that
2104/// there was an error.
2105///
2106/// \returns true if the PCH file is unacceptable, false otherwise.
2107bool PCHReader::ParseLanguageOptions(
2108 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002109 if (Listener) {
2110 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002112 #define PARSE_LANGOPT(Option) \
2113 LangOpts.Option = Record[Idx]; \
2114 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002116 unsigned Idx = 0;
2117 PARSE_LANGOPT(Trigraphs);
2118 PARSE_LANGOPT(BCPLComment);
2119 PARSE_LANGOPT(DollarIdents);
2120 PARSE_LANGOPT(AsmPreprocessor);
2121 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00002122 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002123 PARSE_LANGOPT(ImplicitInt);
2124 PARSE_LANGOPT(Digraphs);
2125 PARSE_LANGOPT(HexFloats);
2126 PARSE_LANGOPT(C99);
2127 PARSE_LANGOPT(Microsoft);
2128 PARSE_LANGOPT(CPlusPlus);
2129 PARSE_LANGOPT(CPlusPlus0x);
2130 PARSE_LANGOPT(CXXOperatorNames);
2131 PARSE_LANGOPT(ObjC1);
2132 PARSE_LANGOPT(ObjC2);
2133 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002134 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00002135 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002136 PARSE_LANGOPT(PascalStrings);
2137 PARSE_LANGOPT(WritableStrings);
2138 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002139 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002140 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002141 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002142 PARSE_LANGOPT(NeXTRuntime);
2143 PARSE_LANGOPT(Freestanding);
2144 PARSE_LANGOPT(NoBuiltin);
2145 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002146 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002147 PARSE_LANGOPT(Blocks);
2148 PARSE_LANGOPT(EmitAllDecls);
2149 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002150 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2151 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002152 PARSE_LANGOPT(HeinousExtensions);
2153 PARSE_LANGOPT(Optimize);
2154 PARSE_LANGOPT(OptimizeSize);
2155 PARSE_LANGOPT(Static);
2156 PARSE_LANGOPT(PICLevel);
2157 PARSE_LANGOPT(GNUInline);
2158 PARSE_LANGOPT(NoInline);
2159 PARSE_LANGOPT(AccessControl);
2160 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002161 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002162 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2163 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002164 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002165 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002166 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002167 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002168 PARSE_LANGOPT(CatchUndefined);
2169 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002170 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002171
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002172 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002173 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002174
2175 return false;
2176}
2177
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002178void PCHReader::ReadPreprocessedEntities() {
2179 ReadDefinedMacros();
2180}
2181
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002182/// \brief Get the correct cursor and offset for loading a type.
2183PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2184 PerFileData *F = 0;
2185 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2186 F = Chain[N - I - 1];
2187 if (Index < F->LocalNumTypes)
2188 break;
2189 Index -= F->LocalNumTypes;
2190 }
2191 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redl971dd442010-07-20 22:55:31 +00002192 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002193}
2194
2195/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00002196///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002197/// The index is the type ID, shifted and minus the number of predefs. This
2198/// routine actually reads the record corresponding to the type at the given
2199/// location. It is a helper routine for GetType, which deals with reading type
2200/// IDs.
2201QualType PCHReader::ReadTypeRecord(unsigned Index) {
2202 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redl971dd442010-07-20 22:55:31 +00002203 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl9137a522010-07-16 17:50:48 +00002204
Douglas Gregor0b748912009-04-14 21:18:50 +00002205 // Keep track of where we are in the stream, then jump back there
2206 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002207 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002208
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002209 ReadingKindTracker ReadingKind(Read_Type, *this);
2210
Douglas Gregord89275b2009-07-06 18:54:52 +00002211 // Note that we are loading a type record.
2212 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002214 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002215 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002216 unsigned Code = DeclsCursor.ReadCode();
2217 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002218 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002219 if (Record.size() != 2) {
2220 Error("Incorrect encoding of extended qualifier type");
2221 return QualType();
2222 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002223 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002224 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2225 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002226 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002227
Douglas Gregor2cf26342009-04-09 22:27:44 +00002228 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002229 if (Record.size() != 1) {
2230 Error("Incorrect encoding of complex type");
2231 return QualType();
2232 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002233 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002234 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002235 }
2236
2237 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002238 if (Record.size() != 1) {
2239 Error("Incorrect encoding of pointer type");
2240 return QualType();
2241 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002242 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002243 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002244 }
2245
2246 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002247 if (Record.size() != 1) {
2248 Error("Incorrect encoding of block pointer type");
2249 return QualType();
2250 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002251 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002252 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002253 }
2254
2255 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002256 if (Record.size() != 1) {
2257 Error("Incorrect encoding of lvalue reference type");
2258 return QualType();
2259 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002260 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002261 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002262 }
2263
2264 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002265 if (Record.size() != 1) {
2266 Error("Incorrect encoding of rvalue reference type");
2267 return QualType();
2268 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002269 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002270 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002271 }
2272
2273 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002274 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002275 Error("Incorrect encoding of member pointer type");
2276 return QualType();
2277 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002278 QualType PointeeType = GetType(Record[0]);
2279 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002280 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002281 }
2282
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002283 case pch::TYPE_CONSTANT_ARRAY: {
2284 QualType ElementType = GetType(Record[0]);
2285 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2286 unsigned IndexTypeQuals = Record[2];
2287 unsigned Idx = 3;
2288 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002289 return Context->getConstantArrayType(ElementType, Size,
2290 ASM, IndexTypeQuals);
2291 }
2292
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002293 case pch::TYPE_INCOMPLETE_ARRAY: {
2294 QualType ElementType = GetType(Record[0]);
2295 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2296 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002297 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002298 }
2299
2300 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002301 QualType ElementType = GetType(Record[0]);
2302 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2303 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002304 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2305 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redl577d4792010-07-22 22:43:28 +00002306 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002307 ASM, IndexTypeQuals,
2308 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002309 }
2310
2311 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002312 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002313 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002314 return QualType();
2315 }
2316
2317 QualType ElementType = GetType(Record[0]);
2318 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002319 unsigned AltiVecSpec = Record[2];
2320 return Context->getVectorType(ElementType, NumElements,
2321 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002322 }
2323
2324 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002325 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002326 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002327 return QualType();
2328 }
2329
2330 QualType ElementType = GetType(Record[0]);
2331 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002332 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002333 }
2334
2335 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002336 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002337 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002338 return QualType();
2339 }
2340 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002341 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002342 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002343 }
2344
2345 case pch::TYPE_FUNCTION_PROTO: {
2346 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002347 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002348 unsigned RegParm = Record[2];
2349 CallingConv CallConv = (CallingConv)Record[3];
2350 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002351 unsigned NumParams = Record[Idx++];
2352 llvm::SmallVector<QualType, 16> ParamTypes;
2353 for (unsigned I = 0; I != NumParams; ++I)
2354 ParamTypes.push_back(GetType(Record[Idx++]));
2355 bool isVariadic = Record[Idx++];
2356 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002357 bool hasExceptionSpec = Record[Idx++];
2358 bool hasAnyExceptionSpec = Record[Idx++];
2359 unsigned NumExceptions = Record[Idx++];
2360 llvm::SmallVector<QualType, 2> Exceptions;
2361 for (unsigned I = 0; I != NumExceptions; ++I)
2362 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002363 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002364 isVariadic, Quals, hasExceptionSpec,
2365 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002366 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002367 FunctionType::ExtInfo(NoReturn, RegParm,
2368 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002369 }
2370
John McCalled976492009-12-04 22:46:56 +00002371 case pch::TYPE_UNRESOLVED_USING:
2372 return Context->getTypeDeclType(
2373 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2374
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002375 case pch::TYPE_TYPEDEF: {
2376 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002377 Error("incorrect encoding of typedef type");
2378 return QualType();
2379 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002380 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2381 QualType Canonical = GetType(Record[1]);
2382 return Context->getTypedefType(Decl, Canonical);
2383 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002384
2385 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redl577d4792010-07-22 22:43:28 +00002386 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002387
2388 case pch::TYPE_TYPEOF: {
2389 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002390 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002391 return QualType();
2392 }
2393 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002394 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002395 }
Mike Stump1eb44332009-09-09 15:08:12 +00002396
Anders Carlsson395b4752009-06-24 19:06:50 +00002397 case pch::TYPE_DECLTYPE:
Sebastian Redl577d4792010-07-22 22:43:28 +00002398 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson395b4752009-06-24 19:06:50 +00002399
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002400 case pch::TYPE_RECORD: {
2401 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002402 Error("incorrect encoding of record type");
2403 return QualType();
2404 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002405 bool IsDependent = Record[0];
2406 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2407 T->Dependent = IsDependent;
2408 return T;
2409 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002410
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002411 case pch::TYPE_ENUM: {
2412 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002413 Error("incorrect encoding of enum type");
2414 return QualType();
2415 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002416 bool IsDependent = Record[0];
2417 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2418 T->Dependent = IsDependent;
2419 return T;
2420 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002421
John McCall7da24312009-09-05 00:15:47 +00002422 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002423 unsigned Idx = 0;
2424 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2425 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2426 QualType NamedType = GetType(Record[Idx++]);
2427 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002428 }
2429
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002430 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002431 unsigned Idx = 0;
2432 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002433 return Context->getObjCInterfaceType(ItfD);
2434 }
2435
2436 case pch::TYPE_OBJC_OBJECT: {
2437 unsigned Idx = 0;
2438 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002439 unsigned NumProtos = Record[Idx++];
2440 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2441 for (unsigned I = 0; I != NumProtos; ++I)
2442 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002443 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002444 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002445
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002446 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002447 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002448 QualType Pointee = GetType(Record[Idx++]);
2449 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002450 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002451
John McCall49a832b2009-10-18 09:09:24 +00002452 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2453 unsigned Idx = 0;
2454 QualType Parm = GetType(Record[Idx++]);
2455 QualType Replacement = GetType(Record[Idx++]);
2456 return
2457 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2458 Replacement);
2459 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002460
2461 case pch::TYPE_INJECTED_CLASS_NAME: {
2462 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2463 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002464 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2465 // for PCH reading, too much interdependencies.
2466 return
2467 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002468 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002469
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002470 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2471 unsigned Idx = 0;
2472 unsigned Depth = Record[Idx++];
2473 unsigned Index = Record[Idx++];
2474 bool Pack = Record[Idx++];
2475 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2476 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2477 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002478
2479 case pch::TYPE_DEPENDENT_NAME: {
2480 unsigned Idx = 0;
2481 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2482 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2483 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002484 QualType Canon = GetType(Record[Idx++]);
2485 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002486 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002487
2488 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2489 unsigned Idx = 0;
2490 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2491 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2492 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2493 unsigned NumArgs = Record[Idx++];
2494 llvm::SmallVector<TemplateArgument, 8> Args;
2495 Args.reserve(NumArgs);
2496 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00002497 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002498 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2499 Args.size(), Args.data());
2500 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002501
2502 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2503 unsigned Idx = 0;
2504
2505 // ArrayType
2506 QualType ElementType = GetType(Record[Idx++]);
2507 ArrayType::ArraySizeModifier ASM
2508 = (ArrayType::ArraySizeModifier)Record[Idx++];
2509 unsigned IndexTypeQuals = Record[Idx++];
2510
2511 // DependentSizedArrayType
Sebastian Redl577d4792010-07-22 22:43:28 +00002512 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002513 SourceRange Brackets = ReadSourceRange(Record, Idx);
2514
2515 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2516 IndexTypeQuals, Brackets);
2517 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002518
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002519 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2520 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002521 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002522 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002523 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redl577d4792010-07-22 22:43:28 +00002524 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002525 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002526 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002527 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002528 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2529 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002530 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002531 T = Context->getTemplateSpecializationType(Name, Args.data(),
2532 Args.size(), Canon);
2533 T->Dependent = IsDependent;
2534 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002535 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002536 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002537 // Suppress a GCC warning
2538 return QualType();
2539}
2540
John McCalla1ee0c52009-10-16 21:56:05 +00002541namespace {
2542
2543class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2544 PCHReader &Reader;
Sebastian Redl577d4792010-07-22 22:43:28 +00002545 llvm::BitstreamCursor &DeclsCursor;
John McCalla1ee0c52009-10-16 21:56:05 +00002546 const PCHReader::RecordData &Record;
2547 unsigned &Idx;
2548
2549public:
Sebastian Redl577d4792010-07-22 22:43:28 +00002550 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2551 const PCHReader::RecordData &Record, unsigned &Idx)
2552 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCalla1ee0c52009-10-16 21:56:05 +00002553
John McCall51bd8032009-10-18 01:05:36 +00002554 // We want compile-time assurance that we've enumerated all of
2555 // these, so unfortunately we have to declare them first, then
2556 // define them out-of-line.
2557#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002558#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002559 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002560#include "clang/AST/TypeLocNodes.def"
2561
John McCall51bd8032009-10-18 01:05:36 +00002562 void VisitFunctionTypeLoc(FunctionTypeLoc);
2563 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002564};
2565
2566}
2567
John McCall51bd8032009-10-18 01:05:36 +00002568void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002569 // nothing to do
2570}
John McCall51bd8032009-10-18 01:05:36 +00002571void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002572 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2573 if (TL.needsExtraLocalData()) {
2574 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2575 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2576 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2577 TL.setModeAttr(Record[Idx++]);
2578 }
John McCalla1ee0c52009-10-16 21:56:05 +00002579}
John McCall51bd8032009-10-18 01:05:36 +00002580void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2581 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002582}
John McCall51bd8032009-10-18 01:05:36 +00002583void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2584 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002585}
John McCall51bd8032009-10-18 01:05:36 +00002586void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2587 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002588}
John McCall51bd8032009-10-18 01:05:36 +00002589void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2590 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002591}
John McCall51bd8032009-10-18 01:05:36 +00002592void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2593 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002594}
John McCall51bd8032009-10-18 01:05:36 +00002595void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2596 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002597}
John McCall51bd8032009-10-18 01:05:36 +00002598void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2599 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2600 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002601 if (Record[Idx++])
Sebastian Redl577d4792010-07-22 22:43:28 +00002602 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002603 else
John McCall51bd8032009-10-18 01:05:36 +00002604 TL.setSizeExpr(0);
2605}
2606void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2607 VisitArrayTypeLoc(TL);
2608}
2609void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2610 VisitArrayTypeLoc(TL);
2611}
2612void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2613 VisitArrayTypeLoc(TL);
2614}
2615void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2616 DependentSizedArrayTypeLoc TL) {
2617 VisitArrayTypeLoc(TL);
2618}
2619void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2620 DependentSizedExtVectorTypeLoc TL) {
2621 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2622}
2623void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2624 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2625}
2626void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2627 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2628}
2629void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2630 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2631 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2632 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002633 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002634 }
2635}
2636void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2637 VisitFunctionTypeLoc(TL);
2638}
2639void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2640 VisitFunctionTypeLoc(TL);
2641}
John McCalled976492009-12-04 22:46:56 +00002642void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2643 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2644}
John McCall51bd8032009-10-18 01:05:36 +00002645void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2646 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2647}
2648void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002649 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2650 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2651 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002652}
2653void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002654 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2655 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2656 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redl577d4792010-07-22 22:43:28 +00002657 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002658}
2659void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2660 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2661}
2662void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2663 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2664}
2665void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2666 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2667}
John McCall51bd8032009-10-18 01:05:36 +00002668void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2669 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2670}
John McCall49a832b2009-10-18 09:09:24 +00002671void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2672 SubstTemplateTypeParmTypeLoc TL) {
2673 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2674}
John McCall51bd8032009-10-18 01:05:36 +00002675void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2676 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002677 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2678 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2679 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2680 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2681 TL.setArgLocInfo(i,
2682 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002683 DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002684}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002685void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002686 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2687 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002688}
John McCall3cb0ebd2010-03-10 03:28:59 +00002689void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2690 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2691}
Douglas Gregor4714c122010-03-31 17:34:00 +00002692void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002693 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2694 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002695 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2696}
John McCall33500952010-06-11 00:33:02 +00002697void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2698 DependentTemplateSpecializationTypeLoc TL) {
2699 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2700 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2701 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2702 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2703 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2704 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2705 TL.setArgLocInfo(I,
2706 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002707 DeclsCursor, Record, Idx));
John McCall33500952010-06-11 00:33:02 +00002708}
John McCall51bd8032009-10-18 01:05:36 +00002709void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2710 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002711}
2712void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2713 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002714 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2715 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2716 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2717 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002718}
John McCall54e14c42009-10-22 22:37:11 +00002719void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2720 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002721}
John McCalla1ee0c52009-10-16 21:56:05 +00002722
Sebastian Redl577d4792010-07-22 22:43:28 +00002723TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2724 const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002725 unsigned &Idx) {
2726 QualType InfoTy = GetType(Record[Idx++]);
2727 if (InfoTy.isNull())
2728 return 0;
2729
John McCalla93c9342009-12-07 02:54:59 +00002730 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redl577d4792010-07-22 22:43:28 +00002731 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002732 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002733 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002734 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002735}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002736
Douglas Gregor8038d512009-04-10 17:25:41 +00002737QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002738 unsigned FastQuals = ID & Qualifiers::FastMask;
2739 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002740
2741 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2742 QualType T;
2743 switch ((pch::PredefinedTypeIDs)Index) {
2744 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002745 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2746 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002747
2748 case pch::PREDEF_TYPE_CHAR_U_ID:
2749 case pch::PREDEF_TYPE_CHAR_S_ID:
2750 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002751 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002752 break;
2753
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002754 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2755 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2756 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2757 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2758 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002759 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002760 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2761 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2762 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2763 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2764 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2765 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002766 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002767 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2768 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2769 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2770 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2771 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002772 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002773 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2774 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002775 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2776 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002777 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002778 }
2779
2780 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002781 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002782 }
2783
2784 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002785 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002786 if (TypesLoaded[Index].isNull()) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002787 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002788 TypesLoaded[Index]->setFromPCH();
Sebastian Redl30c514c2010-07-14 23:45:08 +00002789 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002790 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2791 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002792 }
Mike Stump1eb44332009-09-09 15:08:12 +00002793
John McCall0953e762009-09-24 19:53:00 +00002794 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002795}
2796
John McCall833ca992009-10-29 08:12:44 +00002797TemplateArgumentLocInfo
2798PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redl577d4792010-07-22 22:43:28 +00002799 llvm::BitstreamCursor &DeclsCursor,
John McCall833ca992009-10-29 08:12:44 +00002800 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002801 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002802 switch (Kind) {
2803 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00002804 return ReadExpr(DeclsCursor);
John McCall833ca992009-10-29 08:12:44 +00002805 case TemplateArgument::Type:
Sebastian Redl577d4792010-07-22 22:43:28 +00002806 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002807 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002808 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2809 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2810 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002811 }
John McCall833ca992009-10-29 08:12:44 +00002812 case TemplateArgument::Null:
2813 case TemplateArgument::Integral:
2814 case TemplateArgument::Declaration:
2815 case TemplateArgument::Pack:
2816 return TemplateArgumentLocInfo();
2817 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002818 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002819 return TemplateArgumentLocInfo();
2820}
2821
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002822TemplateArgumentLoc
Sebastian Redl577d4792010-07-22 22:43:28 +00002823PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2824 const RecordData &Record, unsigned &Index) {
2825 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002826
2827 if (Arg.getKind() == TemplateArgument::Expression) {
2828 if (Record[Index++]) // bool InfoHasSameExpr.
2829 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2830 }
2831 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002832 DeclsCursor,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002833 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002834}
2835
John McCall76bd1f32010-06-01 09:23:16 +00002836Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2837 return GetDecl(ID);
2838}
2839
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002840TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl30c514c2010-07-14 23:45:08 +00002841 if (!DeclsLoaded[0]) {
Sebastian Redlcb526aa2010-07-20 22:46:15 +00002842 ReadDeclRecord(0);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002843 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002844 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002845 }
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002846
2847 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2848}
2849
Douglas Gregor8038d512009-04-10 17:25:41 +00002850Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002851 if (ID == 0)
2852 return 0;
2853
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002854 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002855 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002856 return 0;
2857 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002858
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002859 unsigned Index = ID - 1;
Sebastian Redl30c514c2010-07-14 23:45:08 +00002860 if (!DeclsLoaded[Index]) {
Sebastian Redlcb526aa2010-07-20 22:46:15 +00002861 ReadDeclRecord(Index);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002862 if (DeserializationListener)
2863 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2864 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002865
2866 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002867}
2868
Chris Lattner887e2b32009-04-27 05:46:25 +00002869/// \brief Resolve the offset of a statement into a statement.
2870///
2871/// This operation will read a new statement from the external
2872/// source each time it is called, and is meant to be used via a
2873/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002874Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002875 // Offset here is a global offset across the entire chain.
2876 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2877 PerFileData &F = *Chain[N - I - 1];
2878 if (Offset < F.SizeInBits) {
2879 // Since we know that this statement is part of a decl, make sure to use
2880 // the decl cursor to read it.
2881 F.DeclsCursor.JumpToBit(Offset);
2882 return ReadStmtFromStream(F.DeclsCursor);
2883 }
2884 Offset -= F.SizeInBits;
2885 }
2886 llvm_unreachable("Broken chain");
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002887}
2888
John McCall76bd1f32010-06-01 09:23:16 +00002889bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2890 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002891 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002892 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002893
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002894 // There might be lexical decls in multiple parts of the chain, for the TU
2895 // at least.
2896 DeclContextInfos &Infos = DeclContextOffsets[DC];
2897 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2898 I != E; ++I) {
2899 uint64_t Offset = I->OffsetToLexicalDecls;
2900 // Offset can be 0 if this file only contains visible decls.
2901 if (Offset == 0)
2902 continue;
2903 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
2904
2905 // Keep track of where we are in the stream, then jump back there
2906 // after reading this context.
2907 SavedStreamPosition SavedPosition(DeclsCursor);
2908
2909 // Load the record containing all of the declarations lexically in
2910 // this context.
2911 DeclsCursor.JumpToBit(Offset);
2912 RecordData Record;
2913 unsigned Code = DeclsCursor.ReadCode();
2914 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2915 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2916 Error("Expected lexical block");
2917 return true;
2918 }
2919
2920 // Load all of the declaration IDs
2921 for (RecordData::iterator J = Record.begin(), F = Record.end(); J != F; ++J)
2922 Decls.push_back(GetDecl(*J));
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002923 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002924
Douglas Gregor25123082009-04-22 22:34:57 +00002925 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002926 return false;
2927}
2928
John McCall76bd1f32010-06-01 09:23:16 +00002929DeclContext::lookup_result
2930PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2931 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002932 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002933 "DeclContext has no visible decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002934
John McCall76bd1f32010-06-01 09:23:16 +00002935 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002936 // There might be lexical decls in multiple parts of the chain, for the TU
2937 // and namespaces.
2938 DeclContextInfos &Infos = DeclContextOffsets[DC];
2939 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2940 I != E; ++I) {
2941 uint64_t Offset = I->OffsetToVisibleDecls;
2942 if (Offset == 0)
2943 continue;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002944
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002945 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002946
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002947 // Keep track of where we are in the stream, then jump back there
2948 // after reading this context.
2949 SavedStreamPosition SavedPosition(DeclsCursor);
2950
2951 // Load the record containing all of the declarations visible in
2952 // this context.
2953 DeclsCursor.JumpToBit(Offset);
2954 RecordData Record;
2955 unsigned Code = DeclsCursor.ReadCode();
2956 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2957 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2958 Error("Expected visible block");
2959 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2960 DeclContext::lookup_iterator());
2961 }
2962
2963 if (Record.empty())
2964 continue;
2965
2966 unsigned Idx = 0;
2967 while (Idx < Record.size()) {
2968 Decls.push_back(VisibleDeclaration());
2969 Decls.back().Name = ReadDeclarationName(Record, Idx);
2970
2971 unsigned Size = Record[Idx++];
2972 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
2973 LoadedDecls.reserve(Size);
2974 for (unsigned J = 0; J < Size; ++J)
2975 LoadedDecls.push_back(Record[Idx++]);
2976 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002977 }
2978
Douglas Gregor25123082009-04-22 22:34:57 +00002979 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00002980
2981 SetExternalVisibleDecls(DC, Decls);
2982 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002983}
2984
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002985void PCHReader::PassInterestingDeclsToConsumer() {
2986 assert(Consumer);
2987 while (!InterestingDecls.empty()) {
2988 DeclGroupRef DG(InterestingDecls.front());
2989 InterestingDecls.pop_front();
2990 Consumer->HandleTopLevelDecl(DG);
2991 }
2992}
2993
Douglas Gregorfdd01722009-04-14 00:24:19 +00002994void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002995 this->Consumer = Consumer;
2996
Douglas Gregorfdd01722009-04-14 00:24:19 +00002997 if (!Consumer)
2998 return;
2999
3000 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003001 // Force deserialization of this decl, which will cause it to be queued for
3002 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00003003 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00003004 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00003005
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003006 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00003007}
3008
Douglas Gregor2cf26342009-04-09 22:27:44 +00003009void PCHReader::PrintStats() {
3010 std::fprintf(stderr, "*** PCH Statistics:\n");
3011
Mike Stump1eb44332009-09-09 15:08:12 +00003012 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003013 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00003014 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003015 unsigned NumDeclsLoaded
3016 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3017 (Decl *)0);
3018 unsigned NumIdentifiersLoaded
3019 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3020 IdentifiersLoaded.end(),
3021 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00003022 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003023 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3024 SelectorsLoaded.end(),
3025 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00003026
Douglas Gregor4fed3f42009-04-27 18:38:38 +00003027 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3028 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003029 if (TotalNumSLocEntries)
3030 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3031 NumSLocEntriesRead, TotalNumSLocEntries,
3032 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003033 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003034 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003035 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3036 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3037 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003038 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003039 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3040 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003041 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003042 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003043 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3044 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00003045 if (TotalNumSelectors)
3046 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
3047 NumSelectorsLoaded, TotalNumSelectors,
3048 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
3049 if (TotalNumStatements)
3050 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3051 NumStatementsRead, TotalNumStatements,
3052 ((float)NumStatementsRead/TotalNumStatements * 100));
3053 if (TotalNumMacros)
3054 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3055 NumMacrosRead, TotalNumMacros,
3056 ((float)NumMacrosRead/TotalNumMacros * 100));
3057 if (TotalLexicalDeclContexts)
3058 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3059 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3060 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3061 * 100));
3062 if (TotalVisibleDeclContexts)
3063 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3064 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3065 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3066 * 100));
3067 if (TotalSelectorsInMethodPool) {
3068 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
3069 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
3070 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
3071 * 100));
3072 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
3073 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003074 std::fprintf(stderr, "\n");
3075}
3076
Douglas Gregor668c1a42009-04-21 22:25:48 +00003077void PCHReader::InitializeSema(Sema &S) {
3078 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003079 S.ExternalSource = this;
3080
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003081 // Makes sure any declarations that were deserialized "too early"
3082 // still get added to the identifier's declaration chains.
3083 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3084 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3085 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003086 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003087 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003088
3089 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00003090 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003091 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3092 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00003093 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003094 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00003095
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003096 // If there were any unused static functions, deserialize them and add to
3097 // Sema's list of unused static functions.
3098 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3099 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3100 SemaObj->UnusedStaticFuncs.push_back(FD);
3101 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00003102
3103 // If there were any locally-scoped external declarations,
3104 // deserialize them and add them to Sema's table of locally-scoped
3105 // external declarations.
3106 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3107 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3108 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3109 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00003110
3111 // If there were any ext_vector type declarations, deserialize them
3112 // and add them to Sema's vector of such declarations.
3113 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3114 SemaObj->ExtVectorDecls.push_back(
3115 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003116
3117 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3118 // Can we cut them down before writing them ?
3119
3120 // If there were any VTable uses, deserialize the information and add it
3121 // to Sema's vector and map of VTable uses.
3122 unsigned Idx = 0;
3123 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3124 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3125 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3126 bool DefinitionRequired = VTableUses[Idx++];
3127 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3128 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3129 }
3130
3131 // If there were any dynamic classes declarations, deserialize them
3132 // and add them to Sema's vector of such declarations.
3133 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3134 SemaObj->DynamicClasses.push_back(
3135 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanian32019832010-07-23 19:11:11 +00003136
3137 // If there are @selector references added them to its pool. This is for
3138 // implementation of -Wselector.
3139 PerFileData &F = *Chain[0];
3140 if (!F.ReferencedSelectorsData.empty()) {
3141 unsigned int DataSize = F.ReferencedSelectorsData.size()-1;
3142 unsigned I = 0;
3143 while (I < DataSize) {
3144 Selector Sel = DecodeSelector(F.ReferencedSelectorsData[I++]);
3145 SourceLocation SelLoc =
3146 SourceLocation::getFromRawEncoding(F.ReferencedSelectorsData[I++]);
3147 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3148 }
3149 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00003150}
3151
3152IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003153 // Try to find this name within our on-disk hash tables. We need to aggregate
3154 // the info from all of them.
3155 IdentifierInfo *II = 0;
3156 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3157 PCHIdentifierLookupTable *IdTable
3158 = (PCHIdentifierLookupTable *)Chain[N - I - 1]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00003159 if (!IdTable)
3160 continue;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003161 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3162 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3163 if (Pos == IdTable->end())
3164 continue;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003165
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003166 // Dereferencing the iterator has the effect of building the
3167 // IdentifierInfo node and populating it with the various
3168 // declarations it needs.
3169 II = *Pos;
3170 }
3171 return II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003172}
3173
Mike Stump1eb44332009-09-09 15:08:12 +00003174std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003175PCHReader::ReadMethodPool(Selector Sel) {
3176 if (!MethodPoolLookupTable)
3177 return std::pair<ObjCMethodList, ObjCMethodList>();
3178
3179 // Try to find this selector within our on-disk hash table.
3180 PCHMethodPoolLookupTable *PoolTable
3181 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
3182 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00003183 if (Pos == PoolTable->end()) {
3184 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003185 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00003186 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003187
Douglas Gregor83941df2009-04-25 17:48:32 +00003188 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003189 return *Pos;
3190}
3191
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003192void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00003193 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00003194 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003195 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003196 if (DeserializationListener)
3197 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003198}
3199
Douglas Gregord89275b2009-07-06 18:54:52 +00003200/// \brief Set the globally-visible declarations associated with the given
3201/// identifier.
3202///
3203/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00003204/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00003205/// them.
3206///
3207/// \param II an IdentifierInfo that refers to one or more globally-visible
3208/// declarations.
3209///
3210/// \param DeclIDs the set of declaration IDs with the name @p II that are
3211/// visible at global scope.
3212///
3213/// \param Nonrecursive should be true to indicate that the caller knows that
3214/// this call is non-recursive, and therefore the globally-visible declarations
3215/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003216void
3217PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003218 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3219 bool Nonrecursive) {
3220 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
3221 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3222 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3223 PII.II = II;
3224 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3225 PII.DeclIDs.push_back(DeclIDs[I]);
3226 return;
3227 }
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Douglas Gregord89275b2009-07-06 18:54:52 +00003229 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3230 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3231 if (SemaObj) {
3232 // Introduce this declaration into the translation-unit scope
3233 // and add it to the declaration chain for this identifier, so
3234 // that (unqualified) name lookup will find it.
3235 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3236 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3237 } else {
3238 // Queue this declaration so that it will be added to the
3239 // translation unit scope and identifier's declaration chain
3240 // once a Sema object is known.
3241 PreloadedDecls.push_back(D);
3242 }
3243 }
3244}
3245
Chris Lattner7356a312009-04-11 21:15:38 +00003246IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003247 if (ID == 0)
3248 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003249
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003250 if (IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003251 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003252 return 0;
3253 }
Mike Stump1eb44332009-09-09 15:08:12 +00003254
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003255 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003256 ID -= 1;
3257 if (!IdentifiersLoaded[ID]) {
3258 unsigned Index = ID;
3259 const char *Str = 0;
3260 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3261 PerFileData *F = Chain[N - I - 1];
3262 if (Index < F->LocalNumIdentifiers) {
3263 uint32_t Offset = F->IdentifierOffsets[Index];
3264 Str = F->IdentifierTableData + Offset;
3265 break;
3266 }
3267 Index -= F->LocalNumIdentifiers;
3268 }
3269 assert(Str && "Broken Chain");
Douglas Gregord6595a42009-04-25 21:04:17 +00003270
Douglas Gregor02fc7512009-04-28 20:01:51 +00003271 // All of the strings in the PCH file are preceded by a 16-bit
3272 // length. Extract that 16-bit length to avoid having to execute
3273 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003274 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3275 // unsigned integers. This is important to avoid integer overflow when
3276 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003277 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003278 unsigned StrLen = (((unsigned) StrLenPtr[0])
3279 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003280 IdentifiersLoaded[ID]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003281 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003282 if (DeserializationListener)
3283 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003284 }
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003286 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003287}
3288
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003289void PCHReader::ReadSLocEntry(unsigned ID) {
3290 ReadSLocEntryRecord(ID);
3291}
3292
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003293Selector PCHReader::DecodeSelector(unsigned ID) {
3294 if (ID == 0)
3295 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Douglas Gregora02b1472009-04-28 21:53:25 +00003297 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003298 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00003299
3300 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003301 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003302 return Selector();
3303 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003304
3305 unsigned Index = ID - 1;
3306 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3307 // Load this selector from the selector table.
3308 // FIXME: endianness portability issues with SelectorOffsets table
3309 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00003310 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00003311 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3312 }
3313
3314 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003315}
3316
John McCall76bd1f32010-06-01 09:23:16 +00003317Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003318 return DecodeSelector(ID);
3319}
3320
John McCall76bd1f32010-06-01 09:23:16 +00003321uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregor719770d2010-04-06 17:30:22 +00003322 return TotalNumSelectors + 1;
3323}
3324
Mike Stump1eb44332009-09-09 15:08:12 +00003325DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003326PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3327 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3328 switch (Kind) {
3329 case DeclarationName::Identifier:
3330 return DeclarationName(GetIdentifierInfo(Record, Idx));
3331
3332 case DeclarationName::ObjCZeroArgSelector:
3333 case DeclarationName::ObjCOneArgSelector:
3334 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003335 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003336
3337 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003338 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003339 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003340
3341 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003342 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003343 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003344
3345 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003346 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003347 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003348
3349 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003350 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003351 (OverloadedOperatorKind)Record[Idx++]);
3352
Sean Hunt3e518bd2009-11-29 07:34:05 +00003353 case DeclarationName::CXXLiteralOperatorName:
3354 return Context->DeclarationNames.getCXXLiteralOperatorName(
3355 GetIdentifierInfo(Record, Idx));
3356
Douglas Gregor2cf26342009-04-09 22:27:44 +00003357 case DeclarationName::CXXUsingDirective:
3358 return DeclarationName::getUsingDirectiveName();
3359 }
3360
3361 // Required to silence GCC warning
3362 return DeclarationName();
3363}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003364
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003365TemplateName
3366PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3367 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3368 switch (Kind) {
3369 case TemplateName::Template:
3370 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3371
3372 case TemplateName::OverloadedTemplate: {
3373 unsigned size = Record[Idx++];
3374 UnresolvedSet<8> Decls;
3375 while (size--)
3376 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3377
3378 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3379 }
3380
3381 case TemplateName::QualifiedTemplate: {
3382 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3383 bool hasTemplKeyword = Record[Idx++];
3384 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3385 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3386 }
3387
3388 case TemplateName::DependentTemplate: {
3389 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3390 if (Record[Idx++]) // isIdentifier
3391 return Context->getDependentTemplateName(NNS,
3392 GetIdentifierInfo(Record, Idx));
3393 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003394 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003395 }
3396 }
3397
3398 assert(0 && "Unhandled template name kind!");
3399 return TemplateName();
3400}
3401
3402TemplateArgument
Sebastian Redl577d4792010-07-22 22:43:28 +00003403PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3404 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003405 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3406 case TemplateArgument::Null:
3407 return TemplateArgument();
3408 case TemplateArgument::Type:
3409 return TemplateArgument(GetType(Record[Idx++]));
3410 case TemplateArgument::Declaration:
3411 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003412 case TemplateArgument::Integral: {
3413 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3414 QualType T = GetType(Record[Idx++]);
3415 return TemplateArgument(Value, T);
3416 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003417 case TemplateArgument::Template:
3418 return TemplateArgument(ReadTemplateName(Record, Idx));
3419 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00003420 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003421 case TemplateArgument::Pack: {
3422 unsigned NumArgs = Record[Idx++];
3423 llvm::SmallVector<TemplateArgument, 8> Args;
3424 Args.reserve(NumArgs);
3425 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003426 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003427 TemplateArgument TemplArg;
3428 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3429 return TemplArg;
3430 }
3431 }
3432
3433 assert(0 && "Unhandled template argument kind!");
3434 return TemplateArgument();
3435}
3436
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003437TemplateParameterList *
3438PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3439 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3440 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3441 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3442
3443 unsigned NumParams = Record[Idx++];
3444 llvm::SmallVector<NamedDecl *, 16> Params;
3445 Params.reserve(NumParams);
3446 while (NumParams--)
3447 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3448
3449 TemplateParameterList* TemplateParams =
3450 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3451 Params.data(), Params.size(), RAngleLoc);
3452 return TemplateParams;
3453}
3454
3455void
3456PCHReader::
3457ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redl577d4792010-07-22 22:43:28 +00003458 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003459 const RecordData &Record, unsigned &Idx) {
3460 unsigned NumTemplateArgs = Record[Idx++];
3461 TemplArgs.reserve(NumTemplateArgs);
3462 while (NumTemplateArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003463 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003464}
3465
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003466/// \brief Read a UnresolvedSet structure.
3467void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3468 const RecordData &Record, unsigned &Idx) {
3469 unsigned NumDecls = Record[Idx++];
3470 while (NumDecls--) {
3471 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3472 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3473 Set.addDecl(D, AS);
3474 }
3475}
3476
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003477CXXBaseSpecifier
3478PCHReader::ReadCXXBaseSpecifier(const RecordData &Record, unsigned &Idx) {
3479 bool isVirtual = static_cast<bool>(Record[Idx++]);
3480 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3481 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3482 QualType T = GetType(Record[Idx++]);
3483 SourceRange Range = ReadSourceRange(Record, Idx);
3484 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, T);
3485}
3486
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003487NestedNameSpecifier *
3488PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3489 unsigned N = Record[Idx++];
3490 NestedNameSpecifier *NNS = 0, *Prev = 0;
3491 for (unsigned I = 0; I != N; ++I) {
3492 NestedNameSpecifier::SpecifierKind Kind
3493 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3494 switch (Kind) {
3495 case NestedNameSpecifier::Identifier: {
3496 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3497 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3498 break;
3499 }
3500
3501 case NestedNameSpecifier::Namespace: {
3502 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3503 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3504 break;
3505 }
3506
3507 case NestedNameSpecifier::TypeSpec:
3508 case NestedNameSpecifier::TypeSpecWithTemplate: {
3509 Type *T = GetType(Record[Idx++]).getTypePtr();
3510 bool Template = Record[Idx++];
3511 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3512 break;
3513 }
3514
3515 case NestedNameSpecifier::Global: {
3516 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3517 // No associated value, and there can't be a prefix.
3518 break;
3519 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003520 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003521 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003522 }
3523 return NNS;
3524}
3525
3526SourceRange
3527PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003528 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3529 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3530 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003531}
3532
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003533/// \brief Read an integral value
3534llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3535 unsigned BitWidth = Record[Idx++];
3536 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3537 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3538 Idx += NumWords;
3539 return Result;
3540}
3541
3542/// \brief Read a signed integral value
3543llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3544 bool isUnsigned = Record[Idx++];
3545 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3546}
3547
Douglas Gregor17fc2232009-04-14 21:55:33 +00003548/// \brief Read a floating-point value
3549llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003550 return llvm::APFloat(ReadAPInt(Record, Idx));
3551}
3552
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003553// \brief Read a string
3554std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3555 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003556 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003557 Idx += Len;
3558 return Result;
3559}
3560
Chris Lattnerd2598362010-05-10 00:25:06 +00003561CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3562 unsigned &Idx) {
3563 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3564 return CXXTemporary::Create(*Context, Decl);
3565}
3566
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003567DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003568 return Diag(SourceLocation(), DiagID);
3569}
3570
3571DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003572 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003573}
Douglas Gregor025452f2009-04-17 00:04:06 +00003574
Douglas Gregor668c1a42009-04-21 22:25:48 +00003575/// \brief Retrieve the identifier table associated with the
3576/// preprocessor.
3577IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003578 assert(PP && "Forgot to set Preprocessor ?");
3579 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003580}
3581
Douglas Gregor025452f2009-04-17 00:04:06 +00003582/// \brief Record that the given ID maps to the given switch-case
3583/// statement.
3584void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3585 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3586 SwitchCaseStmts[ID] = SC;
3587}
3588
3589/// \brief Retrieve the switch-case statement with the given ID.
3590SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3591 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3592 return SwitchCaseStmts[ID];
3593}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003594
3595/// \brief Record that the given label statement has been
3596/// deserialized and has the given ID.
3597void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003598 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003599 "Deserialized label twice");
3600 LabelStmts[ID] = S;
3601
3602 // If we've already seen any goto statements that point to this
3603 // label, resolve them now.
3604 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3605 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3606 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3607 Goto->second->setLabel(S);
3608 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003609
3610 // If we've already seen any address-label statements that point to
3611 // this label, resolve them now.
3612 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003613 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003614 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003615 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003616 AddrLabel != AddrLabels.second; ++AddrLabel)
3617 AddrLabel->second->setLabel(S);
3618 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003619}
3620
3621/// \brief Set the label of the given statement to the label
3622/// identified by ID.
3623///
3624/// Depending on the order in which the label and other statements
3625/// referencing that label occur, this operation may complete
3626/// immediately (updating the statement) or it may queue the
3627/// statement to be back-patched later.
3628void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3629 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3630 if (Label != LabelStmts.end()) {
3631 // We've already seen this label, so set the label of the goto and
3632 // we're done.
3633 S->setLabel(Label->second);
3634 } else {
3635 // We haven't seen this label yet, so add this goto to the set of
3636 // unresolved goto statements.
3637 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3638 }
3639}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003640
3641/// \brief Set the label of the given expression to the label
3642/// identified by ID.
3643///
3644/// Depending on the order in which the label and other statements
3645/// referencing that label occur, this operation may complete
3646/// immediately (updating the statement) or it may queue the
3647/// statement to be back-patched later.
3648void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3649 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3650 if (Label != LabelStmts.end()) {
3651 // We've already seen this label, so set the label of the
3652 // label-address expression and we're done.
3653 S->setLabel(Label->second);
3654 } else {
3655 // We haven't seen this label yet, so add this label-address
3656 // expression to the set of unresolved label-address expressions.
3657 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3658 }
3659}
Douglas Gregord89275b2009-07-06 18:54:52 +00003660
3661
Mike Stump1eb44332009-09-09 15:08:12 +00003662PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00003663 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3664 Reader.CurrentlyLoadingTypeOrDecl = this;
3665}
3666
3667PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3668 if (!Parent) {
3669 // If any identifiers with corresponding top-level declarations have
3670 // been loaded, load those declarations now.
3671 while (!Reader.PendingIdentifierInfos.empty()) {
3672 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3673 Reader.PendingIdentifierInfos.front().DeclIDs,
3674 true);
3675 Reader.PendingIdentifierInfos.pop_front();
3676 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003677
3678 // We are not in recursive loading, so it's safe to pass the "interesting"
3679 // decls to the consumer.
3680 if (Reader.Consumer)
3681 Reader.PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003682 }
3683
Mike Stump1eb44332009-09-09 15:08:12 +00003684 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00003685}