blob: 2252fd4729e511fb67c809acf10960d83e40fc2f [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Sebastian Redl30c514c2010-07-14 23:45:08 +000016#include "clang/Frontend/PCHDeserializationListener.h"
Daniel Dunbarc7162932009-11-11 23:58:53 +000017#include "clang/Frontend/Utils.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000018#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000021#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000023#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000024#include "clang/Lex/MacroInfo.h"
Douglas Gregor6a5a23f2010-03-19 21:51:54 +000025#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000026#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000027#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000028#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000029#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000030#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000031#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000032#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000033#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000034#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000036#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000037#include "llvm/Support/ErrorHandling.h"
Daniel Dunbard5b21972009-11-18 19:50:41 +000038#include "llvm/System/Path.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000039#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000040#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000041#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000042#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000043using namespace clang;
44
45//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000046// PCH reader validator implementation
47//===----------------------------------------------------------------------===//
48
49PCHReaderListener::~PCHReaderListener() {}
50
51bool
52PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
53 const LangOptions &PPLangOpts = PP.getLangOptions();
54#define PARSE_LANGOPT_BENIGN(Option)
55#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
56 if (PPLangOpts.Option != LangOpts.Option) { \
57 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
58 return true; \
59 }
60
61 PARSE_LANGOPT_BENIGN(Trigraphs);
62 PARSE_LANGOPT_BENIGN(BCPLComment);
63 PARSE_LANGOPT_BENIGN(DollarIdents);
64 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
65 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +000066 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000067 PARSE_LANGOPT_BENIGN(ImplicitInt);
68 PARSE_LANGOPT_BENIGN(Digraphs);
69 PARSE_LANGOPT_BENIGN(HexFloats);
70 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
71 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
72 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
73 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
74 PARSE_LANGOPT_BENIGN(CXXOperatorName);
75 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
76 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
77 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian412e7982010-02-09 19:31:38 +000078 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +000079 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
80 diag::warn_pch_no_constant_cfstrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000081 PARSE_LANGOPT_BENIGN(PascalStrings);
82 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000084 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000085 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +000087 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000088 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
89 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
90 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000091 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000092 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000093 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000094 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
95 PARSE_LANGOPT_BENIGN(EmitAllDecls);
96 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
Chris Lattnera4d71452010-06-26 21:25:03 +000097 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
Mike Stump1eb44332009-09-09 15:08:12 +000098 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000099 diag::warn_pch_heinous_extensions);
100 // FIXME: Most of the options below are benign if the macro wasn't
101 // used. Unfortunately, this means that a PCH compiled without
102 // optimization can't be used with optimization turned on, even
103 // though the only thing that changes is whether __OPTIMIZE__ was
104 // defined... but if __OPTIMIZE__ never showed up in the header, it
105 // doesn't matter. We could consider making this some special kind
106 // of check.
107 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
108 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
109 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
110 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
111 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
112 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
113 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
114 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsona6fda122009-11-05 20:14:16 +0000115 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000116 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000117 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000118 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
119 return true;
120 }
121 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000122 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
123 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000124 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000125 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stump9c276ae2009-12-12 01:27:46 +0000126 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000127 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Douglas Gregora0068fc2010-07-09 17:35:33 +0000128 PARSE_LANGOPT_BENIGN(SpellChecking);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +0000129#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000130#undef PARSE_LANGOPT_BENIGN
131
132 return false;
133}
134
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000135bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
136 if (Triple == PP.getTargetInfo().getTriple().str())
137 return false;
138
139 Reader.Diag(diag::warn_pch_target_triple)
140 << Triple << PP.getTargetInfo().getTriple().str();
141 return true;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000142}
143
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000144struct EmptyStringRef {
Benjamin Kramerec1b1cc2010-07-14 23:19:41 +0000145 bool operator ()(llvm::StringRef r) const { return r.empty(); }
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000146};
147struct EmptyBlock {
148 bool operator ()(const PCHPredefinesBlock &r) const { return r.Data.empty(); }
149};
150
151static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
152 PCHPredefinesBlocks R) {
153 // First, sum up the lengths.
154 unsigned LL = 0, RL = 0;
155 for (unsigned I = 0, N = L.size(); I != N; ++I) {
156 LL += L[I].size();
157 }
158 for (unsigned I = 0, N = R.size(); I != N; ++I) {
159 RL += R[I].Data.size();
160 }
161 if (LL != RL)
162 return false;
163 if (LL == 0 && RL == 0)
164 return true;
165
166 // Kick out empty parts, they confuse the algorithm below.
167 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
168 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
169
170 // Do it the hard way. At this point, both vectors must be non-empty.
171 llvm::StringRef LR = L[0], RR = R[0].Data;
172 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
Daniel Dunbarc76c9e02010-07-16 00:00:11 +0000173 (void) RN;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000174 for (;;) {
175 // Compare the current pieces.
176 if (LR.size() == RR.size()) {
177 // If they're the same length, it's pretty easy.
178 if (LR != RR)
179 return false;
180 // Both pieces are done, advance.
181 ++LI;
182 ++RI;
183 // If either string is done, they're both done, since they're the same
184 // length.
185 if (LI == LN) {
186 assert(RI == RN && "Strings not the same length after all?");
187 return true;
188 }
189 LR = L[LI];
190 RR = R[RI].Data;
191 } else if (LR.size() < RR.size()) {
192 // Right piece is longer.
193 if (!RR.startswith(LR))
194 return false;
195 ++LI;
196 assert(LI != LN && "Strings not the same length after all?");
197 RR = RR.substr(LR.size());
198 LR = L[LI];
199 } else {
200 // Left piece is longer.
201 if (!LR.startswith(RR))
202 return false;
203 ++RI;
204 assert(RI != RN && "Strings not the same length after all?");
205 LR = LR.substr(RR.size());
206 RR = R[RI].Data;
207 }
208 }
209}
210
211static std::pair<FileID, llvm::StringRef::size_type>
212FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
213 std::pair<FileID, llvm::StringRef::size_type> Res;
214 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
215 Res.second = Buffers[I].Data.find(MacroDef);
216 if (Res.second != llvm::StringRef::npos) {
217 Res.first = Buffers[I].BufferID;
218 break;
219 }
220 }
221 return Res;
222}
223
224bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000225 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000226 std::string &SuggestedPredefines) {
Daniel Dunbarc7162932009-11-11 23:58:53 +0000227 // We are in the context of an implicit include, so the predefines buffer will
228 // have a #include entry for the PCH file itself (as normalized by the
229 // preprocessor initialization). Find it and skip over it in the checking
230 // below.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000231 llvm::SmallString<256> PCHInclude;
232 PCHInclude += "#include \"";
Daniel Dunbarc7162932009-11-11 23:58:53 +0000233 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000234 PCHInclude += "\"\n";
235 std::pair<llvm::StringRef,llvm::StringRef> Split =
236 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
237 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000238 if (Left == PP.getPredefines()) {
239 Error("Missing PCH include entry!");
240 return true;
241 }
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000242
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000243 // If the concatenation of all the PCH buffers is equal to the adjusted
244 // command line, we're done.
245 // We build a SmallVector of the command line here, because we'll eventually
246 // need to support an arbitrary amount of pieces anyway (when we have chained
247 // PCH reading).
248 llvm::SmallVector<llvm::StringRef, 2> CommandLine;
249 CommandLine.push_back(Left);
250 CommandLine.push_back(Right);
251 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000252 return false;
253
254 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000256 // The predefines buffers are different. Determine what the differences are,
257 // and whether they require us to reject the PCH file.
Daniel Dunbare6750492009-11-13 16:46:11 +0000258 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000259 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
260 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbare6750492009-11-13 16:46:11 +0000261
262 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
263 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
264 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000265
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000266 // Sort both sets of predefined buffer lines, since we allow some extra
267 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000268 std::sort(CmdLineLines.begin(), CmdLineLines.end());
269 std::sort(PCHLines.begin(), PCHLines.end());
270
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000271 // Determine which predefines that were used to build the PCH file are missing
272 // from the command line.
273 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000274 std::set_difference(PCHLines.begin(), PCHLines.end(),
275 CmdLineLines.begin(), CmdLineLines.end(),
276 std::back_inserter(MissingPredefines));
277
278 bool MissingDefines = false;
279 bool ConflictingDefines = false;
280 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000281 llvm::StringRef Missing = MissingPredefines[I];
282 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000283 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
284 return true;
285 }
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000287 // This is a macro definition. Determine the name of the macro we're
288 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000289 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000290 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000291 = Missing.find_first_of("( \n\r", StartOfMacroName);
292 assert(EndOfMacroName != std::string::npos &&
293 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000294 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000295
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000296 // Determine whether this macro was given a different definition on the
297 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000298 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000299 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbare6750492009-11-13 16:46:11 +0000300 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000301 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
302 MacroDefStart);
303 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000304 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000305 // Different macro; we're done.
306 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000307 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000308 }
Mike Stump1eb44332009-09-09 15:08:12 +0000309
310 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000311 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000312 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000313 (*ConflictPos)[MacroDefLen] != '(')
314 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000316 // We found a conflicting macro definition.
317 break;
318 }
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000320 if (ConflictPos != CmdLineLines.end()) {
321 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
322 << MacroName;
323
324 // Show the definition of this macro within the PCH file.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000325 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
326 FindMacro(Buffers, Missing);
327 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
328 SourceLocation PCHMissingLoc =
329 SourceMgr.getLocForStartOfFile(MacroLoc.first)
330 .getFileLocWithOffset(MacroLoc.second);
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000331 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000332
333 ConflictingDefines = true;
334 continue;
335 }
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000337 // If the macro doesn't conflict, then we'll just pick up the macro
338 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000339 if (ConflictingDefines)
340 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000342 if (!MissingDefines) {
343 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
344 MissingDefines = true;
345 }
346
347 // Show the definition of this macro within the PCH file.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000348 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
349 FindMacro(Buffers, Missing);
350 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
351 SourceLocation PCHMissingLoc =
352 SourceMgr.getLocForStartOfFile(MacroLoc.first)
353 .getFileLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000354 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
355 }
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000357 if (ConflictingDefines)
358 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000360 // Determine what predefines were introduced based on command-line
361 // parameters that were not present when building the PCH
362 // file. Extra #defines are okay, so long as the identifiers being
363 // defined were not used within the precompiled header.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000364 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000365 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
366 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000367 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000368 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000369 llvm::StringRef &Extra = ExtraPredefines[I];
370 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000371 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
372 return true;
373 }
374
375 // This is an extra macro definition. Determine the name of the
376 // macro we're defining.
377 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000378 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000379 = Extra.find_first_of("( \n\r", StartOfMacroName);
380 assert(EndOfMacroName != std::string::npos &&
381 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000382 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000383
384 // Check whether this name was used somewhere in the PCH file. If
385 // so, defining it as a macro could change behavior, so we reject
386 // the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000387 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000388 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000389 return true;
390 }
391
392 // Add this definition to the suggested predefines buffer.
393 SuggestedPredefines += Extra;
394 SuggestedPredefines += '\n';
395 }
396
397 // If we get here, it's because the predefines buffer had compatible
398 // contents. Accept the PCH file.
399 return false;
400}
401
Douglas Gregor12fab312010-03-16 16:35:32 +0000402void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
403 unsigned ID) {
404 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
405 ++NumHeaderInfos;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000406}
407
408void PCHValidator::ReadCounter(unsigned Value) {
409 PP.setCounterValue(Value);
410}
411
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000412//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000413// PCH reader implementation
414//===----------------------------------------------------------------------===//
415
Mike Stump1eb44332009-09-09 15:08:12 +0000416PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000417 const char *isysroot, bool DisableValidation)
Sebastian Redl30c514c2010-07-14 23:45:08 +0000418 : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
419 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
420 Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
Sebastian Redl725cd962010-08-04 20:40:17 +0000421 Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
422 NumStatHits(0), NumStatMisses(0), NumSLocEntriesRead(0),
423 TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
Sebastian Redlfa78dec2010-08-04 21:22:45 +0000424 NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
425 NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
426 TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
Sebastian Redl725cd962010-08-04 20:40:17 +0000427 TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
428 TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(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,
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000433 Diagnostic &Diags, const char *isysroot,
434 bool DisableValidation)
Sebastian Redl30c514c2010-07-14 23:45:08 +0000435 : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
Sebastian Redl9137a522010-07-16 17:50:48 +0000436 Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
Sebastian Redl725cd962010-08-04 20:40:17 +0000437 isysroot(isysroot), DisableValidation(DisableValidation), NumStatHits(0),
438 NumStatMisses(0), NumSLocEntriesRead(0), TotalNumSLocEntries(0),
439 NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
Sebastian Redlfa78dec2010-08-04 21:22:45 +0000440 TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
441 NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
Sebastian Redl725cd962010-08-04 20:40:17 +0000442 NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
443 NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
444 NumCurrentElementsDeserializing(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000445 RelocatablePCH = false;
446}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000447
Sebastian Redl9137a522010-07-16 17:50:48 +0000448PCHReader::~PCHReader() {
449 for (unsigned i = 0, e = Chain.size(); i != e; ++i)
450 delete Chain[e - i - 1];
451}
452
453PCHReader::PerFileData::PerFileData()
Sebastian Redl12d6da02010-07-19 22:06:55 +0000454 : StatCache(0), LocalNumSLocEntries(0), LocalNumTypes(0), TypeOffsets(0),
Sebastian Redl2da08f92010-07-19 22:28:42 +0000455 LocalNumDecls(0), DeclOffsets(0), LocalNumIdentifiers(0),
Sebastian Redl04e6fd42010-07-21 20:07:32 +0000456 IdentifierOffsets(0), IdentifierTableData(0), IdentifierLookupTable(0),
457 LocalNumMacroDefinitions(0), MacroDefinitionOffsets(0),
Sebastian Redl725cd962010-08-04 20:40:17 +0000458 NumPreallocatedPreprocessingEntities(0), SelectorLookupTable(0),
459 SelectorLookupTableData(0), SelectorOffsets(0), LocalNumSelectors(0)
Sebastian Redl9137a522010-07-16 17:50:48 +0000460{}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000461
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000462void
463PCHReader::setDeserializationListener(PCHDeserializationListener *Listener) {
464 DeserializationListener = Listener;
465 if (DeserializationListener)
466 DeserializationListener->SetReader(this);
467}
468
Chris Lattner4c6f9522009-04-27 05:14:47 +0000469
Douglas Gregor668c1a42009-04-21 22:25:48 +0000470namespace {
Sebastian Redl725cd962010-08-04 20:40:17 +0000471class PCHSelectorLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000472 PCHReader &Reader;
473
474public:
Sebastian Redl5d050072010-08-04 17:20:04 +0000475 struct data_type {
476 pch::SelectorID ID;
477 ObjCMethodList Instance, Factory;
478 };
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000479
480 typedef Selector external_key_type;
481 typedef external_key_type internal_key_type;
482
Sebastian Redl725cd962010-08-04 20:40:17 +0000483 explicit PCHSelectorLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000485 static bool EqualKey(const internal_key_type& a,
486 const internal_key_type& b) {
487 return a == b;
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000490 static unsigned ComputeHash(Selector Sel) {
491 unsigned N = Sel.getNumArgs();
492 if (N == 0)
493 ++N;
494 unsigned R = 5381;
495 for (unsigned I = 0; I != N; ++I)
496 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000497 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000498 return R;
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000501 // This hopefully will just get inlined and removed by the optimizer.
502 static const internal_key_type&
503 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000505 static std::pair<unsigned, unsigned>
506 ReadKeyDataLength(const unsigned char*& d) {
507 using namespace clang::io;
508 unsigned KeyLen = ReadUnalignedLE16(d);
509 unsigned DataLen = ReadUnalignedLE16(d);
510 return std::make_pair(KeyLen, DataLen);
511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregor83941df2009-04-25 17:48:32 +0000513 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000514 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000515 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000516 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000517 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000518 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
519 if (N == 0)
520 return SelTable.getNullarySelector(FirstII);
521 else if (N == 1)
522 return SelTable.getUnarySelector(FirstII);
523
524 llvm::SmallVector<IdentifierInfo *, 16> Args;
525 Args.push_back(FirstII);
526 for (unsigned I = 1; I != N; ++I)
527 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
528
Douglas Gregor75fdb232009-05-22 22:45:36 +0000529 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000530 }
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000532 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
533 using namespace clang::io;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000534
535 data_type Result;
536
Sebastian Redl5d050072010-08-04 17:20:04 +0000537 Result.ID = ReadUnalignedLE32(d);
538 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
539 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
540
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000541 // Load instance methods
542 ObjCMethodList *Prev = 0;
543 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000544 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000545 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Sebastian Redl5d050072010-08-04 17:20:04 +0000546 if (!Result.Instance.Method) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000547 // This is the first method, which is the easy case.
Sebastian Redl5d050072010-08-04 17:20:04 +0000548 Result.Instance.Method = Method;
549 Prev = &Result.Instance;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000550 continue;
551 }
552
Ted Kremenek298ed872010-02-11 00:53:01 +0000553 ObjCMethodList *Mem =
554 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
555 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000556 Prev = Prev->Next;
557 }
558
559 // Load factory methods
560 Prev = 0;
561 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000562 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000563 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Sebastian Redl5d050072010-08-04 17:20:04 +0000564 if (!Result.Factory.Method) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000565 // This is the first method, which is the easy case.
Sebastian Redl5d050072010-08-04 17:20:04 +0000566 Result.Factory.Method = Method;
567 Prev = &Result.Factory;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000568 continue;
569 }
570
Ted Kremenek298ed872010-02-11 00:53:01 +0000571 ObjCMethodList *Mem =
572 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
573 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000574 Prev = Prev->Next;
575 }
576
577 return Result;
578 }
579};
Mike Stump1eb44332009-09-09 15:08:12 +0000580
581} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000582
583/// \brief The on-disk hash table used for the global method pool.
Sebastian Redl725cd962010-08-04 20:40:17 +0000584typedef OnDiskChainedHashTable<PCHSelectorLookupTrait>
585 PCHSelectorLookupTable;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000586
587namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000588class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000589 PCHReader &Reader;
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000590 llvm::BitstreamCursor &Stream;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000591
592 // If we know the IdentifierInfo in advance, it is here and we will
593 // not build a new one. Used when deserializing information about an
594 // identifier that was constructed before the PCH file was read.
595 IdentifierInfo *KnownII;
596
597public:
598 typedef IdentifierInfo * data_type;
599
600 typedef const std::pair<const char*, unsigned> external_key_type;
601
602 typedef external_key_type internal_key_type;
603
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000604 PCHIdentifierLookupTrait(PCHReader &Reader, llvm::BitstreamCursor &Stream,
605 IdentifierInfo *II = 0)
606 : Reader(Reader), Stream(Stream), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Douglas Gregor668c1a42009-04-21 22:25:48 +0000608 static bool EqualKey(const internal_key_type& a,
609 const internal_key_type& b) {
610 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
611 : false;
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Douglas Gregor668c1a42009-04-21 22:25:48 +0000614 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000615 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000616 }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregor668c1a42009-04-21 22:25:48 +0000618 // This hopefully will just get inlined and removed by the optimizer.
619 static const internal_key_type&
620 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Douglas Gregor668c1a42009-04-21 22:25:48 +0000622 static std::pair<unsigned, unsigned>
623 ReadKeyDataLength(const unsigned char*& d) {
624 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000625 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000626 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000627 return std::make_pair(KeyLen, DataLen);
628 }
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Douglas Gregor668c1a42009-04-21 22:25:48 +0000630 static std::pair<const char*, unsigned>
631 ReadKey(const unsigned char* d, unsigned n) {
632 assert(n >= 2 && d[n-1] == '\0');
633 return std::make_pair((const char*) d, n-1);
634 }
Mike Stump1eb44332009-09-09 15:08:12 +0000635
636 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000637 const unsigned char* d,
638 unsigned DataLen) {
639 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000640 pch::IdentID ID = ReadUnalignedLE32(d);
641 bool IsInteresting = ID & 0x01;
642
643 // Wipe out the "is interesting" bit.
644 ID = ID >> 1;
645
646 if (!IsInteresting) {
Sebastian Redl083abdf2010-07-27 23:01:28 +0000647 // For uninteresting identifiers, just build the IdentifierInfo
Douglas Gregora92193e2009-04-28 21:18:29 +0000648 // and associate it with the persistent ID.
649 IdentifierInfo *II = KnownII;
650 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000651 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregora92193e2009-04-28 21:18:29 +0000652 Reader.SetIdentifierInfo(ID, II);
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000653 II->setIsFromPCH();
Douglas Gregora92193e2009-04-28 21:18:29 +0000654 return II;
655 }
656
Douglas Gregor5998da52009-04-28 21:32:13 +0000657 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000658 bool CPlusPlusOperatorKeyword = Bits & 0x01;
659 Bits >>= 1;
660 bool Poisoned = Bits & 0x01;
661 Bits >>= 1;
662 bool ExtensionToken = Bits & 0x01;
663 Bits >>= 1;
664 bool hasMacroDefinition = Bits & 0x01;
665 Bits >>= 1;
666 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
667 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Douglas Gregor2deaea32009-04-22 18:49:13 +0000669 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000670 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000671
672 // Build the IdentifierInfo itself and link the identifier ID with
673 // the new IdentifierInfo.
674 IdentifierInfo *II = KnownII;
675 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000676 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000677 Reader.SetIdentifierInfo(ID, II);
678
Douglas Gregor2deaea32009-04-22 18:49:13 +0000679 // Set or check the various bits in the IdentifierInfo structure.
680 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000681 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000682 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000683 "Incorrect extension token flag");
684 (void)ExtensionToken;
685 II->setIsPoisoned(Poisoned);
686 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
687 "Incorrect C++ operator keyword flag");
688 (void)CPlusPlusOperatorKeyword;
689
Douglas Gregor37e26842009-04-21 23:56:24 +0000690 // If this identifier is a macro, deserialize the macro
691 // definition.
692 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000693 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000694 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000695 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000696 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000697
698 // Read all of the declarations visible at global scope with this
699 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000700 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000701 if (DataLen > 0) {
702 llvm::SmallVector<uint32_t, 4> DeclIDs;
703 for (; DataLen > 0; DataLen -= 4)
704 DeclIDs.push_back(ReadUnalignedLE32(d));
705 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000706 }
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000708 II->setIsFromPCH();
Douglas Gregor668c1a42009-04-21 22:25:48 +0000709 return II;
710 }
711};
Mike Stump1eb44332009-09-09 15:08:12 +0000712
713} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000714
715/// \brief The on-disk hash table used to contain information about
716/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000717typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000718 PCHIdentifierLookupTable;
719
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000720void PCHReader::Error(const char *Msg) {
721 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000722}
723
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000724/// \brief Check the contents of the concatenation of all predefines buffers in
725/// the PCH chain against the contents of the predefines buffer of the current
726/// compiler invocation.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000727///
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000728/// The contents should be the same. If not, then some command-line option
729/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000730///
731/// \returns true if there was a mismatch (in which case the PCH file
732/// should be ignored), or false otherwise.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000733bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000734 if (Listener)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000735 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000736 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000737 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000738 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000739}
740
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000741//===----------------------------------------------------------------------===//
742// Source Manager Deserialization
743//===----------------------------------------------------------------------===//
744
Douglas Gregorbd945002009-04-13 16:31:14 +0000745/// \brief Read the line table in the source manager block.
746/// \returns true if ther was an error.
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000747bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000748 unsigned Idx = 0;
749 LineTableInfo &LineTable = SourceMgr.getLineTable();
750
751 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000752 std::map<int, int> FileIDs;
753 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000754 // Extract the file name
755 unsigned FilenameLen = Record[Idx++];
756 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
757 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000758 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000759 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000760 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000761 }
762
763 // Parse the line entries
764 std::vector<LineEntry> Entries;
765 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000766 int FID = Record[Idx++];
Douglas Gregorbd945002009-04-13 16:31:14 +0000767
768 // Extract the line entries
769 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000770 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +0000771 Entries.clear();
772 Entries.reserve(NumEntries);
773 for (unsigned I = 0; I != NumEntries; ++I) {
774 unsigned FileOffset = Record[Idx++];
775 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000776 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +0000777 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000778 = (SrcMgr::CharacteristicKind)Record[Idx++];
779 unsigned IncludeOffset = Record[Idx++];
780 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
781 FileKind, IncludeOffset));
782 }
783 LineTable.AddEntry(FID, Entries);
784 }
785
786 return false;
787}
788
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000789namespace {
790
Benjamin Kramerbd218282009-11-28 10:07:24 +0000791class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000792public:
793 const bool hasStat;
794 const ino_t ino;
795 const dev_t dev;
796 const mode_t mode;
797 const time_t mtime;
798 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000800 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000801 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
802
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000803 PCHStatData()
804 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
805};
806
Benjamin Kramerbd218282009-11-28 10:07:24 +0000807class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000808 public:
809 typedef const char *external_key_type;
810 typedef const char *internal_key_type;
811
812 typedef PCHStatData data_type;
813
814 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000815 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000816 }
817
818 static internal_key_type GetInternalKey(const char *path) { return path; }
819
820 static bool EqualKey(internal_key_type a, internal_key_type b) {
821 return strcmp(a, b) == 0;
822 }
823
824 static std::pair<unsigned, unsigned>
825 ReadKeyDataLength(const unsigned char*& d) {
826 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
827 unsigned DataLen = (unsigned) *d++;
828 return std::make_pair(KeyLen + 1, DataLen);
829 }
830
831 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
832 return (const char *)d;
833 }
834
835 static data_type ReadData(const internal_key_type, const unsigned char *d,
836 unsigned /*DataLen*/) {
837 using namespace clang::io;
838
839 if (*d++ == 1)
840 return data_type();
841
842 ino_t ino = (ino_t) ReadUnalignedLE32(d);
843 dev_t dev = (dev_t) ReadUnalignedLE32(d);
844 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000845 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000846 off_t size = (off_t) ReadUnalignedLE64(d);
847 return data_type(ino, dev, mode, mtime, size);
848 }
849};
850
851/// \brief stat() cache for precompiled headers.
852///
853/// This cache is very similar to the stat cache used by pretokenized
854/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000855class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000856 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
857 CacheTy *Cache;
858
859 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000860public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000861 PCHStatCache(const unsigned char *Buckets,
862 const unsigned char *Base,
863 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000864 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000865 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
866 Cache = CacheTy::Create(Buckets, Base);
867 }
868
869 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000871 int stat(const char *path, struct stat *buf) {
872 // Do the lookup for the file's data in the PCH file.
873 CacheTy::iterator I = Cache->find(path);
874
875 // If we don't get a hit in the PCH file just forward to 'stat'.
876 if (I == Cache->end()) {
877 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000878 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000881 ++NumStatHits;
882 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000884 if (!Data.hasStat)
885 return 1;
886
887 buf->st_ino = Data.ino;
888 buf->st_dev = Data.dev;
889 buf->st_mtime = Data.mtime;
890 buf->st_mode = Data.mode;
891 buf->st_size = Data.size;
892 return 0;
893 }
894};
895} // end anonymous namespace
896
897
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000898/// \brief Read a source manager block
899PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000900 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000901
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000902 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +0000903
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000904 // Set the source-location entry cursor to the current position in
905 // the stream. This cursor will be used to read the contents of the
906 // source manager block initially, and then lazily read
907 // source-location entries as needed.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000908 SLocEntryCursor = F.Stream;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000909
910 // The stream itself is going to skip over the source manager block.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000911 if (F.Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000912 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000913 return Failure;
914 }
915
916 // Enter the source manager block.
917 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000918 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000919 return Failure;
920 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000921
Douglas Gregor14f79002009-04-10 03:52:48 +0000922 RecordData Record;
923 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000924 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000925 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000926 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000927 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000928 return Failure;
929 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000930 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Douglas Gregor14f79002009-04-10 03:52:48 +0000933 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
934 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000935 SLocEntryCursor.ReadSubBlockID();
936 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000937 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000938 return Failure;
939 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000940 continue;
941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Douglas Gregor14f79002009-04-10 03:52:48 +0000943 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000944 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000945 continue;
946 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Douglas Gregor14f79002009-04-10 03:52:48 +0000948 // Read a record.
949 const char *BlobStart;
950 unsigned BlobLen;
951 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000952 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000953 default: // Default behavior: ignore.
954 break;
955
Chris Lattner2c78b872009-04-14 23:22:57 +0000956 case pch::SM_LINE_TABLE:
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000957 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000958 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000959 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000960
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000961 case pch::SM_SLOC_FILE_ENTRY:
962 case pch::SM_SLOC_BUFFER_ENTRY:
963 case pch::SM_SLOC_INSTANTIATION_ENTRY:
964 // Once we hit one of the source location entries, we're done.
965 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000966 }
967 }
968}
969
Sebastian Redl190faf72010-07-20 21:50:20 +0000970/// \brief Get a cursor that's correctly positioned for reading the source
971/// location entry with the given ID.
972llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
973 assert(ID != 0 && ID <= TotalNumSLocEntries &&
974 "SLocCursorForID should only be called for real IDs.");
975
976 ID -= 1;
977 PerFileData *F = 0;
978 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
979 F = Chain[N - I - 1];
980 if (ID < F->LocalNumSLocEntries)
981 break;
982 ID -= F->LocalNumSLocEntries;
983 }
984 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
985
986 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
987 return F->SLocEntryCursor;
988}
989
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000990/// \brief Read in the source location entry with the given ID.
991PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
992 if (ID == 0)
993 return Success;
994
995 if (ID > TotalNumSLocEntries) {
996 Error("source location entry ID out-of-range for PCH file");
997 return Failure;
998 }
999
Sebastian Redl190faf72010-07-20 21:50:20 +00001000 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl9137a522010-07-16 17:50:48 +00001001
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001002 ++NumSLocEntriesRead;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001003 unsigned Code = SLocEntryCursor.ReadCode();
1004 if (Code == llvm::bitc::END_BLOCK ||
1005 Code == llvm::bitc::ENTER_SUBBLOCK ||
1006 Code == llvm::bitc::DEFINE_ABBREV) {
1007 Error("incorrectly-formatted source location entry in PCH file");
1008 return Failure;
1009 }
1010
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001011 RecordData Record;
1012 const char *BlobStart;
1013 unsigned BlobLen;
1014 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1015 default:
1016 Error("incorrectly-formatted source location entry in PCH file");
1017 return Failure;
1018
1019 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001020 std::string Filename(BlobStart, BlobStart + BlobLen);
1021 MaybeAddSystemRootToFilename(Filename);
1022 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001023 if (File == 0) {
1024 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +00001025 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001026 ErrorStr += "' referenced by PCH file";
1027 Error(ErrorStr.c_str());
1028 return Failure;
1029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Douglas Gregor2d52be52010-03-21 22:49:54 +00001031 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +00001032 Error("source location entry is incorrect");
1033 return Failure;
1034 }
1035
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001036 if (!DisableValidation &&
1037 ((off_t)Record[4] != File->getSize()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001038#if !defined(LLVM_ON_WIN32)
1039 // In our regression testing, the Windows file system seems to
1040 // have inconsistent modification times that sometimes
1041 // erroneously trigger this error-handling path.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001042 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001043#endif
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001044 )) {
Douglas Gregor2d52be52010-03-21 22:49:54 +00001045 Diag(diag::err_fe_pch_file_modified)
1046 << Filename;
1047 return Failure;
1048 }
1049
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001050 FileID FID = SourceMgr.createFileID(File,
1051 SourceLocation::getFromRawEncoding(Record[1]),
1052 (SrcMgr::CharacteristicKind)Record[2],
1053 ID, Record[0]);
1054 if (Record[3])
1055 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1056 .setHasLineDirectives();
1057
Douglas Gregor12fab312010-03-16 16:35:32 +00001058 // Reconstruct header-search information for this file.
1059 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001060 HFI.isImport = Record[6];
1061 HFI.DirInfo = Record[7];
1062 HFI.NumIncludes = Record[8];
1063 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +00001064 if (Listener)
1065 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001066 break;
1067 }
1068
1069 case pch::SM_SLOC_BUFFER_ENTRY: {
1070 const char *Name = BlobStart;
1071 unsigned Offset = Record[0];
1072 unsigned Code = SLocEntryCursor.ReadCode();
1073 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001074 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001075 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001076
1077 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1078 Error("PCH record has invalid code");
1079 return Failure;
1080 }
1081
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001082 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001083 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1084 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001085 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Douglas Gregor92b059e2009-04-28 20:33:11 +00001087 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001088 PCHPredefinesBlock Block = {
1089 BufferID,
1090 llvm::StringRef(BlobStart, BlobLen - 1)
1091 };
1092 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001093 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001094
1095 break;
1096 }
1097
1098 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +00001099 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001100 = SourceLocation::getFromRawEncoding(Record[1]);
1101 SourceMgr.createInstantiationLoc(SpellingLoc,
1102 SourceLocation::getFromRawEncoding(Record[2]),
1103 SourceLocation::getFromRawEncoding(Record[3]),
1104 Record[4],
1105 ID,
1106 Record[0]);
1107 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001108 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001109 }
1110
1111 return Success;
1112}
1113
Chris Lattner6367f6d2009-04-27 01:05:14 +00001114/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1115/// specified cursor. Read the abbreviations that are at the top of the block
1116/// and then leave the cursor pointing into the block.
1117bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1118 unsigned BlockID) {
1119 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001120 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001121 return Failure;
1122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner6367f6d2009-04-27 01:05:14 +00001124 while (true) {
1125 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Chris Lattner6367f6d2009-04-27 01:05:14 +00001127 // We expect all abbrevs to be at the start of the block.
1128 if (Code != llvm::bitc::DEFINE_ABBREV)
1129 return false;
1130 Cursor.ReadAbbrevRecord();
1131 }
1132}
1133
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001134void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001135 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Douglas Gregor37e26842009-04-21 23:56:24 +00001137 // Keep track of where we are in the stream, then jump back there
1138 // after reading this macro.
1139 SavedStreamPosition SavedPosition(Stream);
1140
1141 Stream.JumpToBit(Offset);
1142 RecordData Record;
1143 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1144 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Douglas Gregor37e26842009-04-21 23:56:24 +00001146 while (true) {
1147 unsigned Code = Stream.ReadCode();
1148 switch (Code) {
1149 case llvm::bitc::END_BLOCK:
1150 return;
1151
1152 case llvm::bitc::ENTER_SUBBLOCK:
1153 // No known subblocks, always skip them.
1154 Stream.ReadSubBlockID();
1155 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001156 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001157 return;
1158 }
1159 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Douglas Gregor37e26842009-04-21 23:56:24 +00001161 case llvm::bitc::DEFINE_ABBREV:
1162 Stream.ReadAbbrevRecord();
1163 continue;
1164 default: break;
1165 }
1166
1167 // Read a record.
1168 Record.clear();
1169 pch::PreprocessorRecordTypes RecType =
1170 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1171 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001172 case pch::PP_MACRO_OBJECT_LIKE:
1173 case pch::PP_MACRO_FUNCTION_LIKE: {
1174 // If we already have a macro, that means that we've hit the end
1175 // of the definition of the macro we were looking for. We're
1176 // done.
1177 if (Macro)
1178 return;
1179
1180 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1181 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001182 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001183 return;
1184 }
1185 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1186 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001188 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001189 MI->setIsUsed(isUsed);
Sebastian Redl083abdf2010-07-27 23:01:28 +00001190 MI->setIsFromPCH();
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001192 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001193 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1194 // Decode function-like macro info.
1195 bool isC99VarArgs = Record[3];
1196 bool isGNUVarArgs = Record[4];
1197 MacroArgs.clear();
1198 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001199 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001200 for (unsigned i = 0; i != NumArgs; ++i)
1201 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1202
1203 // Install function-like macro info.
1204 MI->setIsFunctionLike();
1205 if (isC99VarArgs) MI->setIsC99Varargs();
1206 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001207 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001208 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001209 }
1210
1211 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001212 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001213
1214 // Remember that we saw this macro last so that we add the tokens that
1215 // form its body to it.
1216 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001217
1218 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1219 // We have a macro definition. Load it now.
1220 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1221 getMacroDefinition(Record[NextIndex]));
1222 }
1223
Douglas Gregor37e26842009-04-21 23:56:24 +00001224 ++NumMacrosRead;
1225 break;
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregor37e26842009-04-21 23:56:24 +00001228 case pch::PP_TOKEN: {
1229 // If we see a TOKEN before a PP_MACRO_*, then the file is
1230 // erroneous, just pretend we didn't see this.
1231 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Douglas Gregor37e26842009-04-21 23:56:24 +00001233 Token Tok;
1234 Tok.startToken();
1235 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1236 Tok.setLength(Record[1]);
1237 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1238 Tok.setIdentifierInfo(II);
1239 Tok.setKind((tok::TokenKind)Record[3]);
1240 Tok.setFlag((Token::TokenFlags)Record[4]);
1241 Macro->AddTokenToBody(Tok);
1242 break;
1243 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001244
1245 case pch::PP_MACRO_INSTANTIATION: {
1246 // If we already have a macro, that means that we've hit the end
1247 // of the definition of the macro we were looking for. We're
1248 // done.
1249 if (Macro)
1250 return;
1251
1252 if (!PP->getPreprocessingRecord()) {
1253 Error("missing preprocessing record in PCH file");
1254 return;
1255 }
1256
1257 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1258 if (PPRec.getPreprocessedEntity(Record[0]))
1259 return;
1260
1261 MacroInstantiation *MI
1262 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1263 SourceRange(
1264 SourceLocation::getFromRawEncoding(Record[1]),
1265 SourceLocation::getFromRawEncoding(Record[2])),
1266 getMacroDefinition(Record[4]));
1267 PPRec.SetPreallocatedEntity(Record[0], MI);
1268 return;
1269 }
1270
1271 case pch::PP_MACRO_DEFINITION: {
1272 // If we already have a macro, that means that we've hit the end
1273 // of the definition of the macro we were looking for. We're
1274 // done.
1275 if (Macro)
1276 return;
1277
1278 if (!PP->getPreprocessingRecord()) {
1279 Error("missing preprocessing record in PCH file");
1280 return;
1281 }
1282
1283 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1284 if (PPRec.getPreprocessedEntity(Record[0]))
1285 return;
1286
1287 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1288 Error("out-of-bounds macro definition record");
1289 return;
1290 }
1291
1292 MacroDefinition *MD
1293 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1294 SourceLocation::getFromRawEncoding(Record[5]),
1295 SourceRange(
1296 SourceLocation::getFromRawEncoding(Record[2]),
1297 SourceLocation::getFromRawEncoding(Record[3])));
1298 PPRec.SetPreallocatedEntity(Record[0], MD);
1299 MacroDefinitionsLoaded[Record[1]] = MD;
1300 return;
1301 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001302 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001303 }
1304}
1305
Douglas Gregor88a35862010-01-04 19:18:44 +00001306void PCHReader::ReadDefinedMacros() {
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001307 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1308 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001309
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001310 // If there was no preprocessor block, skip this file.
1311 if (!MacroCursor.getBitStreamReader())
1312 continue;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001313
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001314 llvm::BitstreamCursor Cursor = MacroCursor;
1315 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1316 Error("malformed preprocessor block record in PCH file");
Douglas Gregor88a35862010-01-04 19:18:44 +00001317 return;
1318 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001319
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001320 RecordData Record;
1321 while (true) {
1322 unsigned Code = Cursor.ReadCode();
1323 if (Code == llvm::bitc::END_BLOCK) {
1324 if (Cursor.ReadBlockEnd()) {
1325 Error("error at end of preprocessor block in PCH file");
1326 return;
1327 }
1328 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001329 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001330
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001331 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1332 // No known subblocks, always skip them.
1333 Cursor.ReadSubBlockID();
1334 if (Cursor.SkipBlock()) {
1335 Error("malformed block record in PCH file");
1336 return;
1337 }
1338 continue;
1339 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001340
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001341 if (Code == llvm::bitc::DEFINE_ABBREV) {
1342 Cursor.ReadAbbrevRecord();
1343 continue;
1344 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001345
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001346 // Read a record.
1347 const char *BlobStart;
1348 unsigned BlobLen;
1349 Record.clear();
1350 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1351 default: // Default behavior: ignore.
1352 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001353
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001354 case pch::PP_MACRO_OBJECT_LIKE:
1355 case pch::PP_MACRO_FUNCTION_LIKE:
1356 DecodeIdentifierInfo(Record[0]);
1357 break;
1358
1359 case pch::PP_TOKEN:
1360 // Ignore tokens.
1361 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001362
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001363 case pch::PP_MACRO_INSTANTIATION:
1364 case pch::PP_MACRO_DEFINITION:
1365 // Read the macro record.
1366 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1367 break;
1368 }
Douglas Gregor88a35862010-01-04 19:18:44 +00001369 }
1370 }
1371}
1372
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001373MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1374 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1375 return 0;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001376
1377 if (!MacroDefinitionsLoaded[ID]) {
1378 unsigned Index = ID;
1379 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1380 PerFileData &F = *Chain[N - I - 1];
1381 if (Index < F.LocalNumMacroDefinitions) {
1382 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1383 break;
1384 }
1385 Index -= F.LocalNumMacroDefinitions;
1386 }
1387 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1388 }
1389
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001390 return MacroDefinitionsLoaded[ID];
1391}
1392
Douglas Gregore650c8c2009-07-07 00:12:59 +00001393/// \brief If we are loading a relocatable PCH file, and the filename is
1394/// not an absolute path, add the system root to the beginning of the file
1395/// name.
1396void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1397 // If this is not a relocatable PCH file, there's nothing to do.
1398 if (!RelocatablePCH)
1399 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Daniel Dunbard5b21972009-11-18 19:50:41 +00001401 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001402 return;
1403
Douglas Gregore650c8c2009-07-07 00:12:59 +00001404 if (isysroot == 0) {
1405 // If no system root was given, default to '/'
1406 Filename.insert(Filename.begin(), '/');
1407 return;
1408 }
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Douglas Gregore650c8c2009-07-07 00:12:59 +00001410 unsigned Length = strlen(isysroot);
1411 if (isysroot[Length - 1] != '/')
1412 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Douglas Gregore650c8c2009-07-07 00:12:59 +00001414 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1415}
1416
Mike Stump1eb44332009-09-09 15:08:12 +00001417PCHReader::PCHReadResult
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001418PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00001419 llvm::BitstreamCursor &Stream = F.Stream;
1420
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001421 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001422 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001423 return Failure;
1424 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001425
1426 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001427 RecordData Record;
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001428 bool First = true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001429 while (!Stream.AtEndOfStream()) {
1430 unsigned Code = Stream.ReadCode();
1431 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001432 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001433 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001434 return Failure;
1435 }
Chris Lattner7356a312009-04-11 21:15:38 +00001436
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001437 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001438 }
1439
1440 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1441 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001442 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001443 // We lazily load the decls block, but we want to set up the
1444 // DeclsCursor cursor to point into it. Clone our current bitcode
1445 // cursor to it, enter the block and read the abbrevs in that block.
1446 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00001447 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00001448 if (Stream.SkipBlock() || // Skip with the main cursor.
1449 // Read the abbrevs.
Sebastian Redl9137a522010-07-16 17:50:48 +00001450 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001451 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001452 return Failure;
1453 }
1454 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Chris Lattner7356a312009-04-11 21:15:38 +00001456 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00001457 F.MacroCursor = Stream;
Douglas Gregor88a35862010-01-04 19:18:44 +00001458 if (PP)
1459 PP->setExternalSource(this);
1460
Chris Lattner7356a312009-04-11 21:15:38 +00001461 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001462 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001463 return Failure;
1464 }
1465 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001466
Douglas Gregor14f79002009-04-10 03:52:48 +00001467 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001468 switch (ReadSourceManagerBlock(F)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001469 case Success:
1470 break;
1471
1472 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001473 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001474 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001475
1476 case IgnorePCH:
1477 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001478 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001479 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001480 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001481 First = false;
Douglas Gregor8038d512009-04-10 17:25:41 +00001482 continue;
1483 }
1484
1485 if (Code == llvm::bitc::DEFINE_ABBREV) {
1486 Stream.ReadAbbrevRecord();
1487 continue;
1488 }
1489
1490 // Read and process a record.
1491 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001492 const char *BlobStart = 0;
1493 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001494 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001495 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001496 default: // Default behavior: ignore.
1497 break;
1498
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001499 case pch::METADATA: {
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001500 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001501 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1502 : diag::warn_pch_version_too_new);
1503 return IgnorePCH;
1504 }
1505
1506 RelocatablePCH = Record[4];
1507 if (Listener) {
1508 std::string TargetTriple(BlobStart, BlobLen);
1509 if (Listener->ReadTargetTriple(TargetTriple))
1510 return IgnorePCH;
1511 }
1512 break;
1513 }
1514
1515 case pch::CHAINED_METADATA: {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001516 if (!First) {
1517 Error("CHAINED_METADATA is not first record in block");
1518 return Failure;
1519 }
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001520 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001521 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1522 : diag::warn_pch_version_too_new);
1523 return IgnorePCH;
1524 }
1525
1526 // Load the chained file.
1527 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1528 case Failure: return Failure;
1529 // If we have to ignore the dependency, we'll have to ignore this too.
1530 case IgnorePCH: return IgnorePCH;
1531 case Success: break;
1532 }
1533 break;
1534 }
1535
Douglas Gregor8038d512009-04-10 17:25:41 +00001536 case pch::TYPE_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001537 if (F.LocalNumTypes != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001538 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001539 return Failure;
1540 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001541 F.TypeOffsets = (const uint32_t *)BlobStart;
1542 F.LocalNumTypes = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001543 break;
1544
1545 case pch::DECL_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001546 if (F.LocalNumDecls != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001547 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001548 return Failure;
1549 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001550 F.DeclOffsets = (const uint32_t *)BlobStart;
1551 F.LocalNumDecls = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001552 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001553
Sebastian Redld692af72010-07-27 18:24:41 +00001554 case pch::TU_UPDATE_LEXICAL: {
1555 DeclContextInfo Info = {
1556 /* No visible information */ 0, 0,
1557 reinterpret_cast<const pch::DeclID *>(BlobStart),
1558 BlobLen / sizeof(pch::DeclID)
1559 };
1560 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1561 break;
1562 }
1563
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00001564 case pch::REDECLS_UPDATE_LATEST: {
1565 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1566 for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
1567 pch::DeclID First = Record[i], Latest = Record[i+1];
1568 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
1569 Latest > FirstLatestDeclIDs[First]) &&
1570 "The new latest is supposed to come after the previous latest");
1571 FirstLatestDeclIDs[First] = Latest;
1572 }
1573 break;
1574 }
1575
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001576 case pch::LANGUAGE_OPTIONS:
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001577 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001578 return IgnorePCH;
1579 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001580
Douglas Gregorafaf3082009-04-11 00:14:32 +00001581 case pch::IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001582 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001583 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001584 F.IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001585 = PCHIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001586 (const unsigned char *)F.IdentifierTableData + Record[0],
1587 (const unsigned char *)F.IdentifierTableData,
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001588 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001589 if (PP)
1590 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001591 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001592 break;
1593
1594 case pch::IDENTIFIER_OFFSET:
Sebastian Redl2da08f92010-07-19 22:28:42 +00001595 if (F.LocalNumIdentifiers != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001596 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001597 return Failure;
1598 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001599 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1600 F.LocalNumIdentifiers = Record[0];
Douglas Gregorafaf3082009-04-11 00:14:32 +00001601 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001602
1603 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001604 // Optimization for the first block.
1605 if (ExternalDefinitions.empty())
1606 ExternalDefinitions.swap(Record);
1607 else
1608 ExternalDefinitions.insert(ExternalDefinitions.end(),
1609 Record.begin(), Record.end());
Douglas Gregorfdd01722009-04-14 00:24:19 +00001610 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001611
Douglas Gregorad1de002009-04-18 05:55:16 +00001612 case pch::SPECIAL_TYPES:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001613 // Optimization for the first block
1614 if (SpecialTypes.empty())
1615 SpecialTypes.swap(Record);
1616 else
1617 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregorad1de002009-04-18 05:55:16 +00001618 break;
1619
Douglas Gregor3e1af842009-04-17 22:13:46 +00001620 case pch::STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001621 TotalNumStatements += Record[0];
1622 TotalNumMacros += Record[1];
1623 TotalLexicalDeclContexts += Record[2];
1624 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001625 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001626
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001627 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001628 // Optimization for the first block.
1629 if (TentativeDefinitions.empty())
1630 TentativeDefinitions.swap(Record);
1631 else
1632 TentativeDefinitions.insert(TentativeDefinitions.end(),
1633 Record.begin(), Record.end());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001634 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001635
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001636 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001637 // Optimization for the first block.
1638 if (UnusedStaticFuncs.empty())
1639 UnusedStaticFuncs.swap(Record);
1640 else
1641 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1642 Record.begin(), Record.end());
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001643 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001644
Douglas Gregor14c22f22009-04-22 22:18:58 +00001645 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001646 // Optimization for the first block.
1647 if (LocallyScopedExternalDecls.empty())
1648 LocallyScopedExternalDecls.swap(Record);
1649 else
1650 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1651 Record.begin(), Record.end());
Douglas Gregor14c22f22009-04-22 22:18:58 +00001652 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001653
Douglas Gregor83941df2009-04-25 17:48:32 +00001654 case pch::SELECTOR_OFFSETS:
Sebastian Redl059612d2010-08-03 21:58:15 +00001655 F.SelectorOffsets = (const uint32_t *)BlobStart;
Sebastian Redl725cd962010-08-04 20:40:17 +00001656 F.LocalNumSelectors = Record[0];
Douglas Gregor83941df2009-04-25 17:48:32 +00001657 break;
1658
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001659 case pch::METHOD_POOL:
Sebastian Redl725cd962010-08-04 20:40:17 +00001660 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
Douglas Gregor83941df2009-04-25 17:48:32 +00001661 if (Record[0])
Sebastian Redl725cd962010-08-04 20:40:17 +00001662 F.SelectorLookupTable
1663 = PCHSelectorLookupTable::Create(
1664 F.SelectorLookupTableData + Record[0],
1665 F.SelectorLookupTableData,
1666 PCHSelectorLookupTrait(*this));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00001667 TotalNumMethodPoolEntries += Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001668 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001669
Fariborz Jahanian32019832010-07-23 19:11:11 +00001670 case pch::REFERENCED_SELECTOR_POOL: {
Sebastian Redl725cd962010-08-04 20:40:17 +00001671 ReferencedSelectorsData.insert(ReferencedSelectorsData.end(),
1672 Record.begin(), Record.end());
Fariborz Jahanian32019832010-07-23 19:11:11 +00001673 break;
Sebastian Redl681d7232010-07-27 00:17:23 +00001674 }
Fariborz Jahanian32019832010-07-23 19:11:11 +00001675
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001676 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001677 if (!Record.empty() && Listener)
1678 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001679 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001680
1681 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001682 F.SLocOffsets = (const uint32_t *)BlobStart;
1683 F.LocalNumSLocEntries = Record[0];
1684 // We cannot delay this until all PCHs are loaded, because then source
1685 // location preloads would also have to be delayed.
1686 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001687 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001688 break;
1689
1690 case pch::SOURCE_LOCATION_PRELOADS:
1691 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1692 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1693 if (Result != Success)
1694 return Result;
1695 }
1696 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001697
Douglas Gregor52e71082009-10-16 18:18:30 +00001698 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001699 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001700 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1701 (const unsigned char *)BlobStart,
1702 NumStatHits, NumStatMisses);
1703 FileMgr.addStatCache(MyStatCache);
Sebastian Redl9137a522010-07-16 17:50:48 +00001704 F.StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001705 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001706 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001707
Douglas Gregorb81c1702009-04-27 20:06:05 +00001708 case pch::EXT_VECTOR_DECLS:
Sebastian Redla9f23682010-07-28 21:38:49 +00001709 // Optimization for the first block.
1710 if (ExtVectorDecls.empty())
1711 ExtVectorDecls.swap(Record);
1712 else
1713 ExtVectorDecls.insert(ExtVectorDecls.end(),
1714 Record.begin(), Record.end());
Douglas Gregorb81c1702009-04-27 20:06:05 +00001715 break;
1716
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001717 case pch::VTABLE_USES:
1718 if (!VTableUses.empty()) {
1719 Error("duplicate VTABLE_USES record in PCH file");
1720 return Failure;
1721 }
1722 VTableUses.swap(Record);
1723 break;
1724
1725 case pch::DYNAMIC_CLASSES:
1726 if (!DynamicClasses.empty()) {
1727 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1728 return Failure;
1729 }
1730 DynamicClasses.swap(Record);
1731 break;
1732
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001733 case pch::SEMA_DECL_REFS:
1734 if (!SemaDeclRefs.empty()) {
1735 Error("duplicate SEMA_DECL_REFS record in PCH file");
1736 return Failure;
1737 }
1738 SemaDeclRefs.swap(Record);
1739 break;
1740
Douglas Gregorb64c1932009-05-12 01:31:05 +00001741 case pch::ORIGINAL_FILE_NAME:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001742 // The primary PCH will be the last to get here, so it will be the one
1743 // that's used.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001744 ActualOriginalFileName.assign(BlobStart, BlobLen);
1745 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001746 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001747 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001749 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001750 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001751 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001752 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001753 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1754 return IgnorePCH;
1755 }
1756 break;
1757 }
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001758
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001759 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001760 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1761 F.NumPreallocatedPreprocessingEntities = Record[0];
1762 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001763 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001764 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001765 First = false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001766 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001767 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001768 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001769}
1770
Douglas Gregore1d918e2009-04-10 23:10:45 +00001771PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001772 switch(ReadPCHCore(FileName)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001773 case Failure: return Failure;
1774 case IgnorePCH: return IgnorePCH;
1775 case Success: break;
1776 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001777
1778 // Here comes stuff that we only do once the entire chain is loaded.
1779
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001780 // Allocate space for loaded identifiers, decls and types.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001781 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
Sebastian Redl725cd962010-08-04 20:40:17 +00001782 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
1783 TotalNumSelectors = 0;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001784 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redl2da08f92010-07-19 22:28:42 +00001785 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001786 TotalNumTypes += Chain[I]->LocalNumTypes;
1787 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001788 TotalNumPreallocatedPreprocessingEntities +=
1789 Chain[I]->NumPreallocatedPreprocessingEntities;
1790 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redl725cd962010-08-04 20:40:17 +00001791 TotalNumSelectors += Chain[I]->LocalNumSelectors;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001792 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001793 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001794 TypesLoaded.resize(TotalNumTypes);
1795 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001796 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1797 if (PP) {
1798 if (TotalNumIdentifiers > 0)
1799 PP->getHeaderSearchInfo().SetExternalLookup(this);
1800 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1801 if (!PP->getPreprocessingRecord())
1802 PP->createPreprocessingRecord();
1803 PP->getPreprocessingRecord()->SetExternalSource(*this,
1804 TotalNumPreallocatedPreprocessingEntities);
1805 }
1806 }
Sebastian Redl725cd962010-08-04 20:40:17 +00001807 SelectorsLoaded.resize(TotalNumSelectors);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001808
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001809 // Check the predefines buffers.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001810 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001811 return IgnorePCH;
1812
1813 if (PP) {
1814 // Initialization of keywords and pragmas occurs before the
1815 // PCH file is read, so there may be some identifiers that were
1816 // loaded into the IdentifierTable before we intercepted the
1817 // creation of identifiers. Iterate through the list of known
1818 // identifiers and determine whether we have to establish
1819 // preprocessor definitions or top-level identifier declaration
1820 // chains for those identifiers.
1821 //
1822 // We copy the IdentifierInfo pointers to a small vector first,
1823 // since de-serializing declarations or macro definitions can add
1824 // new entries into the identifier table, invalidating the
1825 // iterators.
1826 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1827 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1828 IdEnd = PP->getIdentifierTable().end();
1829 Id != IdEnd; ++Id)
1830 Identifiers.push_back(Id->second);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001831 // We need to search the tables in all files.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001832 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1833 PCHIdentifierLookupTable *IdTable
1834 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00001835 // Not all PCH files necessarily have identifier tables, only the useful
1836 // ones.
1837 if (!IdTable)
1838 continue;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001839 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1840 IdentifierInfo *II = Identifiers[I];
1841 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001842 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001843 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001844 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1845 if (Pos == IdTable->end())
1846 continue;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001847
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001848 // Dereferencing the iterator has the effect of populating the
1849 // IdentifierInfo node with the various declarations it needs.
1850 (void)*Pos;
1851 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001852 }
1853 }
1854
1855 if (Context)
1856 InitializeContext(*Context);
1857
1858 return Success;
1859}
1860
1861PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1862 Chain.push_back(new PerFileData());
Sebastian Redl9137a522010-07-16 17:50:48 +00001863 PerFileData &F = *Chain.back();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001864
1865 // Set the PCH file name.
1866 F.FileName = FileName;
1867
1868 // Open the PCH file.
1869 //
1870 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1871 std::string ErrStr;
1872 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1873 if (!F.Buffer) {
1874 Error(ErrStr.c_str());
1875 return IgnorePCH;
1876 }
1877
1878 // Initialize the stream
1879 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1880 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl9137a522010-07-16 17:50:48 +00001881 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001882 Stream.init(F.StreamFile);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001883 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001884
1885 // Sniff for the signature.
1886 if (Stream.Read(8) != 'C' ||
1887 Stream.Read(8) != 'P' ||
1888 Stream.Read(8) != 'C' ||
1889 Stream.Read(8) != 'H') {
1890 Diag(diag::err_not_a_pch_file) << FileName;
1891 return Failure;
1892 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001893
Douglas Gregor2cf26342009-04-09 22:27:44 +00001894 while (!Stream.AtEndOfStream()) {
1895 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Douglas Gregore1d918e2009-04-10 23:10:45 +00001897 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001898 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001899 return Failure;
1900 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001901
1902 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001903
Douglas Gregor2cf26342009-04-09 22:27:44 +00001904 // We only know the PCH subblock ID.
1905 switch (BlockID) {
1906 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001907 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001908 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001909 return Failure;
1910 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001911 break;
1912 case pch::PCH_BLOCK_ID:
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001913 switch (ReadPCHBlock(F)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001914 case Success:
1915 break;
1916
1917 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001918 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001919
1920 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001921 // FIXME: We could consider reading through to the end of this
1922 // PCH block, skipping subblocks, to see if there are other
1923 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001924
1925 // Clear out any preallocated source location entries, so that
1926 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001927 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001928
1929 // Remove the stat cache.
Sebastian Redl9137a522010-07-16 17:50:48 +00001930 if (F.StatCache)
1931 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001932
Douglas Gregore1d918e2009-04-10 23:10:45 +00001933 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001934 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001935 break;
1936 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001937 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001938 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001939 return Failure;
1940 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001941 break;
1942 }
Mike Stump1eb44332009-09-09 15:08:12 +00001943 }
1944
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001945 return Success;
1946}
1947
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001948void PCHReader::setPreprocessor(Preprocessor &pp) {
1949 PP = &pp;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001950
1951 unsigned TotalNum = 0;
1952 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1953 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1954 if (TotalNum) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001955 if (!PP->getPreprocessingRecord())
1956 PP->createPreprocessingRecord();
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001957 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001958 }
1959}
1960
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001961void PCHReader::InitializeContext(ASTContext &Ctx) {
1962 Context = &Ctx;
1963 assert(Context && "Passed null context!");
1964
1965 assert(PP && "Forgot to set Preprocessor ?");
1966 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1967 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001968 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001969
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001970 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001971 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001972
1973 // Load the special types.
1974 Context->setBuiltinVaListType(
1975 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1976 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1977 Context->setObjCIdType(GetType(Id));
1978 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1979 Context->setObjCSelType(GetType(Sel));
1980 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1981 Context->setObjCProtoType(GetType(Proto));
1982 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1983 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001984
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001985 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1986 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001987 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001988 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1989 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001990 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1991 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001992 if (FileType.isNull()) {
1993 Error("FILE type is NULL");
1994 return;
1995 }
John McCall183700f2009-09-21 23:43:11 +00001996 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001997 Context->setFILEDecl(Typedef->getDecl());
1998 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001999 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002000 if (!Tag) {
2001 Error("Invalid FILE type in PCH file");
2002 return;
2003 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002004 Context->setFILEDecl(Tag->getDecl());
2005 }
2006 }
Mike Stump782fa302009-07-28 02:25:19 +00002007 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
2008 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002009 if (Jmp_bufType.isNull()) {
2010 Error("jmp_bug type is NULL");
2011 return;
2012 }
John McCall183700f2009-09-21 23:43:11 +00002013 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002014 Context->setjmp_bufDecl(Typedef->getDecl());
2015 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002016 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002017 if (!Tag) {
2018 Error("Invalid jmp_bug type in PCH file");
2019 return;
2020 }
Mike Stump782fa302009-07-28 02:25:19 +00002021 Context->setjmp_bufDecl(Tag->getDecl());
2022 }
2023 }
2024 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2025 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002026 if (Sigjmp_bufType.isNull()) {
2027 Error("sigjmp_buf type is NULL");
2028 return;
2029 }
John McCall183700f2009-09-21 23:43:11 +00002030 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002031 Context->setsigjmp_bufDecl(Typedef->getDecl());
2032 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002033 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00002034 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2035 Context->setsigjmp_bufDecl(Tag->getDecl());
2036 }
2037 }
Mike Stump1eb44332009-09-09 15:08:12 +00002038 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002039 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2040 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00002041 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002042 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2043 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00002044 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2045 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00002046 if (unsigned String
2047 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2048 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002049 if (unsigned ObjCSelRedef
2050 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2051 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2052 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2053 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00002054
2055 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2056 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002057}
2058
Douglas Gregorb64c1932009-05-12 01:31:05 +00002059/// \brief Retrieve the name of the original source file name
2060/// directly from the PCH file, without actually loading the PCH
2061/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002062std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2063 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00002064 // Open the PCH file.
2065 std::string ErrStr;
2066 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2067 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2068 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002069 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002070 return std::string();
2071 }
2072
2073 // Initialize the stream
2074 llvm::BitstreamReader StreamFile;
2075 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00002076 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00002077 (const unsigned char *)Buffer->getBufferEnd());
2078 Stream.init(StreamFile);
2079
2080 // Sniff for the signature.
2081 if (Stream.Read(8) != 'C' ||
2082 Stream.Read(8) != 'P' ||
2083 Stream.Read(8) != 'C' ||
2084 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002085 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002086 return std::string();
2087 }
2088
2089 RecordData Record;
2090 while (!Stream.AtEndOfStream()) {
2091 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Douglas Gregorb64c1932009-05-12 01:31:05 +00002093 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2094 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Douglas Gregorb64c1932009-05-12 01:31:05 +00002096 // We only know the PCH subblock ID.
2097 switch (BlockID) {
2098 case pch::PCH_BLOCK_ID:
2099 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002100 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002101 return std::string();
2102 }
2103 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Douglas Gregorb64c1932009-05-12 01:31:05 +00002105 default:
2106 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002107 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002108 return std::string();
2109 }
2110 break;
2111 }
2112 continue;
2113 }
2114
2115 if (Code == llvm::bitc::END_BLOCK) {
2116 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002117 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002118 return std::string();
2119 }
2120 continue;
2121 }
2122
2123 if (Code == llvm::bitc::DEFINE_ABBREV) {
2124 Stream.ReadAbbrevRecord();
2125 continue;
2126 }
2127
2128 Record.clear();
2129 const char *BlobStart = 0;
2130 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002131 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00002132 == pch::ORIGINAL_FILE_NAME)
2133 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00002134 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00002135
2136 return std::string();
2137}
2138
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002139/// \brief Parse the record that corresponds to a LangOptions data
2140/// structure.
2141///
2142/// This routine compares the language options used to generate the
2143/// PCH file against the language options set for the current
2144/// compilation. For each option, we classify differences between the
2145/// two compiler states as either "benign" or "important". Benign
2146/// differences don't matter, and we accept them without complaint
2147/// (and without modifying the language options). Differences between
2148/// the states for important options cause the PCH file to be
2149/// unusable, so we emit a warning and return true to indicate that
2150/// there was an error.
2151///
2152/// \returns true if the PCH file is unacceptable, false otherwise.
2153bool PCHReader::ParseLanguageOptions(
2154 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002155 if (Listener) {
2156 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002158 #define PARSE_LANGOPT(Option) \
2159 LangOpts.Option = Record[Idx]; \
2160 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002162 unsigned Idx = 0;
2163 PARSE_LANGOPT(Trigraphs);
2164 PARSE_LANGOPT(BCPLComment);
2165 PARSE_LANGOPT(DollarIdents);
2166 PARSE_LANGOPT(AsmPreprocessor);
2167 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00002168 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002169 PARSE_LANGOPT(ImplicitInt);
2170 PARSE_LANGOPT(Digraphs);
2171 PARSE_LANGOPT(HexFloats);
2172 PARSE_LANGOPT(C99);
2173 PARSE_LANGOPT(Microsoft);
2174 PARSE_LANGOPT(CPlusPlus);
2175 PARSE_LANGOPT(CPlusPlus0x);
2176 PARSE_LANGOPT(CXXOperatorNames);
2177 PARSE_LANGOPT(ObjC1);
2178 PARSE_LANGOPT(ObjC2);
2179 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002180 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00002181 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002182 PARSE_LANGOPT(PascalStrings);
2183 PARSE_LANGOPT(WritableStrings);
2184 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002185 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002186 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002187 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002188 PARSE_LANGOPT(NeXTRuntime);
2189 PARSE_LANGOPT(Freestanding);
2190 PARSE_LANGOPT(NoBuiltin);
2191 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002192 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002193 PARSE_LANGOPT(Blocks);
2194 PARSE_LANGOPT(EmitAllDecls);
2195 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002196 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2197 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002198 PARSE_LANGOPT(HeinousExtensions);
2199 PARSE_LANGOPT(Optimize);
2200 PARSE_LANGOPT(OptimizeSize);
2201 PARSE_LANGOPT(Static);
2202 PARSE_LANGOPT(PICLevel);
2203 PARSE_LANGOPT(GNUInline);
2204 PARSE_LANGOPT(NoInline);
2205 PARSE_LANGOPT(AccessControl);
2206 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002207 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002208 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2209 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002210 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002211 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002212 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002213 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002214 PARSE_LANGOPT(CatchUndefined);
2215 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002216 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002217
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002218 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002219 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002220
2221 return false;
2222}
2223
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002224void PCHReader::ReadPreprocessedEntities() {
2225 ReadDefinedMacros();
2226}
2227
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002228/// \brief Get the correct cursor and offset for loading a type.
2229PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2230 PerFileData *F = 0;
2231 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2232 F = Chain[N - I - 1];
2233 if (Index < F->LocalNumTypes)
2234 break;
2235 Index -= F->LocalNumTypes;
2236 }
2237 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redl971dd442010-07-20 22:55:31 +00002238 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002239}
2240
2241/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00002242///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002243/// The index is the type ID, shifted and minus the number of predefs. This
2244/// routine actually reads the record corresponding to the type at the given
2245/// location. It is a helper routine for GetType, which deals with reading type
2246/// IDs.
2247QualType PCHReader::ReadTypeRecord(unsigned Index) {
2248 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redl971dd442010-07-20 22:55:31 +00002249 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl9137a522010-07-16 17:50:48 +00002250
Douglas Gregor0b748912009-04-14 21:18:50 +00002251 // Keep track of where we are in the stream, then jump back there
2252 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002253 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002254
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002255 ReadingKindTracker ReadingKind(Read_Type, *this);
2256
Douglas Gregord89275b2009-07-06 18:54:52 +00002257 // Note that we are loading a type record.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00002258 Deserializing AType(this);
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002260 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002261 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002262 unsigned Code = DeclsCursor.ReadCode();
2263 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002264 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002265 if (Record.size() != 2) {
2266 Error("Incorrect encoding of extended qualifier type");
2267 return QualType();
2268 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002269 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002270 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2271 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002272 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002273
Douglas Gregor2cf26342009-04-09 22:27:44 +00002274 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002275 if (Record.size() != 1) {
2276 Error("Incorrect encoding of complex type");
2277 return QualType();
2278 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002279 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002280 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002281 }
2282
2283 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002284 if (Record.size() != 1) {
2285 Error("Incorrect encoding of pointer type");
2286 return QualType();
2287 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002288 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002289 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002290 }
2291
2292 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002293 if (Record.size() != 1) {
2294 Error("Incorrect encoding of block pointer type");
2295 return QualType();
2296 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002297 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002298 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002299 }
2300
2301 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002302 if (Record.size() != 1) {
2303 Error("Incorrect encoding of lvalue reference type");
2304 return QualType();
2305 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002306 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002307 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002308 }
2309
2310 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002311 if (Record.size() != 1) {
2312 Error("Incorrect encoding of rvalue reference type");
2313 return QualType();
2314 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002315 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002316 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002317 }
2318
2319 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002320 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002321 Error("Incorrect encoding of member pointer type");
2322 return QualType();
2323 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002324 QualType PointeeType = GetType(Record[0]);
2325 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002326 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002327 }
2328
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002329 case pch::TYPE_CONSTANT_ARRAY: {
2330 QualType ElementType = GetType(Record[0]);
2331 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2332 unsigned IndexTypeQuals = Record[2];
2333 unsigned Idx = 3;
2334 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002335 return Context->getConstantArrayType(ElementType, Size,
2336 ASM, IndexTypeQuals);
2337 }
2338
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002339 case pch::TYPE_INCOMPLETE_ARRAY: {
2340 QualType ElementType = GetType(Record[0]);
2341 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2342 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002343 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002344 }
2345
2346 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002347 QualType ElementType = GetType(Record[0]);
2348 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2349 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002350 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2351 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redl577d4792010-07-22 22:43:28 +00002352 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002353 ASM, IndexTypeQuals,
2354 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002355 }
2356
2357 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002358 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002359 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002360 return QualType();
2361 }
2362
2363 QualType ElementType = GetType(Record[0]);
2364 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002365 unsigned AltiVecSpec = Record[2];
2366 return Context->getVectorType(ElementType, NumElements,
2367 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002368 }
2369
2370 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002371 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002372 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002373 return QualType();
2374 }
2375
2376 QualType ElementType = GetType(Record[0]);
2377 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002378 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002379 }
2380
2381 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002382 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002383 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002384 return QualType();
2385 }
2386 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002387 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002388 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002389 }
2390
2391 case pch::TYPE_FUNCTION_PROTO: {
2392 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002393 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002394 unsigned RegParm = Record[2];
2395 CallingConv CallConv = (CallingConv)Record[3];
2396 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002397 unsigned NumParams = Record[Idx++];
2398 llvm::SmallVector<QualType, 16> ParamTypes;
2399 for (unsigned I = 0; I != NumParams; ++I)
2400 ParamTypes.push_back(GetType(Record[Idx++]));
2401 bool isVariadic = Record[Idx++];
2402 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002403 bool hasExceptionSpec = Record[Idx++];
2404 bool hasAnyExceptionSpec = Record[Idx++];
2405 unsigned NumExceptions = Record[Idx++];
2406 llvm::SmallVector<QualType, 2> Exceptions;
2407 for (unsigned I = 0; I != NumExceptions; ++I)
2408 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002409 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002410 isVariadic, Quals, hasExceptionSpec,
2411 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002412 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002413 FunctionType::ExtInfo(NoReturn, RegParm,
2414 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002415 }
2416
John McCalled976492009-12-04 22:46:56 +00002417 case pch::TYPE_UNRESOLVED_USING:
2418 return Context->getTypeDeclType(
2419 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2420
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002421 case pch::TYPE_TYPEDEF: {
2422 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002423 Error("incorrect encoding of typedef type");
2424 return QualType();
2425 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002426 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2427 QualType Canonical = GetType(Record[1]);
2428 return Context->getTypedefType(Decl, Canonical);
2429 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002430
2431 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redl577d4792010-07-22 22:43:28 +00002432 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002433
2434 case pch::TYPE_TYPEOF: {
2435 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002436 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002437 return QualType();
2438 }
2439 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002440 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002441 }
Mike Stump1eb44332009-09-09 15:08:12 +00002442
Anders Carlsson395b4752009-06-24 19:06:50 +00002443 case pch::TYPE_DECLTYPE:
Sebastian Redl577d4792010-07-22 22:43:28 +00002444 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson395b4752009-06-24 19:06:50 +00002445
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002446 case pch::TYPE_RECORD: {
2447 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002448 Error("incorrect encoding of record type");
2449 return QualType();
2450 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002451 bool IsDependent = Record[0];
2452 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2453 T->Dependent = IsDependent;
2454 return T;
2455 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002456
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002457 case pch::TYPE_ENUM: {
2458 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002459 Error("incorrect encoding of enum type");
2460 return QualType();
2461 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002462 bool IsDependent = Record[0];
2463 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2464 T->Dependent = IsDependent;
2465 return T;
2466 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002467
John McCall7da24312009-09-05 00:15:47 +00002468 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002469 unsigned Idx = 0;
2470 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2471 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2472 QualType NamedType = GetType(Record[Idx++]);
2473 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002474 }
2475
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002476 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002477 unsigned Idx = 0;
2478 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002479 return Context->getObjCInterfaceType(ItfD);
2480 }
2481
2482 case pch::TYPE_OBJC_OBJECT: {
2483 unsigned Idx = 0;
2484 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002485 unsigned NumProtos = Record[Idx++];
2486 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2487 for (unsigned I = 0; I != NumProtos; ++I)
2488 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002489 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002490 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002491
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002492 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002493 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002494 QualType Pointee = GetType(Record[Idx++]);
2495 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002496 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002497
John McCall49a832b2009-10-18 09:09:24 +00002498 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2499 unsigned Idx = 0;
2500 QualType Parm = GetType(Record[Idx++]);
2501 QualType Replacement = GetType(Record[Idx++]);
2502 return
2503 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2504 Replacement);
2505 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002506
2507 case pch::TYPE_INJECTED_CLASS_NAME: {
2508 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2509 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002510 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2511 // for PCH reading, too much interdependencies.
2512 return
2513 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002514 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002515
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002516 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2517 unsigned Idx = 0;
2518 unsigned Depth = Record[Idx++];
2519 unsigned Index = Record[Idx++];
2520 bool Pack = Record[Idx++];
2521 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2522 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2523 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002524
2525 case pch::TYPE_DEPENDENT_NAME: {
2526 unsigned Idx = 0;
2527 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2528 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2529 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002530 QualType Canon = GetType(Record[Idx++]);
2531 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002532 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002533
2534 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2535 unsigned Idx = 0;
2536 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2537 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2538 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2539 unsigned NumArgs = Record[Idx++];
2540 llvm::SmallVector<TemplateArgument, 8> Args;
2541 Args.reserve(NumArgs);
2542 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00002543 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002544 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2545 Args.size(), Args.data());
2546 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002547
2548 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2549 unsigned Idx = 0;
2550
2551 // ArrayType
2552 QualType ElementType = GetType(Record[Idx++]);
2553 ArrayType::ArraySizeModifier ASM
2554 = (ArrayType::ArraySizeModifier)Record[Idx++];
2555 unsigned IndexTypeQuals = Record[Idx++];
2556
2557 // DependentSizedArrayType
Sebastian Redl577d4792010-07-22 22:43:28 +00002558 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002559 SourceRange Brackets = ReadSourceRange(Record, Idx);
2560
2561 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2562 IndexTypeQuals, Brackets);
2563 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002564
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002565 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2566 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002567 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002568 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002569 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redl577d4792010-07-22 22:43:28 +00002570 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002571 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002572 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002573 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002574 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2575 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002576 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002577 T = Context->getTemplateSpecializationType(Name, Args.data(),
2578 Args.size(), Canon);
2579 T->Dependent = IsDependent;
2580 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002581 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002582 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002583 // Suppress a GCC warning
2584 return QualType();
2585}
2586
John McCalla1ee0c52009-10-16 21:56:05 +00002587namespace {
2588
2589class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2590 PCHReader &Reader;
Sebastian Redl577d4792010-07-22 22:43:28 +00002591 llvm::BitstreamCursor &DeclsCursor;
John McCalla1ee0c52009-10-16 21:56:05 +00002592 const PCHReader::RecordData &Record;
2593 unsigned &Idx;
2594
2595public:
Sebastian Redl577d4792010-07-22 22:43:28 +00002596 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2597 const PCHReader::RecordData &Record, unsigned &Idx)
2598 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCalla1ee0c52009-10-16 21:56:05 +00002599
John McCall51bd8032009-10-18 01:05:36 +00002600 // We want compile-time assurance that we've enumerated all of
2601 // these, so unfortunately we have to declare them first, then
2602 // define them out-of-line.
2603#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002604#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002605 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002606#include "clang/AST/TypeLocNodes.def"
2607
John McCall51bd8032009-10-18 01:05:36 +00002608 void VisitFunctionTypeLoc(FunctionTypeLoc);
2609 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002610};
2611
2612}
2613
John McCall51bd8032009-10-18 01:05:36 +00002614void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002615 // nothing to do
2616}
John McCall51bd8032009-10-18 01:05:36 +00002617void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002618 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2619 if (TL.needsExtraLocalData()) {
2620 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2621 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2622 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2623 TL.setModeAttr(Record[Idx++]);
2624 }
John McCalla1ee0c52009-10-16 21:56:05 +00002625}
John McCall51bd8032009-10-18 01:05:36 +00002626void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2627 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002628}
John McCall51bd8032009-10-18 01:05:36 +00002629void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2630 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002631}
John McCall51bd8032009-10-18 01:05:36 +00002632void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2633 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002634}
John McCall51bd8032009-10-18 01:05:36 +00002635void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2636 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002637}
John McCall51bd8032009-10-18 01:05:36 +00002638void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2639 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002640}
John McCall51bd8032009-10-18 01:05:36 +00002641void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2642 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002643}
John McCall51bd8032009-10-18 01:05:36 +00002644void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2645 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2646 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002647 if (Record[Idx++])
Sebastian Redl577d4792010-07-22 22:43:28 +00002648 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002649 else
John McCall51bd8032009-10-18 01:05:36 +00002650 TL.setSizeExpr(0);
2651}
2652void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2653 VisitArrayTypeLoc(TL);
2654}
2655void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2656 VisitArrayTypeLoc(TL);
2657}
2658void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2659 VisitArrayTypeLoc(TL);
2660}
2661void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2662 DependentSizedArrayTypeLoc TL) {
2663 VisitArrayTypeLoc(TL);
2664}
2665void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2666 DependentSizedExtVectorTypeLoc TL) {
2667 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2668}
2669void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2670 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2671}
2672void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2673 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2674}
2675void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2676 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2677 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2678 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002679 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002680 }
2681}
2682void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2683 VisitFunctionTypeLoc(TL);
2684}
2685void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2686 VisitFunctionTypeLoc(TL);
2687}
John McCalled976492009-12-04 22:46:56 +00002688void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2689 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2690}
John McCall51bd8032009-10-18 01:05:36 +00002691void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2692 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2693}
2694void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002695 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2696 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2697 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002698}
2699void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002700 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2701 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2702 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redl577d4792010-07-22 22:43:28 +00002703 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002704}
2705void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2706 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2707}
2708void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2709 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2710}
2711void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2712 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2713}
John McCall51bd8032009-10-18 01:05:36 +00002714void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2715 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2716}
John McCall49a832b2009-10-18 09:09:24 +00002717void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2718 SubstTemplateTypeParmTypeLoc TL) {
2719 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2720}
John McCall51bd8032009-10-18 01:05:36 +00002721void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2722 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002723 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2724 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2725 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2726 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2727 TL.setArgLocInfo(i,
2728 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002729 DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002730}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002731void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002732 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2733 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002734}
John McCall3cb0ebd2010-03-10 03:28:59 +00002735void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2736 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2737}
Douglas Gregor4714c122010-03-31 17:34:00 +00002738void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002739 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2740 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002741 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2742}
John McCall33500952010-06-11 00:33:02 +00002743void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2744 DependentTemplateSpecializationTypeLoc TL) {
2745 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2746 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2747 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2748 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2749 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2750 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2751 TL.setArgLocInfo(I,
2752 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002753 DeclsCursor, Record, Idx));
John McCall33500952010-06-11 00:33:02 +00002754}
John McCall51bd8032009-10-18 01:05:36 +00002755void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2756 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002757}
2758void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2759 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002760 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2761 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2762 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2763 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002764}
John McCall54e14c42009-10-22 22:37:11 +00002765void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2766 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002767}
John McCalla1ee0c52009-10-16 21:56:05 +00002768
Sebastian Redl577d4792010-07-22 22:43:28 +00002769TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2770 const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002771 unsigned &Idx) {
2772 QualType InfoTy = GetType(Record[Idx++]);
2773 if (InfoTy.isNull())
2774 return 0;
2775
John McCalla93c9342009-12-07 02:54:59 +00002776 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redl577d4792010-07-22 22:43:28 +00002777 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002778 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002779 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002780 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002781}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002782
Douglas Gregor8038d512009-04-10 17:25:41 +00002783QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002784 unsigned FastQuals = ID & Qualifiers::FastMask;
2785 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002786
2787 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2788 QualType T;
2789 switch ((pch::PredefinedTypeIDs)Index) {
2790 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002791 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2792 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002793
2794 case pch::PREDEF_TYPE_CHAR_U_ID:
2795 case pch::PREDEF_TYPE_CHAR_S_ID:
2796 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002797 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002798 break;
2799
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002800 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2801 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2802 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2803 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2804 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002805 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002806 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2807 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2808 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2809 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2810 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2811 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002812 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002813 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2814 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2815 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2816 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2817 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002818 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002819 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2820 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002821 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2822 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002823 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002824 }
2825
2826 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002827 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002828 }
2829
2830 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002831 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002832 if (TypesLoaded[Index].isNull()) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002833 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002834 TypesLoaded[Index]->setFromPCH();
Sebastian Redl30c514c2010-07-14 23:45:08 +00002835 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002836 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2837 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002838 }
Mike Stump1eb44332009-09-09 15:08:12 +00002839
John McCall0953e762009-09-24 19:53:00 +00002840 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002841}
2842
John McCall833ca992009-10-29 08:12:44 +00002843TemplateArgumentLocInfo
2844PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redl577d4792010-07-22 22:43:28 +00002845 llvm::BitstreamCursor &DeclsCursor,
John McCall833ca992009-10-29 08:12:44 +00002846 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002847 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002848 switch (Kind) {
2849 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00002850 return ReadExpr(DeclsCursor);
John McCall833ca992009-10-29 08:12:44 +00002851 case TemplateArgument::Type:
Sebastian Redl577d4792010-07-22 22:43:28 +00002852 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002853 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002854 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2855 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2856 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002857 }
John McCall833ca992009-10-29 08:12:44 +00002858 case TemplateArgument::Null:
2859 case TemplateArgument::Integral:
2860 case TemplateArgument::Declaration:
2861 case TemplateArgument::Pack:
2862 return TemplateArgumentLocInfo();
2863 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002864 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002865 return TemplateArgumentLocInfo();
2866}
2867
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002868TemplateArgumentLoc
Sebastian Redl577d4792010-07-22 22:43:28 +00002869PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2870 const RecordData &Record, unsigned &Index) {
2871 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002872
2873 if (Arg.getKind() == TemplateArgument::Expression) {
2874 if (Record[Index++]) // bool InfoHasSameExpr.
2875 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2876 }
2877 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002878 DeclsCursor,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002879 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002880}
2881
John McCall76bd1f32010-06-01 09:23:16 +00002882Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2883 return GetDecl(ID);
2884}
2885
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002886TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl30c514c2010-07-14 23:45:08 +00002887 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00002888 ReadDeclRecord(0, 0);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002889 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002890 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002891 }
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002892
2893 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2894}
2895
Douglas Gregor8038d512009-04-10 17:25:41 +00002896Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002897 if (ID == 0)
2898 return 0;
2899
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002900 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002901 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002902 return 0;
2903 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002904
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002905 unsigned Index = ID - 1;
Sebastian Redl30c514c2010-07-14 23:45:08 +00002906 if (!DeclsLoaded[Index]) {
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00002907 ReadDeclRecord(Index, ID);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002908 if (DeserializationListener)
2909 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2910 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002911
2912 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002913}
2914
Chris Lattner887e2b32009-04-27 05:46:25 +00002915/// \brief Resolve the offset of a statement into a statement.
2916///
2917/// This operation will read a new statement from the external
2918/// source each time it is called, and is meant to be used via a
2919/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002920Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002921 // Offset here is a global offset across the entire chain.
2922 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2923 PerFileData &F = *Chain[N - I - 1];
2924 if (Offset < F.SizeInBits) {
2925 // Since we know that this statement is part of a decl, make sure to use
2926 // the decl cursor to read it.
2927 F.DeclsCursor.JumpToBit(Offset);
2928 return ReadStmtFromStream(F.DeclsCursor);
2929 }
2930 Offset -= F.SizeInBits;
2931 }
2932 llvm_unreachable("Broken chain");
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002933}
2934
John McCall76bd1f32010-06-01 09:23:16 +00002935bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2936 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002937 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002938 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002939
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002940 // There might be lexical decls in multiple parts of the chain, for the TU
2941 // at least.
2942 DeclContextInfos &Infos = DeclContextOffsets[DC];
2943 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2944 I != E; ++I) {
Sebastian Redl681d7232010-07-27 00:17:23 +00002945 // IDs can be 0 if this context doesn't contain declarations.
2946 if (!I->LexicalDecls)
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002947 continue;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002948
2949 // Load all of the declaration IDs
Sebastian Redl681d7232010-07-27 00:17:23 +00002950 for (const pch::DeclID *ID = I->LexicalDecls,
2951 *IDE = ID + I->NumLexicalDecls;
2952 ID != IDE; ++ID)
2953 Decls.push_back(GetDecl(*ID));
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002954 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002955
Douglas Gregor25123082009-04-22 22:34:57 +00002956 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002957 return false;
2958}
2959
John McCall76bd1f32010-06-01 09:23:16 +00002960DeclContext::lookup_result
2961PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2962 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002963 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002964 "DeclContext has no visible decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002965
John McCall76bd1f32010-06-01 09:23:16 +00002966 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002967 // There might be lexical decls in multiple parts of the chain, for the TU
2968 // and namespaces.
2969 DeclContextInfos &Infos = DeclContextOffsets[DC];
2970 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2971 I != E; ++I) {
2972 uint64_t Offset = I->OffsetToVisibleDecls;
2973 if (Offset == 0)
2974 continue;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002975
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002976 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002977
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002978 // Keep track of where we are in the stream, then jump back there
2979 // after reading this context.
2980 SavedStreamPosition SavedPosition(DeclsCursor);
2981
2982 // Load the record containing all of the declarations visible in
2983 // this context.
2984 DeclsCursor.JumpToBit(Offset);
2985 RecordData Record;
2986 unsigned Code = DeclsCursor.ReadCode();
2987 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
2988 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2989 Error("Expected visible block");
2990 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2991 DeclContext::lookup_iterator());
2992 }
2993
2994 if (Record.empty())
2995 continue;
2996
2997 unsigned Idx = 0;
2998 while (Idx < Record.size()) {
2999 Decls.push_back(VisibleDeclaration());
3000 Decls.back().Name = ReadDeclarationName(Record, Idx);
3001
3002 unsigned Size = Record[Idx++];
3003 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
3004 LoadedDecls.reserve(Size);
3005 for (unsigned J = 0; J < Size; ++J)
3006 LoadedDecls.push_back(Record[Idx++]);
3007 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003008 }
3009
Douglas Gregor25123082009-04-22 22:34:57 +00003010 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00003011
3012 SetExternalVisibleDecls(DC, Decls);
3013 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00003014}
3015
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003016void PCHReader::PassInterestingDeclsToConsumer() {
3017 assert(Consumer);
3018 while (!InterestingDecls.empty()) {
3019 DeclGroupRef DG(InterestingDecls.front());
3020 InterestingDecls.pop_front();
3021 Consumer->HandleTopLevelDecl(DG);
3022 }
3023}
3024
Douglas Gregorfdd01722009-04-14 00:24:19 +00003025void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00003026 this->Consumer = Consumer;
3027
Douglas Gregorfdd01722009-04-14 00:24:19 +00003028 if (!Consumer)
3029 return;
3030
3031 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003032 // Force deserialization of this decl, which will cause it to be queued for
3033 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00003034 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00003035 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00003036
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003037 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00003038}
3039
Douglas Gregor2cf26342009-04-09 22:27:44 +00003040void PCHReader::PrintStats() {
3041 std::fprintf(stderr, "*** PCH Statistics:\n");
3042
Mike Stump1eb44332009-09-09 15:08:12 +00003043 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003044 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00003045 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003046 unsigned NumDeclsLoaded
3047 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3048 (Decl *)0);
3049 unsigned NumIdentifiersLoaded
3050 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3051 IdentifiersLoaded.end(),
3052 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00003053 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003054 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3055 SelectorsLoaded.end(),
3056 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00003057
Douglas Gregor4fed3f42009-04-27 18:38:38 +00003058 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3059 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003060 if (TotalNumSLocEntries)
3061 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3062 NumSLocEntriesRead, TotalNumSLocEntries,
3063 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003064 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003065 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003066 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3067 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3068 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003069 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003070 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3071 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003072 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003073 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003074 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3075 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Sebastian Redl725cd962010-08-04 20:40:17 +00003076 if (!SelectorsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003077 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
Sebastian Redl725cd962010-08-04 20:40:17 +00003078 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3079 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00003080 if (TotalNumStatements)
3081 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3082 NumStatementsRead, TotalNumStatements,
3083 ((float)NumStatementsRead/TotalNumStatements * 100));
3084 if (TotalNumMacros)
3085 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3086 NumMacrosRead, TotalNumMacros,
3087 ((float)NumMacrosRead/TotalNumMacros * 100));
3088 if (TotalLexicalDeclContexts)
3089 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3090 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3091 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3092 * 100));
3093 if (TotalVisibleDeclContexts)
3094 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3095 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3096 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3097 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003098 if (TotalNumMethodPoolEntries) {
Douglas Gregor83941df2009-04-25 17:48:32 +00003099 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003100 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
3101 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
Douglas Gregor83941df2009-04-25 17:48:32 +00003102 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003103 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
Douglas Gregor83941df2009-04-25 17:48:32 +00003104 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003105 std::fprintf(stderr, "\n");
3106}
3107
Douglas Gregor668c1a42009-04-21 22:25:48 +00003108void PCHReader::InitializeSema(Sema &S) {
3109 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003110 S.ExternalSource = this;
3111
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003112 // Makes sure any declarations that were deserialized "too early"
3113 // still get added to the identifier's declaration chains.
3114 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3115 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3116 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003117 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003118 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003119
3120 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00003121 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003122 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3123 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00003124 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003125 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00003126
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003127 // If there were any unused static functions, deserialize them and add to
3128 // Sema's list of unused static functions.
3129 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3130 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3131 SemaObj->UnusedStaticFuncs.push_back(FD);
3132 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00003133
3134 // If there were any locally-scoped external declarations,
3135 // deserialize them and add them to Sema's table of locally-scoped
3136 // external declarations.
3137 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3138 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3139 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3140 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00003141
3142 // If there were any ext_vector type declarations, deserialize them
3143 // and add them to Sema's vector of such declarations.
3144 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3145 SemaObj->ExtVectorDecls.push_back(
3146 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003147
3148 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3149 // Can we cut them down before writing them ?
3150
3151 // If there were any VTable uses, deserialize the information and add it
3152 // to Sema's vector and map of VTable uses.
Argyrios Kyrtzidisbe4ebcd2010-08-03 17:29:52 +00003153 if (!VTableUses.empty()) {
3154 unsigned Idx = 0;
3155 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3156 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3157 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3158 bool DefinitionRequired = VTableUses[Idx++];
3159 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3160 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3161 }
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003162 }
3163
3164 // If there were any dynamic classes declarations, deserialize them
3165 // and add them to Sema's vector of such declarations.
3166 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3167 SemaObj->DynamicClasses.push_back(
3168 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanian32019832010-07-23 19:11:11 +00003169
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003170 // Load the offsets of the declarations that Sema references.
3171 // They will be lazily deserialized when needed.
3172 if (!SemaDeclRefs.empty()) {
3173 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3174 SemaObj->StdNamespace = SemaDeclRefs[0];
3175 SemaObj->StdBadAlloc = SemaDeclRefs[1];
3176 }
3177
Fariborz Jahanian32019832010-07-23 19:11:11 +00003178 // If there are @selector references added them to its pool. This is for
3179 // implementation of -Wselector.
Sebastian Redl725cd962010-08-04 20:40:17 +00003180 if (!ReferencedSelectorsData.empty()) {
3181 unsigned int DataSize = ReferencedSelectorsData.size()-1;
Fariborz Jahanian32019832010-07-23 19:11:11 +00003182 unsigned I = 0;
3183 while (I < DataSize) {
Sebastian Redl725cd962010-08-04 20:40:17 +00003184 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
Fariborz Jahanian32019832010-07-23 19:11:11 +00003185 SourceLocation SelLoc =
Sebastian Redl725cd962010-08-04 20:40:17 +00003186 SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
Fariborz Jahanian32019832010-07-23 19:11:11 +00003187 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3188 }
3189 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00003190}
3191
3192IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003193 // Try to find this name within our on-disk hash tables. We start with the
3194 // most recent one, since that one contains the most up-to-date info.
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003195 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3196 PCHIdentifierLookupTable *IdTable
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003197 = (PCHIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00003198 if (!IdTable)
3199 continue;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003200 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3201 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3202 if (Pos == IdTable->end())
3203 continue;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003204
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003205 // Dereferencing the iterator has the effect of building the
3206 // IdentifierInfo node and populating it with the various
3207 // declarations it needs.
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003208 return *Pos;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003209 }
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003210 return 0;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003211}
3212
Mike Stump1eb44332009-09-09 15:08:12 +00003213std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003214PCHReader::ReadMethodPool(Selector Sel) {
Sebastian Redl725cd962010-08-04 20:40:17 +00003215 // Find this selector in a hash table. We want to find the most recent entry.
3216 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3217 PerFileData &F = *Chain[I];
3218 if (!F.SelectorLookupTable)
3219 continue;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003220
Sebastian Redl725cd962010-08-04 20:40:17 +00003221 PCHSelectorLookupTable *PoolTable
3222 = (PCHSelectorLookupTable*)F.SelectorLookupTable;
3223 PCHSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
3224 if (Pos != PoolTable->end()) {
3225 ++NumSelectorsRead;
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003226 // FIXME: Not quite happy with the statistics here. We probably should
3227 // disable this tracking when called via LoadSelector.
3228 // Also, should entries without methods count as misses?
3229 ++NumMethodPoolEntriesRead;
Sebastian Redl725cd962010-08-04 20:40:17 +00003230 PCHSelectorLookupTrait::data_type Data = *Pos;
3231 if (DeserializationListener)
3232 DeserializationListener->SelectorRead(Data.ID, Sel);
3233 return std::make_pair(Data.Instance, Data.Factory);
3234 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003235 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003236
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003237 ++NumMethodPoolMisses;
Sebastian Redl725cd962010-08-04 20:40:17 +00003238 return std::pair<ObjCMethodList, ObjCMethodList>();
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003239}
3240
Sebastian Redle58aa892010-08-04 18:21:41 +00003241void PCHReader::LoadSelector(Selector Sel) {
3242 // It would be complicated to avoid reading the methods anyway. So don't.
3243 ReadMethodPool(Sel);
3244}
3245
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003246void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00003247 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00003248 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003249 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003250 if (DeserializationListener)
3251 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003252}
3253
Douglas Gregord89275b2009-07-06 18:54:52 +00003254/// \brief Set the globally-visible declarations associated with the given
3255/// identifier.
3256///
3257/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00003258/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00003259/// them.
3260///
3261/// \param II an IdentifierInfo that refers to one or more globally-visible
3262/// declarations.
3263///
3264/// \param DeclIDs the set of declaration IDs with the name @p II that are
3265/// visible at global scope.
3266///
3267/// \param Nonrecursive should be true to indicate that the caller knows that
3268/// this call is non-recursive, and therefore the globally-visible declarations
3269/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003270void
3271PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003272 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3273 bool Nonrecursive) {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003274 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003275 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3276 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3277 PII.II = II;
3278 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3279 PII.DeclIDs.push_back(DeclIDs[I]);
3280 return;
3281 }
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Douglas Gregord89275b2009-07-06 18:54:52 +00003283 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3284 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3285 if (SemaObj) {
3286 // Introduce this declaration into the translation-unit scope
3287 // and add it to the declaration chain for this identifier, so
3288 // that (unqualified) name lookup will find it.
3289 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3290 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3291 } else {
3292 // Queue this declaration so that it will be added to the
3293 // translation unit scope and identifier's declaration chain
3294 // once a Sema object is known.
3295 PreloadedDecls.push_back(D);
3296 }
3297 }
3298}
3299
Chris Lattner7356a312009-04-11 21:15:38 +00003300IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003301 if (ID == 0)
3302 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003304 if (IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003305 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003306 return 0;
3307 }
Mike Stump1eb44332009-09-09 15:08:12 +00003308
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003309 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003310 ID -= 1;
3311 if (!IdentifiersLoaded[ID]) {
3312 unsigned Index = ID;
3313 const char *Str = 0;
3314 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3315 PerFileData *F = Chain[N - I - 1];
3316 if (Index < F->LocalNumIdentifiers) {
3317 uint32_t Offset = F->IdentifierOffsets[Index];
3318 Str = F->IdentifierTableData + Offset;
3319 break;
3320 }
3321 Index -= F->LocalNumIdentifiers;
3322 }
3323 assert(Str && "Broken Chain");
Douglas Gregord6595a42009-04-25 21:04:17 +00003324
Douglas Gregor02fc7512009-04-28 20:01:51 +00003325 // All of the strings in the PCH file are preceded by a 16-bit
3326 // length. Extract that 16-bit length to avoid having to execute
3327 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003328 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3329 // unsigned integers. This is important to avoid integer overflow when
3330 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003331 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003332 unsigned StrLen = (((unsigned) StrLenPtr[0])
3333 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003334 IdentifiersLoaded[ID]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003335 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003336 if (DeserializationListener)
3337 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003338 }
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003340 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003341}
3342
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003343void PCHReader::ReadSLocEntry(unsigned ID) {
3344 ReadSLocEntryRecord(ID);
3345}
3346
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003347Selector PCHReader::DecodeSelector(unsigned ID) {
3348 if (ID == 0)
3349 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003350
Sebastian Redl725cd962010-08-04 20:40:17 +00003351 if (ID > SelectorsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003352 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003353 return Selector();
3354 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003355
Sebastian Redl725cd962010-08-04 20:40:17 +00003356 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
Douglas Gregor83941df2009-04-25 17:48:32 +00003357 // Load this selector from the selector table.
Sebastian Redl725cd962010-08-04 20:40:17 +00003358 unsigned Idx = ID - 1;
3359 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3360 PerFileData &F = *Chain[N - I - 1];
3361 if (Idx < F.LocalNumSelectors) {
3362 PCHSelectorLookupTrait Trait(*this);
3363 SelectorsLoaded[ID - 1] =
3364 Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
3365 if (DeserializationListener)
3366 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
3367 break;
3368 }
3369 Idx -= F.LocalNumSelectors;
3370 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003371 }
3372
Sebastian Redl725cd962010-08-04 20:40:17 +00003373 return SelectorsLoaded[ID - 1];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003374}
3375
John McCall76bd1f32010-06-01 09:23:16 +00003376Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003377 return DecodeSelector(ID);
3378}
3379
John McCall76bd1f32010-06-01 09:23:16 +00003380uint32_t PCHReader::GetNumExternalSelectors() {
Sebastian Redl725cd962010-08-04 20:40:17 +00003381 // ID 0 (the null selector) is considered an external selector.
3382 return getTotalNumSelectors() + 1;
Douglas Gregor719770d2010-04-06 17:30:22 +00003383}
3384
Mike Stump1eb44332009-09-09 15:08:12 +00003385DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003386PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3387 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3388 switch (Kind) {
3389 case DeclarationName::Identifier:
3390 return DeclarationName(GetIdentifierInfo(Record, Idx));
3391
3392 case DeclarationName::ObjCZeroArgSelector:
3393 case DeclarationName::ObjCOneArgSelector:
3394 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003395 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003396
3397 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003398 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003399 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003400
3401 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003402 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003403 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003404
3405 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003406 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003407 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003408
3409 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003410 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003411 (OverloadedOperatorKind)Record[Idx++]);
3412
Sean Hunt3e518bd2009-11-29 07:34:05 +00003413 case DeclarationName::CXXLiteralOperatorName:
3414 return Context->DeclarationNames.getCXXLiteralOperatorName(
3415 GetIdentifierInfo(Record, Idx));
3416
Douglas Gregor2cf26342009-04-09 22:27:44 +00003417 case DeclarationName::CXXUsingDirective:
3418 return DeclarationName::getUsingDirectiveName();
3419 }
3420
3421 // Required to silence GCC warning
3422 return DeclarationName();
3423}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003424
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003425TemplateName
3426PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3427 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3428 switch (Kind) {
3429 case TemplateName::Template:
3430 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3431
3432 case TemplateName::OverloadedTemplate: {
3433 unsigned size = Record[Idx++];
3434 UnresolvedSet<8> Decls;
3435 while (size--)
3436 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3437
3438 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3439 }
3440
3441 case TemplateName::QualifiedTemplate: {
3442 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3443 bool hasTemplKeyword = Record[Idx++];
3444 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3445 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3446 }
3447
3448 case TemplateName::DependentTemplate: {
3449 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3450 if (Record[Idx++]) // isIdentifier
3451 return Context->getDependentTemplateName(NNS,
3452 GetIdentifierInfo(Record, Idx));
3453 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003454 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003455 }
3456 }
3457
3458 assert(0 && "Unhandled template name kind!");
3459 return TemplateName();
3460}
3461
3462TemplateArgument
Sebastian Redl577d4792010-07-22 22:43:28 +00003463PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3464 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003465 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3466 case TemplateArgument::Null:
3467 return TemplateArgument();
3468 case TemplateArgument::Type:
3469 return TemplateArgument(GetType(Record[Idx++]));
3470 case TemplateArgument::Declaration:
3471 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003472 case TemplateArgument::Integral: {
3473 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3474 QualType T = GetType(Record[Idx++]);
3475 return TemplateArgument(Value, T);
3476 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003477 case TemplateArgument::Template:
3478 return TemplateArgument(ReadTemplateName(Record, Idx));
3479 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00003480 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003481 case TemplateArgument::Pack: {
3482 unsigned NumArgs = Record[Idx++];
3483 llvm::SmallVector<TemplateArgument, 8> Args;
3484 Args.reserve(NumArgs);
3485 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003486 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003487 TemplateArgument TemplArg;
3488 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3489 return TemplArg;
3490 }
3491 }
3492
3493 assert(0 && "Unhandled template argument kind!");
3494 return TemplateArgument();
3495}
3496
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003497TemplateParameterList *
3498PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3499 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3500 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3501 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3502
3503 unsigned NumParams = Record[Idx++];
3504 llvm::SmallVector<NamedDecl *, 16> Params;
3505 Params.reserve(NumParams);
3506 while (NumParams--)
3507 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3508
3509 TemplateParameterList* TemplateParams =
3510 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3511 Params.data(), Params.size(), RAngleLoc);
3512 return TemplateParams;
3513}
3514
3515void
3516PCHReader::
3517ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redl577d4792010-07-22 22:43:28 +00003518 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003519 const RecordData &Record, unsigned &Idx) {
3520 unsigned NumTemplateArgs = Record[Idx++];
3521 TemplArgs.reserve(NumTemplateArgs);
3522 while (NumTemplateArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003523 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003524}
3525
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003526/// \brief Read a UnresolvedSet structure.
3527void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3528 const RecordData &Record, unsigned &Idx) {
3529 unsigned NumDecls = Record[Idx++];
3530 while (NumDecls--) {
3531 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3532 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3533 Set.addDecl(D, AS);
3534 }
3535}
3536
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003537CXXBaseSpecifier
Nick Lewycky56062202010-07-26 16:56:01 +00003538PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3539 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003540 bool isVirtual = static_cast<bool>(Record[Idx++]);
3541 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3542 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky56062202010-07-26 16:56:01 +00003543 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003544 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky56062202010-07-26 16:56:01 +00003545 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003546}
3547
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003548NestedNameSpecifier *
3549PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3550 unsigned N = Record[Idx++];
3551 NestedNameSpecifier *NNS = 0, *Prev = 0;
3552 for (unsigned I = 0; I != N; ++I) {
3553 NestedNameSpecifier::SpecifierKind Kind
3554 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3555 switch (Kind) {
3556 case NestedNameSpecifier::Identifier: {
3557 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3558 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3559 break;
3560 }
3561
3562 case NestedNameSpecifier::Namespace: {
3563 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3564 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3565 break;
3566 }
3567
3568 case NestedNameSpecifier::TypeSpec:
3569 case NestedNameSpecifier::TypeSpecWithTemplate: {
3570 Type *T = GetType(Record[Idx++]).getTypePtr();
3571 bool Template = Record[Idx++];
3572 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3573 break;
3574 }
3575
3576 case NestedNameSpecifier::Global: {
3577 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3578 // No associated value, and there can't be a prefix.
3579 break;
3580 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003581 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003582 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003583 }
3584 return NNS;
3585}
3586
3587SourceRange
3588PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003589 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3590 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3591 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003592}
3593
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003594/// \brief Read an integral value
3595llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3596 unsigned BitWidth = Record[Idx++];
3597 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3598 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3599 Idx += NumWords;
3600 return Result;
3601}
3602
3603/// \brief Read a signed integral value
3604llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3605 bool isUnsigned = Record[Idx++];
3606 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3607}
3608
Douglas Gregor17fc2232009-04-14 21:55:33 +00003609/// \brief Read a floating-point value
3610llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003611 return llvm::APFloat(ReadAPInt(Record, Idx));
3612}
3613
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003614// \brief Read a string
3615std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3616 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003617 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003618 Idx += Len;
3619 return Result;
3620}
3621
Chris Lattnerd2598362010-05-10 00:25:06 +00003622CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3623 unsigned &Idx) {
3624 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3625 return CXXTemporary::Create(*Context, Decl);
3626}
3627
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003628DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003629 return Diag(SourceLocation(), DiagID);
3630}
3631
3632DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003633 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003634}
Douglas Gregor025452f2009-04-17 00:04:06 +00003635
Douglas Gregor668c1a42009-04-21 22:25:48 +00003636/// \brief Retrieve the identifier table associated with the
3637/// preprocessor.
3638IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003639 assert(PP && "Forgot to set Preprocessor ?");
3640 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003641}
3642
Douglas Gregor025452f2009-04-17 00:04:06 +00003643/// \brief Record that the given ID maps to the given switch-case
3644/// statement.
3645void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3646 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3647 SwitchCaseStmts[ID] = SC;
3648}
3649
3650/// \brief Retrieve the switch-case statement with the given ID.
3651SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3652 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3653 return SwitchCaseStmts[ID];
3654}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003655
3656/// \brief Record that the given label statement has been
3657/// deserialized and has the given ID.
3658void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003659 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003660 "Deserialized label twice");
3661 LabelStmts[ID] = S;
3662
3663 // If we've already seen any goto statements that point to this
3664 // label, resolve them now.
3665 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3666 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3667 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3668 Goto->second->setLabel(S);
3669 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003670
3671 // If we've already seen any address-label statements that point to
3672 // this label, resolve them now.
3673 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003674 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003675 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003676 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003677 AddrLabel != AddrLabels.second; ++AddrLabel)
3678 AddrLabel->second->setLabel(S);
3679 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003680}
3681
3682/// \brief Set the label of the given statement to the label
3683/// identified by ID.
3684///
3685/// Depending on the order in which the label and other statements
3686/// referencing that label occur, this operation may complete
3687/// immediately (updating the statement) or it may queue the
3688/// statement to be back-patched later.
3689void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3690 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3691 if (Label != LabelStmts.end()) {
3692 // We've already seen this label, so set the label of the goto and
3693 // we're done.
3694 S->setLabel(Label->second);
3695 } else {
3696 // We haven't seen this label yet, so add this goto to the set of
3697 // unresolved goto statements.
3698 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3699 }
3700}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003701
3702/// \brief Set the label of the given expression to the label
3703/// identified by ID.
3704///
3705/// Depending on the order in which the label and other statements
3706/// referencing that label occur, this operation may complete
3707/// immediately (updating the statement) or it may queue the
3708/// statement to be back-patched later.
3709void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3710 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3711 if (Label != LabelStmts.end()) {
3712 // We've already seen this label, so set the label of the
3713 // label-address expression and we're done.
3714 S->setLabel(Label->second);
3715 } else {
3716 // We haven't seen this label yet, so add this label-address
3717 // expression to the set of unresolved label-address expressions.
3718 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3719 }
3720}
Douglas Gregord89275b2009-07-06 18:54:52 +00003721
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003722void PCHReader::FinishedDeserializing() {
3723 assert(NumCurrentElementsDeserializing &&
3724 "FinishedDeserializing not paired with StartedDeserializing");
3725 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003726 // If any identifiers with corresponding top-level declarations have
3727 // been loaded, load those declarations now.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003728 while (!PendingIdentifierInfos.empty()) {
3729 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3730 PendingIdentifierInfos.front().DeclIDs, true);
3731 PendingIdentifierInfos.pop_front();
Douglas Gregord89275b2009-07-06 18:54:52 +00003732 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003733
3734 // We are not in recursive loading, so it's safe to pass the "interesting"
3735 // decls to the consumer.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003736 if (Consumer)
3737 PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003738 }
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003739 --NumCurrentElementsDeserializing;
Douglas Gregord89275b2009-07-06 18:54:52 +00003740}