blob: 56b77b1e94c1d7b89f1c11b3050f6ce26b7c0b12 [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"
Daniel Dunbarc7162932009-11-11 23:58:53 +000016#include "clang/Frontend/Utils.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000017#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000018#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000022#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000023#include "clang/Lex/MacroInfo.h"
Douglas Gregor6a5a23f2010-03-19 21:51:54 +000024#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000026#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000027#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000028#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000029#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000030#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000031#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000032#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000033#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include "llvm/Bitcode/BitstreamReader.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000036#include "llvm/Support/ErrorHandling.h"
Daniel Dunbard5b21972009-11-18 19:50:41 +000037#include "llvm/System/Path.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000038#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000039#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000040#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000041#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000042using namespace clang;
43
44//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000045// PCH reader validator implementation
46//===----------------------------------------------------------------------===//
47
48PCHReaderListener::~PCHReaderListener() {}
49
50bool
51PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
52 const LangOptions &PPLangOpts = PP.getLangOptions();
53#define PARSE_LANGOPT_BENIGN(Option)
54#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
55 if (PPLangOpts.Option != LangOpts.Option) { \
56 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
57 return true; \
58 }
59
60 PARSE_LANGOPT_BENIGN(Trigraphs);
61 PARSE_LANGOPT_BENIGN(BCPLComment);
62 PARSE_LANGOPT_BENIGN(DollarIdents);
63 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
64 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +000065 PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000066 PARSE_LANGOPT_BENIGN(ImplicitInt);
67 PARSE_LANGOPT_BENIGN(Digraphs);
68 PARSE_LANGOPT_BENIGN(HexFloats);
69 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
70 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
71 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
72 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
73 PARSE_LANGOPT_BENIGN(CXXOperatorName);
74 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
75 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
76 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
Fariborz Jahanian412e7982010-02-09 19:31:38 +000077 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +000078 PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
79 diag::warn_pch_no_constant_cfstrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000080 PARSE_LANGOPT_BENIGN(PascalStrings);
81 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000082 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000083 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000084 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000085 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +000086 PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000087 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
88 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
89 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000090 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000091 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000092 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000093 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
94 PARSE_LANGOPT_BENIGN(EmitAllDecls);
95 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
Chris Lattnera4d71452010-06-26 21:25:03 +000096 PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
Mike Stump1eb44332009-09-09 15:08:12 +000097 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000098 diag::warn_pch_heinous_extensions);
99 // FIXME: Most of the options below are benign if the macro wasn't
100 // used. Unfortunately, this means that a PCH compiled without
101 // optimization can't be used with optimization turned on, even
102 // though the only thing that changes is whether __OPTIMIZE__ was
103 // defined... but if __OPTIMIZE__ never showed up in the header, it
104 // doesn't matter. We could consider making this some special kind
105 // of check.
106 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
107 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
108 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
109 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
110 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
111 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
112 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
113 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsona6fda122009-11-05 20:14:16 +0000114 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000115 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000116 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000117 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
118 return true;
119 }
120 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000121 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
122 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000123 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000124 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Mike Stump9c276ae2009-12-12 01:27:46 +0000125 PARSE_LANGOPT_BENIGN(CatchUndefined);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000126 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Douglas Gregora0068fc2010-07-09 17:35:33 +0000127 PARSE_LANGOPT_BENIGN(SpellChecking);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +0000128#undef PARSE_LANGOPT_IMPORTANT
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000129#undef PARSE_LANGOPT_BENIGN
130
131 return false;
132}
133
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000134bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
135 if (Triple == PP.getTargetInfo().getTriple().str())
136 return false;
137
138 Reader.Diag(diag::warn_pch_target_triple)
139 << Triple << PP.getTargetInfo().getTriple().str();
140 return true;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000141}
142
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000143struct EmptyStringRef {
144 bool operator ()(const llvm::StringRef &r) const { return r.empty(); }
145};
146struct EmptyBlock {
147 bool operator ()(const PCHPredefinesBlock &r) const { return r.Data.empty(); }
148};
149
150static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
151 PCHPredefinesBlocks R) {
152 // First, sum up the lengths.
153 unsigned LL = 0, RL = 0;
154 for (unsigned I = 0, N = L.size(); I != N; ++I) {
155 LL += L[I].size();
156 }
157 for (unsigned I = 0, N = R.size(); I != N; ++I) {
158 RL += R[I].Data.size();
159 }
160 if (LL != RL)
161 return false;
162 if (LL == 0 && RL == 0)
163 return true;
164
165 // Kick out empty parts, they confuse the algorithm below.
166 L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
167 R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
168
169 // Do it the hard way. At this point, both vectors must be non-empty.
170 llvm::StringRef LR = L[0], RR = R[0].Data;
171 unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
172 for (;;) {
173 // Compare the current pieces.
174 if (LR.size() == RR.size()) {
175 // If they're the same length, it's pretty easy.
176 if (LR != RR)
177 return false;
178 // Both pieces are done, advance.
179 ++LI;
180 ++RI;
181 // If either string is done, they're both done, since they're the same
182 // length.
183 if (LI == LN) {
184 assert(RI == RN && "Strings not the same length after all?");
185 return true;
186 }
187 LR = L[LI];
188 RR = R[RI].Data;
189 } else if (LR.size() < RR.size()) {
190 // Right piece is longer.
191 if (!RR.startswith(LR))
192 return false;
193 ++LI;
194 assert(LI != LN && "Strings not the same length after all?");
195 RR = RR.substr(LR.size());
196 LR = L[LI];
197 } else {
198 // Left piece is longer.
199 if (!LR.startswith(RR))
200 return false;
201 ++RI;
202 assert(RI != RN && "Strings not the same length after all?");
203 LR = LR.substr(RR.size());
204 RR = R[RI].Data;
205 }
206 }
207}
208
209static std::pair<FileID, llvm::StringRef::size_type>
210FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
211 std::pair<FileID, llvm::StringRef::size_type> Res;
212 for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
213 Res.second = Buffers[I].Data.find(MacroDef);
214 if (Res.second != llvm::StringRef::npos) {
215 Res.first = Buffers[I].BufferID;
216 break;
217 }
218 }
219 return Res;
220}
221
222bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000223 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000224 std::string &SuggestedPredefines) {
Daniel Dunbarc7162932009-11-11 23:58:53 +0000225 // We are in the context of an implicit include, so the predefines buffer will
226 // have a #include entry for the PCH file itself (as normalized by the
227 // preprocessor initialization). Find it and skip over it in the checking
228 // below.
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000229 llvm::SmallString<256> PCHInclude;
230 PCHInclude += "#include \"";
Daniel Dunbarc7162932009-11-11 23:58:53 +0000231 PCHInclude += NormalizeDashIncludePath(OriginalFileName);
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000232 PCHInclude += "\"\n";
233 std::pair<llvm::StringRef,llvm::StringRef> Split =
234 llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
235 llvm::StringRef Left = Split.first, Right = Split.second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000236 if (Left == PP.getPredefines()) {
237 Error("Missing PCH include entry!");
238 return true;
239 }
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000240
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000241 // If the concatenation of all the PCH buffers is equal to the adjusted
242 // command line, we're done.
243 // We build a SmallVector of the command line here, because we'll eventually
244 // need to support an arbitrary amount of pieces anyway (when we have chained
245 // PCH reading).
246 llvm::SmallVector<llvm::StringRef, 2> CommandLine;
247 CommandLine.push_back(Left);
248 CommandLine.push_back(Right);
249 if (EqualConcatenations(CommandLine, Buffers))
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000250 return false;
251
252 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000254 // The predefines buffers are different. Determine what the differences are,
255 // and whether they require us to reject the PCH file.
Daniel Dunbare6750492009-11-13 16:46:11 +0000256 llvm::SmallVector<llvm::StringRef, 8> PCHLines;
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000257 for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
258 Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Daniel Dunbare6750492009-11-13 16:46:11 +0000259
260 llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
261 Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
262 Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000263
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000264 // Sort both sets of predefined buffer lines, since we allow some extra
265 // definitions and they may appear at any point in the output.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000266 std::sort(CmdLineLines.begin(), CmdLineLines.end());
267 std::sort(PCHLines.begin(), PCHLines.end());
268
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000269 // Determine which predefines that were used to build the PCH file are missing
270 // from the command line.
271 std::vector<llvm::StringRef> MissingPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000272 std::set_difference(PCHLines.begin(), PCHLines.end(),
273 CmdLineLines.begin(), CmdLineLines.end(),
274 std::back_inserter(MissingPredefines));
275
276 bool MissingDefines = false;
277 bool ConflictingDefines = false;
278 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000279 llvm::StringRef Missing = MissingPredefines[I];
280 if (!Missing.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000281 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
282 return true;
283 }
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000285 // This is a macro definition. Determine the name of the macro we're
286 // defining.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000287 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000288 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000289 = Missing.find_first_of("( \n\r", StartOfMacroName);
290 assert(EndOfMacroName != std::string::npos &&
291 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000292 llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000293
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000294 // Determine whether this macro was given a different definition on the
295 // command line.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000296 std::string MacroDefStart = "#define " + MacroName.str();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000297 std::string::size_type MacroDefLen = MacroDefStart.size();
Daniel Dunbare6750492009-11-13 16:46:11 +0000298 llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000299 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
300 MacroDefStart);
301 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000302 if (!ConflictPos->startswith(MacroDefStart)) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000303 // Different macro; we're done.
304 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000305 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000306 }
Mike Stump1eb44332009-09-09 15:08:12 +0000307
308 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000309 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000310 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000311 (*ConflictPos)[MacroDefLen] != '(')
312 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000314 // We found a conflicting macro definition.
315 break;
316 }
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000318 if (ConflictPos != CmdLineLines.end()) {
319 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
320 << MacroName;
321
322 // Show the definition of this macro within the PCH file.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000323 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
324 FindMacro(Buffers, Missing);
325 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
326 SourceLocation PCHMissingLoc =
327 SourceMgr.getLocForStartOfFile(MacroLoc.first)
328 .getFileLocWithOffset(MacroLoc.second);
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000329 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000330
331 ConflictingDefines = true;
332 continue;
333 }
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Daniel Dunbar10014aa2009-11-11 03:45:59 +0000335 // If the macro doesn't conflict, then we'll just pick up the macro
336 // definition from the PCH file. Warn the user that they made a mistake.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000337 if (ConflictingDefines)
338 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000340 if (!MissingDefines) {
341 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
342 MissingDefines = true;
343 }
344
345 // Show the definition of this macro within the PCH file.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000346 std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
347 FindMacro(Buffers, Missing);
348 assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
349 SourceLocation PCHMissingLoc =
350 SourceMgr.getLocForStartOfFile(MacroLoc.first)
351 .getFileLocWithOffset(MacroLoc.second);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000352 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
353 }
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000355 if (ConflictingDefines)
356 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000358 // Determine what predefines were introduced based on command-line
359 // parameters that were not present when building the PCH
360 // file. Extra #defines are okay, so long as the identifiers being
361 // defined were not used within the precompiled header.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000362 std::vector<llvm::StringRef> ExtraPredefines;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000363 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
364 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000365 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000366 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000367 llvm::StringRef &Extra = ExtraPredefines[I];
368 if (!Extra.startswith("#define ")) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000369 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
370 return true;
371 }
372
373 // This is an extra macro definition. Determine the name of the
374 // macro we're defining.
375 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000376 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000377 = Extra.find_first_of("( \n\r", StartOfMacroName);
378 assert(EndOfMacroName != std::string::npos &&
379 "Couldn't find the end of the macro name");
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000380 llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000381
382 // Check whether this name was used somewhere in the PCH file. If
383 // so, defining it as a macro could change behavior, so we reject
384 // the PCH file.
Daniel Dunbar4d5936a2009-11-11 05:26:28 +0000385 if (IdentifierInfo *II = Reader.get(MacroName)) {
Daniel Dunbar4fda42e2009-11-11 00:52:00 +0000386 Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000387 return true;
388 }
389
390 // Add this definition to the suggested predefines buffer.
391 SuggestedPredefines += Extra;
392 SuggestedPredefines += '\n';
393 }
394
395 // If we get here, it's because the predefines buffer had compatible
396 // contents. Accept the PCH file.
397 return false;
398}
399
Douglas Gregor12fab312010-03-16 16:35:32 +0000400void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
401 unsigned ID) {
402 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
403 ++NumHeaderInfos;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000404}
405
406void PCHValidator::ReadCounter(unsigned Value) {
407 PP.setCounterValue(Value);
408}
409
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000410//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000411// PCH reader implementation
412//===----------------------------------------------------------------------===//
413
Mike Stump1eb44332009-09-09 15:08:12 +0000414PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
415 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000416 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
417 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000418 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000419 IdentifierTableData(0), IdentifierLookupTable(0),
420 IdentifierOffsets(0),
421 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
422 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000423 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000424 NumPreallocatedPreprocessingEntities(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000425 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000426 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000427 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000428 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000429 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000430 RelocatablePCH = false;
431}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000432
433PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000434 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000435 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000436 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000437 IdentifierTableData(0), IdentifierLookupTable(0),
438 IdentifierOffsets(0),
439 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
440 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000441 TotalNumSelectors(0), MacroDefinitionOffsets(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +0000442 NumPreallocatedPreprocessingEntities(0),
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000443 isysroot(isysroot), NumStatHits(0), NumStatMisses(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000444 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000445 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000446 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000447 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000448 RelocatablePCH = false;
449}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000450
451PCHReader::~PCHReader() {}
452
Chris Lattner4c6f9522009-04-27 05:14:47 +0000453
Douglas Gregor668c1a42009-04-21 22:25:48 +0000454namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000455class PCHMethodPoolLookupTrait {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000456 PCHReader &Reader;
457
458public:
459 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
460
461 typedef Selector external_key_type;
462 typedef external_key_type internal_key_type;
463
464 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000466 static bool EqualKey(const internal_key_type& a,
467 const internal_key_type& b) {
468 return a == b;
469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000471 static unsigned ComputeHash(Selector Sel) {
472 unsigned N = Sel.getNumArgs();
473 if (N == 0)
474 ++N;
475 unsigned R = 5381;
476 for (unsigned I = 0; I != N; ++I)
477 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000478 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000479 return R;
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000482 // This hopefully will just get inlined and removed by the optimizer.
483 static const internal_key_type&
484 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000486 static std::pair<unsigned, unsigned>
487 ReadKeyDataLength(const unsigned char*& d) {
488 using namespace clang::io;
489 unsigned KeyLen = ReadUnalignedLE16(d);
490 unsigned DataLen = ReadUnalignedLE16(d);
491 return std::make_pair(KeyLen, DataLen);
492 }
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Douglas Gregor83941df2009-04-25 17:48:32 +0000494 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000495 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000496 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000497 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000498 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000499 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
500 if (N == 0)
501 return SelTable.getNullarySelector(FirstII);
502 else if (N == 1)
503 return SelTable.getUnarySelector(FirstII);
504
505 llvm::SmallVector<IdentifierInfo *, 16> Args;
506 Args.push_back(FirstII);
507 for (unsigned I = 1; I != N; ++I)
508 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
509
Douglas Gregor75fdb232009-05-22 22:45:36 +0000510 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000513 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
514 using namespace clang::io;
515 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
516 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
517
518 data_type Result;
519
520 // Load instance methods
521 ObjCMethodList *Prev = 0;
522 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000523 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000524 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
525 if (!Result.first.Method) {
526 // This is the first method, which is the easy case.
527 Result.first.Method = Method;
528 Prev = &Result.first;
529 continue;
530 }
531
Ted Kremenek298ed872010-02-11 00:53:01 +0000532 ObjCMethodList *Mem =
533 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
534 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000535 Prev = Prev->Next;
536 }
537
538 // Load factory methods
539 Prev = 0;
540 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000541 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000542 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
543 if (!Result.second.Method) {
544 // This is the first method, which is the easy case.
545 Result.second.Method = Method;
546 Prev = &Result.second;
547 continue;
548 }
549
Ted Kremenek298ed872010-02-11 00:53:01 +0000550 ObjCMethodList *Mem =
551 Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
552 Prev->Next = new (Mem) ObjCMethodList(Method, 0);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000553 Prev = Prev->Next;
554 }
555
556 return Result;
557 }
558};
Mike Stump1eb44332009-09-09 15:08:12 +0000559
560} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000561
562/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000563typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000564 PCHMethodPoolLookupTable;
565
566namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +0000567class PCHIdentifierLookupTrait {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000568 PCHReader &Reader;
569
570 // If we know the IdentifierInfo in advance, it is here and we will
571 // not build a new one. Used when deserializing information about an
572 // identifier that was constructed before the PCH file was read.
573 IdentifierInfo *KnownII;
574
575public:
576 typedef IdentifierInfo * data_type;
577
578 typedef const std::pair<const char*, unsigned> external_key_type;
579
580 typedef external_key_type internal_key_type;
581
Mike Stump1eb44332009-09-09 15:08:12 +0000582 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000583 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Douglas Gregor668c1a42009-04-21 22:25:48 +0000585 static bool EqualKey(const internal_key_type& a,
586 const internal_key_type& b) {
587 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
588 : false;
589 }
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Douglas Gregor668c1a42009-04-21 22:25:48 +0000591 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000592 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000593 }
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Douglas Gregor668c1a42009-04-21 22:25:48 +0000595 // This hopefully will just get inlined and removed by the optimizer.
596 static const internal_key_type&
597 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Douglas Gregor668c1a42009-04-21 22:25:48 +0000599 static std::pair<unsigned, unsigned>
600 ReadKeyDataLength(const unsigned char*& d) {
601 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000602 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000603 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000604 return std::make_pair(KeyLen, DataLen);
605 }
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Douglas Gregor668c1a42009-04-21 22:25:48 +0000607 static std::pair<const char*, unsigned>
608 ReadKey(const unsigned char* d, unsigned n) {
609 assert(n >= 2 && d[n-1] == '\0');
610 return std::make_pair((const char*) d, n-1);
611 }
Mike Stump1eb44332009-09-09 15:08:12 +0000612
613 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000614 const unsigned char* d,
615 unsigned DataLen) {
616 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000617 pch::IdentID ID = ReadUnalignedLE32(d);
618 bool IsInteresting = ID & 0x01;
619
620 // Wipe out the "is interesting" bit.
621 ID = ID >> 1;
622
623 if (!IsInteresting) {
624 // For unintersting identifiers, just build the IdentifierInfo
625 // and associate it with the persistent ID.
626 IdentifierInfo *II = KnownII;
627 if (!II)
628 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
629 k.first, k.first + k.second);
630 Reader.SetIdentifierInfo(ID, II);
631 return II;
632 }
633
Douglas Gregor5998da52009-04-28 21:32:13 +0000634 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000635 bool CPlusPlusOperatorKeyword = Bits & 0x01;
636 Bits >>= 1;
637 bool Poisoned = Bits & 0x01;
638 Bits >>= 1;
639 bool ExtensionToken = Bits & 0x01;
640 Bits >>= 1;
641 bool hasMacroDefinition = Bits & 0x01;
642 Bits >>= 1;
643 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
644 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Douglas Gregor2deaea32009-04-22 18:49:13 +0000646 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000647 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000648
649 // Build the IdentifierInfo itself and link the identifier ID with
650 // the new IdentifierInfo.
651 IdentifierInfo *II = KnownII;
652 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000653 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
654 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000655 Reader.SetIdentifierInfo(ID, II);
656
Douglas Gregor2deaea32009-04-22 18:49:13 +0000657 // Set or check the various bits in the IdentifierInfo structure.
658 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000659 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000660 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000661 "Incorrect extension token flag");
662 (void)ExtensionToken;
663 II->setIsPoisoned(Poisoned);
664 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
665 "Incorrect C++ operator keyword flag");
666 (void)CPlusPlusOperatorKeyword;
667
Douglas Gregor37e26842009-04-21 23:56:24 +0000668 // If this identifier is a macro, deserialize the macro
669 // definition.
670 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000671 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000672 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000673 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000674 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000675
676 // Read all of the declarations visible at global scope with this
677 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000678 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000679 if (DataLen > 0) {
680 llvm::SmallVector<uint32_t, 4> DeclIDs;
681 for (; DataLen > 0; DataLen -= 4)
682 DeclIDs.push_back(ReadUnalignedLE32(d));
683 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000684 }
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Douglas Gregor668c1a42009-04-21 22:25:48 +0000686 return II;
687 }
688};
Mike Stump1eb44332009-09-09 15:08:12 +0000689
690} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000691
692/// \brief The on-disk hash table used to contain information about
693/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000694typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000695 PCHIdentifierLookupTable;
696
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +0000697void PCHReader::Error(const char *Msg) {
698 Diag(diag::err_fe_pch_malformed) << Msg;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000699}
700
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000701/// \brief Check the contents of the concatenation of all predefines buffers in
702/// the PCH chain against the contents of the predefines buffer of the current
703/// compiler invocation.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000704///
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000705/// The contents should be the same. If not, then some command-line option
706/// changed the preprocessor state and we must probably reject the PCH file.
Douglas Gregore1d918e2009-04-10 23:10:45 +0000707///
708/// \returns true if there was a mismatch (in which case the PCH file
709/// should be ignored), or false otherwise.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000710bool PCHReader::CheckPredefinesBuffers() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000711 if (Listener)
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +0000712 return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000713 ActualOriginalFileName,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000714 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000715 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000716}
717
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000718//===----------------------------------------------------------------------===//
719// Source Manager Deserialization
720//===----------------------------------------------------------------------===//
721
Douglas Gregorbd945002009-04-13 16:31:14 +0000722/// \brief Read the line table in the source manager block.
723/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000724bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000725 unsigned Idx = 0;
726 LineTableInfo &LineTable = SourceMgr.getLineTable();
727
728 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000729 std::map<int, int> FileIDs;
730 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000731 // Extract the file name
732 unsigned FilenameLen = Record[Idx++];
733 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
734 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000735 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000736 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000737 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000738 }
739
740 // Parse the line entries
741 std::vector<LineEntry> Entries;
742 while (Idx < Record.size()) {
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000743 int FID = Record[Idx++];
Douglas Gregorbd945002009-04-13 16:31:14 +0000744
745 // Extract the line entries
746 unsigned NumEntries = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000747 assert(NumEntries && "Numentries is 00000");
Douglas Gregorbd945002009-04-13 16:31:14 +0000748 Entries.clear();
749 Entries.reserve(NumEntries);
750 for (unsigned I = 0; I != NumEntries; ++I) {
751 unsigned FileOffset = Record[Idx++];
752 unsigned LineNo = Record[Idx++];
Argyrios Kyrtzidisf52a5d22010-07-02 11:55:05 +0000753 int FilenameID = FileIDs[Record[Idx++]];
Mike Stump1eb44332009-09-09 15:08:12 +0000754 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000755 = (SrcMgr::CharacteristicKind)Record[Idx++];
756 unsigned IncludeOffset = Record[Idx++];
757 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
758 FileKind, IncludeOffset));
759 }
760 LineTable.AddEntry(FID, Entries);
761 }
762
763 return false;
764}
765
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000766namespace {
767
Benjamin Kramerbd218282009-11-28 10:07:24 +0000768class PCHStatData {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000769public:
770 const bool hasStat;
771 const ino_t ino;
772 const dev_t dev;
773 const mode_t mode;
774 const time_t mtime;
775 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000777 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000778 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
779
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000780 PCHStatData()
781 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
782};
783
Benjamin Kramerbd218282009-11-28 10:07:24 +0000784class PCHStatLookupTrait {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000785 public:
786 typedef const char *external_key_type;
787 typedef const char *internal_key_type;
788
789 typedef PCHStatData data_type;
790
791 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000792 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000793 }
794
795 static internal_key_type GetInternalKey(const char *path) { return path; }
796
797 static bool EqualKey(internal_key_type a, internal_key_type b) {
798 return strcmp(a, b) == 0;
799 }
800
801 static std::pair<unsigned, unsigned>
802 ReadKeyDataLength(const unsigned char*& d) {
803 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
804 unsigned DataLen = (unsigned) *d++;
805 return std::make_pair(KeyLen + 1, DataLen);
806 }
807
808 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
809 return (const char *)d;
810 }
811
812 static data_type ReadData(const internal_key_type, const unsigned char *d,
813 unsigned /*DataLen*/) {
814 using namespace clang::io;
815
816 if (*d++ == 1)
817 return data_type();
818
819 ino_t ino = (ino_t) ReadUnalignedLE32(d);
820 dev_t dev = (dev_t) ReadUnalignedLE32(d);
821 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000822 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000823 off_t size = (off_t) ReadUnalignedLE64(d);
824 return data_type(ino, dev, mode, mtime, size);
825 }
826};
827
828/// \brief stat() cache for precompiled headers.
829///
830/// This cache is very similar to the stat cache used by pretokenized
831/// headers.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000832class PCHStatCache : public StatSysCallCache {
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000833 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
834 CacheTy *Cache;
835
836 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000837public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000838 PCHStatCache(const unsigned char *Buckets,
839 const unsigned char *Base,
840 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000841 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000842 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
843 Cache = CacheTy::Create(Buckets, Base);
844 }
845
846 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000848 int stat(const char *path, struct stat *buf) {
849 // Do the lookup for the file's data in the PCH file.
850 CacheTy::iterator I = Cache->find(path);
851
852 // If we don't get a hit in the PCH file just forward to 'stat'.
853 if (I == Cache->end()) {
854 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000855 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000856 }
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000858 ++NumStatHits;
859 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000861 if (!Data.hasStat)
862 return 1;
863
864 buf->st_ino = Data.ino;
865 buf->st_dev = Data.dev;
866 buf->st_mtime = Data.mtime;
867 buf->st_mode = Data.mode;
868 buf->st_size = Data.size;
869 return 0;
870 }
871};
872} // end anonymous namespace
873
874
Douglas Gregor14f79002009-04-10 03:52:48 +0000875/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000876PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000877 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000878
879 // Set the source-location entry cursor to the current position in
880 // the stream. This cursor will be used to read the contents of the
881 // source manager block initially, and then lazily read
882 // source-location entries as needed.
883 SLocEntryCursor = Stream;
884
885 // The stream itself is going to skip over the source manager block.
886 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000887 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000888 return Failure;
889 }
890
891 // Enter the source manager block.
892 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000893 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000894 return Failure;
895 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000896
Douglas Gregor14f79002009-04-10 03:52:48 +0000897 RecordData Record;
898 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000899 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000900 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000901 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000902 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000903 return Failure;
904 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000905 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Douglas Gregor14f79002009-04-10 03:52:48 +0000908 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
909 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000910 SLocEntryCursor.ReadSubBlockID();
911 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000912 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000913 return Failure;
914 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000915 continue;
916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Douglas Gregor14f79002009-04-10 03:52:48 +0000918 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000919 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000920 continue;
921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregor14f79002009-04-10 03:52:48 +0000923 // Read a record.
924 const char *BlobStart;
925 unsigned BlobLen;
926 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000927 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000928 default: // Default behavior: ignore.
929 break;
930
Chris Lattner2c78b872009-04-14 23:22:57 +0000931 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000932 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000933 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000934 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000935
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000936 case pch::SM_SLOC_FILE_ENTRY:
937 case pch::SM_SLOC_BUFFER_ENTRY:
938 case pch::SM_SLOC_INSTANTIATION_ENTRY:
939 // Once we hit one of the source location entries, we're done.
940 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000941 }
942 }
943}
944
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000945/// \brief Read in the source location entry with the given ID.
946PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
947 if (ID == 0)
948 return Success;
949
950 if (ID > TotalNumSLocEntries) {
951 Error("source location entry ID out-of-range for PCH file");
952 return Failure;
953 }
954
955 ++NumSLocEntriesRead;
956 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
957 unsigned Code = SLocEntryCursor.ReadCode();
958 if (Code == llvm::bitc::END_BLOCK ||
959 Code == llvm::bitc::ENTER_SUBBLOCK ||
960 Code == llvm::bitc::DEFINE_ABBREV) {
961 Error("incorrectly-formatted source location entry in PCH file");
962 return Failure;
963 }
964
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000965 RecordData Record;
966 const char *BlobStart;
967 unsigned BlobLen;
968 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
969 default:
970 Error("incorrectly-formatted source location entry in PCH file");
971 return Failure;
972
973 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000974 std::string Filename(BlobStart, BlobStart + BlobLen);
975 MaybeAddSystemRootToFilename(Filename);
976 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000977 if (File == 0) {
978 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000979 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000980 ErrorStr += "' referenced by PCH file";
981 Error(ErrorStr.c_str());
982 return Failure;
983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Douglas Gregor2d52be52010-03-21 22:49:54 +0000985 if (Record.size() < 10) {
Ted Kremenek1857f622010-03-18 21:23:05 +0000986 Error("source location entry is incorrect");
987 return Failure;
988 }
989
Douglas Gregor9f692a02010-04-09 15:54:22 +0000990 if ((off_t)Record[4] != File->getSize()
991#if !defined(LLVM_ON_WIN32)
992 // In our regression testing, the Windows file system seems to
993 // have inconsistent modification times that sometimes
994 // erroneously trigger this error-handling path.
995 || (time_t)Record[5] != File->getModificationTime()
996#endif
997 ) {
Douglas Gregor2d52be52010-03-21 22:49:54 +0000998 Diag(diag::err_fe_pch_file_modified)
999 << Filename;
1000 return Failure;
1001 }
1002
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001003 FileID FID = SourceMgr.createFileID(File,
1004 SourceLocation::getFromRawEncoding(Record[1]),
1005 (SrcMgr::CharacteristicKind)Record[2],
1006 ID, Record[0]);
1007 if (Record[3])
1008 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1009 .setHasLineDirectives();
1010
Douglas Gregor12fab312010-03-16 16:35:32 +00001011 // Reconstruct header-search information for this file.
1012 HeaderFileInfo HFI;
Douglas Gregor2d52be52010-03-21 22:49:54 +00001013 HFI.isImport = Record[6];
1014 HFI.DirInfo = Record[7];
1015 HFI.NumIncludes = Record[8];
1016 HFI.ControllingMacroID = Record[9];
Douglas Gregor12fab312010-03-16 16:35:32 +00001017 if (Listener)
1018 Listener->ReadHeaderFileInfo(HFI, File->getUID());
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001019 break;
1020 }
1021
1022 case pch::SM_SLOC_BUFFER_ENTRY: {
1023 const char *Name = BlobStart;
1024 unsigned Offset = Record[0];
1025 unsigned Code = SLocEntryCursor.ReadCode();
1026 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00001027 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001028 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001029
1030 if (RecCode != pch::SM_SLOC_BUFFER_BLOB) {
1031 Error("PCH record has invalid code");
1032 return Failure;
1033 }
1034
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001035 llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00001036 = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1037 Name);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001038 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Douglas Gregor92b059e2009-04-28 20:33:11 +00001040 if (strcmp(Name, "<built-in>") == 0) {
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001041 PCHPredefinesBlock Block = {
1042 BufferID,
1043 llvm::StringRef(BlobStart, BlobLen - 1)
1044 };
1045 PCHPredefinesBuffers.push_back(Block);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001046 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001047
1048 break;
1049 }
1050
1051 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +00001052 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001053 = SourceLocation::getFromRawEncoding(Record[1]);
1054 SourceMgr.createInstantiationLoc(SpellingLoc,
1055 SourceLocation::getFromRawEncoding(Record[2]),
1056 SourceLocation::getFromRawEncoding(Record[3]),
1057 Record[4],
1058 ID,
1059 Record[0]);
1060 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001061 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001062 }
1063
1064 return Success;
1065}
1066
Chris Lattner6367f6d2009-04-27 01:05:14 +00001067/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1068/// specified cursor. Read the abbreviations that are at the top of the block
1069/// and then leave the cursor pointing into the block.
1070bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1071 unsigned BlockID) {
1072 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001073 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001074 return Failure;
1075 }
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Chris Lattner6367f6d2009-04-27 01:05:14 +00001077 while (true) {
1078 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Chris Lattner6367f6d2009-04-27 01:05:14 +00001080 // We expect all abbrevs to be at the start of the block.
1081 if (Code != llvm::bitc::DEFINE_ABBREV)
1082 return false;
1083 Cursor.ReadAbbrevRecord();
1084 }
1085}
1086
Douglas Gregor37e26842009-04-21 23:56:24 +00001087void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001088 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Douglas Gregor37e26842009-04-21 23:56:24 +00001090 // Keep track of where we are in the stream, then jump back there
1091 // after reading this macro.
1092 SavedStreamPosition SavedPosition(Stream);
1093
1094 Stream.JumpToBit(Offset);
1095 RecordData Record;
1096 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1097 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Douglas Gregor37e26842009-04-21 23:56:24 +00001099 while (true) {
1100 unsigned Code = Stream.ReadCode();
1101 switch (Code) {
1102 case llvm::bitc::END_BLOCK:
1103 return;
1104
1105 case llvm::bitc::ENTER_SUBBLOCK:
1106 // No known subblocks, always skip them.
1107 Stream.ReadSubBlockID();
1108 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001109 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001110 return;
1111 }
1112 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Douglas Gregor37e26842009-04-21 23:56:24 +00001114 case llvm::bitc::DEFINE_ABBREV:
1115 Stream.ReadAbbrevRecord();
1116 continue;
1117 default: break;
1118 }
1119
1120 // Read a record.
1121 Record.clear();
1122 pch::PreprocessorRecordTypes RecType =
1123 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1124 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001125 case pch::PP_MACRO_OBJECT_LIKE:
1126 case pch::PP_MACRO_FUNCTION_LIKE: {
1127 // If we already have a macro, that means that we've hit the end
1128 // of the definition of the macro we were looking for. We're
1129 // done.
1130 if (Macro)
1131 return;
1132
1133 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1134 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001135 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001136 return;
1137 }
1138 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1139 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001141 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001142 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001144 unsigned NextIndex = 3;
Douglas Gregor37e26842009-04-21 23:56:24 +00001145 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1146 // Decode function-like macro info.
1147 bool isC99VarArgs = Record[3];
1148 bool isGNUVarArgs = Record[4];
1149 MacroArgs.clear();
1150 unsigned NumArgs = Record[5];
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001151 NextIndex = 6 + NumArgs;
Douglas Gregor37e26842009-04-21 23:56:24 +00001152 for (unsigned i = 0; i != NumArgs; ++i)
1153 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1154
1155 // Install function-like macro info.
1156 MI->setIsFunctionLike();
1157 if (isC99VarArgs) MI->setIsC99Varargs();
1158 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001159 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001160 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001161 }
1162
1163 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001164 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001165
1166 // Remember that we saw this macro last so that we add the tokens that
1167 // form its body to it.
1168 Macro = MI;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001169
1170 if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1171 // We have a macro definition. Load it now.
1172 PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1173 getMacroDefinition(Record[NextIndex]));
1174 }
1175
Douglas Gregor37e26842009-04-21 23:56:24 +00001176 ++NumMacrosRead;
1177 break;
1178 }
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Douglas Gregor37e26842009-04-21 23:56:24 +00001180 case pch::PP_TOKEN: {
1181 // If we see a TOKEN before a PP_MACRO_*, then the file is
1182 // erroneous, just pretend we didn't see this.
1183 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Douglas Gregor37e26842009-04-21 23:56:24 +00001185 Token Tok;
1186 Tok.startToken();
1187 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1188 Tok.setLength(Record[1]);
1189 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1190 Tok.setIdentifierInfo(II);
1191 Tok.setKind((tok::TokenKind)Record[3]);
1192 Tok.setFlag((Token::TokenFlags)Record[4]);
1193 Macro->AddTokenToBody(Tok);
1194 break;
1195 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001196
1197 case pch::PP_MACRO_INSTANTIATION: {
1198 // If we already have a macro, that means that we've hit the end
1199 // of the definition of the macro we were looking for. We're
1200 // done.
1201 if (Macro)
1202 return;
1203
1204 if (!PP->getPreprocessingRecord()) {
1205 Error("missing preprocessing record in PCH file");
1206 return;
1207 }
1208
1209 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1210 if (PPRec.getPreprocessedEntity(Record[0]))
1211 return;
1212
1213 MacroInstantiation *MI
1214 = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1215 SourceRange(
1216 SourceLocation::getFromRawEncoding(Record[1]),
1217 SourceLocation::getFromRawEncoding(Record[2])),
1218 getMacroDefinition(Record[4]));
1219 PPRec.SetPreallocatedEntity(Record[0], MI);
1220 return;
1221 }
1222
1223 case pch::PP_MACRO_DEFINITION: {
1224 // If we already have a macro, that means that we've hit the end
1225 // of the definition of the macro we were looking for. We're
1226 // done.
1227 if (Macro)
1228 return;
1229
1230 if (!PP->getPreprocessingRecord()) {
1231 Error("missing preprocessing record in PCH file");
1232 return;
1233 }
1234
1235 PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1236 if (PPRec.getPreprocessedEntity(Record[0]))
1237 return;
1238
1239 if (Record[1] >= MacroDefinitionsLoaded.size()) {
1240 Error("out-of-bounds macro definition record");
1241 return;
1242 }
1243
1244 MacroDefinition *MD
1245 = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1246 SourceLocation::getFromRawEncoding(Record[5]),
1247 SourceRange(
1248 SourceLocation::getFromRawEncoding(Record[2]),
1249 SourceLocation::getFromRawEncoding(Record[3])));
1250 PPRec.SetPreallocatedEntity(Record[0], MD);
1251 MacroDefinitionsLoaded[Record[1]] = MD;
1252 return;
1253 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001254 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001255 }
1256}
1257
Douglas Gregor88a35862010-01-04 19:18:44 +00001258void PCHReader::ReadDefinedMacros() {
1259 // If there was no preprocessor block, do nothing.
1260 if (!MacroCursor.getBitStreamReader())
1261 return;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001262
Douglas Gregor88a35862010-01-04 19:18:44 +00001263 llvm::BitstreamCursor Cursor = MacroCursor;
1264 if (Cursor.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID)) {
1265 Error("malformed preprocessor block record in PCH file");
1266 return;
1267 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001268
Douglas Gregor88a35862010-01-04 19:18:44 +00001269 RecordData Record;
1270 while (true) {
1271 unsigned Code = Cursor.ReadCode();
1272 if (Code == llvm::bitc::END_BLOCK) {
1273 if (Cursor.ReadBlockEnd())
1274 Error("error at end of preprocessor block in PCH file");
1275 return;
1276 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001277
Douglas Gregor88a35862010-01-04 19:18:44 +00001278 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1279 // No known subblocks, always skip them.
1280 Cursor.ReadSubBlockID();
1281 if (Cursor.SkipBlock()) {
1282 Error("malformed block record in PCH file");
1283 return;
1284 }
1285 continue;
1286 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001287
Douglas Gregor88a35862010-01-04 19:18:44 +00001288 if (Code == llvm::bitc::DEFINE_ABBREV) {
1289 Cursor.ReadAbbrevRecord();
1290 continue;
1291 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001292
Douglas Gregor88a35862010-01-04 19:18:44 +00001293 // Read a record.
1294 const char *BlobStart;
1295 unsigned BlobLen;
1296 Record.clear();
1297 switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1298 default: // Default behavior: ignore.
1299 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001300
Douglas Gregor88a35862010-01-04 19:18:44 +00001301 case pch::PP_MACRO_OBJECT_LIKE:
1302 case pch::PP_MACRO_FUNCTION_LIKE:
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001303 DecodeIdentifierInfo(Record[0]);
Douglas Gregor88a35862010-01-04 19:18:44 +00001304 break;
1305
1306 case pch::PP_TOKEN:
1307 // Ignore tokens.
1308 break;
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001309
1310 case pch::PP_MACRO_INSTANTIATION:
1311 case pch::PP_MACRO_DEFINITION:
1312 // Read the macro record.
1313 ReadMacroRecord(Cursor.GetCurrentBitNo());
1314 break;
Douglas Gregor88a35862010-01-04 19:18:44 +00001315 }
1316 }
1317}
1318
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001319MacroDefinition *PCHReader::getMacroDefinition(pch::IdentID ID) {
1320 if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1321 return 0;
1322
1323 if (!MacroDefinitionsLoaded[ID])
1324 ReadMacroRecord(MacroDefinitionOffsets[ID]);
1325
1326 return MacroDefinitionsLoaded[ID];
1327}
1328
Douglas Gregore650c8c2009-07-07 00:12:59 +00001329/// \brief If we are loading a relocatable PCH file, and the filename is
1330/// not an absolute path, add the system root to the beginning of the file
1331/// name.
1332void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1333 // If this is not a relocatable PCH file, there's nothing to do.
1334 if (!RelocatablePCH)
1335 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Daniel Dunbard5b21972009-11-18 19:50:41 +00001337 if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
Douglas Gregore650c8c2009-07-07 00:12:59 +00001338 return;
1339
Douglas Gregore650c8c2009-07-07 00:12:59 +00001340 if (isysroot == 0) {
1341 // If no system root was given, default to '/'
1342 Filename.insert(Filename.begin(), '/');
1343 return;
1344 }
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Douglas Gregore650c8c2009-07-07 00:12:59 +00001346 unsigned Length = strlen(isysroot);
1347 if (isysroot[Length - 1] != '/')
1348 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Douglas Gregore650c8c2009-07-07 00:12:59 +00001350 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1351}
1352
Mike Stump1eb44332009-09-09 15:08:12 +00001353PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001354PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001355 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001356 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001357 return Failure;
1358 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001359
1360 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001361 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001362 while (!Stream.AtEndOfStream()) {
1363 unsigned Code = Stream.ReadCode();
1364 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001365 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001366 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001367 return Failure;
1368 }
Chris Lattner7356a312009-04-11 21:15:38 +00001369
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001370 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001371 }
1372
1373 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1374 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001375 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001376 // We lazily load the decls block, but we want to set up the
1377 // DeclsCursor cursor to point into it. Clone our current bitcode
1378 // cursor to it, enter the block and read the abbrevs in that block.
1379 // With the main cursor, we just skip over it.
1380 DeclsCursor = Stream;
1381 if (Stream.SkipBlock() || // Skip with the main cursor.
1382 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001383 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001384 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001385 return Failure;
1386 }
1387 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattner7356a312009-04-11 21:15:38 +00001389 case pch::PREPROCESSOR_BLOCK_ID:
Douglas Gregor88a35862010-01-04 19:18:44 +00001390 MacroCursor = Stream;
1391 if (PP)
1392 PP->setExternalSource(this);
1393
Chris Lattner7356a312009-04-11 21:15:38 +00001394 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001395 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001396 return Failure;
1397 }
1398 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001399
Douglas Gregor14f79002009-04-10 03:52:48 +00001400 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001401 switch (ReadSourceManagerBlock()) {
1402 case Success:
1403 break;
1404
1405 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001406 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001407 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001408
1409 case IgnorePCH:
1410 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001411 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001412 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001413 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001414 continue;
1415 }
1416
1417 if (Code == llvm::bitc::DEFINE_ABBREV) {
1418 Stream.ReadAbbrevRecord();
1419 continue;
1420 }
1421
1422 // Read and process a record.
1423 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001424 const char *BlobStart = 0;
1425 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001426 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001427 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001428 default: // Default behavior: ignore.
1429 break;
1430
1431 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001432 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001433 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001434 return Failure;
1435 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001436 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001437 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001438 break;
1439
1440 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001441 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001442 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001443 return Failure;
1444 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001445 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001446 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001447 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001448
1449 case pch::LANGUAGE_OPTIONS:
1450 if (ParseLanguageOptions(Record))
1451 return IgnorePCH;
1452 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001453
Douglas Gregorab41e632009-04-27 22:23:34 +00001454 case pch::METADATA: {
1455 if (Record[0] != pch::VERSION_MAJOR) {
1456 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1457 : diag::warn_pch_version_too_new);
1458 return IgnorePCH;
1459 }
1460
Douglas Gregore650c8c2009-07-07 00:12:59 +00001461 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001462 if (Listener) {
1463 std::string TargetTriple(BlobStart, BlobLen);
1464 if (Listener->ReadTargetTriple(TargetTriple))
1465 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001466 }
1467 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001468 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001469
1470 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001471 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001472 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001473 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001474 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001475 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001476 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001477 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001478 if (PP)
1479 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001480 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001481 break;
1482
1483 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001484 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001485 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001486 return Failure;
1487 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001488 IdentifierOffsets = (const uint32_t *)BlobStart;
1489 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001490 if (PP)
1491 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001492 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001493
1494 case pch::EXTERNAL_DEFINITIONS:
1495 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001496 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001497 return Failure;
1498 }
1499 ExternalDefinitions.swap(Record);
1500 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001501
Douglas Gregorad1de002009-04-18 05:55:16 +00001502 case pch::SPECIAL_TYPES:
1503 SpecialTypes.swap(Record);
1504 break;
1505
Douglas Gregor3e1af842009-04-17 22:13:46 +00001506 case pch::STATISTICS:
1507 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001508 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001509 TotalLexicalDeclContexts = Record[2];
1510 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001511 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001512
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001513 case pch::TENTATIVE_DEFINITIONS:
1514 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001515 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001516 return Failure;
1517 }
1518 TentativeDefinitions.swap(Record);
1519 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001520
Tanya Lattnere6bbc012010-02-12 00:07:30 +00001521 case pch::UNUSED_STATIC_FUNCS:
1522 if (!UnusedStaticFuncs.empty()) {
1523 Error("duplicate UNUSED_STATIC_FUNCS record in PCH file");
1524 return Failure;
1525 }
1526 UnusedStaticFuncs.swap(Record);
1527 break;
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001528
Douglas Gregor14c22f22009-04-22 22:18:58 +00001529 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1530 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001531 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001532 return Failure;
1533 }
1534 LocallyScopedExternalDecls.swap(Record);
1535 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001536
Douglas Gregor83941df2009-04-25 17:48:32 +00001537 case pch::SELECTOR_OFFSETS:
1538 SelectorOffsets = (const uint32_t *)BlobStart;
1539 TotalNumSelectors = Record[0];
1540 SelectorsLoaded.resize(TotalNumSelectors);
1541 break;
1542
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001543 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001544 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1545 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001546 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001547 = PCHMethodPoolLookupTable::Create(
1548 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001549 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001550 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001551 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001552 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001553
1554 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001555 if (!Record.empty() && Listener)
1556 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001557 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001558
1559 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001560 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001561 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001562 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001563 break;
1564
1565 case pch::SOURCE_LOCATION_PRELOADS:
1566 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1567 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1568 if (Result != Success)
1569 return Result;
1570 }
1571 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001572
Douglas Gregor52e71082009-10-16 18:18:30 +00001573 case pch::STAT_CACHE: {
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001574 PCHStatCache *MyStatCache =
Douglas Gregor52e71082009-10-16 18:18:30 +00001575 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1576 (const unsigned char *)BlobStart,
1577 NumStatHits, NumStatMisses);
1578 FileMgr.addStatCache(MyStatCache);
1579 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001580 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001581 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001582
Douglas Gregorb81c1702009-04-27 20:06:05 +00001583 case pch::EXT_VECTOR_DECLS:
1584 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001585 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001586 return Failure;
1587 }
1588 ExtVectorDecls.swap(Record);
1589 break;
1590
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00001591 case pch::VTABLE_USES:
1592 if (!VTableUses.empty()) {
1593 Error("duplicate VTABLE_USES record in PCH file");
1594 return Failure;
1595 }
1596 VTableUses.swap(Record);
1597 break;
1598
1599 case pch::DYNAMIC_CLASSES:
1600 if (!DynamicClasses.empty()) {
1601 Error("duplicate DYNAMIC_CLASSES record in PCH file");
1602 return Failure;
1603 }
1604 DynamicClasses.swap(Record);
1605 break;
1606
Douglas Gregorb64c1932009-05-12 01:31:05 +00001607 case pch::ORIGINAL_FILE_NAME:
Daniel Dunbar7b5a1212009-11-11 05:29:04 +00001608 ActualOriginalFileName.assign(BlobStart, BlobLen);
1609 OriginalFileName = ActualOriginalFileName;
Douglas Gregore650c8c2009-07-07 00:12:59 +00001610 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001611 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Ted Kremenek5b4ec632010-01-22 20:59:36 +00001613 case pch::VERSION_CONTROL_BRANCH_REVISION: {
Ted Kremenek974be4d2010-02-12 23:31:14 +00001614 const std::string &CurBranch = getClangFullRepositoryVersion();
Ted Kremenek517e6762010-01-22 20:55:35 +00001615 llvm::StringRef PCHBranch(BlobStart, BlobLen);
Ted Kremenek974be4d2010-02-12 23:31:14 +00001616 if (llvm::StringRef(CurBranch) != PCHBranch) {
Douglas Gregor445e23e2009-10-05 21:07:28 +00001617 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1618 return IgnorePCH;
1619 }
1620 break;
1621 }
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001622
1623 case pch::MACRO_DEFINITION_OFFSETS:
1624 MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1625 if (PP) {
1626 if (!PP->getPreprocessingRecord())
1627 PP->createPreprocessingRecord();
1628 PP->getPreprocessingRecord()->SetExternalSource(*this, Record[0]);
1629 } else {
1630 NumPreallocatedPreprocessingEntities = Record[0];
1631 }
1632
1633 MacroDefinitionsLoaded.resize(Record[1]);
1634 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001635 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001636 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001637 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001638 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001639}
1640
Douglas Gregore1d918e2009-04-10 23:10:45 +00001641PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001642 // Set the PCH file name.
1643 this->FileName = FileName;
1644
Douglas Gregor2cf26342009-04-09 22:27:44 +00001645 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001646 //
1647 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001648 std::string ErrStr;
Daniel Dunbar731ad8f2009-11-10 00:46:19 +00001649 Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001650 if (!Buffer) {
1651 Error(ErrStr.c_str());
1652 return IgnorePCH;
1653 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001654
1655 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001656 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001657 (const unsigned char *)Buffer->getBufferEnd());
1658 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001659
1660 // Sniff for the signature.
1661 if (Stream.Read(8) != 'C' ||
1662 Stream.Read(8) != 'P' ||
1663 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001664 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001665 Diag(diag::err_not_a_pch_file) << FileName;
1666 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001667 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001668
Douglas Gregor2cf26342009-04-09 22:27:44 +00001669 while (!Stream.AtEndOfStream()) {
1670 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Douglas Gregore1d918e2009-04-10 23:10:45 +00001672 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001673 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001674 return Failure;
1675 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001676
1677 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001678
Douglas Gregor2cf26342009-04-09 22:27:44 +00001679 // We only know the PCH subblock ID.
1680 switch (BlockID) {
1681 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001682 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001683 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001684 return Failure;
1685 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001686 break;
1687 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001688 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001689 case Success:
1690 break;
1691
1692 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001693 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001694
1695 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001696 // FIXME: We could consider reading through to the end of this
1697 // PCH block, skipping subblocks, to see if there are other
1698 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001699
1700 // Clear out any preallocated source location entries, so that
1701 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001702 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001703
1704 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001705 if (StatCache)
1706 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001707
Douglas Gregore1d918e2009-04-10 23:10:45 +00001708 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001709 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001710 break;
1711 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001712 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001713 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001714 return Failure;
1715 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001716 break;
1717 }
Mike Stump1eb44332009-09-09 15:08:12 +00001718 }
1719
Douglas Gregor92b059e2009-04-28 20:33:11 +00001720 // Check the predefines buffer.
Sebastian Redl7e9ad8b2010-07-14 17:49:11 +00001721 if (CheckPredefinesBuffers())
Douglas Gregor92b059e2009-04-28 20:33:11 +00001722 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001724 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001725 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001726 // PCH file is read, so there may be some identifiers that were
1727 // loaded into the IdentifierTable before we intercepted the
1728 // creation of identifiers. Iterate through the list of known
1729 // identifiers and determine whether we have to establish
1730 // preprocessor definitions or top-level identifier declaration
1731 // chains for those identifiers.
1732 //
1733 // We copy the IdentifierInfo pointers to a small vector first,
1734 // since de-serializing declarations or macro definitions can add
1735 // new entries into the identifier table, invalidating the
1736 // iterators.
1737 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1738 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1739 IdEnd = PP->getIdentifierTable().end();
1740 Id != IdEnd; ++Id)
1741 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001742 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001743 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1744 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1745 IdentifierInfo *II = Identifiers[I];
1746 // Look in the on-disk hash table for an entry for
1747 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001748 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001749 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1750 if (Pos == IdTable->end())
1751 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001753 // Dereferencing the iterator has the effect of populating the
1754 // IdentifierInfo node with the various declarations it needs.
1755 (void)*Pos;
1756 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001757 }
1758
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001759 if (Context)
1760 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001761
Douglas Gregor668c1a42009-04-21 22:25:48 +00001762 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001763}
1764
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00001765void PCHReader::setPreprocessor(Preprocessor &pp) {
1766 PP = &pp;
1767
1768 if (NumPreallocatedPreprocessingEntities) {
1769 if (!PP->getPreprocessingRecord())
1770 PP->createPreprocessingRecord();
1771 PP->getPreprocessingRecord()->SetExternalSource(*this,
1772 NumPreallocatedPreprocessingEntities);
1773 NumPreallocatedPreprocessingEntities = 0;
1774 }
1775}
1776
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001777void PCHReader::InitializeContext(ASTContext &Ctx) {
1778 Context = &Ctx;
1779 assert(Context && "Passed null context!");
1780
1781 assert(PP && "Forgot to set Preprocessor ?");
1782 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1783 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor88a35862010-01-04 19:18:44 +00001784 PP->setExternalSource(this);
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00001785
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001786 // Load the translation unit declaration
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00001787 GetTranslationUnitDecl();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001788
1789 // Load the special types.
1790 Context->setBuiltinVaListType(
1791 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1792 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1793 Context->setObjCIdType(GetType(Id));
1794 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1795 Context->setObjCSelType(GetType(Sel));
1796 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1797 Context->setObjCProtoType(GetType(Proto));
1798 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1799 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001800
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001801 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1802 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001803 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001804 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1805 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001806 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1807 QualType FileType = GetType(File);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001808 if (FileType.isNull()) {
1809 Error("FILE type is NULL");
1810 return;
1811 }
John McCall183700f2009-09-21 23:43:11 +00001812 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001813 Context->setFILEDecl(Typedef->getDecl());
1814 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001815 const TagType *Tag = FileType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001816 if (!Tag) {
1817 Error("Invalid FILE type in PCH file");
1818 return;
1819 }
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001820 Context->setFILEDecl(Tag->getDecl());
1821 }
1822 }
Mike Stump782fa302009-07-28 02:25:19 +00001823 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1824 QualType Jmp_bufType = GetType(Jmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001825 if (Jmp_bufType.isNull()) {
1826 Error("jmp_bug type is NULL");
1827 return;
1828 }
John McCall183700f2009-09-21 23:43:11 +00001829 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001830 Context->setjmp_bufDecl(Typedef->getDecl());
1831 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001832 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001833 if (!Tag) {
1834 Error("Invalid jmp_bug type in PCH file");
1835 return;
1836 }
Mike Stump782fa302009-07-28 02:25:19 +00001837 Context->setjmp_bufDecl(Tag->getDecl());
1838 }
1839 }
1840 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1841 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00001842 if (Sigjmp_bufType.isNull()) {
1843 Error("sigjmp_buf type is NULL");
1844 return;
1845 }
John McCall183700f2009-09-21 23:43:11 +00001846 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001847 Context->setsigjmp_bufDecl(Typedef->getDecl());
1848 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001849 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001850 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1851 Context->setsigjmp_bufDecl(Tag->getDecl());
1852 }
1853 }
Mike Stump1eb44332009-09-09 15:08:12 +00001854 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001855 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1856 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001857 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001858 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1859 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00001860 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1861 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001862 if (unsigned String
1863 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1864 Context->setBlockDescriptorExtendedType(GetType(String));
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001865 if (unsigned ObjCSelRedef
1866 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
1867 Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
1868 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_NS_CONSTANT_STRING])
1869 Context->setNSConstantStringType(GetType(String));
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +00001870
1871 if (SpecialTypes[pch::SPECIAL_TYPE_INT128_INSTALLED])
1872 Context->setInt128Installed();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001873}
1874
Douglas Gregorb64c1932009-05-12 01:31:05 +00001875/// \brief Retrieve the name of the original source file name
1876/// directly from the PCH file, without actually loading the PCH
1877/// file.
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001878std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName,
1879 Diagnostic &Diags) {
Douglas Gregorb64c1932009-05-12 01:31:05 +00001880 // Open the PCH file.
1881 std::string ErrStr;
1882 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1883 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1884 if (!Buffer) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001885 Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001886 return std::string();
1887 }
1888
1889 // Initialize the stream
1890 llvm::BitstreamReader StreamFile;
1891 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001892 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001893 (const unsigned char *)Buffer->getBufferEnd());
1894 Stream.init(StreamFile);
1895
1896 // Sniff for the signature.
1897 if (Stream.Read(8) != 'C' ||
1898 Stream.Read(8) != 'P' ||
1899 Stream.Read(8) != 'C' ||
1900 Stream.Read(8) != 'H') {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001901 Diags.Report(diag::err_fe_not_a_pch_file) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001902 return std::string();
1903 }
1904
1905 RecordData Record;
1906 while (!Stream.AtEndOfStream()) {
1907 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregorb64c1932009-05-12 01:31:05 +00001909 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1910 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Douglas Gregorb64c1932009-05-12 01:31:05 +00001912 // We only know the PCH subblock ID.
1913 switch (BlockID) {
1914 case pch::PCH_BLOCK_ID:
1915 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001916 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001917 return std::string();
1918 }
1919 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Douglas Gregorb64c1932009-05-12 01:31:05 +00001921 default:
1922 if (Stream.SkipBlock()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001923 Diags.Report(diag::err_fe_pch_malformed_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001924 return std::string();
1925 }
1926 break;
1927 }
1928 continue;
1929 }
1930
1931 if (Code == llvm::bitc::END_BLOCK) {
1932 if (Stream.ReadBlockEnd()) {
Daniel Dunbar93ebb1b2009-12-03 09:13:06 +00001933 Diags.Report(diag::err_fe_pch_error_at_end_block) << PCHFileName;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001934 return std::string();
1935 }
1936 continue;
1937 }
1938
1939 if (Code == llvm::bitc::DEFINE_ABBREV) {
1940 Stream.ReadAbbrevRecord();
1941 continue;
1942 }
1943
1944 Record.clear();
1945 const char *BlobStart = 0;
1946 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001947 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001948 == pch::ORIGINAL_FILE_NAME)
1949 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001950 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001951
1952 return std::string();
1953}
1954
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001955/// \brief Parse the record that corresponds to a LangOptions data
1956/// structure.
1957///
1958/// This routine compares the language options used to generate the
1959/// PCH file against the language options set for the current
1960/// compilation. For each option, we classify differences between the
1961/// two compiler states as either "benign" or "important". Benign
1962/// differences don't matter, and we accept them without complaint
1963/// (and without modifying the language options). Differences between
1964/// the states for important options cause the PCH file to be
1965/// unusable, so we emit a warning and return true to indicate that
1966/// there was an error.
1967///
1968/// \returns true if the PCH file is unacceptable, false otherwise.
1969bool PCHReader::ParseLanguageOptions(
1970 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001971 if (Listener) {
1972 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001974 #define PARSE_LANGOPT(Option) \
1975 LangOpts.Option = Record[Idx]; \
1976 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001978 unsigned Idx = 0;
1979 PARSE_LANGOPT(Trigraphs);
1980 PARSE_LANGOPT(BCPLComment);
1981 PARSE_LANGOPT(DollarIdents);
1982 PARSE_LANGOPT(AsmPreprocessor);
1983 PARSE_LANGOPT(GNUMode);
Chandler Carrutheb5d7b72010-04-17 20:17:31 +00001984 PARSE_LANGOPT(GNUKeywords);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001985 PARSE_LANGOPT(ImplicitInt);
1986 PARSE_LANGOPT(Digraphs);
1987 PARSE_LANGOPT(HexFloats);
1988 PARSE_LANGOPT(C99);
1989 PARSE_LANGOPT(Microsoft);
1990 PARSE_LANGOPT(CPlusPlus);
1991 PARSE_LANGOPT(CPlusPlus0x);
1992 PARSE_LANGOPT(CXXOperatorNames);
1993 PARSE_LANGOPT(ObjC1);
1994 PARSE_LANGOPT(ObjC2);
1995 PARSE_LANGOPT(ObjCNonFragileABI);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001996 PARSE_LANGOPT(ObjCNonFragileABI2);
Fariborz Jahanian4c9d8d02010-04-22 21:01:59 +00001997 PARSE_LANGOPT(NoConstantCFStrings);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001998 PARSE_LANGOPT(PascalStrings);
1999 PARSE_LANGOPT(WritableStrings);
2000 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002001 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002002 PARSE_LANGOPT(Exceptions);
Daniel Dunbar73482882010-02-10 18:48:44 +00002003 PARSE_LANGOPT(SjLjExceptions);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002004 PARSE_LANGOPT(NeXTRuntime);
2005 PARSE_LANGOPT(Freestanding);
2006 PARSE_LANGOPT(NoBuiltin);
2007 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00002008 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002009 PARSE_LANGOPT(Blocks);
2010 PARSE_LANGOPT(EmitAllDecls);
2011 PARSE_LANGOPT(MathErrno);
Chris Lattnera4d71452010-06-26 21:25:03 +00002012 LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2013 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002014 PARSE_LANGOPT(HeinousExtensions);
2015 PARSE_LANGOPT(Optimize);
2016 PARSE_LANGOPT(OptimizeSize);
2017 PARSE_LANGOPT(Static);
2018 PARSE_LANGOPT(PICLevel);
2019 PARSE_LANGOPT(GNUInline);
2020 PARSE_LANGOPT(NoInline);
2021 PARSE_LANGOPT(AccessControl);
2022 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00002023 PARSE_LANGOPT(ShortWChar);
Chris Lattnera4d71452010-06-26 21:25:03 +00002024 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2025 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
Daniel Dunbarab8e2812009-09-21 04:16:19 +00002026 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
Chris Lattnera4d71452010-06-26 21:25:03 +00002027 Record[Idx++]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002028 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00002029 PARSE_LANGOPT(OpenCL);
Mike Stump9c276ae2009-12-12 01:27:46 +00002030 PARSE_LANGOPT(CatchUndefined);
2031 // FIXME: Missing ElideConstructors?!
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002032 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002033
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002034 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002035 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002036
2037 return false;
2038}
2039
Douglas Gregor6a5a23f2010-03-19 21:51:54 +00002040void PCHReader::ReadPreprocessedEntities() {
2041 ReadDefinedMacros();
2042}
2043
Douglas Gregor2cf26342009-04-09 22:27:44 +00002044/// \brief Read and return the type at the given offset.
2045///
2046/// This routine actually reads the record corresponding to the type
2047/// at the given offset in the bitstream. It is a helper routine for
2048/// GetType, which deals with reading type IDs.
2049QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00002050 // Keep track of where we are in the stream, then jump back there
2051 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002052 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002053
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002054 ReadingKindTracker ReadingKind(Read_Type, *this);
2055
Douglas Gregord89275b2009-07-06 18:54:52 +00002056 // Note that we are loading a type record.
2057 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002059 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002060 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002061 unsigned Code = DeclsCursor.ReadCode();
2062 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00002063 case pch::TYPE_EXT_QUAL: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002064 if (Record.size() != 2) {
2065 Error("Incorrect encoding of extended qualifier type");
2066 return QualType();
2067 }
Douglas Gregor6d473962009-04-15 22:00:08 +00002068 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00002069 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2070 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00002071 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002072
Douglas Gregor2cf26342009-04-09 22:27:44 +00002073 case pch::TYPE_COMPLEX: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002074 if (Record.size() != 1) {
2075 Error("Incorrect encoding of complex type");
2076 return QualType();
2077 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002078 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002079 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002080 }
2081
2082 case pch::TYPE_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002083 if (Record.size() != 1) {
2084 Error("Incorrect encoding of pointer type");
2085 return QualType();
2086 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002087 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002088 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002089 }
2090
2091 case pch::TYPE_BLOCK_POINTER: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002092 if (Record.size() != 1) {
2093 Error("Incorrect encoding of block pointer type");
2094 return QualType();
2095 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002096 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002097 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002098 }
2099
2100 case pch::TYPE_LVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002101 if (Record.size() != 1) {
2102 Error("Incorrect encoding of lvalue reference type");
2103 return QualType();
2104 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002105 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002106 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002107 }
2108
2109 case pch::TYPE_RVALUE_REFERENCE: {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002110 if (Record.size() != 1) {
2111 Error("Incorrect encoding of rvalue reference type");
2112 return QualType();
2113 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002114 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002115 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002116 }
2117
2118 case pch::TYPE_MEMBER_POINTER: {
Argyrios Kyrtzidis240437b2010-07-02 11:55:15 +00002119 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002120 Error("Incorrect encoding of member pointer type");
2121 return QualType();
2122 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002123 QualType PointeeType = GetType(Record[0]);
2124 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002125 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00002126 }
2127
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002128 case pch::TYPE_CONSTANT_ARRAY: {
2129 QualType ElementType = GetType(Record[0]);
2130 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2131 unsigned IndexTypeQuals = Record[2];
2132 unsigned Idx = 3;
2133 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002134 return Context->getConstantArrayType(ElementType, Size,
2135 ASM, IndexTypeQuals);
2136 }
2137
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002138 case pch::TYPE_INCOMPLETE_ARRAY: {
2139 QualType ElementType = GetType(Record[0]);
2140 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2141 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002142 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002143 }
2144
2145 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00002146 QualType ElementType = GetType(Record[0]);
2147 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2148 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002149 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2150 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002151 return Context->getVariableArrayType(ElementType, ReadExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002152 ASM, IndexTypeQuals,
2153 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002154 }
2155
2156 case pch::TYPE_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002157 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002158 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002159 return QualType();
2160 }
2161
2162 QualType ElementType = GetType(Record[0]);
2163 unsigned NumElements = Record[1];
Chris Lattner788b0fd2010-06-23 06:00:24 +00002164 unsigned AltiVecSpec = Record[2];
2165 return Context->getVectorType(ElementType, NumElements,
2166 (VectorType::AltiVecSpecific)AltiVecSpec);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002167 }
2168
2169 case pch::TYPE_EXT_VECTOR: {
Chris Lattner788b0fd2010-06-23 06:00:24 +00002170 if (Record.size() != 3) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002171 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002172 return QualType();
2173 }
2174
2175 QualType ElementType = GetType(Record[0]);
2176 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002177 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002178 }
2179
2180 case pch::TYPE_FUNCTION_NO_PROTO: {
Rafael Espindola425ef722010-03-30 22:15:11 +00002181 if (Record.size() != 4) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002182 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002183 return QualType();
2184 }
2185 QualType ResultType = GetType(Record[0]);
Rafael Espindola425ef722010-03-30 22:15:11 +00002186 FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
Rafael Espindola264ba482010-03-30 20:24:48 +00002187 return Context->getFunctionNoProtoType(ResultType, Info);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002188 }
2189
2190 case pch::TYPE_FUNCTION_PROTO: {
2191 QualType ResultType = GetType(Record[0]);
Douglas Gregor91236662009-12-22 18:11:50 +00002192 bool NoReturn = Record[1];
Rafael Espindola425ef722010-03-30 22:15:11 +00002193 unsigned RegParm = Record[2];
2194 CallingConv CallConv = (CallingConv)Record[3];
2195 unsigned Idx = 4;
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002196 unsigned NumParams = Record[Idx++];
2197 llvm::SmallVector<QualType, 16> ParamTypes;
2198 for (unsigned I = 0; I != NumParams; ++I)
2199 ParamTypes.push_back(GetType(Record[Idx++]));
2200 bool isVariadic = Record[Idx++];
2201 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00002202 bool hasExceptionSpec = Record[Idx++];
2203 bool hasAnyExceptionSpec = Record[Idx++];
2204 unsigned NumExceptions = Record[Idx++];
2205 llvm::SmallVector<QualType, 2> Exceptions;
2206 for (unsigned I = 0; I != NumExceptions; ++I)
2207 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00002208 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00002209 isVariadic, Quals, hasExceptionSpec,
2210 hasAnyExceptionSpec, NumExceptions,
Rafael Espindola264ba482010-03-30 20:24:48 +00002211 Exceptions.data(),
Rafael Espindola425ef722010-03-30 22:15:11 +00002212 FunctionType::ExtInfo(NoReturn, RegParm,
2213 CallConv));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002214 }
2215
John McCalled976492009-12-04 22:46:56 +00002216 case pch::TYPE_UNRESOLVED_USING:
2217 return Context->getTypeDeclType(
2218 cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2219
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002220 case pch::TYPE_TYPEDEF: {
2221 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002222 Error("incorrect encoding of typedef type");
2223 return QualType();
2224 }
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002225 TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2226 QualType Canonical = GetType(Record[1]);
2227 return Context->getTypedefType(Decl, Canonical);
2228 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002229
2230 case pch::TYPE_TYPEOF_EXPR:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002231 return Context->getTypeOfExprType(ReadExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002232
2233 case pch::TYPE_TYPEOF: {
2234 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002235 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002236 return QualType();
2237 }
2238 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002239 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002240 }
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Anders Carlsson395b4752009-06-24 19:06:50 +00002242 case pch::TYPE_DECLTYPE:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002243 return Context->getDecltypeType(ReadExpr());
Anders Carlsson395b4752009-06-24 19:06:50 +00002244
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002245 case pch::TYPE_RECORD: {
2246 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002247 Error("incorrect encoding of record type");
2248 return QualType();
2249 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002250 bool IsDependent = Record[0];
2251 QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2252 T->Dependent = IsDependent;
2253 return T;
2254 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002255
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002256 case pch::TYPE_ENUM: {
2257 if (Record.size() != 2) {
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002258 Error("incorrect encoding of enum type");
2259 return QualType();
2260 }
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002261 bool IsDependent = Record[0];
2262 QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2263 T->Dependent = IsDependent;
2264 return T;
2265 }
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002266
John McCall7da24312009-09-05 00:15:47 +00002267 case pch::TYPE_ELABORATED: {
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002268 unsigned Idx = 0;
2269 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2270 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2271 QualType NamedType = GetType(Record[Idx++]);
2272 return Context->getElaboratedType(Keyword, NNS, NamedType);
John McCall7da24312009-09-05 00:15:47 +00002273 }
2274
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002275 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002276 unsigned Idx = 0;
2277 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002278 return Context->getObjCInterfaceType(ItfD);
2279 }
2280
2281 case pch::TYPE_OBJC_OBJECT: {
2282 unsigned Idx = 0;
2283 QualType Base = GetType(Record[Idx++]);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002284 unsigned NumProtos = Record[Idx++];
2285 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2286 for (unsigned I = 0; I != NumProtos; ++I)
2287 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
John McCallc12c5bb2010-05-15 11:32:37 +00002288 return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00002289 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00002290
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002291 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002292 unsigned Idx = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002293 QualType Pointee = GetType(Record[Idx++]);
2294 return Context->getObjCObjectPointerType(Pointee);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00002295 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00002296
John McCall49a832b2009-10-18 09:09:24 +00002297 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2298 unsigned Idx = 0;
2299 QualType Parm = GetType(Record[Idx++]);
2300 QualType Replacement = GetType(Record[Idx++]);
2301 return
2302 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2303 Replacement);
2304 }
John McCall3cb0ebd2010-03-10 03:28:59 +00002305
2306 case pch::TYPE_INJECTED_CLASS_NAME: {
2307 CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2308 QualType TST = GetType(Record[1]); // probably derivable
Argyrios Kyrtzidis43921b52010-07-02 11:55:20 +00002309 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2310 // for PCH reading, too much interdependencies.
2311 return
2312 QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
John McCall3cb0ebd2010-03-10 03:28:59 +00002313 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002314
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002315 case pch::TYPE_TEMPLATE_TYPE_PARM: {
2316 unsigned Idx = 0;
2317 unsigned Depth = Record[Idx++];
2318 unsigned Index = Record[Idx++];
2319 bool Pack = Record[Idx++];
2320 IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2321 return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2322 }
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002323
2324 case pch::TYPE_DEPENDENT_NAME: {
2325 unsigned Idx = 0;
2326 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2327 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2328 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
Argyrios Kyrtzidisf48d45e2010-07-02 11:55:24 +00002329 QualType Canon = GetType(Record[Idx++]);
2330 return Context->getDependentNameType(Keyword, NNS, Name, Canon);
Argyrios Kyrtzidis8dfbd8b2010-06-24 08:57:31 +00002331 }
Argyrios Kyrtzidis3acad622010-06-25 16:24:58 +00002332
2333 case pch::TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2334 unsigned Idx = 0;
2335 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2336 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2337 const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2338 unsigned NumArgs = Record[Idx++];
2339 llvm::SmallVector<TemplateArgument, 8> Args;
2340 Args.reserve(NumArgs);
2341 while (NumArgs--)
2342 Args.push_back(ReadTemplateArgument(Record, Idx));
2343 return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2344 Args.size(), Args.data());
2345 }
Argyrios Kyrtzidisae8b17f2010-06-30 08:49:25 +00002346
2347 case pch::TYPE_DEPENDENT_SIZED_ARRAY: {
2348 unsigned Idx = 0;
2349
2350 // ArrayType
2351 QualType ElementType = GetType(Record[Idx++]);
2352 ArrayType::ArraySizeModifier ASM
2353 = (ArrayType::ArraySizeModifier)Record[Idx++];
2354 unsigned IndexTypeQuals = Record[Idx++];
2355
2356 // DependentSizedArrayType
2357 Expr *NumElts = ReadExpr();
2358 SourceRange Brackets = ReadSourceRange(Record, Idx);
2359
2360 return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2361 IndexTypeQuals, Brackets);
2362 }
Argyrios Kyrtzidis90b715e2010-06-19 19:28:53 +00002363
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002364 case pch::TYPE_TEMPLATE_SPECIALIZATION: {
2365 unsigned Idx = 0;
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002366 bool IsDependent = Record[Idx++];
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002367 TemplateName Name = ReadTemplateName(Record, Idx);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002368 llvm::SmallVector<TemplateArgument, 8> Args;
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00002369 ReadTemplateArgumentList(Args, Record, Idx);
2370 QualType Canon = GetType(Record[Idx++]);
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002371 QualType T;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002372 if (Canon.isNull())
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002373 T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2374 Args.size());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002375 else
Argyrios Kyrtzidisbe191102010-07-08 13:09:53 +00002376 T = Context->getTemplateSpecializationType(Name, Args.data(),
2377 Args.size(), Canon);
2378 T->Dependent = IsDependent;
2379 return T;
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00002380 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002381 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002382 // Suppress a GCC warning
2383 return QualType();
2384}
2385
John McCalla1ee0c52009-10-16 21:56:05 +00002386namespace {
2387
2388class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2389 PCHReader &Reader;
2390 const PCHReader::RecordData &Record;
2391 unsigned &Idx;
2392
2393public:
2394 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
2395 unsigned &Idx)
2396 : Reader(Reader), Record(Record), Idx(Idx) { }
2397
John McCall51bd8032009-10-18 01:05:36 +00002398 // We want compile-time assurance that we've enumerated all of
2399 // these, so unfortunately we have to declare them first, then
2400 // define them out-of-line.
2401#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00002402#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002403 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002404#include "clang/AST/TypeLocNodes.def"
2405
John McCall51bd8032009-10-18 01:05:36 +00002406 void VisitFunctionTypeLoc(FunctionTypeLoc);
2407 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002408};
2409
2410}
2411
John McCall51bd8032009-10-18 01:05:36 +00002412void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002413 // nothing to do
2414}
John McCall51bd8032009-10-18 01:05:36 +00002415void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorddf889a2010-01-18 18:04:31 +00002416 TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2417 if (TL.needsExtraLocalData()) {
2418 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2419 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2420 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2421 TL.setModeAttr(Record[Idx++]);
2422 }
John McCalla1ee0c52009-10-16 21:56:05 +00002423}
John McCall51bd8032009-10-18 01:05:36 +00002424void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2425 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002426}
John McCall51bd8032009-10-18 01:05:36 +00002427void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2428 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002429}
John McCall51bd8032009-10-18 01:05:36 +00002430void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2431 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002432}
John McCall51bd8032009-10-18 01:05:36 +00002433void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2434 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002435}
John McCall51bd8032009-10-18 01:05:36 +00002436void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2437 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002438}
John McCall51bd8032009-10-18 01:05:36 +00002439void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2440 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002441}
John McCall51bd8032009-10-18 01:05:36 +00002442void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2443 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2444 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002445 if (Record[Idx++])
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002446 TL.setSizeExpr(Reader.ReadExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002447 else
John McCall51bd8032009-10-18 01:05:36 +00002448 TL.setSizeExpr(0);
2449}
2450void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2451 VisitArrayTypeLoc(TL);
2452}
2453void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2454 VisitArrayTypeLoc(TL);
2455}
2456void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2457 VisitArrayTypeLoc(TL);
2458}
2459void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2460 DependentSizedArrayTypeLoc TL) {
2461 VisitArrayTypeLoc(TL);
2462}
2463void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2464 DependentSizedExtVectorTypeLoc TL) {
2465 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2466}
2467void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2468 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2469}
2470void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2471 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2472}
2473void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2474 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2475 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2476 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002477 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002478 }
2479}
2480void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2481 VisitFunctionTypeLoc(TL);
2482}
2483void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2484 VisitFunctionTypeLoc(TL);
2485}
John McCalled976492009-12-04 22:46:56 +00002486void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2487 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2488}
John McCall51bd8032009-10-18 01:05:36 +00002489void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2490 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2491}
2492void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002493 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2494 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2495 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002496}
2497void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCallcfb708c2010-01-13 20:03:27 +00002498 TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2499 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2500 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2501 TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002502}
2503void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2504 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2505}
2506void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2507 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2508}
2509void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2510 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2511}
John McCall51bd8032009-10-18 01:05:36 +00002512void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2513 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2514}
John McCall49a832b2009-10-18 09:09:24 +00002515void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2516 SubstTemplateTypeParmTypeLoc TL) {
2517 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2518}
John McCall51bd8032009-10-18 01:05:36 +00002519void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2520 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002521 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2522 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2523 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2524 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2525 TL.setArgLocInfo(i,
2526 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2527 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002528}
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002529void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002530 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2531 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002532}
John McCall3cb0ebd2010-03-10 03:28:59 +00002533void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2534 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2535}
Douglas Gregor4714c122010-03-31 17:34:00 +00002536void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00002537 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2538 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002539 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2540}
John McCall33500952010-06-11 00:33:02 +00002541void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2542 DependentTemplateSpecializationTypeLoc TL) {
2543 TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2544 TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2545 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2546 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2547 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2548 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2549 TL.setArgLocInfo(I,
2550 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
2551 Record, Idx));
2552}
John McCall51bd8032009-10-18 01:05:36 +00002553void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2554 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCallc12c5bb2010-05-15 11:32:37 +00002555}
2556void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2557 TL.setHasBaseTypeAsWritten(Record[Idx++]);
John McCall51bd8032009-10-18 01:05:36 +00002558 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2559 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2560 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2561 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002562}
John McCall54e14c42009-10-22 22:37:11 +00002563void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2564 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall54e14c42009-10-22 22:37:11 +00002565}
John McCalla1ee0c52009-10-16 21:56:05 +00002566
John McCalla93c9342009-12-07 02:54:59 +00002567TypeSourceInfo *PCHReader::GetTypeSourceInfo(const RecordData &Record,
John McCalla1ee0c52009-10-16 21:56:05 +00002568 unsigned &Idx) {
2569 QualType InfoTy = GetType(Record[Idx++]);
2570 if (InfoTy.isNull())
2571 return 0;
2572
John McCalla93c9342009-12-07 02:54:59 +00002573 TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
John McCalla1ee0c52009-10-16 21:56:05 +00002574 TypeLocReader TLR(*this, Record, Idx);
John McCalla93c9342009-12-07 02:54:59 +00002575 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
John McCalla1ee0c52009-10-16 21:56:05 +00002576 TLR.Visit(TL);
John McCalla93c9342009-12-07 02:54:59 +00002577 return TInfo;
John McCalla1ee0c52009-10-16 21:56:05 +00002578}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002579
Douglas Gregor8038d512009-04-10 17:25:41 +00002580QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002581 unsigned FastQuals = ID & Qualifiers::FastMask;
2582 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002583
2584 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2585 QualType T;
2586 switch ((pch::PredefinedTypeIDs)Index) {
2587 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002588 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2589 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002590
2591 case pch::PREDEF_TYPE_CHAR_U_ID:
2592 case pch::PREDEF_TYPE_CHAR_S_ID:
2593 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002594 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002595 break;
2596
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002597 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2598 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2599 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2600 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2601 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002602 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002603 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2604 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2605 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2606 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2607 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2608 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002609 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002610 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2611 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2612 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2613 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2614 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002615 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002616 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2617 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002618 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2619 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00002620 case pch::PREDEF_TYPE_OBJC_SEL: T = Context->ObjCBuiltinSelTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002621 }
2622
2623 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002624 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002625 }
2626
2627 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002628 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Sebastian Redl07a353c2010-07-14 20:26:45 +00002629 if (TypesLoaded[Index].isNull()) {
John McCall0953e762009-09-24 19:53:00 +00002630 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Sebastian Redl07a353c2010-07-14 20:26:45 +00002631 TypesLoaded[Index]->setFromPCH();
2632 }
Mike Stump1eb44332009-09-09 15:08:12 +00002633
John McCall0953e762009-09-24 19:53:00 +00002634 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002635}
2636
John McCall833ca992009-10-29 08:12:44 +00002637TemplateArgumentLocInfo
2638PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2639 const RecordData &Record,
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002640 unsigned &Index) {
John McCall833ca992009-10-29 08:12:44 +00002641 switch (Kind) {
2642 case TemplateArgument::Expression:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002643 return ReadExpr();
John McCall833ca992009-10-29 08:12:44 +00002644 case TemplateArgument::Type:
John McCalla93c9342009-12-07 02:54:59 +00002645 return GetTypeSourceInfo(Record, Index);
Douglas Gregor788cd062009-11-11 01:00:40 +00002646 case TemplateArgument::Template: {
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002647 SourceRange QualifierRange = ReadSourceRange(Record, Index);
2648 SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
2649 return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
Douglas Gregor788cd062009-11-11 01:00:40 +00002650 }
John McCall833ca992009-10-29 08:12:44 +00002651 case TemplateArgument::Null:
2652 case TemplateArgument::Integral:
2653 case TemplateArgument::Declaration:
2654 case TemplateArgument::Pack:
2655 return TemplateArgumentLocInfo();
2656 }
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002657 llvm_unreachable("unexpected template argument loc");
John McCall833ca992009-10-29 08:12:44 +00002658 return TemplateArgumentLocInfo();
2659}
2660
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002661TemplateArgumentLoc
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002662PCHReader::ReadTemplateArgumentLoc(const RecordData &Record, unsigned &Index) {
2663 TemplateArgument Arg = ReadTemplateArgument(Record, Index);
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00002664
2665 if (Arg.getKind() == TemplateArgument::Expression) {
2666 if (Record[Index++]) // bool InfoHasSameExpr.
2667 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
2668 }
2669 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002670 Record, Index));
Argyrios Kyrtzidis44f8c372010-06-22 09:54:59 +00002671}
2672
John McCall76bd1f32010-06-01 09:23:16 +00002673Decl *PCHReader::GetExternalDecl(uint32_t ID) {
2674 return GetDecl(ID);
2675}
2676
Argyrios Kyrtzidis8871a442010-07-08 17:13:02 +00002677TranslationUnitDecl *PCHReader::GetTranslationUnitDecl() {
2678 if (!DeclsLoaded[0])
2679 ReadDeclRecord(DeclOffsets[0], 0);
2680
2681 return cast<TranslationUnitDecl>(DeclsLoaded[0]);
2682}
2683
Douglas Gregor8038d512009-04-10 17:25:41 +00002684Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002685 if (ID == 0)
2686 return 0;
2687
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002688 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002689 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002690 return 0;
2691 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002692
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002693 unsigned Index = ID - 1;
2694 if (!DeclsLoaded[Index])
2695 ReadDeclRecord(DeclOffsets[Index], Index);
2696
2697 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002698}
2699
Chris Lattner887e2b32009-04-27 05:46:25 +00002700/// \brief Resolve the offset of a statement into a statement.
2701///
2702/// This operation will read a new statement from the external
2703/// source each time it is called, and is meant to be used via a
2704/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
John McCall76bd1f32010-06-01 09:23:16 +00002705Stmt *PCHReader::GetExternalDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002706 // Since we know tha this statement is part of a decl, make sure to use the
2707 // decl cursor to read it.
2708 DeclsCursor.JumpToBit(Offset);
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00002709 return ReadStmtFromStream(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002710}
2711
John McCall76bd1f32010-06-01 09:23:16 +00002712bool PCHReader::FindExternalLexicalDecls(const DeclContext *DC,
2713 llvm::SmallVectorImpl<Decl*> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002714 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002715 "DeclContext has no lexical decls in storage");
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002716
Douglas Gregor2cf26342009-04-09 22:27:44 +00002717 uint64_t Offset = DeclContextOffsets[DC].first;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002718 if (Offset == 0) {
2719 Error("DeclContext has no lexical decls in storage");
2720 return true;
2721 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002722
Douglas Gregor0b748912009-04-14 21:18:50 +00002723 // Keep track of where we are in the stream, then jump back there
2724 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002725 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002726
Douglas Gregor2cf26342009-04-09 22:27:44 +00002727 // Load the record containing all of the declarations lexically in
2728 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002729 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002730 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002731 unsigned Code = DeclsCursor.ReadCode();
2732 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002733 if (RecCode != pch::DECL_CONTEXT_LEXICAL) {
2734 Error("Expected lexical block");
2735 return true;
2736 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002737
2738 // Load all of the declaration IDs
John McCall76bd1f32010-06-01 09:23:16 +00002739 for (RecordData::iterator I = Record.begin(), E = Record.end(); I != E; ++I)
2740 Decls.push_back(GetDecl(*I));
Douglas Gregor25123082009-04-22 22:34:57 +00002741 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002742 return false;
2743}
2744
John McCall76bd1f32010-06-01 09:23:16 +00002745DeclContext::lookup_result
2746PCHReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
2747 DeclarationName Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00002748 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002749 "DeclContext has no visible decls in storage");
2750 uint64_t Offset = DeclContextOffsets[DC].second;
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002751 if (Offset == 0) {
2752 Error("DeclContext has no visible decls in storage");
John McCall76bd1f32010-06-01 09:23:16 +00002753 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2754 DeclContext::lookup_iterator());
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002755 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002756
Douglas Gregor0b748912009-04-14 21:18:50 +00002757 // Keep track of where we are in the stream, then jump back there
2758 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002759 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002760
Douglas Gregor2cf26342009-04-09 22:27:44 +00002761 // Load the record containing all of the declarations visible in
2762 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002763 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002764 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002765 unsigned Code = DeclsCursor.ReadCode();
2766 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002767 if (RecCode != pch::DECL_CONTEXT_VISIBLE) {
2768 Error("Expected visible block");
John McCall76bd1f32010-06-01 09:23:16 +00002769 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2770 DeclContext::lookup_iterator());
Ted Kremenekd5d7b3f2010-03-18 00:56:54 +00002771 }
2772
John McCall76bd1f32010-06-01 09:23:16 +00002773 llvm::SmallVector<VisibleDeclaration, 64> Decls;
2774 if (Record.empty()) {
2775 SetExternalVisibleDecls(DC, Decls);
2776 return DeclContext::lookup_result(DeclContext::lookup_iterator(),
2777 DeclContext::lookup_iterator());
2778 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002779
2780 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002781 while (Idx < Record.size()) {
2782 Decls.push_back(VisibleDeclaration());
2783 Decls.back().Name = ReadDeclarationName(Record, Idx);
2784
Douglas Gregor2cf26342009-04-09 22:27:44 +00002785 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002786 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002787 LoadedDecls.reserve(Size);
2788 for (unsigned I = 0; I < Size; ++I)
2789 LoadedDecls.push_back(Record[Idx++]);
2790 }
2791
Douglas Gregor25123082009-04-22 22:34:57 +00002792 ++NumVisibleDeclContextsRead;
John McCall76bd1f32010-06-01 09:23:16 +00002793
2794 SetExternalVisibleDecls(DC, Decls);
2795 return const_cast<DeclContext*>(DC)->lookup(Name);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002796}
2797
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002798void PCHReader::PassInterestingDeclsToConsumer() {
2799 assert(Consumer);
2800 while (!InterestingDecls.empty()) {
2801 DeclGroupRef DG(InterestingDecls.front());
2802 InterestingDecls.pop_front();
2803 Consumer->HandleTopLevelDecl(DG);
2804 }
2805}
2806
Douglas Gregorfdd01722009-04-14 00:24:19 +00002807void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002808 this->Consumer = Consumer;
2809
Douglas Gregorfdd01722009-04-14 00:24:19 +00002810 if (!Consumer)
2811 return;
2812
2813 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002814 // Force deserialization of this decl, which will cause it to be queued for
2815 // passing to the consumer.
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002816 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002817 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002818
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00002819 PassInterestingDeclsToConsumer();
Douglas Gregorfdd01722009-04-14 00:24:19 +00002820}
2821
Douglas Gregor2cf26342009-04-09 22:27:44 +00002822void PCHReader::PrintStats() {
2823 std::fprintf(stderr, "*** PCH Statistics:\n");
2824
Mike Stump1eb44332009-09-09 15:08:12 +00002825 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002826 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002827 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002828 unsigned NumDeclsLoaded
2829 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2830 (Decl *)0);
2831 unsigned NumIdentifiersLoaded
2832 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2833 IdentifiersLoaded.end(),
2834 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002835 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002836 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2837 SelectorsLoaded.end(),
2838 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002839
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002840 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2841 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002842 if (TotalNumSLocEntries)
2843 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2844 NumSLocEntriesRead, TotalNumSLocEntries,
2845 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002846 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002847 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002848 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2849 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2850 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002851 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002852 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2853 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002854 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002855 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002856 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2857 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002858 if (TotalNumSelectors)
2859 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2860 NumSelectorsLoaded, TotalNumSelectors,
2861 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2862 if (TotalNumStatements)
2863 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2864 NumStatementsRead, TotalNumStatements,
2865 ((float)NumStatementsRead/TotalNumStatements * 100));
2866 if (TotalNumMacros)
2867 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2868 NumMacrosRead, TotalNumMacros,
2869 ((float)NumMacrosRead/TotalNumMacros * 100));
2870 if (TotalLexicalDeclContexts)
2871 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2872 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2873 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2874 * 100));
2875 if (TotalVisibleDeclContexts)
2876 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2877 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2878 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2879 * 100));
2880 if (TotalSelectorsInMethodPool) {
2881 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2882 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2883 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2884 * 100));
2885 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2886 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002887 std::fprintf(stderr, "\n");
2888}
2889
Douglas Gregor668c1a42009-04-21 22:25:48 +00002890void PCHReader::InitializeSema(Sema &S) {
2891 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002892 S.ExternalSource = this;
2893
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002894 // Makes sure any declarations that were deserialized "too early"
2895 // still get added to the identifier's declaration chains.
2896 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2897 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2898 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002899 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002900 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002901
2902 // If there were any tentative definitions, deserialize them and add
Sebastian Redle9d12b62010-01-31 22:27:38 +00002903 // them to Sema's list of tentative definitions.
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002904 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2905 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
Sebastian Redle9d12b62010-01-31 22:27:38 +00002906 SemaObj->TentativeDefinitions.push_back(Var);
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002907 }
Kovarththanan Rajaratnam6b82f642010-03-07 19:10:13 +00002908
Tanya Lattnere6bbc012010-02-12 00:07:30 +00002909 // If there were any unused static functions, deserialize them and add to
2910 // Sema's list of unused static functions.
2911 for (unsigned I = 0, N = UnusedStaticFuncs.size(); I != N; ++I) {
2912 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(UnusedStaticFuncs[I]));
2913 SemaObj->UnusedStaticFuncs.push_back(FD);
2914 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002915
2916 // If there were any locally-scoped external declarations,
2917 // deserialize them and add them to Sema's table of locally-scoped
2918 // external declarations.
2919 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2920 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2921 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2922 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002923
2924 // If there were any ext_vector type declarations, deserialize them
2925 // and add them to Sema's vector of such declarations.
2926 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2927 SemaObj->ExtVectorDecls.push_back(
2928 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Argyrios Kyrtzidisd455add2010-07-06 15:37:04 +00002929
2930 // FIXME: Do VTable uses and dynamic classes deserialize too much ?
2931 // Can we cut them down before writing them ?
2932
2933 // If there were any VTable uses, deserialize the information and add it
2934 // to Sema's vector and map of VTable uses.
2935 unsigned Idx = 0;
2936 for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
2937 CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
2938 SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
2939 bool DefinitionRequired = VTableUses[Idx++];
2940 SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
2941 SemaObj->VTablesUsed[Class] = DefinitionRequired;
2942 }
2943
2944 // If there were any dynamic classes declarations, deserialize them
2945 // and add them to Sema's vector of such declarations.
2946 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
2947 SemaObj->DynamicClasses.push_back(
2948 cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002949}
2950
2951IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2952 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002953 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002954 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2955 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2956 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2957 if (Pos == IdTable->end())
2958 return 0;
2959
2960 // Dereferencing the iterator has the effect of building the
2961 // IdentifierInfo node and populating it with the various
2962 // declarations it needs.
2963 return *Pos;
2964}
2965
Mike Stump1eb44332009-09-09 15:08:12 +00002966std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002967PCHReader::ReadMethodPool(Selector Sel) {
2968 if (!MethodPoolLookupTable)
2969 return std::pair<ObjCMethodList, ObjCMethodList>();
2970
2971 // Try to find this selector within our on-disk hash table.
2972 PCHMethodPoolLookupTable *PoolTable
2973 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2974 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002975 if (Pos == PoolTable->end()) {
2976 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002977 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002978 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002979
Douglas Gregor83941df2009-04-25 17:48:32 +00002980 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002981 return *Pos;
2982}
2983
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002984void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002985 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002986 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002987 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002988}
2989
Douglas Gregord89275b2009-07-06 18:54:52 +00002990/// \brief Set the globally-visible declarations associated with the given
2991/// identifier.
2992///
2993/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002994/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002995/// them.
2996///
2997/// \param II an IdentifierInfo that refers to one or more globally-visible
2998/// declarations.
2999///
3000/// \param DeclIDs the set of declaration IDs with the name @p II that are
3001/// visible at global scope.
3002///
3003/// \param Nonrecursive should be true to indicate that the caller knows that
3004/// this call is non-recursive, and therefore the globally-visible declarations
3005/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00003006void
3007PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00003008 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3009 bool Nonrecursive) {
3010 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
3011 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3012 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3013 PII.II = II;
3014 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
3015 PII.DeclIDs.push_back(DeclIDs[I]);
3016 return;
3017 }
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Douglas Gregord89275b2009-07-06 18:54:52 +00003019 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3020 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3021 if (SemaObj) {
3022 // Introduce this declaration into the translation-unit scope
3023 // and add it to the declaration chain for this identifier, so
3024 // that (unqualified) name lookup will find it.
3025 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
3026 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3027 } else {
3028 // Queue this declaration so that it will be added to the
3029 // translation unit scope and identifier's declaration chain
3030 // once a Sema object is known.
3031 PreloadedDecls.push_back(D);
3032 }
3033 }
3034}
3035
Chris Lattner7356a312009-04-11 21:15:38 +00003036IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00003037 if (ID == 0)
3038 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003039
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003040 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003041 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00003042 return 0;
3043 }
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003045 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003046 if (!IdentifiersLoaded[ID - 1]) {
3047 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00003048 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00003049
Douglas Gregor02fc7512009-04-28 20:01:51 +00003050 // All of the strings in the PCH file are preceded by a 16-bit
3051 // length. Extract that 16-bit length to avoid having to execute
3052 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00003053 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3054 // unsigned integers. This is important to avoid integer overflow when
3055 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00003056 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00003057 unsigned StrLen = (((unsigned) StrLenPtr[0])
3058 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003059 IdentifiersLoaded[ID - 1]
Kovarththanan Rajaratnam811f4262010-03-12 10:32:27 +00003060 = &PP->getIdentifierTable().get(Str, StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00003061 }
Mike Stump1eb44332009-09-09 15:08:12 +00003062
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00003063 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00003064}
3065
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00003066void PCHReader::ReadSLocEntry(unsigned ID) {
3067 ReadSLocEntryRecord(ID);
3068}
3069
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003070Selector PCHReader::DecodeSelector(unsigned ID) {
3071 if (ID == 0)
3072 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Douglas Gregora02b1472009-04-28 21:53:25 +00003074 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003075 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00003076
3077 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00003078 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003079 return Selector();
3080 }
Douglas Gregor83941df2009-04-25 17:48:32 +00003081
3082 unsigned Index = ID - 1;
3083 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
3084 // Load this selector from the selector table.
3085 // FIXME: endianness portability issues with SelectorOffsets table
3086 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00003087 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00003088 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
3089 }
3090
3091 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00003092}
3093
John McCall76bd1f32010-06-01 09:23:16 +00003094Selector PCHReader::GetExternalSelector(uint32_t ID) {
Douglas Gregor719770d2010-04-06 17:30:22 +00003095 return DecodeSelector(ID);
3096}
3097
John McCall76bd1f32010-06-01 09:23:16 +00003098uint32_t PCHReader::GetNumExternalSelectors() {
Douglas Gregor719770d2010-04-06 17:30:22 +00003099 return TotalNumSelectors + 1;
3100}
3101
Mike Stump1eb44332009-09-09 15:08:12 +00003102DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00003103PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3104 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3105 switch (Kind) {
3106 case DeclarationName::Identifier:
3107 return DeclarationName(GetIdentifierInfo(Record, Idx));
3108
3109 case DeclarationName::ObjCZeroArgSelector:
3110 case DeclarationName::ObjCOneArgSelector:
3111 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00003112 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003113
3114 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003115 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003116 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003117
3118 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003119 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003120 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003121
3122 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003123 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00003124 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00003125
3126 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00003127 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00003128 (OverloadedOperatorKind)Record[Idx++]);
3129
Sean Hunt3e518bd2009-11-29 07:34:05 +00003130 case DeclarationName::CXXLiteralOperatorName:
3131 return Context->DeclarationNames.getCXXLiteralOperatorName(
3132 GetIdentifierInfo(Record, Idx));
3133
Douglas Gregor2cf26342009-04-09 22:27:44 +00003134 case DeclarationName::CXXUsingDirective:
3135 return DeclarationName::getUsingDirectiveName();
3136 }
3137
3138 // Required to silence GCC warning
3139 return DeclarationName();
3140}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003141
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003142TemplateName
3143PCHReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3144 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3145 switch (Kind) {
3146 case TemplateName::Template:
3147 return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3148
3149 case TemplateName::OverloadedTemplate: {
3150 unsigned size = Record[Idx++];
3151 UnresolvedSet<8> Decls;
3152 while (size--)
3153 Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3154
3155 return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3156 }
3157
3158 case TemplateName::QualifiedTemplate: {
3159 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3160 bool hasTemplKeyword = Record[Idx++];
3161 TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3162 return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3163 }
3164
3165 case TemplateName::DependentTemplate: {
3166 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3167 if (Record[Idx++]) // isIdentifier
3168 return Context->getDependentTemplateName(NNS,
3169 GetIdentifierInfo(Record, Idx));
3170 return Context->getDependentTemplateName(NNS,
Argyrios Kyrtzidis17cfded2010-06-28 09:31:42 +00003171 (OverloadedOperatorKind)Record[Idx++]);
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003172 }
3173 }
3174
3175 assert(0 && "Unhandled template name kind!");
3176 return TemplateName();
3177}
3178
3179TemplateArgument
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003180PCHReader::ReadTemplateArgument(const RecordData &Record, unsigned &Idx) {
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003181 switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3182 case TemplateArgument::Null:
3183 return TemplateArgument();
3184 case TemplateArgument::Type:
3185 return TemplateArgument(GetType(Record[Idx++]));
3186 case TemplateArgument::Declaration:
3187 return TemplateArgument(GetDecl(Record[Idx++]));
Argyrios Kyrtzidisdc767e32010-06-28 09:31:34 +00003188 case TemplateArgument::Integral: {
3189 llvm::APSInt Value = ReadAPSInt(Record, Idx);
3190 QualType T = GetType(Record[Idx++]);
3191 return TemplateArgument(Value, T);
3192 }
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003193 case TemplateArgument::Template:
3194 return TemplateArgument(ReadTemplateName(Record, Idx));
3195 case TemplateArgument::Expression:
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003196 return TemplateArgument(ReadExpr());
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003197 case TemplateArgument::Pack: {
3198 unsigned NumArgs = Record[Idx++];
3199 llvm::SmallVector<TemplateArgument, 8> Args;
3200 Args.reserve(NumArgs);
3201 while (NumArgs--)
Argyrios Kyrtzidis919e6932010-06-28 22:28:35 +00003202 Args.push_back(ReadTemplateArgument(Record, Idx));
Argyrios Kyrtzidis8731ca72010-06-19 19:29:09 +00003203 TemplateArgument TemplArg;
3204 TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3205 return TemplArg;
3206 }
3207 }
3208
3209 assert(0 && "Unhandled template argument kind!");
3210 return TemplateArgument();
3211}
3212
Argyrios Kyrtzidisdd41c142010-06-23 13:48:30 +00003213TemplateParameterList *
3214PCHReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3215 SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3216 SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3217 SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3218
3219 unsigned NumParams = Record[Idx++];
3220 llvm::SmallVector<NamedDecl *, 16> Params;
3221 Params.reserve(NumParams);
3222 while (NumParams--)
3223 Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3224
3225 TemplateParameterList* TemplateParams =
3226 TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3227 Params.data(), Params.size(), RAngleLoc);
3228 return TemplateParams;
3229}
3230
3231void
3232PCHReader::
3233ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
3234 const RecordData &Record, unsigned &Idx) {
3235 unsigned NumTemplateArgs = Record[Idx++];
3236 TemplArgs.reserve(NumTemplateArgs);
3237 while (NumTemplateArgs--)
3238 TemplArgs.push_back(ReadTemplateArgument(Record, Idx));
3239}
3240
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00003241/// \brief Read a UnresolvedSet structure.
3242void PCHReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3243 const RecordData &Record, unsigned &Idx) {
3244 unsigned NumDecls = Record[Idx++];
3245 while (NumDecls--) {
3246 NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3247 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3248 Set.addDecl(D, AS);
3249 }
3250}
3251
Argyrios Kyrtzidis0745d0a2010-07-02 23:30:27 +00003252CXXBaseSpecifier
3253PCHReader::ReadCXXBaseSpecifier(const RecordData &Record, unsigned &Idx) {
3254 bool isVirtual = static_cast<bool>(Record[Idx++]);
3255 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3256 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3257 QualType T = GetType(Record[Idx++]);
3258 SourceRange Range = ReadSourceRange(Record, Idx);
3259 return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, T);
3260}
3261
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003262NestedNameSpecifier *
3263PCHReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3264 unsigned N = Record[Idx++];
3265 NestedNameSpecifier *NNS = 0, *Prev = 0;
3266 for (unsigned I = 0; I != N; ++I) {
3267 NestedNameSpecifier::SpecifierKind Kind
3268 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3269 switch (Kind) {
3270 case NestedNameSpecifier::Identifier: {
3271 IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3272 NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3273 break;
3274 }
3275
3276 case NestedNameSpecifier::Namespace: {
3277 NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3278 NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3279 break;
3280 }
3281
3282 case NestedNameSpecifier::TypeSpec:
3283 case NestedNameSpecifier::TypeSpecWithTemplate: {
3284 Type *T = GetType(Record[Idx++]).getTypePtr();
3285 bool Template = Record[Idx++];
3286 NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3287 break;
3288 }
3289
3290 case NestedNameSpecifier::Global: {
3291 NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3292 // No associated value, and there can't be a prefix.
3293 break;
3294 }
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003295 }
Argyrios Kyrtzidisd2bb2c02010-07-07 15:46:30 +00003296 Prev = NNS;
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003297 }
3298 return NNS;
3299}
3300
3301SourceRange
3302PCHReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
Daniel Dunbar8ee59392010-06-02 15:47:10 +00003303 SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3304 SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3305 return SourceRange(beg, end);
Chris Lattner6ad9ac02010-05-07 21:43:38 +00003306}
3307
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00003308/// \brief Read an integral value
3309llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3310 unsigned BitWidth = Record[Idx++];
3311 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3312 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3313 Idx += NumWords;
3314 return Result;
3315}
3316
3317/// \brief Read a signed integral value
3318llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3319 bool isUnsigned = Record[Idx++];
3320 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3321}
3322
Douglas Gregor17fc2232009-04-14 21:55:33 +00003323/// \brief Read a floating-point value
3324llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00003325 return llvm::APFloat(ReadAPInt(Record, Idx));
3326}
3327
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003328// \brief Read a string
3329std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
3330 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00003331 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00003332 Idx += Len;
3333 return Result;
3334}
3335
Chris Lattnerd2598362010-05-10 00:25:06 +00003336CXXTemporary *PCHReader::ReadCXXTemporary(const RecordData &Record,
3337 unsigned &Idx) {
3338 CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3339 return CXXTemporary::Create(*Context, Decl);
3340}
3341
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003342DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00003343 return Diag(SourceLocation(), DiagID);
3344}
3345
3346DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003347 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00003348}
Douglas Gregor025452f2009-04-17 00:04:06 +00003349
Douglas Gregor668c1a42009-04-21 22:25:48 +00003350/// \brief Retrieve the identifier table associated with the
3351/// preprocessor.
3352IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00003353 assert(PP && "Forgot to set Preprocessor ?");
3354 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00003355}
3356
Douglas Gregor025452f2009-04-17 00:04:06 +00003357/// \brief Record that the given ID maps to the given switch-case
3358/// statement.
3359void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3360 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3361 SwitchCaseStmts[ID] = SC;
3362}
3363
3364/// \brief Retrieve the switch-case statement with the given ID.
3365SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
3366 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3367 return SwitchCaseStmts[ID];
3368}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003369
3370/// \brief Record that the given label statement has been
3371/// deserialized and has the given ID.
3372void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00003373 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003374 "Deserialized label twice");
3375 LabelStmts[ID] = S;
3376
3377 // If we've already seen any goto statements that point to this
3378 // label, resolve them now.
3379 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
3380 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
3381 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
3382 Goto->second->setLabel(S);
3383 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003384
3385 // If we've already seen any address-label statements that point to
3386 // this label, resolve them now.
3387 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00003388 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003389 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00003390 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003391 AddrLabel != AddrLabels.second; ++AddrLabel)
3392 AddrLabel->second->setLabel(S);
3393 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00003394}
3395
3396/// \brief Set the label of the given statement to the label
3397/// identified by ID.
3398///
3399/// Depending on the order in which the label and other statements
3400/// referencing that label occur, this operation may complete
3401/// immediately (updating the statement) or it may queue the
3402/// statement to be back-patched later.
3403void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
3404 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3405 if (Label != LabelStmts.end()) {
3406 // We've already seen this label, so set the label of the goto and
3407 // we're done.
3408 S->setLabel(Label->second);
3409 } else {
3410 // We haven't seen this label yet, so add this goto to the set of
3411 // unresolved goto statements.
3412 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
3413 }
3414}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00003415
3416/// \brief Set the label of the given expression to the label
3417/// identified by ID.
3418///
3419/// Depending on the order in which the label and other statements
3420/// referencing that label occur, this operation may complete
3421/// immediately (updating the statement) or it may queue the
3422/// statement to be back-patched later.
3423void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
3424 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
3425 if (Label != LabelStmts.end()) {
3426 // We've already seen this label, so set the label of the
3427 // label-address expression and we're done.
3428 S->setLabel(Label->second);
3429 } else {
3430 // We haven't seen this label yet, so add this label-address
3431 // expression to the set of unresolved label-address expressions.
3432 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
3433 }
3434}
Douglas Gregord89275b2009-07-06 18:54:52 +00003435
3436
Mike Stump1eb44332009-09-09 15:08:12 +00003437PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00003438 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
3439 Reader.CurrentlyLoadingTypeOrDecl = this;
3440}
3441
3442PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
3443 if (!Parent) {
3444 // If any identifiers with corresponding top-level declarations have
3445 // been loaded, load those declarations now.
3446 while (!Reader.PendingIdentifierInfos.empty()) {
3447 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
3448 Reader.PendingIdentifierInfos.front().DeclIDs,
3449 true);
3450 Reader.PendingIdentifierInfos.pop_front();
3451 }
Argyrios Kyrtzidisbb80a8e2010-07-07 15:46:26 +00003452
3453 // We are not in recursive loading, so it's safe to pass the "interesting"
3454 // decls to the consumer.
3455 if (Reader.Consumer)
3456 Reader.PassInterestingDeclsToConsumer();
Douglas Gregord89275b2009-07-06 18:54:52 +00003457 }
3458
Mike Stump1eb44332009-09-09 15:08:12 +00003459 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00003460}