blob: e55605b27439b08eef31f9a9e5de3b4184b59b0e [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 Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Sema.h"
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;
Argyrios Kyrtzidis646395b2010-08-11 22:55:12 +0000660 bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
661 Bits >>= 1;
Douglas Gregor2deaea32009-04-22 18:49:13 +0000662 bool Poisoned = Bits & 0x01;
663 Bits >>= 1;
664 bool ExtensionToken = Bits & 0x01;
665 Bits >>= 1;
666 bool hasMacroDefinition = Bits & 0x01;
667 Bits >>= 1;
668 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
669 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Douglas Gregor2deaea32009-04-22 18:49:13 +0000671 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000672 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000673
674 // Build the IdentifierInfo itself and link the identifier ID with
675 // the new IdentifierInfo.
676 IdentifierInfo *II = KnownII;
677 if (!II)
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000678 II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000679 Reader.SetIdentifierInfo(ID, II);
680
Douglas Gregor2deaea32009-04-22 18:49:13 +0000681 // Set or check the various bits in the IdentifierInfo structure.
Argyrios Kyrtzidis646395b2010-08-11 22:55:12 +0000682 // Token IDs are read-only.
683 if (HasRevertedTokenIDToIdentifier)
684 II->RevertTokenIDToIdentifier();
Douglas Gregor2deaea32009-04-22 18:49:13 +0000685 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000686 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000687 "Incorrect extension token flag");
688 (void)ExtensionToken;
689 II->setIsPoisoned(Poisoned);
690 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
691 "Incorrect C++ operator keyword flag");
692 (void)CPlusPlusOperatorKeyword;
693
Douglas Gregor37e26842009-04-21 23:56:24 +0000694 // If this identifier is a macro, deserialize the macro
695 // definition.
696 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000697 uint32_t Offset = ReadUnalignedLE32(d);
Sebastian Redld27d3fc2010-07-21 22:31:37 +0000698 Reader.ReadMacroRecord(Stream, Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000699 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000700 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000701
702 // Read all of the declarations visible at global scope with this
703 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000704 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000705 if (DataLen > 0) {
706 llvm::SmallVector<uint32_t, 4> DeclIDs;
707 for (; DataLen > 0; DataLen -= 4)
708 DeclIDs.push_back(ReadUnalignedLE32(d));
709 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Sebastian Redlffaab3e2010-07-30 00:29:29 +0000712 II->setIsFromPCH();
Douglas Gregor668c1a42009-04-21 22:25:48 +0000713 return II;
714 }
715};
Mike Stump1eb44332009-09-09 15:08:12 +0000716
717} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000718
719/// \brief The on-disk hash table used to contain information about
720/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000721typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000722 PCHIdentifierLookupTable;
723
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000724void PCHReader::Error(const char *Msg) {
725 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000726}
727
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000728/// \brief Check the contents of the concatenation of all predefines buffers in
729/// the PCH chain against the contents of the predefines buffer of the current
730/// compiler invocation.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000731///
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000732/// The contents should be the same. If not, then some command-line option
733/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000734///
735/// \returns true if there was a mismatch (in which case the PCH file
736/// should be ignored), or false otherwise.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000737bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000738 if (Listener)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000739 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000740 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000741 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000742 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000743}
744
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000745//===----------------------------------------------------------------------===//
746// Source Manager Deserialization
747//===----------------------------------------------------------------------===//
748
Douglas Gregorbd945002009-04-13 16:31:14 +0000749/// \brief Read the line table in the source manager block.
750/// \returns true if ther was an error.
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000751bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000752 unsigned Idx = 0;
753 LineTableInfo &LineTable = SourceMgr.getLineTable();
754
755 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000756 std::map<int, int> FileIDs;
757 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000758 // Extract the file name
759 unsigned FilenameLen = Record[Idx++];
760 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
761 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000762 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000763 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000764 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000765 }
766
767 // Parse the line entries
768 std::vector<LineEntry> Entries;
769 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000770 int FID = Record[Idx++];
Douglas Gregorbd945002009-04-13 16:31:14 +0000771
772 // Extract the line entries
773 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000774 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +0000775 Entries.clear();
776 Entries.reserve(NumEntries);
777 for (unsigned I = 0; I != NumEntries; ++I) {
778 unsigned FileOffset = Record[Idx++];
779 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000780 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +0000781 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000782 = (SrcMgr::CharacteristicKind)Record[Idx++];
783 unsigned IncludeOffset = Record[Idx++];
784 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
785 FileKind, IncludeOffset));
786 }
787 LineTable.AddEntry(FID, Entries);
788 }
789
790 return false;
791}
792
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000793namespace {
794
Benjamin Kramerbd218282009-11-28 10:07:24 +0000795class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000796public:
797 const bool hasStat;
798 const ino_t ino;
799 const dev_t dev;
800 const mode_t mode;
801 const time_t mtime;
802 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000804 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000805 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
806
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000807 PCHStatData()
808 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
809};
810
Benjamin Kramerbd218282009-11-28 10:07:24 +0000811class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000812 public:
813 typedef const char *external_key_type;
814 typedef const char *internal_key_type;
815
816 typedef PCHStatData data_type;
817
818 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000819 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000820 }
821
822 static internal_key_type GetInternalKey(const char *path) { return path; }
823
824 static bool EqualKey(internal_key_type a, internal_key_type b) {
825 return strcmp(a, b) == 0;
826 }
827
828 static std::pair<unsigned, unsigned>
829 ReadKeyDataLength(const unsigned char*& d) {
830 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
831 unsigned DataLen = (unsigned) *d++;
832 return std::make_pair(KeyLen + 1, DataLen);
833 }
834
835 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
836 return (const char *)d;
837 }
838
839 static data_type ReadData(const internal_key_type, const unsigned char *d,
840 unsigned /*DataLen*/) {
841 using namespace clang::io;
842
843 if (*d++ == 1)
844 return data_type();
845
846 ino_t ino = (ino_t) ReadUnalignedLE32(d);
847 dev_t dev = (dev_t) ReadUnalignedLE32(d);
848 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000849 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000850 off_t size = (off_t) ReadUnalignedLE64(d);
851 return data_type(ino, dev, mode, mtime, size);
852 }
853};
854
855/// \brief stat() cache for precompiled headers.
856///
857/// This cache is very similar to the stat cache used by pretokenized
858/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000859class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000860 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
861 CacheTy *Cache;
862
863 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000864public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000865 PCHStatCache(const unsigned char *Buckets,
866 const unsigned char *Base,
867 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000868 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000869 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
870 Cache = CacheTy::Create(Buckets, Base);
871 }
872
873 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000875 int stat(const char *path, struct stat *buf) {
876 // Do the lookup for the file's data in the PCH file.
877 CacheTy::iterator I = Cache->find(path);
878
879 // If we don't get a hit in the PCH file just forward to 'stat'.
880 if (I == Cache->end()) {
881 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000882 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000883 }
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000885 ++NumStatHits;
886 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000888 if (!Data.hasStat)
889 return 1;
890
891 buf->st_ino = Data.ino;
892 buf->st_dev = Data.dev;
893 buf->st_mtime = Data.mtime;
894 buf->st_mode = Data.mode;
895 buf->st_size = Data.size;
896 return 0;
897 }
898};
899} // end anonymous namespace
900
901
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000902/// \brief Read a source manager block
903PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock(PerFileData &F) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000904 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000905
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000906 llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +0000907
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000908 // Set the source-location entry cursor to the current position in
909 // the stream. This cursor will be used to read the contents of the
910 // source manager block initially, and then lazily read
911 // source-location entries as needed.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000912 SLocEntryCursor = F.Stream;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000913
914 // The stream itself is going to skip over the source manager block.
Sebastian Redl93fb9ed2010-07-19 20:52:06 +0000915 if (F.Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000916 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000917 return Failure;
918 }
919
920 // Enter the source manager block.
921 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000922 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000923 return Failure;
924 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000925
Douglas Gregor14f79002009-04-10 03:52:48 +0000926 RecordData Record;
927 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000928 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000929 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000930 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000931 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000932 return Failure;
933 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000934 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000935 }
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Douglas Gregor14f79002009-04-10 03:52:48 +0000937 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
938 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000939 SLocEntryCursor.ReadSubBlockID();
940 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000941 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000942 return Failure;
943 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000944 continue;
945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Douglas Gregor14f79002009-04-10 03:52:48 +0000947 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000948 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000949 continue;
950 }
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Douglas Gregor14f79002009-04-10 03:52:48 +0000952 // Read a record.
953 const char *BlobStart;
954 unsigned BlobLen;
955 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000956 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000957 default: // Default behavior: ignore.
958 break;
959
Chris Lattner2c78b872009-04-14 23:22:57 +0000960 case pch::SM_LINE_TABLE:
Sebastian Redl518d8cb2010-07-20 21:20:32 +0000961 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000962 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000963 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000964
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000965 case pch::SM_SLOC_FILE_ENTRY:
966 case pch::SM_SLOC_BUFFER_ENTRY:
967 case pch::SM_SLOC_INSTANTIATION_ENTRY:
968 // Once we hit one of the source location entries, we're done.
969 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000970 }
971 }
972}
973
Sebastian Redl190faf72010-07-20 21:50:20 +0000974/// \brief Get a cursor that's correctly positioned for reading the source
975/// location entry with the given ID.
976llvm::BitstreamCursor &PCHReader::SLocCursorForID(unsigned ID) {
977 assert(ID != 0 && ID <= TotalNumSLocEntries &&
978 "SLocCursorForID should only be called for real IDs.");
979
980 ID -= 1;
981 PerFileData *F = 0;
982 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
983 F = Chain[N - I - 1];
984 if (ID < F->LocalNumSLocEntries)
985 break;
986 ID -= F->LocalNumSLocEntries;
987 }
988 assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
989
990 F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
991 return F->SLocEntryCursor;
992}
993
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000994/// \brief Read in the source location entry with the given ID.
995PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
996 if (ID == 0)
997 return Success;
998
999 if (ID > TotalNumSLocEntries) {
1000 Error("source location entry ID out-of-range for PCH file");
1001 return Failure;
1002 }
1003
Sebastian Redl190faf72010-07-20 21:50:20 +00001004 llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
Sebastian Redl9137a522010-07-16 17:50:48 +00001005
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001006 ++NumSLocEntriesRead;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001007 unsigned Code = SLocEntryCursor.ReadCode();
1008 if (Code == llvm::bitc::END_BLOCK ||
1009 Code == llvm::bitc::ENTER_SUBBLOCK ||
1010 Code == llvm::bitc::DEFINE_ABBREV) {
1011 Error("incorrectly-formatted source location entry in PCH file");
1012 return Failure;
1013 }
1014
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001015 RecordData Record;
1016 const char *BlobStart;
1017 unsigned BlobLen;
1018 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1019 default:
1020 Error("incorrectly-formatted source location entry in PCH file");
1021 return Failure;
1022
1023 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +00001024 std::string Filename(BlobStart, BlobStart + BlobLen);
1025 MaybeAddSystemRootToFilename(Filename);
1026 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001027 if (File == 0) {
1028 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +00001029 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +00001030 ErrorStr += "' referenced by PCH file";
1031 Error(ErrorStr.c_str());
1032 return Failure;
1033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Douglas Gregor2d52be52010-03-21 22:49:54 +00001035 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +00001036 Error("source location entry is incorrect");
1037 return Failure;
1038 }
1039
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001040 if (!DisableValidation &&
1041 ((off_t)Record[4] != File->getSize()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001042#if !defined(LLVM_ON_WIN32)
1043 // In our regression testing, the Windows file system seems to
1044 // have inconsistent modification times that sometimes
1045 // erroneously trigger this error-handling path.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001046 || (time_t)Record[5] != File->getModificationTime()
Douglas Gregor9f692a02010-04-09 15:54:22 +00001047#endif
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001048 )) {
Douglas Gregor2d52be52010-03-21 22:49:54 +00001049 Diag(diag::err_fe_pch_file_modified)
1050 << Filename;
1051 return Failure;
1052 }
1053
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001054 FileID FID = SourceMgr.createFileID(File,
1055 SourceLocation::getFromRawEncoding(Record[1]),
1056 (SrcMgr::CharacteristicKind)Record[2],
1057 ID, Record[0]);
1058 if (Record[3])
1059 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1060 .setHasLineDirectives();
1061
Douglas Gregor12fab312010-03-16 16:35:32 +00001062 // Reconstruct header-search information for this file.
1063 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001064 HFI.isImport = Record[6];
1065 HFI.DirInfo = Record[7];
1066 HFI.NumIncludes = Record[8];
1067 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +00001068 if (Listener)
1069 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001070 break;
1071 }
1072
1073 case pch::SM_SLOC_BUFFER_ENTRY: {
1074 const char *Name = BlobStart;
1075 unsigned Offset = Record[0];
1076 unsigned Code = SLocEntryCursor.ReadCode();
1077 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001078 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001079 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001080
1081 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1082 Error("PCH record has invalid code");
1083 return Failure;
1084 }
1085
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001086 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001087 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1088 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001089 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Douglas Gregor92b059e2009-04-28 20:33:11 +00001091 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001092 PCHPredefinesBlock Block = {
1093 BufferID,
1094 llvm::StringRef(BlobStart, BlobLen - 1)
1095 };
1096 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001097 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001098
1099 break;
1100 }
1101
1102 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +00001103 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001104 = SourceLocation::getFromRawEncoding(Record[1]);
1105 SourceMgr.createInstantiationLoc(SpellingLoc,
1106 SourceLocation::getFromRawEncoding(Record[2]),
1107 SourceLocation::getFromRawEncoding(Record[3]),
1108 Record[4],
1109 ID,
1110 Record[0]);
1111 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001112 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001113 }
1114
1115 return Success;
1116}
1117
Chris Lattner6367f6d2009-04-27 01:05:14 +00001118/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1119/// specified cursor. Read the abbreviations that are at the top of the block
1120/// and then leave the cursor pointing into the block.
1121bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1122 unsigned BlockID) {
1123 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001124 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001125 return Failure;
1126 }
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Chris Lattner6367f6d2009-04-27 01:05:14 +00001128 while (true) {
1129 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Chris Lattner6367f6d2009-04-27 01:05:14 +00001131 // We expect all abbrevs to be at the start of the block.
1132 if (Code != llvm::bitc::DEFINE_ABBREV)
1133 return false;
1134 Cursor.ReadAbbrevRecord();
1135 }
1136}
1137
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001138void PCHReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001139 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Douglas Gregor37e26842009-04-21 23:56:24 +00001141 // Keep track of where we are in the stream, then jump back there
1142 // after reading this macro.
1143 SavedStreamPosition SavedPosition(Stream);
1144
1145 Stream.JumpToBit(Offset);
1146 RecordData Record;
1147 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1148 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Douglas Gregor37e26842009-04-21 23:56:24 +00001150 while (true) {
1151 unsigned Code = Stream.ReadCode();
1152 switch (Code) {
1153 case llvm::bitc::END_BLOCK:
1154 return;
1155
1156 case llvm::bitc::ENTER_SUBBLOCK:
1157 // No known subblocks, always skip them.
1158 Stream.ReadSubBlockID();
1159 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001160 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001161 return;
1162 }
1163 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Douglas Gregor37e26842009-04-21 23:56:24 +00001165 case llvm::bitc::DEFINE_ABBREV:
1166 Stream.ReadAbbrevRecord();
1167 continue;
1168 default: break;
1169 }
1170
1171 // Read a record.
1172 Record.clear();
1173 pch::PreprocessorRecordTypes RecType =
1174 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1175 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001176 case pch::PP_MACRO_OBJECT_LIKE:
1177 case pch::PP_MACRO_FUNCTION_LIKE: {
1178 // If we already have a macro, that means that we've hit the end
1179 // of the definition of the macro we were looking for. We're
1180 // done.
1181 if (Macro)
1182 return;
1183
1184 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1185 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001186 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001187 return;
1188 }
1189 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1190 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001192 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001193 MI->setIsUsed(isUsed);
Sebastian Redl083abdf2010-07-27 23:01:28 +00001194 MI->setIsFromPCH();
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001196 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001197 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1198 // Decode function-like macro info.
1199 bool isC99VarArgs = Record[3];
1200 bool isGNUVarArgs = Record[4];
1201 MacroArgs.clear();
1202 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001203 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001204 for (unsigned i = 0; i != NumArgs; ++i)
1205 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1206
1207 // Install function-like macro info.
1208 MI->setIsFunctionLike();
1209 if (isC99VarArgs) MI->setIsC99Varargs();
1210 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001211 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001212 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001213 }
1214
1215 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001216 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001217
1218 // Remember that we saw this macro last so that we add the tokens that
1219 // form its body to it.
1220 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001221
1222 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1223 // We have a macro definition. Load it now.
1224 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1225 getMacroDefinition(Record[NextIndex]));
1226 }
1227
Douglas Gregor37e26842009-04-21 23:56:24 +00001228 ++NumMacrosRead;
1229 break;
1230 }
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Douglas Gregor37e26842009-04-21 23:56:24 +00001232 case pch::PP_TOKEN: {
1233 // If we see a TOKEN before a PP_MACRO_*, then the file is
1234 // erroneous, just pretend we didn't see this.
1235 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Douglas Gregor37e26842009-04-21 23:56:24 +00001237 Token Tok;
1238 Tok.startToken();
1239 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1240 Tok.setLength(Record[1]);
1241 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1242 Tok.setIdentifierInfo(II);
1243 Tok.setKind((tok::TokenKind)Record[3]);
1244 Tok.setFlag((Token::TokenFlags)Record[4]);
1245 Macro->AddTokenToBody(Tok);
1246 break;
1247 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001248
1249 case pch::PP_MACRO_INSTANTIATION: {
1250 // If we already have a macro, that means that we've hit the end
1251 // of the definition of the macro we were looking for. We're
1252 // done.
1253 if (Macro)
1254 return;
1255
1256 if (!PP->getPreprocessingRecord()) {
1257 Error("missing preprocessing record in PCH file");
1258 return;
1259 }
1260
1261 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1262 if (PPRec.getPreprocessedEntity(Record[0]))
1263 return;
1264
1265 MacroInstantiation *MI
1266 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1267 SourceRange(
1268 SourceLocation::getFromRawEncoding(Record[1]),
1269 SourceLocation::getFromRawEncoding(Record[2])),
1270 getMacroDefinition(Record[4]));
1271 PPRec.SetPreallocatedEntity(Record[0], MI);
1272 return;
1273 }
1274
1275 case pch::PP_MACRO_DEFINITION: {
1276 // If we already have a macro, that means that we've hit the end
1277 // of the definition of the macro we were looking for. We're
1278 // done.
1279 if (Macro)
1280 return;
1281
1282 if (!PP->getPreprocessingRecord()) {
1283 Error("missing preprocessing record in PCH file");
1284 return;
1285 }
1286
1287 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1288 if (PPRec.getPreprocessedEntity(Record[0]))
1289 return;
1290
1291 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1292 Error("out-of-bounds macro definition record");
1293 return;
1294 }
1295
1296 MacroDefinition *MD
1297 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1298 SourceLocation::getFromRawEncoding(Record[5]),
1299 SourceRange(
1300 SourceLocation::getFromRawEncoding(Record[2]),
1301 SourceLocation::getFromRawEncoding(Record[3])));
1302 PPRec.SetPreallocatedEntity(Record[0], MD);
1303 MacroDefinitionsLoaded[Record[1]] = MD;
1304 return;
1305 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001306 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001307 }
1308}
1309
Douglas Gregor88a35862010-01-04 19:18:44 +00001310void PCHReader::ReadDefinedMacros() {
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001311 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1312 llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
Sebastian Redl9137a522010-07-16 17:50:48 +00001313
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001314 // If there was no preprocessor block, skip this file.
1315 if (!MacroCursor.getBitStreamReader())
1316 continue;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001317
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001318 llvm::BitstreamCursor Cursor = MacroCursor;
1319 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1320 Error("malformed preprocessor block record in PCH file");
Douglas Gregor88a35862010-01-04 19:18:44 +00001321 return;
1322 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001323
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001324 RecordData Record;
1325 while (true) {
1326 unsigned Code = Cursor.ReadCode();
1327 if (Code == llvm::bitc::END_BLOCK) {
1328 if (Cursor.ReadBlockEnd()) {
1329 Error("error at end of preprocessor block in PCH file");
1330 return;
1331 }
1332 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001333 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001334
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001335 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1336 // No known subblocks, always skip them.
1337 Cursor.ReadSubBlockID();
1338 if (Cursor.SkipBlock()) {
1339 Error("malformed block record in PCH file");
1340 return;
1341 }
1342 continue;
1343 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001344
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001345 if (Code == llvm::bitc::DEFINE_ABBREV) {
1346 Cursor.ReadAbbrevRecord();
1347 continue;
1348 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001349
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001350 // Read a record.
1351 const char *BlobStart;
1352 unsigned BlobLen;
1353 Record.clear();
1354 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1355 default: // Default behavior: ignore.
1356 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001357
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001358 case pch::PP_MACRO_OBJECT_LIKE:
1359 case pch::PP_MACRO_FUNCTION_LIKE:
1360 DecodeIdentifierInfo(Record[0]);
1361 break;
1362
1363 case pch::PP_TOKEN:
1364 // Ignore tokens.
1365 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001366
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001367 case pch::PP_MACRO_INSTANTIATION:
1368 case pch::PP_MACRO_DEFINITION:
1369 // Read the macro record.
1370 ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1371 break;
1372 }
Douglas Gregor88a35862010-01-04 19:18:44 +00001373 }
1374 }
1375}
1376
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001377MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1378 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1379 return 0;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001380
1381 if (!MacroDefinitionsLoaded[ID]) {
1382 unsigned Index = ID;
1383 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1384 PerFileData &F = *Chain[N - I - 1];
1385 if (Index < F.LocalNumMacroDefinitions) {
1386 ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1387 break;
1388 }
1389 Index -= F.LocalNumMacroDefinitions;
1390 }
1391 assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1392 }
1393
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001394 return MacroDefinitionsLoaded[ID];
1395}
1396
Douglas Gregore650c8c2009-07-07 00:12:59 +00001397/// \brief If we are loading a relocatable PCH file, and the filename is
1398/// not an absolute path, add the system root to the beginning of the file
1399/// name.
1400void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1401 // If this is not a relocatable PCH file, there's nothing to do.
1402 if (!RelocatablePCH)
1403 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Daniel Dunbard5b21972009-11-18 19:50:41 +00001405 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001406 return;
1407
Douglas Gregore650c8c2009-07-07 00:12:59 +00001408 if (isysroot == 0) {
1409 // If no system root was given, default to '/'
1410 Filename.insert(Filename.begin(), '/');
1411 return;
1412 }
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Douglas Gregore650c8c2009-07-07 00:12:59 +00001414 unsigned Length = strlen(isysroot);
1415 if (isysroot[Length - 1] != '/')
1416 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Douglas Gregore650c8c2009-07-07 00:12:59 +00001418 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1419}
1420
Mike Stump1eb44332009-09-09 15:08:12 +00001421PCHReader::PCHReadResult
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001422PCHReader::ReadPCHBlock(PerFileData &F) {
Sebastian Redl9137a522010-07-16 17:50:48 +00001423 llvm::BitstreamCursor &Stream = F.Stream;
1424
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001425 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001426 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001427 return Failure;
1428 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001429
1430 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001431 RecordData Record;
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001432 bool First = true;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001433 while (!Stream.AtEndOfStream()) {
1434 unsigned Code = Stream.ReadCode();
1435 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001436 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001437 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001438 return Failure;
1439 }
Chris Lattner7356a312009-04-11 21:15:38 +00001440
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001441 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001442 }
1443
1444 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1445 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001446 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001447 // We lazily load the decls block, but we want to set up the
1448 // DeclsCursor cursor to point into it. Clone our current bitcode
1449 // cursor to it, enter the block and read the abbrevs in that block.
1450 // With the main cursor, we just skip over it.
Sebastian Redl9137a522010-07-16 17:50:48 +00001451 F.DeclsCursor = Stream;
Chris Lattner6367f6d2009-04-27 01:05:14 +00001452 if (Stream.SkipBlock() || // Skip with the main cursor.
1453 // Read the abbrevs.
Sebastian Redl9137a522010-07-16 17:50:48 +00001454 ReadBlockAbbrevs(F.DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001455 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001456 return Failure;
1457 }
1458 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chris Lattner7356a312009-04-11 21:15:38 +00001460 case pch::PREPROCESSOR_BLOCK_ID:
Sebastian Redl9137a522010-07-16 17:50:48 +00001461 F.MacroCursor = Stream;
Douglas Gregor88a35862010-01-04 19:18:44 +00001462 if (PP)
1463 PP->setExternalSource(this);
1464
Chris Lattner7356a312009-04-11 21:15:38 +00001465 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001466 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001467 return Failure;
1468 }
1469 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001470
Douglas Gregor14f79002009-04-10 03:52:48 +00001471 case pch::SOURCE_MANAGER_BLOCK_ID:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001472 switch (ReadSourceManagerBlock(F)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00001473 case Success:
1474 break;
1475
1476 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001477 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001478 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001479
1480 case IgnorePCH:
1481 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001482 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001483 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001484 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001485 First = false;
Douglas Gregor8038d512009-04-10 17:25:41 +00001486 continue;
1487 }
1488
1489 if (Code == llvm::bitc::DEFINE_ABBREV) {
1490 Stream.ReadAbbrevRecord();
1491 continue;
1492 }
1493
1494 // Read and process a record.
1495 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001496 const char *BlobStart = 0;
1497 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001498 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001499 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001500 default: // Default behavior: ignore.
1501 break;
1502
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001503 case pch::METADATA: {
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001504 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001505 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1506 : diag::warn_pch_version_too_new);
1507 return IgnorePCH;
1508 }
1509
1510 RelocatablePCH = Record[4];
1511 if (Listener) {
1512 std::string TargetTriple(BlobStart, BlobLen);
1513 if (Listener->ReadTargetTriple(TargetTriple))
1514 return IgnorePCH;
1515 }
1516 break;
1517 }
1518
1519 case pch::CHAINED_METADATA: {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001520 if (!First) {
1521 Error("CHAINED_METADATA is not first record in block");
1522 return Failure;
1523 }
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001524 if (Record[0] != pch::VERSION_MAJOR && !DisableValidation) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001525 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1526 : diag::warn_pch_version_too_new);
1527 return IgnorePCH;
1528 }
1529
1530 // Load the chained file.
1531 switch(ReadPCHCore(llvm::StringRef(BlobStart, BlobLen))) {
1532 case Failure: return Failure;
1533 // If we have to ignore the dependency, we'll have to ignore this too.
1534 case IgnorePCH: return IgnorePCH;
1535 case Success: break;
1536 }
1537 break;
1538 }
1539
Douglas Gregor8038d512009-04-10 17:25:41 +00001540 case pch::TYPE_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001541 if (F.LocalNumTypes != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001542 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001543 return Failure;
1544 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001545 F.TypeOffsets = (const uint32_t *)BlobStart;
1546 F.LocalNumTypes = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001547 break;
1548
1549 case pch::DECL_OFFSET:
Sebastian Redl12d6da02010-07-19 22:06:55 +00001550 if (F.LocalNumDecls != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001551 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001552 return Failure;
1553 }
Sebastian Redl12d6da02010-07-19 22:06:55 +00001554 F.DeclOffsets = (const uint32_t *)BlobStart;
1555 F.LocalNumDecls = Record[0];
Douglas Gregor8038d512009-04-10 17:25:41 +00001556 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001557
Sebastian Redld692af72010-07-27 18:24:41 +00001558 case pch::TU_UPDATE_LEXICAL: {
1559 DeclContextInfo Info = {
1560 /* No visible information */ 0, 0,
1561 reinterpret_cast<const pch::DeclID *>(BlobStart),
1562 BlobLen / sizeof(pch::DeclID)
1563 };
1564 DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1565 break;
1566 }
1567
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00001568 case pch::REDECLS_UPDATE_LATEST: {
1569 assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1570 for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
1571 pch::DeclID First = Record[i], Latest = Record[i+1];
1572 assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
1573 Latest > FirstLatestDeclIDs[First]) &&
1574 "The new latest is supposed to come after the previous latest");
1575 FirstLatestDeclIDs[First] = Latest;
1576 }
1577 break;
1578 }
1579
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001580 case pch::LANGUAGE_OPTIONS:
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001581 if (ParseLanguageOptions(Record) && !DisableValidation)
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001582 return IgnorePCH;
1583 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001584
Douglas Gregorafaf3082009-04-11 00:14:32 +00001585 case pch::IDENTIFIER_TABLE:
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001586 F.IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001587 if (Record[0]) {
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001588 F.IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001589 = PCHIdentifierLookupTable::Create(
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001590 (const unsigned char *)F.IdentifierTableData + Record[0],
1591 (const unsigned char *)F.IdentifierTableData,
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001592 PCHIdentifierLookupTrait(*this, F.Stream));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001593 if (PP)
1594 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001595 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001596 break;
1597
1598 case pch::IDENTIFIER_OFFSET:
Sebastian Redl2da08f92010-07-19 22:28:42 +00001599 if (F.LocalNumIdentifiers != 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001600 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001601 return Failure;
1602 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001603 F.IdentifierOffsets = (const uint32_t *)BlobStart;
1604 F.LocalNumIdentifiers = Record[0];
Douglas Gregorafaf3082009-04-11 00:14:32 +00001605 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001606
1607 case pch::EXTERNAL_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001608 // Optimization for the first block.
1609 if (ExternalDefinitions.empty())
1610 ExternalDefinitions.swap(Record);
1611 else
1612 ExternalDefinitions.insert(ExternalDefinitions.end(),
1613 Record.begin(), Record.end());
Douglas Gregorfdd01722009-04-14 00:24:19 +00001614 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001615
Douglas Gregorad1de002009-04-18 05:55:16 +00001616 case pch::SPECIAL_TYPES:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001617 // Optimization for the first block
1618 if (SpecialTypes.empty())
1619 SpecialTypes.swap(Record);
1620 else
1621 SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
Douglas Gregorad1de002009-04-18 05:55:16 +00001622 break;
1623
Douglas Gregor3e1af842009-04-17 22:13:46 +00001624 case pch::STATISTICS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001625 TotalNumStatements += Record[0];
1626 TotalNumMacros += Record[1];
1627 TotalLexicalDeclContexts += Record[2];
1628 TotalVisibleDeclContexts += Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001629 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001630
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001631 case pch::TENTATIVE_DEFINITIONS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001632 // Optimization for the first block.
1633 if (TentativeDefinitions.empty())
1634 TentativeDefinitions.swap(Record);
1635 else
1636 TentativeDefinitions.insert(TentativeDefinitions.end(),
1637 Record.begin(), Record.end());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001638 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001639
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001640 case pch::UNUSED_STATIC_FUNCS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001641 // Optimization for the first block.
1642 if (UnusedStaticFuncs.empty())
1643 UnusedStaticFuncs.swap(Record);
1644 else
1645 UnusedStaticFuncs.insert(UnusedStaticFuncs.end(),
1646 Record.begin(), Record.end());
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001647 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001648
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00001649 case pch::WEAK_UNDECLARED_IDENTIFIERS:
Sebastian Redl40566802010-08-05 18:21:25 +00001650 // Later blocks overwrite earlier ones.
1651 WeakUndeclaredIdentifiers.swap(Record);
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00001652 break;
1653
Douglas Gregor14c22f22009-04-22 22:18:58 +00001654 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001655 // Optimization for the first block.
1656 if (LocallyScopedExternalDecls.empty())
1657 LocallyScopedExternalDecls.swap(Record);
1658 else
1659 LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1660 Record.begin(), Record.end());
Douglas Gregor14c22f22009-04-22 22:18:58 +00001661 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001662
Douglas Gregor83941df2009-04-25 17:48:32 +00001663 case pch::SELECTOR_OFFSETS:
Sebastian Redl059612d2010-08-03 21:58:15 +00001664 F.SelectorOffsets = (const uint32_t *)BlobStart;
Sebastian Redl725cd962010-08-04 20:40:17 +00001665 F.LocalNumSelectors = Record[0];
Douglas Gregor83941df2009-04-25 17:48:32 +00001666 break;
1667
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001668 case pch::METHOD_POOL:
Sebastian Redl725cd962010-08-04 20:40:17 +00001669 F.SelectorLookupTableData = (const unsigned char *)BlobStart;
Douglas Gregor83941df2009-04-25 17:48:32 +00001670 if (Record[0])
Sebastian Redl725cd962010-08-04 20:40:17 +00001671 F.SelectorLookupTable
1672 = PCHSelectorLookupTable::Create(
1673 F.SelectorLookupTableData + Record[0],
1674 F.SelectorLookupTableData,
1675 PCHSelectorLookupTrait(*this));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00001676 TotalNumMethodPoolEntries += Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001677 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001678
Fariborz Jahanian32019832010-07-23 19:11:11 +00001679 case pch::REFERENCED_SELECTOR_POOL: {
Sebastian Redl725cd962010-08-04 20:40:17 +00001680 ReferencedSelectorsData.insert(ReferencedSelectorsData.end(),
1681 Record.begin(), Record.end());
Fariborz Jahanian32019832010-07-23 19:11:11 +00001682 break;
Sebastian Redl681d7232010-07-27 00:17:23 +00001683 }
Fariborz Jahanian32019832010-07-23 19:11:11 +00001684
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001685 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001686 if (!Record.empty() && Listener)
1687 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001688 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001689
1690 case pch::SOURCE_LOCATION_OFFSETS:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001691 F.SLocOffsets = (const uint32_t *)BlobStart;
1692 F.LocalNumSLocEntries = Record[0];
1693 // We cannot delay this until all PCHs are loaded, because then source
1694 // location preloads would also have to be delayed.
1695 TotalNumSLocEntries += F.LocalNumSLocEntries;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001696 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001697 break;
1698
1699 case pch::SOURCE_LOCATION_PRELOADS:
1700 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1701 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1702 if (Result != Success)
1703 return Result;
1704 }
1705 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001706
Douglas Gregor52e71082009-10-16 18:18:30 +00001707 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001708 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001709 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1710 (const unsigned char *)BlobStart,
1711 NumStatHits, NumStatMisses);
1712 FileMgr.addStatCache(MyStatCache);
Sebastian Redl9137a522010-07-16 17:50:48 +00001713 F.StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001714 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001715 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001716
Douglas Gregorb81c1702009-04-27 20:06:05 +00001717 case pch::EXT_VECTOR_DECLS:
Sebastian Redla9f23682010-07-28 21:38:49 +00001718 // Optimization for the first block.
1719 if (ExtVectorDecls.empty())
1720 ExtVectorDecls.swap(Record);
1721 else
1722 ExtVectorDecls.insert(ExtVectorDecls.end(),
1723 Record.begin(), Record.end());
Douglas Gregorb81c1702009-04-27 20:06:05 +00001724 break;
1725
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001726 case pch::VTABLE_USES:
Sebastian Redl40566802010-08-05 18:21:25 +00001727 // Later tables overwrite earlier ones.
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001728 VTableUses.swap(Record);
1729 break;
1730
1731 case pch::DYNAMIC_CLASSES:
Sebastian Redl40566802010-08-05 18:21:25 +00001732 // Optimization for the first block.
1733 if (DynamicClasses.empty())
1734 DynamicClasses.swap(Record);
1735 else
1736 DynamicClasses.insert(DynamicClasses.end(),
1737 Record.begin(), Record.end());
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001738 break;
1739
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00001740 case pch::PENDING_IMPLICIT_INSTANTIATIONS:
1741 // Optimization for the first block.
1742 if (PendingImplicitInstantiations.empty())
1743 PendingImplicitInstantiations.swap(Record);
1744 else
1745 PendingImplicitInstantiations.insert(
1746 PendingImplicitInstantiations.end(), Record.begin(), Record.end());
1747 break;
1748
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001749 case pch::SEMA_DECL_REFS:
Sebastian Redl40566802010-08-05 18:21:25 +00001750 // Later tables overwrite earlier ones.
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001751 SemaDeclRefs.swap(Record);
1752 break;
1753
Douglas Gregorb64c1932009-05-12 01:31:05 +00001754 case pch::ORIGINAL_FILE_NAME:
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001755 // The primary PCH will be the last to get here, so it will be the one
1756 // that's used.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001757 ActualOriginalFileName.assign(BlobStart, BlobLen);
1758 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001759 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001760 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001762 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001763 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001764 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001765 if (llvm::StringRef(CurBranch) != PCHBranch && !DisableValidation) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001766 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1767 return IgnorePCH;
1768 }
1769 break;
1770 }
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001771
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001772 case pch::MACRO_DEFINITION_OFFSETS:
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001773 F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1774 F.NumPreallocatedPreprocessingEntities = Record[0];
1775 F.LocalNumMacroDefinitions = Record[1];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001776 break;
Sebastian Redl0b17c612010-08-13 00:28:03 +00001777
1778 case pch::DECL_REPLACEMENTS: {
1779 if (Record.size() % 2 != 0) {
1780 Error("invalid DECL_REPLACEMENTS block in PCH file");
1781 return Failure;
1782 }
1783 for (unsigned I = 0, N = Record.size(); I != N; I += 2)
1784 ReplacedDecls[static_cast<pch::DeclID>(Record[I])] =
1785 std::make_pair(&F, Record[I+1]);
1786 break;
1787 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001788 }
Sebastian Redl93fb9ed2010-07-19 20:52:06 +00001789 First = false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001790 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001791 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001792 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001793}
1794
Douglas Gregore1d918e2009-04-10 23:10:45 +00001795PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001796 switch(ReadPCHCore(FileName)) {
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001797 case Failure: return Failure;
1798 case IgnorePCH: return IgnorePCH;
1799 case Success: break;
1800 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001801
1802 // Here comes stuff that we only do once the entire chain is loaded.
1803
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001804 // Allocate space for loaded identifiers, decls and types.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001805 unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
Sebastian Redl725cd962010-08-04 20:40:17 +00001806 TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
1807 TotalNumSelectors = 0;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001808 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
Sebastian Redl2da08f92010-07-19 22:28:42 +00001809 TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001810 TotalNumTypes += Chain[I]->LocalNumTypes;
1811 TotalNumDecls += Chain[I]->LocalNumDecls;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001812 TotalNumPreallocatedPreprocessingEntities +=
1813 Chain[I]->NumPreallocatedPreprocessingEntities;
1814 TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
Sebastian Redl725cd962010-08-04 20:40:17 +00001815 TotalNumSelectors += Chain[I]->LocalNumSelectors;
Sebastian Redl12d6da02010-07-19 22:06:55 +00001816 }
Sebastian Redl2da08f92010-07-19 22:28:42 +00001817 IdentifiersLoaded.resize(TotalNumIdentifiers);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001818 TypesLoaded.resize(TotalNumTypes);
1819 DeclsLoaded.resize(TotalNumDecls);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001820 MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
1821 if (PP) {
1822 if (TotalNumIdentifiers > 0)
1823 PP->getHeaderSearchInfo().SetExternalLookup(this);
1824 if (TotalNumPreallocatedPreprocessingEntities > 0) {
1825 if (!PP->getPreprocessingRecord())
1826 PP->createPreprocessingRecord();
1827 PP->getPreprocessingRecord()->SetExternalSource(*this,
1828 TotalNumPreallocatedPreprocessingEntities);
1829 }
1830 }
Sebastian Redl725cd962010-08-04 20:40:17 +00001831 SelectorsLoaded.resize(TotalNumSelectors);
Sebastian Redl12d6da02010-07-19 22:06:55 +00001832
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001833 // Check the predefines buffers.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001834 if (!DisableValidation && CheckPredefinesBuffers())
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001835 return IgnorePCH;
1836
1837 if (PP) {
1838 // Initialization of keywords and pragmas occurs before the
1839 // PCH file is read, so there may be some identifiers that were
1840 // loaded into the IdentifierTable before we intercepted the
1841 // creation of identifiers. Iterate through the list of known
1842 // identifiers and determine whether we have to establish
1843 // preprocessor definitions or top-level identifier declaration
1844 // chains for those identifiers.
1845 //
1846 // We copy the IdentifierInfo pointers to a small vector first,
1847 // since de-serializing declarations or macro definitions can add
1848 // new entries into the identifier table, invalidating the
1849 // iterators.
1850 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1851 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1852 IdEnd = PP->getIdentifierTable().end();
1853 Id != IdEnd; ++Id)
1854 Identifiers.push_back(Id->second);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001855 // We need to search the tables in all files.
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001856 for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
1857 PCHIdentifierLookupTable *IdTable
1858 = (PCHIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00001859 // Not all PCH files necessarily have identifier tables, only the useful
1860 // ones.
1861 if (!IdTable)
1862 continue;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001863 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1864 IdentifierInfo *II = Identifiers[I];
1865 // Look in the on-disk hash tables for an entry for this identifier
Sebastian Redld27d3fc2010-07-21 22:31:37 +00001866 PCHIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001867 std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001868 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1869 if (Pos == IdTable->end())
1870 continue;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001871
Sebastian Redl518d8cb2010-07-20 21:20:32 +00001872 // Dereferencing the iterator has the effect of populating the
1873 // IdentifierInfo node with the various declarations it needs.
1874 (void)*Pos;
1875 }
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001876 }
1877 }
1878
1879 if (Context)
1880 InitializeContext(*Context);
1881
1882 return Success;
1883}
1884
1885PCHReader::PCHReadResult PCHReader::ReadPCHCore(llvm::StringRef FileName) {
1886 Chain.push_back(new PerFileData());
Sebastian Redl9137a522010-07-16 17:50:48 +00001887 PerFileData &F = *Chain.back();
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001888
1889 // Set the PCH file name.
1890 F.FileName = FileName;
1891
1892 // Open the PCH file.
1893 //
1894 // FIXME: This shouldn't be here, we should just take a raw_ostream.
1895 std::string ErrStr;
1896 F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
1897 if (!F.Buffer) {
1898 Error(ErrStr.c_str());
1899 return IgnorePCH;
1900 }
1901
1902 // Initialize the stream
1903 F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
1904 (const unsigned char *)F.Buffer->getBufferEnd());
Sebastian Redl9137a522010-07-16 17:50:48 +00001905 llvm::BitstreamCursor &Stream = F.Stream;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001906 Stream.init(F.StreamFile);
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001907 F.SizeInBits = F.Buffer->getBufferSize() * 8;
Sebastian Redlfbd4bf12010-07-17 00:12:06 +00001908
1909 // Sniff for the signature.
1910 if (Stream.Read(8) != 'C' ||
1911 Stream.Read(8) != 'P' ||
1912 Stream.Read(8) != 'C' ||
1913 Stream.Read(8) != 'H') {
1914 Diag(diag::err_not_a_pch_file) << FileName;
1915 return Failure;
1916 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001917
Douglas Gregor2cf26342009-04-09 22:27:44 +00001918 while (!Stream.AtEndOfStream()) {
1919 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Douglas Gregore1d918e2009-04-10 23:10:45 +00001921 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001922 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001923 return Failure;
1924 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001925
1926 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001927
Douglas Gregor2cf26342009-04-09 22:27:44 +00001928 // We only know the PCH subblock ID.
1929 switch (BlockID) {
1930 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001931 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001932 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001933 return Failure;
1934 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001935 break;
1936 case pch::PCH_BLOCK_ID:
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001937 switch (ReadPCHBlock(F)) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001938 case Success:
1939 break;
1940
1941 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001942 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001943
1944 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001945 // FIXME: We could consider reading through to the end of this
1946 // PCH block, skipping subblocks, to see if there are other
1947 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001948
1949 // Clear out any preallocated source location entries, so that
1950 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001951 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001952
1953 // Remove the stat cache.
Sebastian Redl9137a522010-07-16 17:50:48 +00001954 if (F.StatCache)
1955 FileMgr.removeStatCache((PCHStatCache*)F.StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001956
Douglas Gregore1d918e2009-04-10 23:10:45 +00001957 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001958 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001959 break;
1960 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001961 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001962 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001963 return Failure;
1964 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001965 break;
1966 }
Mike Stump1eb44332009-09-09 15:08:12 +00001967 }
1968
Sebastian Redlcdf3b832010-07-16 20:41:52 +00001969 return Success;
1970}
1971
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001972void PCHReader::setPreprocessor(Preprocessor &pp) {
1973 PP = &pp;
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001974
1975 unsigned TotalNum = 0;
1976 for (unsigned I = 0, N = Chain.size(); I != N; ++I)
1977 TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
1978 if (TotalNum) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001979 if (!PP->getPreprocessingRecord())
1980 PP->createPreprocessingRecord();
Sebastian Redl04e6fd42010-07-21 20:07:32 +00001981 PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001982 }
1983}
1984
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001985void PCHReader::InitializeContext(ASTContext &Ctx) {
1986 Context = &Ctx;
1987 assert(Context && "Passed null context!");
1988
1989 assert(PP && "Forgot to set Preprocessor ?");
1990 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1991 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001992 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001993
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001994 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001995 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001996
1997 // Load the special types.
1998 Context->setBuiltinVaListType(
1999 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
2000 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
2001 Context->setObjCIdType(GetType(Id));
2002 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
2003 Context->setObjCSelType(GetType(Sel));
2004 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
2005 Context->setObjCProtoType(GetType(Proto));
2006 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
2007 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00002008
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002009 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
2010 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00002011 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002012 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
2013 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002014 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
2015 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002016 if (FileType.isNull()) {
2017 Error("FILE type is NULL");
2018 return;
2019 }
John McCall183700f2009-09-21 23:43:11 +00002020 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002021 Context->setFILEDecl(Typedef->getDecl());
2022 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002023 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002024 if (!Tag) {
2025 Error("Invalid FILE type in PCH file");
2026 return;
2027 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00002028 Context->setFILEDecl(Tag->getDecl());
2029 }
2030 }
Mike Stump782fa302009-07-28 02:25:19 +00002031 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
2032 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002033 if (Jmp_bufType.isNull()) {
2034 Error("jmp_bug type is NULL");
2035 return;
2036 }
John McCall183700f2009-09-21 23:43:11 +00002037 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002038 Context->setjmp_bufDecl(Typedef->getDecl());
2039 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002040 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002041 if (!Tag) {
2042 Error("Invalid jmp_bug type in PCH file");
2043 return;
2044 }
Mike Stump782fa302009-07-28 02:25:19 +00002045 Context->setjmp_bufDecl(Tag->getDecl());
2046 }
2047 }
2048 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
2049 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002050 if (Sigjmp_bufType.isNull()) {
2051 Error("sigjmp_buf type is NULL");
2052 return;
2053 }
John McCall183700f2009-09-21 23:43:11 +00002054 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00002055 Context->setsigjmp_bufDecl(Typedef->getDecl());
2056 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00002057 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00002058 assert(Tag && "Invalid sigjmp_buf type in PCH file");
2059 Context->setsigjmp_bufDecl(Tag->getDecl());
2060 }
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002063 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2064 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00002065 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00002066 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2067 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00002068 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2069 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00002070 if (unsigned String
2071 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2072 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002073 if (unsigned ObjCSelRedef
2074 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2075 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2076 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
2077 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00002078
2079 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
2080 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002081}
2082
Douglas Gregorb64c1932009-05-12 01:31:05 +00002083/// \brief Retrieve the name of the original source file name
2084/// directly from the PCH file, without actually loading the PCH
2085/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002086std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
2087 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00002088 // Open the PCH file.
2089 std::string ErrStr;
2090 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2091 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
2092 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002093 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002094 return std::string();
2095 }
2096
2097 // Initialize the stream
2098 llvm::BitstreamReader StreamFile;
2099 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00002100 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00002101 (const unsigned char *)Buffer->getBufferEnd());
2102 Stream.init(StreamFile);
2103
2104 // Sniff for the signature.
2105 if (Stream.Read(8) != 'C' ||
2106 Stream.Read(8) != 'P' ||
2107 Stream.Read(8) != 'C' ||
2108 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002109 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002110 return std::string();
2111 }
2112
2113 RecordData Record;
2114 while (!Stream.AtEndOfStream()) {
2115 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Douglas Gregorb64c1932009-05-12 01:31:05 +00002117 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2118 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Douglas Gregorb64c1932009-05-12 01:31:05 +00002120 // We only know the PCH subblock ID.
2121 switch (BlockID) {
2122 case pch::PCH_BLOCK_ID:
2123 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002124 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002125 return std::string();
2126 }
2127 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Douglas Gregorb64c1932009-05-12 01:31:05 +00002129 default:
2130 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002131 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002132 return std::string();
2133 }
2134 break;
2135 }
2136 continue;
2137 }
2138
2139 if (Code == llvm::bitc::END_BLOCK) {
2140 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00002141 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00002142 return std::string();
2143 }
2144 continue;
2145 }
2146
2147 if (Code == llvm::bitc::DEFINE_ABBREV) {
2148 Stream.ReadAbbrevRecord();
2149 continue;
2150 }
2151
2152 Record.clear();
2153 const char *BlobStart = 0;
2154 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002155 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00002156 == pch::ORIGINAL_FILE_NAME)
2157 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00002158 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00002159
2160 return std::string();
2161}
2162
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002163/// \brief Parse the record that corresponds to a LangOptions data
2164/// structure.
2165///
2166/// This routine compares the language options used to generate the
2167/// PCH file against the language options set for the current
2168/// compilation. For each option, we classify differences between the
2169/// two compiler states as either "benign" or "important". Benign
2170/// differences don't matter, and we accept them without complaint
2171/// (and without modifying the language options). Differences between
2172/// the states for important options cause the PCH file to be
2173/// unusable, so we emit a warning and return true to indicate that
2174/// there was an error.
2175///
2176/// \returns true if the PCH file is unacceptable, false otherwise.
2177bool PCHReader::ParseLanguageOptions(
2178 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002179 if (Listener) {
2180 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002182 #define PARSE_LANGOPT(Option) \
2183 LangOpts.Option = Record[Idx]; \
2184 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002186 unsigned Idx = 0;
2187 PARSE_LANGOPT(Trigraphs);
2188 PARSE_LANGOPT(BCPLComment);
2189 PARSE_LANGOPT(DollarIdents);
2190 PARSE_LANGOPT(AsmPreprocessor);
2191 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00002192 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002193 PARSE_LANGOPT(ImplicitInt);
2194 PARSE_LANGOPT(Digraphs);
2195 PARSE_LANGOPT(HexFloats);
2196 PARSE_LANGOPT(C99);
2197 PARSE_LANGOPT(Microsoft);
2198 PARSE_LANGOPT(CPlusPlus);
2199 PARSE_LANGOPT(CPlusPlus0x);
2200 PARSE_LANGOPT(CXXOperatorNames);
2201 PARSE_LANGOPT(ObjC1);
2202 PARSE_LANGOPT(ObjC2);
2203 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00002204 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00002205 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002206 PARSE_LANGOPT(PascalStrings);
2207 PARSE_LANGOPT(WritableStrings);
2208 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002209 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002210 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002211 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002212 PARSE_LANGOPT(NeXTRuntime);
2213 PARSE_LANGOPT(Freestanding);
2214 PARSE_LANGOPT(NoBuiltin);
2215 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002216 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002217 PARSE_LANGOPT(Blocks);
2218 PARSE_LANGOPT(EmitAllDecls);
2219 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002220 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2221 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002222 PARSE_LANGOPT(HeinousExtensions);
2223 PARSE_LANGOPT(Optimize);
2224 PARSE_LANGOPT(OptimizeSize);
2225 PARSE_LANGOPT(Static);
2226 PARSE_LANGOPT(PICLevel);
2227 PARSE_LANGOPT(GNUInline);
2228 PARSE_LANGOPT(NoInline);
2229 PARSE_LANGOPT(AccessControl);
2230 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002231 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002232 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2233 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002234 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002235 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002236 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002237 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002238 PARSE_LANGOPT(CatchUndefined);
2239 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002240 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002241
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002242 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002243 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002244
2245 return false;
2246}
2247
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002248void PCHReader::ReadPreprocessedEntities() {
2249 ReadDefinedMacros();
2250}
2251
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002252/// \brief Get the correct cursor and offset for loading a type.
2253PCHReader::RecordLocation PCHReader::TypeCursorForIndex(unsigned Index) {
2254 PerFileData *F = 0;
2255 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2256 F = Chain[N - I - 1];
2257 if (Index < F->LocalNumTypes)
2258 break;
2259 Index -= F->LocalNumTypes;
2260 }
2261 assert(F && F->LocalNumTypes > Index && "Broken chain");
Sebastian Redl971dd442010-07-20 22:55:31 +00002262 return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002263}
2264
2265/// \brief Read and return the type with the given index..
Douglas Gregor2cf26342009-04-09 22:27:44 +00002266///
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002267/// The index is the type ID, shifted and minus the number of predefs. This
2268/// routine actually reads the record corresponding to the type at the given
2269/// location. It is a helper routine for GetType, which deals with reading type
2270/// IDs.
2271QualType PCHReader::ReadTypeRecord(unsigned Index) {
2272 RecordLocation Loc = TypeCursorForIndex(Index);
Sebastian Redl971dd442010-07-20 22:55:31 +00002273 llvm::BitstreamCursor &DeclsCursor = *Loc.first;
Sebastian Redl9137a522010-07-16 17:50:48 +00002274
Douglas Gregor0b748912009-04-14 21:18:50 +00002275 // Keep track of where we are in the stream, then jump back there
2276 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002277 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002278
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002279 ReadingKindTracker ReadingKind(Read_Type, *this);
Sebastian Redl27372b42010-08-11 18:52:41 +00002280
Douglas Gregord89275b2009-07-06 18:54:52 +00002281 // Note that we are loading a type record.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00002282 Deserializing AType(this);
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002284 DeclsCursor.JumpToBit(Loc.second);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002285 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002286 unsigned Code = DeclsCursor.ReadCode();
2287 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002288 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002289 if (Record.size() != 2) {
2290 Error("Incorrect encoding of extended qualifier type");
2291 return QualType();
2292 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002293 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002294 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2295 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002296 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002297
Douglas Gregor2cf26342009-04-09 22:27:44 +00002298 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002299 if (Record.size() != 1) {
2300 Error("Incorrect encoding of complex type");
2301 return QualType();
2302 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002303 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002304 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002305 }
2306
2307 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002308 if (Record.size() != 1) {
2309 Error("Incorrect encoding of pointer type");
2310 return QualType();
2311 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002312 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002313 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002314 }
2315
2316 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002317 if (Record.size() != 1) {
2318 Error("Incorrect encoding of block pointer type");
2319 return QualType();
2320 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002321 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002322 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002323 }
2324
2325 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002326 if (Record.size() != 1) {
2327 Error("Incorrect encoding of lvalue reference type");
2328 return QualType();
2329 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002330 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002331 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002332 }
2333
2334 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002335 if (Record.size() != 1) {
2336 Error("Incorrect encoding of rvalue reference type");
2337 return QualType();
2338 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002339 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002340 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002341 }
2342
2343 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002344 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002345 Error("Incorrect encoding of member pointer type");
2346 return QualType();
2347 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002348 QualType PointeeType = GetType(Record[0]);
2349 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002350 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002351 }
2352
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002353 case pch::TYPE_CONSTANT_ARRAY: {
2354 QualType ElementType = GetType(Record[0]);
2355 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2356 unsigned IndexTypeQuals = Record[2];
2357 unsigned Idx = 3;
2358 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002359 return Context->getConstantArrayType(ElementType, Size,
2360 ASM, IndexTypeQuals);
2361 }
2362
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002363 case pch::TYPE_INCOMPLETE_ARRAY: {
2364 QualType ElementType = GetType(Record[0]);
2365 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2366 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002367 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002368 }
2369
2370 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002371 QualType ElementType = GetType(Record[0]);
2372 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2373 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002374 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2375 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Sebastian Redl577d4792010-07-22 22:43:28 +00002376 return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002377 ASM, IndexTypeQuals,
2378 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002379 }
2380
2381 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002382 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002383 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002384 return QualType();
2385 }
2386
2387 QualType ElementType = GetType(Record[0]);
2388 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002389 unsigned AltiVecSpec = Record[2];
2390 return Context->getVectorType(ElementType, NumElements,
2391 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002392 }
2393
2394 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002395 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002396 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002397 return QualType();
2398 }
2399
2400 QualType ElementType = GetType(Record[0]);
2401 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002402 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002403 }
2404
2405 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002406 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002407 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002408 return QualType();
2409 }
2410 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002411 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002412 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002413 }
2414
2415 case pch::TYPE_FUNCTION_PROTO: {
2416 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002417 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002418 unsigned RegParm = Record[2];
2419 CallingConv CallConv = (CallingConv)Record[3];
2420 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002421 unsigned NumParams = Record[Idx++];
2422 llvm::SmallVector<QualType, 16> ParamTypes;
2423 for (unsigned I = 0; I != NumParams; ++I)
2424 ParamTypes.push_back(GetType(Record[Idx++]));
2425 bool isVariadic = Record[Idx++];
2426 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002427 bool hasExceptionSpec = Record[Idx++];
2428 bool hasAnyExceptionSpec = Record[Idx++];
2429 unsigned NumExceptions = Record[Idx++];
2430 llvm::SmallVector<QualType, 2> Exceptions;
2431 for (unsigned I = 0; I != NumExceptions; ++I)
2432 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002433 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002434 isVariadic, Quals, hasExceptionSpec,
2435 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002436 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002437 FunctionType::ExtInfo(NoReturn, RegParm,
2438 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002439 }
2440
John McCalled976492009-12-04 22:46:56 +00002441 case pch::TYPE_UNRESOLVED_USING:
2442 return Context->getTypeDeclType(
2443 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2444
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002445 case pch::TYPE_TYPEDEF: {
2446 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002447 Error("incorrect encoding of typedef type");
2448 return QualType();
2449 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002450 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2451 QualType Canonical = GetType(Record[1]);
2452 return Context->getTypedefType(Decl, Canonical);
2453 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002454
2455 case pch::TYPE_TYPEOF_EXPR:
Sebastian Redl577d4792010-07-22 22:43:28 +00002456 return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002457
2458 case pch::TYPE_TYPEOF: {
2459 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002460 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002461 return QualType();
2462 }
2463 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002464 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002465 }
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Anders Carlsson395b4752009-06-24 19:06:50 +00002467 case pch::TYPE_DECLTYPE:
Sebastian Redl577d4792010-07-22 22:43:28 +00002468 return Context->getDecltypeType(ReadExpr(DeclsCursor));
Anders Carlsson395b4752009-06-24 19:06:50 +00002469
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002470 case pch::TYPE_RECORD: {
2471 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002472 Error("incorrect encoding of record type");
2473 return QualType();
2474 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002475 bool IsDependent = Record[0];
2476 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2477 T->Dependent = IsDependent;
2478 return T;
2479 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002480
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002481 case pch::TYPE_ENUM: {
2482 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002483 Error("incorrect encoding of enum type");
2484 return QualType();
2485 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002486 bool IsDependent = Record[0];
2487 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2488 T->Dependent = IsDependent;
2489 return T;
2490 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002491
John McCall7da24312009-09-05 00:15:47 +00002492 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002493 unsigned Idx = 0;
2494 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2495 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2496 QualType NamedType = GetType(Record[Idx++]);
2497 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002498 }
2499
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002500 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002501 unsigned Idx = 0;
2502 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002503 return Context->getObjCInterfaceType(ItfD);
2504 }
2505
2506 case pch::TYPE_OBJC_OBJECT: {
2507 unsigned Idx = 0;
2508 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002509 unsigned NumProtos = Record[Idx++];
2510 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2511 for (unsigned I = 0; I != NumProtos; ++I)
2512 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002513 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002514 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002515
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002516 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002517 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002518 QualType Pointee = GetType(Record[Idx++]);
2519 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002520 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002521
John McCall49a832b2009-10-18 09:09:24 +00002522 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2523 unsigned Idx = 0;
2524 QualType Parm = GetType(Record[Idx++]);
2525 QualType Replacement = GetType(Record[Idx++]);
2526 return
2527 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2528 Replacement);
2529 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002530
2531 case pch::TYPE_INJECTED_CLASS_NAME: {
2532 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2533 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002534 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2535 // for PCH reading, too much interdependencies.
2536 return
2537 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002538 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002539
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002540 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2541 unsigned Idx = 0;
2542 unsigned Depth = Record[Idx++];
2543 unsigned Index = Record[Idx++];
2544 bool Pack = Record[Idx++];
2545 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2546 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2547 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002548
2549 case pch::TYPE_DEPENDENT_NAME: {
2550 unsigned Idx = 0;
2551 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2552 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2553 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002554 QualType Canon = GetType(Record[Idx++]);
2555 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002556 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002557
2558 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2559 unsigned Idx = 0;
2560 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2561 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2562 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2563 unsigned NumArgs = Record[Idx++];
2564 llvm::SmallVector<TemplateArgument, 8> Args;
2565 Args.reserve(NumArgs);
2566 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00002567 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002568 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2569 Args.size(), Args.data());
2570 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002571
2572 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2573 unsigned Idx = 0;
2574
2575 // ArrayType
2576 QualType ElementType = GetType(Record[Idx++]);
2577 ArrayType::ArraySizeModifier ASM
2578 = (ArrayType::ArraySizeModifier)Record[Idx++];
2579 unsigned IndexTypeQuals = Record[Idx++];
2580
2581 // DependentSizedArrayType
Sebastian Redl577d4792010-07-22 22:43:28 +00002582 Expr *NumElts = ReadExpr(DeclsCursor);
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002583 SourceRange Brackets = ReadSourceRange(Record, Idx);
2584
2585 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2586 IndexTypeQuals, Brackets);
2587 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002588
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002589 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2590 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002591 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002592 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002593 llvm::SmallVector<TemplateArgument, 8> Args;
Sebastian Redl577d4792010-07-22 22:43:28 +00002594 ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002595 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002596 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002597 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002598 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2599 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002600 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002601 T = Context->getTemplateSpecializationType(Name, Args.data(),
2602 Args.size(), Canon);
2603 T->Dependent = IsDependent;
2604 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002605 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002606 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002607 // Suppress a GCC warning
2608 return QualType();
2609}
2610
John McCalla1ee0c52009-10-16 21:56:05 +00002611namespace {
2612
2613class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2614 PCHReader &Reader;
Sebastian Redl577d4792010-07-22 22:43:28 +00002615 llvm::BitstreamCursor &DeclsCursor;
John McCalla1ee0c52009-10-16 21:56:05 +00002616 const PCHReader::RecordData &Record;
2617 unsigned &Idx;
2618
2619public:
Sebastian Redl577d4792010-07-22 22:43:28 +00002620 TypeLocReader(PCHReader &Reader, llvm::BitstreamCursor &Cursor,
2621 const PCHReader::RecordData &Record, unsigned &Idx)
2622 : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
John McCalla1ee0c52009-10-16 21:56:05 +00002623
John McCall51bd8032009-10-18 01:05:36 +00002624 // We want compile-time assurance that we've enumerated all of
2625 // these, so unfortunately we have to declare them first, then
2626 // define them out-of-line.
2627#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002628#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002629 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002630#include "clang/AST/TypeLocNodes.def"
2631
John McCall51bd8032009-10-18 01:05:36 +00002632 void VisitFunctionTypeLoc(FunctionTypeLoc);
2633 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002634};
2635
2636}
2637
John McCall51bd8032009-10-18 01:05:36 +00002638void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002639 // nothing to do
2640}
John McCall51bd8032009-10-18 01:05:36 +00002641void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002642 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2643 if (TL.needsExtraLocalData()) {
2644 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2645 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2646 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2647 TL.setModeAttr(Record[Idx++]);
2648 }
John McCalla1ee0c52009-10-16 21:56:05 +00002649}
John McCall51bd8032009-10-18 01:05:36 +00002650void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2651 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002652}
John McCall51bd8032009-10-18 01:05:36 +00002653void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2654 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002655}
John McCall51bd8032009-10-18 01:05:36 +00002656void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2657 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002658}
John McCall51bd8032009-10-18 01:05:36 +00002659void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2660 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002661}
John McCall51bd8032009-10-18 01:05:36 +00002662void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2663 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002664}
John McCall51bd8032009-10-18 01:05:36 +00002665void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2666 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002667}
John McCall51bd8032009-10-18 01:05:36 +00002668void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2669 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2670 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002671 if (Record[Idx++])
Sebastian Redl577d4792010-07-22 22:43:28 +00002672 TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002673 else
John McCall51bd8032009-10-18 01:05:36 +00002674 TL.setSizeExpr(0);
2675}
2676void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2677 VisitArrayTypeLoc(TL);
2678}
2679void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2680 VisitArrayTypeLoc(TL);
2681}
2682void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2683 VisitArrayTypeLoc(TL);
2684}
2685void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2686 DependentSizedArrayTypeLoc TL) {
2687 VisitArrayTypeLoc(TL);
2688}
2689void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2690 DependentSizedExtVectorTypeLoc TL) {
2691 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2692}
2693void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2694 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2695}
2696void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2697 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2698}
2699void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2700 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2701 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2702 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002703 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002704 }
2705}
2706void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2707 VisitFunctionTypeLoc(TL);
2708}
2709void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2710 VisitFunctionTypeLoc(TL);
2711}
John McCalled976492009-12-04 22:46:56 +00002712void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2713 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2714}
John McCall51bd8032009-10-18 01:05:36 +00002715void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2716 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2717}
2718void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002719 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2720 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2721 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002722}
2723void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002724 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2725 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2726 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Sebastian Redl577d4792010-07-22 22:43:28 +00002727 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002728}
2729void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2730 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2731}
2732void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2733 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2734}
2735void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2736 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2737}
John McCall51bd8032009-10-18 01:05:36 +00002738void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2739 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2740}
John McCall49a832b2009-10-18 09:09:24 +00002741void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2742 SubstTemplateTypeParmTypeLoc TL) {
2743 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2744}
John McCall51bd8032009-10-18 01:05:36 +00002745void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2746 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002747 TL.setTemplateNameLoc(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 McCall51bd8032009-10-18 01:05:36 +00002754}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002755void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002756 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2757 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002758}
John McCall3cb0ebd2010-03-10 03:28:59 +00002759void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2760 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2761}
Douglas Gregor4714c122010-03-31 17:34:00 +00002762void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002763 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2764 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002765 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2766}
John McCall33500952010-06-11 00:33:02 +00002767void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2768 DependentTemplateSpecializationTypeLoc TL) {
2769 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2770 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2771 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2772 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2773 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2774 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2775 TL.setArgLocInfo(I,
2776 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002777 DeclsCursor, Record, Idx));
John McCall33500952010-06-11 00:33:02 +00002778}
John McCall51bd8032009-10-18 01:05:36 +00002779void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2780 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002781}
2782void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2783 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002784 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2785 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2786 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2787 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002788}
John McCall54e14c42009-10-22 22:37:11 +00002789void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2790 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002791}
John McCalla1ee0c52009-10-16 21:56:05 +00002792
Sebastian Redl577d4792010-07-22 22:43:28 +00002793TypeSourceInfo *PCHReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2794 const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002795 unsigned &Idx) {
2796 QualType InfoTy = GetType(Record[Idx++]);
2797 if (InfoTy.isNull())
2798 return 0;
2799
John McCalla93c9342009-12-07 02:54:59 +00002800 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
Sebastian Redl577d4792010-07-22 22:43:28 +00002801 TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002802 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002803 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002804 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002805}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002806
Douglas Gregor8038d512009-04-10 17:25:41 +00002807QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002808 unsigned FastQuals = ID & Qualifiers::FastMask;
2809 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002810
2811 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2812 QualType T;
2813 switch ((pch::PredefinedTypeIDs)Index) {
2814 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002815 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2816 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002817
2818 case pch::PREDEF_TYPE_CHAR_U_ID:
2819 case pch::PREDEF_TYPE_CHAR_S_ID:
2820 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002821 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002822 break;
2823
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002824 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2825 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2826 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2827 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2828 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002829 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002830 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2831 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2832 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2833 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2834 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2835 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002836 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002837 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2838 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2839 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2840 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2841 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002842 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002843 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2844 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002845 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2846 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002847 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002848 }
2849
2850 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002851 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002852 }
2853
2854 Index -= pch::NUM_PREDEF_TYPE_IDS;
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002855 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002856 if (TypesLoaded[Index].isNull()) {
Sebastian Redlaaec0aa2010-07-20 22:37:49 +00002857 TypesLoaded[Index] = ReadTypeRecord(Index);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002858 TypesLoaded[Index]->setFromPCH();
Sebastian Redl30c514c2010-07-14 23:45:08 +00002859 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002860 DeserializationListener->TypeRead(ID >> Qualifiers::FastWidth,
2861 TypesLoaded[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002862 }
Mike Stump1eb44332009-09-09 15:08:12 +00002863
John McCall0953e762009-09-24 19:53:00 +00002864 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002865}
2866
John McCall833ca992009-10-29 08:12:44 +00002867TemplateArgumentLocInfo
2868PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Sebastian Redl577d4792010-07-22 22:43:28 +00002869 llvm::BitstreamCursor &DeclsCursor,
John McCall833ca992009-10-29 08:12:44 +00002870 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002871 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002872 switch (Kind) {
2873 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00002874 return ReadExpr(DeclsCursor);
John McCall833ca992009-10-29 08:12:44 +00002875 case TemplateArgument::Type:
Sebastian Redl577d4792010-07-22 22:43:28 +00002876 return GetTypeSourceInfo(DeclsCursor, Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002877 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002878 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2879 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2880 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002881 }
John McCall833ca992009-10-29 08:12:44 +00002882 case TemplateArgument::Null:
2883 case TemplateArgument::Integral:
2884 case TemplateArgument::Declaration:
2885 case TemplateArgument::Pack:
2886 return TemplateArgumentLocInfo();
2887 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002888 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002889 return TemplateArgumentLocInfo();
2890}
2891
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002892TemplateArgumentLoc
Sebastian Redl577d4792010-07-22 22:43:28 +00002893PCHReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
2894 const RecordData &Record, unsigned &Index) {
2895 TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002896
2897 if (Arg.getKind() == TemplateArgument::Expression) {
2898 if (Record[Index++]) // bool InfoHasSameExpr.
2899 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2900 }
2901 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Sebastian Redl577d4792010-07-22 22:43:28 +00002902 DeclsCursor,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002903 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002904}
2905
John McCall76bd1f32010-06-01 09:23:16 +00002906Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2907 return GetDecl(ID);
2908}
2909
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002910TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
Sebastian Redl30c514c2010-07-14 23:45:08 +00002911 if (!DeclsLoaded[0]) {
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00002912 ReadDeclRecord(0, 0);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002913 if (DeserializationListener)
Sebastian Redl1476ed42010-07-16 16:36:56 +00002914 DeserializationListener->DeclRead(1, DeclsLoaded[0]);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002915 }
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002916
2917 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2918}
2919
Douglas Gregor8038d512009-04-10 17:25:41 +00002920Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002921 if (ID == 0)
2922 return 0;
2923
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002924 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002925 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002926 return 0;
2927 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002928
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002929 unsigned Index = ID - 1;
Sebastian Redl30c514c2010-07-14 23:45:08 +00002930 if (!DeclsLoaded[Index]) {
Argyrios Kyrtzidisa8650052010-08-03 17:30:10 +00002931 ReadDeclRecord(Index, ID);
Sebastian Redl30c514c2010-07-14 23:45:08 +00002932 if (DeserializationListener)
2933 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
2934 }
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002935
2936 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002937}
2938
Chris Lattner887e2b32009-04-27 05:46:25 +00002939/// \brief Resolve the offset of a statement into a statement.
2940///
2941/// This operation will read a new statement from the external
2942/// source each time it is called, and is meant to be used via a
2943/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002944Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002945 // Offset here is a global offset across the entire chain.
2946 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2947 PerFileData &F = *Chain[N - I - 1];
2948 if (Offset < F.SizeInBits) {
2949 // Since we know that this statement is part of a decl, make sure to use
2950 // the decl cursor to read it.
2951 F.DeclsCursor.JumpToBit(Offset);
2952 return ReadStmtFromStream(F.DeclsCursor);
2953 }
2954 Offset -= F.SizeInBits;
2955 }
2956 llvm_unreachable("Broken chain");
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002957}
2958
John McCall76bd1f32010-06-01 09:23:16 +00002959bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2960 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002961 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002962 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002963
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002964 // There might be lexical decls in multiple parts of the chain, for the TU
2965 // at least.
2966 DeclContextInfos &Infos = DeclContextOffsets[DC];
2967 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2968 I != E; ++I) {
Sebastian Redl681d7232010-07-27 00:17:23 +00002969 // IDs can be 0 if this context doesn't contain declarations.
2970 if (!I->LexicalDecls)
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002971 continue;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002972
2973 // Load all of the declaration IDs
Sebastian Redl681d7232010-07-27 00:17:23 +00002974 for (const pch::DeclID *ID = I->LexicalDecls,
2975 *IDE = ID + I->NumLexicalDecls;
2976 ID != IDE; ++ID)
2977 Decls.push_back(GetDecl(*ID));
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002978 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002979
Douglas Gregor25123082009-04-22 22:34:57 +00002980 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002981 return false;
2982}
2983
John McCall76bd1f32010-06-01 09:23:16 +00002984DeclContext::lookup_result
2985PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2986 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002987 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002988 "DeclContext has no visible decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002989
John McCall76bd1f32010-06-01 09:23:16 +00002990 llvm::SmallVector<VisibleDeclaration, 64> Decls;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00002991 // There might be lexical decls in multiple parts of the chain, for the TU
2992 // and namespaces.
2993 DeclContextInfos &Infos = DeclContextOffsets[DC];
2994 for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
2995 I != E; ++I) {
2996 uint64_t Offset = I->OffsetToVisibleDecls;
2997 if (Offset == 0)
2998 continue;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002999
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00003000 llvm::BitstreamCursor &DeclsCursor = *I->Stream;
Douglas Gregor2cf26342009-04-09 22:27:44 +00003001
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00003002 // Keep track of where we are in the stream, then jump back there
3003 // after reading this context.
3004 SavedStreamPosition SavedPosition(DeclsCursor);
3005
3006 // Load the record containing all of the declarations visible in
3007 // this context.
3008 DeclsCursor.JumpToBit(Offset);
3009 RecordData Record;
3010 unsigned Code = DeclsCursor.ReadCode();
3011 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
3012 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
3013 Error("Expected visible block");
3014 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
3015 DeclContext::lookup_iterator());
3016 }
3017
3018 if (Record.empty())
3019 continue;
3020
3021 unsigned Idx = 0;
3022 while (Idx < Record.size()) {
3023 Decls.push_back(VisibleDeclaration());
3024 Decls.back().Name = ReadDeclarationName(Record, Idx);
3025
3026 unsigned Size = Record[Idx++];
3027 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
3028 LoadedDecls.reserve(Size);
3029 for (unsigned J = 0; J < Size; ++J)
3030 LoadedDecls.push_back(Record[Idx++]);
3031 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003032 }
3033
Douglas Gregor25123082009-04-22 22:34:57 +00003034 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00003035
3036 SetExternalVisibleDecls(DC, Decls);
3037 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00003038}
3039
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003040void PCHReader::PassInterestingDeclsToConsumer() {
3041 assert(Consumer);
3042 while (!InterestingDecls.empty()) {
3043 DeclGroupRef DG(InterestingDecls.front());
3044 InterestingDecls.pop_front();
Sebastian Redl27372b42010-08-11 18:52:41 +00003045 Consumer->HandleInterestingDecl(DG);
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003046 }
3047}
3048
Douglas Gregorfdd01722009-04-14 00:24:19 +00003049void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00003050 this->Consumer = Consumer;
3051
Douglas Gregorfdd01722009-04-14 00:24:19 +00003052 if (!Consumer)
3053 return;
3054
3055 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003056 // Force deserialization of this decl, which will cause it to be queued for
3057 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00003058 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00003059 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00003060
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003061 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00003062}
3063
Douglas Gregor2cf26342009-04-09 22:27:44 +00003064void PCHReader::PrintStats() {
3065 std::fprintf(stderr, "*** PCH Statistics:\n");
3066
Mike Stump1eb44332009-09-09 15:08:12 +00003067 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003068 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00003069 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003070 unsigned NumDeclsLoaded
3071 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3072 (Decl *)0);
3073 unsigned NumIdentifiersLoaded
3074 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3075 IdentifiersLoaded.end(),
3076 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00003077 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003078 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3079 SelectorsLoaded.end(),
3080 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00003081
Douglas Gregor4fed3f42009-04-27 18:38:38 +00003082 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
3083 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003084 if (TotalNumSLocEntries)
3085 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
3086 NumSLocEntriesRead, TotalNumSLocEntries,
3087 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003088 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003089 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003090 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3091 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3092 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003093 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00003094 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3095 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003096 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003097 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003098 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3099 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Sebastian Redl725cd962010-08-04 20:40:17 +00003100 if (!SelectorsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00003101 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
Sebastian Redl725cd962010-08-04 20:40:17 +00003102 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3103 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00003104 if (TotalNumStatements)
3105 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
3106 NumStatementsRead, TotalNumStatements,
3107 ((float)NumStatementsRead/TotalNumStatements * 100));
3108 if (TotalNumMacros)
3109 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
3110 NumMacrosRead, TotalNumMacros,
3111 ((float)NumMacrosRead/TotalNumMacros * 100));
3112 if (TotalLexicalDeclContexts)
3113 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
3114 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3115 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3116 * 100));
3117 if (TotalVisibleDeclContexts)
3118 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
3119 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3120 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3121 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003122 if (TotalNumMethodPoolEntries) {
Douglas Gregor83941df2009-04-25 17:48:32 +00003123 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003124 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
3125 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
Douglas Gregor83941df2009-04-25 17:48:32 +00003126 * 100));
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003127 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
Douglas Gregor83941df2009-04-25 17:48:32 +00003128 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00003129 std::fprintf(stderr, "\n");
3130}
3131
Douglas Gregor668c1a42009-04-21 22:25:48 +00003132void PCHReader::InitializeSema(Sema &S) {
3133 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003134 S.ExternalSource = this;
3135
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003136 // Makes sure any declarations that were deserialized "too early"
3137 // still get added to the identifier's declaration chains.
3138 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3139 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
3140 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003141 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00003142 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003143
3144 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00003145 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003146 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3147 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00003148 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00003149 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00003150
Tanya Lattnere6bbc012010-02-12 00:07:30 +00003151 // If there were any unused static functions, deserialize them and add to
3152 // Sema's list of unused static functions.
3153 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
3154 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
3155 SemaObj->UnusedStaticFuncs.push_back(FD);
3156 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00003157
Argyrios Kyrtzidis72b90572010-08-05 09:48:08 +00003158 // If there were any weak undeclared identifiers, deserialize them and add to
3159 // Sema's list of weak undeclared identifiers.
3160 if (!WeakUndeclaredIdentifiers.empty()) {
3161 unsigned Idx = 0;
3162 for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
3163 IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3164 IdentifierInfo *AliasId=GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3165 SourceLocation Loc = ReadSourceLocation(WeakUndeclaredIdentifiers, Idx);
3166 bool Used = WeakUndeclaredIdentifiers[Idx++];
3167 Sema::WeakInfo WI(AliasId, Loc);
3168 WI.setUsed(Used);
3169 SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
3170 }
3171 }
3172
Douglas Gregor14c22f22009-04-22 22:18:58 +00003173 // If there were any locally-scoped external declarations,
3174 // deserialize them and add them to Sema's table of locally-scoped
3175 // external declarations.
3176 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3177 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3178 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3179 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00003180
3181 // If there were any ext_vector type declarations, deserialize them
3182 // and add them to Sema's vector of such declarations.
3183 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3184 SemaObj->ExtVectorDecls.push_back(
3185 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003186
3187 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3188 // Can we cut them down before writing them ?
3189
3190 // If there were any VTable uses, deserialize the information and add it
3191 // to Sema's vector and map of VTable uses.
Argyrios Kyrtzidisbe4ebcd2010-08-03 17:29:52 +00003192 if (!VTableUses.empty()) {
3193 unsigned Idx = 0;
3194 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3195 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3196 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3197 bool DefinitionRequired = VTableUses[Idx++];
3198 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3199 SemaObj->VTablesUsed[Class] = DefinitionRequired;
3200 }
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00003201 }
3202
3203 // If there were any dynamic classes declarations, deserialize them
3204 // and add them to Sema's vector of such declarations.
3205 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3206 SemaObj->DynamicClasses.push_back(
3207 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Fariborz Jahanian32019832010-07-23 19:11:11 +00003208
Argyrios Kyrtzidis0e036382010-08-05 09:48:16 +00003209 // If there were any pending implicit instantiations, deserialize them
3210 // and add them to Sema's queue of such instantiations.
3211 assert(PendingImplicitInstantiations.size() % 2 == 0 &&
3212 "Expected pairs of entries");
3213 for (unsigned Idx = 0, N = PendingImplicitInstantiations.size(); Idx < N;) {
3214 ValueDecl *D=cast<ValueDecl>(GetDecl(PendingImplicitInstantiations[Idx++]));
3215 SourceLocation Loc = ReadSourceLocation(PendingImplicitInstantiations, Idx);
3216 SemaObj->PendingImplicitInstantiations.push_back(std::make_pair(D, Loc));
3217 }
3218
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00003219 // Load the offsets of the declarations that Sema references.
3220 // They will be lazily deserialized when needed.
3221 if (!SemaDeclRefs.empty()) {
3222 assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3223 SemaObj->StdNamespace = SemaDeclRefs[0];
3224 SemaObj->StdBadAlloc = SemaDeclRefs[1];
3225 }
3226
Fariborz Jahanian32019832010-07-23 19:11:11 +00003227 // If there are @selector references added them to its pool. This is for
3228 // implementation of -Wselector.
Sebastian Redl725cd962010-08-04 20:40:17 +00003229 if (!ReferencedSelectorsData.empty()) {
3230 unsigned int DataSize = ReferencedSelectorsData.size()-1;
Fariborz Jahanian32019832010-07-23 19:11:11 +00003231 unsigned I = 0;
3232 while (I < DataSize) {
Sebastian Redl725cd962010-08-04 20:40:17 +00003233 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
Fariborz Jahanian32019832010-07-23 19:11:11 +00003234 SourceLocation SelLoc =
Sebastian Redl725cd962010-08-04 20:40:17 +00003235 SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
Fariborz Jahanian32019832010-07-23 19:11:11 +00003236 SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3237 }
3238 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00003239}
3240
3241IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003242 // Try to find this name within our on-disk hash tables. We start with the
3243 // most recent one, since that one contains the most up-to-date info.
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003244 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3245 PCHIdentifierLookupTable *IdTable
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003246 = (PCHIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
Sebastian Redl0fa7d0b2010-07-22 17:01:13 +00003247 if (!IdTable)
3248 continue;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003249 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3250 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3251 if (Pos == IdTable->end())
3252 continue;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003253
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003254 // Dereferencing the iterator has the effect of building the
3255 // IdentifierInfo node and populating it with the various
3256 // declarations it needs.
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003257 return *Pos;
Sebastian Redld27d3fc2010-07-21 22:31:37 +00003258 }
Sebastian Redld8c5abb2010-08-02 18:30:12 +00003259 return 0;
Douglas Gregor668c1a42009-04-21 22:25:48 +00003260}
3261
Mike Stump1eb44332009-09-09 15:08:12 +00003262std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003263PCHReader::ReadMethodPool(Selector Sel) {
Sebastian Redl725cd962010-08-04 20:40:17 +00003264 // Find this selector in a hash table. We want to find the most recent entry.
3265 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3266 PerFileData &F = *Chain[I];
3267 if (!F.SelectorLookupTable)
3268 continue;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003269
Sebastian Redl725cd962010-08-04 20:40:17 +00003270 PCHSelectorLookupTable *PoolTable
3271 = (PCHSelectorLookupTable*)F.SelectorLookupTable;
3272 PCHSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
3273 if (Pos != PoolTable->end()) {
3274 ++NumSelectorsRead;
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003275 // FIXME: Not quite happy with the statistics here. We probably should
3276 // disable this tracking when called via LoadSelector.
3277 // Also, should entries without methods count as misses?
3278 ++NumMethodPoolEntriesRead;
Sebastian Redl725cd962010-08-04 20:40:17 +00003279 PCHSelectorLookupTrait::data_type Data = *Pos;
3280 if (DeserializationListener)
3281 DeserializationListener->SelectorRead(Data.ID, Sel);
3282 return std::make_pair(Data.Instance, Data.Factory);
3283 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003284 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003285
Sebastian Redlfa78dec2010-08-04 21:22:45 +00003286 ++NumMethodPoolMisses;
Sebastian Redl725cd962010-08-04 20:40:17 +00003287 return std::pair<ObjCMethodList, ObjCMethodList>();
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00003288}
3289
Sebastian Redle58aa892010-08-04 18:21:41 +00003290void PCHReader::LoadSelector(Selector Sel) {
3291 // It would be complicated to avoid reading the methods anyway. So don't.
3292 ReadMethodPool(Sel);
3293}
3294
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003295void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00003296 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00003297 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003298 IdentifiersLoaded[ID - 1] = II;
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003299 if (DeserializationListener)
3300 DeserializationListener->IdentifierRead(ID, II);
Douglas Gregor668c1a42009-04-21 22:25:48 +00003301}
3302
Douglas Gregord89275b2009-07-06 18:54:52 +00003303/// \brief Set the globally-visible declarations associated with the given
3304/// identifier.
3305///
3306/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00003307/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00003308/// them.
3309///
3310/// \param II an IdentifierInfo that refers to one or more globally-visible
3311/// declarations.
3312///
3313/// \param DeclIDs the set of declaration IDs with the name @p II that are
3314/// visible at global scope.
3315///
3316/// \param Nonrecursive should be true to indicate that the caller knows that
3317/// this call is non-recursive, and therefore the globally-visible declarations
3318/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003319void
3320PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003321 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3322 bool Nonrecursive) {
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003323 if (NumCurrentElementsDeserializing && !Nonrecursive) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003324 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3325 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3326 PII.II = II;
3327 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3328 PII.DeclIDs.push_back(DeclIDs[I]);
3329 return;
3330 }
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Douglas Gregord89275b2009-07-06 18:54:52 +00003332 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3333 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3334 if (SemaObj) {
3335 // Introduce this declaration into the translation-unit scope
3336 // and add it to the declaration chain for this identifier, so
3337 // that (unqualified) name lookup will find it.
3338 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3339 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3340 } else {
3341 // Queue this declaration so that it will be added to the
3342 // translation unit scope and identifier's declaration chain
3343 // once a Sema object is known.
3344 PreloadedDecls.push_back(D);
3345 }
3346 }
3347}
3348
Chris Lattner7356a312009-04-11 21:15:38 +00003349IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003350 if (ID == 0)
3351 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003352
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003353 if (IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003354 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003355 return 0;
3356 }
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003358 assert(PP && "Forgot to set Preprocessor ?");
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003359 ID -= 1;
3360 if (!IdentifiersLoaded[ID]) {
3361 unsigned Index = ID;
3362 const char *Str = 0;
3363 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3364 PerFileData *F = Chain[N - I - 1];
3365 if (Index < F->LocalNumIdentifiers) {
3366 uint32_t Offset = F->IdentifierOffsets[Index];
3367 Str = F->IdentifierTableData + Offset;
3368 break;
3369 }
3370 Index -= F->LocalNumIdentifiers;
3371 }
3372 assert(Str && "Broken Chain");
Douglas Gregord6595a42009-04-25 21:04:17 +00003373
Douglas Gregor02fc7512009-04-28 20:01:51 +00003374 // All of the strings in the PCH file are preceded by a 16-bit
3375 // length. Extract that 16-bit length to avoid having to execute
3376 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003377 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3378 // unsigned integers. This is important to avoid integer overflow when
3379 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003380 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003381 unsigned StrLen = (((unsigned) StrLenPtr[0])
3382 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003383 IdentifiersLoaded[ID]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003384 = &PP->getIdentifierTable().get(Str, StrLen);
Sebastian Redlf2f0f032010-07-23 23:49:55 +00003385 if (DeserializationListener)
3386 DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003387 }
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Sebastian Redl11f5ccf2010-07-21 00:46:22 +00003389 return IdentifiersLoaded[ID];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003390}
3391
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003392void PCHReader::ReadSLocEntry(unsigned ID) {
3393 ReadSLocEntryRecord(ID);
3394}
3395
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003396Selector PCHReader::DecodeSelector(unsigned ID) {
3397 if (ID == 0)
3398 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003399
Sebastian Redl725cd962010-08-04 20:40:17 +00003400 if (ID > SelectorsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003401 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003402 return Selector();
3403 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003404
Sebastian Redl725cd962010-08-04 20:40:17 +00003405 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
Douglas Gregor83941df2009-04-25 17:48:32 +00003406 // Load this selector from the selector table.
Sebastian Redl725cd962010-08-04 20:40:17 +00003407 unsigned Idx = ID - 1;
3408 for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3409 PerFileData &F = *Chain[N - I - 1];
3410 if (Idx < F.LocalNumSelectors) {
3411 PCHSelectorLookupTrait Trait(*this);
3412 SelectorsLoaded[ID - 1] =
3413 Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
3414 if (DeserializationListener)
3415 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
3416 break;
3417 }
3418 Idx -= F.LocalNumSelectors;
3419 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003420 }
3421
Sebastian Redl725cd962010-08-04 20:40:17 +00003422 return SelectorsLoaded[ID - 1];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003423}
3424
John McCall76bd1f32010-06-01 09:23:16 +00003425Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003426 return DecodeSelector(ID);
3427}
3428
John McCall76bd1f32010-06-01 09:23:16 +00003429uint32_t PCHReader::GetNumExternalSelectors() {
Sebastian Redl725cd962010-08-04 20:40:17 +00003430 // ID 0 (the null selector) is considered an external selector.
3431 return getTotalNumSelectors() + 1;
Douglas Gregor719770d2010-04-06 17:30:22 +00003432}
3433
Mike Stump1eb44332009-09-09 15:08:12 +00003434DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003435PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3436 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3437 switch (Kind) {
3438 case DeclarationName::Identifier:
3439 return DeclarationName(GetIdentifierInfo(Record, Idx));
3440
3441 case DeclarationName::ObjCZeroArgSelector:
3442 case DeclarationName::ObjCOneArgSelector:
3443 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003444 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003445
3446 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003447 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003448 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003449
3450 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003451 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003452 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003453
3454 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003455 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003456 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003457
3458 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003459 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003460 (OverloadedOperatorKind)Record[Idx++]);
3461
Sean Hunt3e518bd2009-11-29 07:34:05 +00003462 case DeclarationName::CXXLiteralOperatorName:
3463 return Context->DeclarationNames.getCXXLiteralOperatorName(
3464 GetIdentifierInfo(Record, Idx));
3465
Douglas Gregor2cf26342009-04-09 22:27:44 +00003466 case DeclarationName::CXXUsingDirective:
3467 return DeclarationName::getUsingDirectiveName();
3468 }
3469
3470 // Required to silence GCC warning
3471 return DeclarationName();
3472}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003473
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003474TemplateName
3475PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3476 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3477 switch (Kind) {
3478 case TemplateName::Template:
3479 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3480
3481 case TemplateName::OverloadedTemplate: {
3482 unsigned size = Record[Idx++];
3483 UnresolvedSet<8> Decls;
3484 while (size--)
3485 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3486
3487 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3488 }
3489
3490 case TemplateName::QualifiedTemplate: {
3491 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3492 bool hasTemplKeyword = Record[Idx++];
3493 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3494 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3495 }
3496
3497 case TemplateName::DependentTemplate: {
3498 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3499 if (Record[Idx++]) // isIdentifier
3500 return Context->getDependentTemplateName(NNS,
3501 GetIdentifierInfo(Record, Idx));
3502 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003503 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003504 }
3505 }
3506
3507 assert(0 && "Unhandled template name kind!");
3508 return TemplateName();
3509}
3510
3511TemplateArgument
Sebastian Redl577d4792010-07-22 22:43:28 +00003512PCHReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3513 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003514 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3515 case TemplateArgument::Null:
3516 return TemplateArgument();
3517 case TemplateArgument::Type:
3518 return TemplateArgument(GetType(Record[Idx++]));
3519 case TemplateArgument::Declaration:
3520 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003521 case TemplateArgument::Integral: {
3522 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3523 QualType T = GetType(Record[Idx++]);
3524 return TemplateArgument(Value, T);
3525 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003526 case TemplateArgument::Template:
3527 return TemplateArgument(ReadTemplateName(Record, Idx));
3528 case TemplateArgument::Expression:
Sebastian Redl577d4792010-07-22 22:43:28 +00003529 return TemplateArgument(ReadExpr(DeclsCursor));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003530 case TemplateArgument::Pack: {
3531 unsigned NumArgs = Record[Idx++];
3532 llvm::SmallVector<TemplateArgument, 8> Args;
3533 Args.reserve(NumArgs);
3534 while (NumArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003535 Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003536 TemplateArgument TemplArg;
3537 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3538 return TemplArg;
3539 }
3540 }
3541
3542 assert(0 && "Unhandled template argument kind!");
3543 return TemplateArgument();
3544}
3545
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003546TemplateParameterList *
3547PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3548 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3549 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3550 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3551
3552 unsigned NumParams = Record[Idx++];
3553 llvm::SmallVector<NamedDecl *, 16> Params;
3554 Params.reserve(NumParams);
3555 while (NumParams--)
3556 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3557
3558 TemplateParameterList* TemplateParams =
3559 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3560 Params.data(), Params.size(), RAngleLoc);
3561 return TemplateParams;
3562}
3563
3564void
3565PCHReader::
3566ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
Sebastian Redl577d4792010-07-22 22:43:28 +00003567 llvm::BitstreamCursor &DeclsCursor,
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003568 const RecordData &Record, unsigned &Idx) {
3569 unsigned NumTemplateArgs = Record[Idx++];
3570 TemplArgs.reserve(NumTemplateArgs);
3571 while (NumTemplateArgs--)
Sebastian Redl577d4792010-07-22 22:43:28 +00003572 TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003573}
3574
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003575/// \brief Read a UnresolvedSet structure.
3576void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3577 const RecordData &Record, unsigned &Idx) {
3578 unsigned NumDecls = Record[Idx++];
3579 while (NumDecls--) {
3580 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3581 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3582 Set.addDecl(D, AS);
3583 }
3584}
3585
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003586CXXBaseSpecifier
Nick Lewycky56062202010-07-26 16:56:01 +00003587PCHReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3588 const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003589 bool isVirtual = static_cast<bool>(Record[Idx++]);
3590 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3591 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
Nick Lewycky56062202010-07-26 16:56:01 +00003592 TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003593 SourceRange Range = ReadSourceRange(Record, Idx);
Nick Lewycky56062202010-07-26 16:56:01 +00003594 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003595}
3596
Argyrios Kyrtzidis8e706f42010-08-09 10:54:12 +00003597std::pair<CXXBaseOrMemberInitializer **, unsigned>
3598PCHReader::ReadCXXBaseOrMemberInitializers(llvm::BitstreamCursor &Cursor,
3599 const RecordData &Record,
3600 unsigned &Idx) {
3601 CXXBaseOrMemberInitializer **BaseOrMemberInitializers = 0;
3602 unsigned NumInitializers = Record[Idx++];
3603 if (NumInitializers) {
3604 ASTContext &C = *getContext();
3605
3606 BaseOrMemberInitializers
3607 = new (C) CXXBaseOrMemberInitializer*[NumInitializers];
3608 for (unsigned i=0; i != NumInitializers; ++i) {
3609 TypeSourceInfo *BaseClassInfo = 0;
3610 bool IsBaseVirtual = false;
3611 FieldDecl *Member = 0;
3612
3613 bool IsBaseInitializer = Record[Idx++];
3614 if (IsBaseInitializer) {
3615 BaseClassInfo = GetTypeSourceInfo(Cursor, Record, Idx);
3616 IsBaseVirtual = Record[Idx++];
3617 } else {
3618 Member = cast<FieldDecl>(GetDecl(Record[Idx++]));
3619 }
3620 SourceLocation MemberLoc = ReadSourceLocation(Record, Idx);
3621 Expr *Init = ReadExpr(Cursor);
3622 FieldDecl *AnonUnionMember
3623 = cast_or_null<FieldDecl>(GetDecl(Record[Idx++]));
3624 SourceLocation LParenLoc = ReadSourceLocation(Record, Idx);
3625 SourceLocation RParenLoc = ReadSourceLocation(Record, Idx);
3626 bool IsWritten = Record[Idx++];
3627 unsigned SourceOrderOrNumArrayIndices;
3628 llvm::SmallVector<VarDecl *, 8> Indices;
3629 if (IsWritten) {
3630 SourceOrderOrNumArrayIndices = Record[Idx++];
3631 } else {
3632 SourceOrderOrNumArrayIndices = Record[Idx++];
3633 Indices.reserve(SourceOrderOrNumArrayIndices);
3634 for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
3635 Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++])));
3636 }
3637
3638 CXXBaseOrMemberInitializer *BOMInit;
3639 if (IsBaseInitializer) {
3640 BOMInit = new (C) CXXBaseOrMemberInitializer(C, BaseClassInfo,
3641 IsBaseVirtual, LParenLoc,
3642 Init, RParenLoc);
3643 } else if (IsWritten) {
3644 BOMInit = new (C) CXXBaseOrMemberInitializer(C, Member, MemberLoc,
3645 LParenLoc, Init, RParenLoc);
3646 } else {
3647 BOMInit = CXXBaseOrMemberInitializer::Create(C, Member, MemberLoc,
3648 LParenLoc, Init, RParenLoc,
3649 Indices.data(),
3650 Indices.size());
3651 }
3652
3653 BOMInit->setAnonUnionMember(AnonUnionMember);
3654 BaseOrMemberInitializers[i] = BOMInit;
3655 }
3656 }
3657
3658 return std::make_pair(BaseOrMemberInitializers, NumInitializers);
3659}
3660
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003661NestedNameSpecifier *
3662PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3663 unsigned N = Record[Idx++];
3664 NestedNameSpecifier *NNS = 0, *Prev = 0;
3665 for (unsigned I = 0; I != N; ++I) {
3666 NestedNameSpecifier::SpecifierKind Kind
3667 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3668 switch (Kind) {
3669 case NestedNameSpecifier::Identifier: {
3670 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3671 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3672 break;
3673 }
3674
3675 case NestedNameSpecifier::Namespace: {
3676 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3677 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3678 break;
3679 }
3680
3681 case NestedNameSpecifier::TypeSpec:
3682 case NestedNameSpecifier::TypeSpecWithTemplate: {
3683 Type *T = GetType(Record[Idx++]).getTypePtr();
3684 bool Template = Record[Idx++];
3685 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3686 break;
3687 }
3688
3689 case NestedNameSpecifier::Global: {
3690 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3691 // No associated value, and there can't be a prefix.
3692 break;
3693 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003694 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003695 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003696 }
3697 return NNS;
3698}
3699
3700SourceRange
3701PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003702 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3703 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3704 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003705}
3706
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003707/// \brief Read an integral value
3708llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3709 unsigned BitWidth = Record[Idx++];
3710 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3711 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3712 Idx += NumWords;
3713 return Result;
3714}
3715
3716/// \brief Read a signed integral value
3717llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3718 bool isUnsigned = Record[Idx++];
3719 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3720}
3721
Douglas Gregor17fc2232009-04-14 21:55:33 +00003722/// \brief Read a floating-point value
3723llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003724 return llvm::APFloat(ReadAPInt(Record, Idx));
3725}
3726
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003727// \brief Read a string
3728std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3729 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003730 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003731 Idx += Len;
3732 return Result;
3733}
3734
Chris Lattnerd2598362010-05-10 00:25:06 +00003735CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3736 unsigned &Idx) {
3737 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3738 return CXXTemporary::Create(*Context, Decl);
3739}
3740
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003741DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003742 return Diag(SourceLocation(), DiagID);
3743}
3744
3745DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003746 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003747}
Douglas Gregor025452f2009-04-17 00:04:06 +00003748
Douglas Gregor668c1a42009-04-21 22:25:48 +00003749/// \brief Retrieve the identifier table associated with the
3750/// preprocessor.
3751IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003752 assert(PP && "Forgot to set Preprocessor ?");
3753 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003754}
3755
Douglas Gregor025452f2009-04-17 00:04:06 +00003756/// \brief Record that the given ID maps to the given switch-case
3757/// statement.
3758void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3759 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3760 SwitchCaseStmts[ID] = SC;
3761}
3762
3763/// \brief Retrieve the switch-case statement with the given ID.
3764SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3765 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3766 return SwitchCaseStmts[ID];
3767}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003768
3769/// \brief Record that the given label statement has been
3770/// deserialized and has the given ID.
3771void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003772 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003773 "Deserialized label twice");
3774 LabelStmts[ID] = S;
3775
3776 // If we've already seen any goto statements that point to this
3777 // label, resolve them now.
3778 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3779 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3780 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3781 Goto->second->setLabel(S);
3782 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003783
3784 // If we've already seen any address-label statements that point to
3785 // this label, resolve them now.
3786 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003787 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003788 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003789 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003790 AddrLabel != AddrLabels.second; ++AddrLabel)
3791 AddrLabel->second->setLabel(S);
3792 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003793}
3794
3795/// \brief Set the label of the given statement to the label
3796/// identified by ID.
3797///
3798/// Depending on the order in which the label and other statements
3799/// referencing that label occur, this operation may complete
3800/// immediately (updating the statement) or it may queue the
3801/// statement to be back-patched later.
3802void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3803 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3804 if (Label != LabelStmts.end()) {
3805 // We've already seen this label, so set the label of the goto and
3806 // we're done.
3807 S->setLabel(Label->second);
3808 } else {
3809 // We haven't seen this label yet, so add this goto to the set of
3810 // unresolved goto statements.
3811 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3812 }
3813}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003814
3815/// \brief Set the label of the given expression to the label
3816/// identified by ID.
3817///
3818/// Depending on the order in which the label and other statements
3819/// referencing that label occur, this operation may complete
3820/// immediately (updating the statement) or it may queue the
3821/// statement to be back-patched later.
3822void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3823 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3824 if (Label != LabelStmts.end()) {
3825 // We've already seen this label, so set the label of the
3826 // label-address expression and we're done.
3827 S->setLabel(Label->second);
3828 } else {
3829 // We haven't seen this label yet, so add this label-address
3830 // expression to the set of unresolved label-address expressions.
3831 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3832 }
3833}
Douglas Gregord89275b2009-07-06 18:54:52 +00003834
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003835void PCHReader::FinishedDeserializing() {
3836 assert(NumCurrentElementsDeserializing &&
3837 "FinishedDeserializing not paired with StartedDeserializing");
3838 if (NumCurrentElementsDeserializing == 1) {
Douglas Gregord89275b2009-07-06 18:54:52 +00003839 // If any identifiers with corresponding top-level declarations have
3840 // been loaded, load those declarations now.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003841 while (!PendingIdentifierInfos.empty()) {
3842 SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
3843 PendingIdentifierInfos.front().DeclIDs, true);
3844 PendingIdentifierInfos.pop_front();
Douglas Gregord89275b2009-07-06 18:54:52 +00003845 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003846
3847 // We are not in recursive loading, so it's safe to pass the "interesting"
3848 // decls to the consumer.
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003849 if (Consumer)
3850 PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003851 }
Argyrios Kyrtzidis29ee3a22010-07-30 10:03:16 +00003852 --NumCurrentElementsDeserializing;
Douglas Gregord89275b2009-07-06 18:54:52 +00003853}