blob: a812604e395e7344c532c70a275278b488798442 [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"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
John McCalla1ee0c52009-10-16 21:56:05 +000021#include "clang/AST/TypeLocVisitor.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000022#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000023#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000025#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000026#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000027#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000028#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000030#include "clang/Basic/Version.h"
Daniel Dunbar2596e422009-10-17 23:52:28 +000031#include "llvm/ADT/StringExtras.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamReader.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/MemoryBuffer.h"
John McCall833ca992009-10-29 08:12:44 +000035#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000036#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000037#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000038#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000039#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000043// PCH reader validator implementation
44//===----------------------------------------------------------------------===//
45
46PCHReaderListener::~PCHReaderListener() {}
47
48bool
49PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
50 const LangOptions &PPLangOpts = PP.getLangOptions();
51#define PARSE_LANGOPT_BENIGN(Option)
52#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
53 if (PPLangOpts.Option != LangOpts.Option) { \
54 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
55 return true; \
56 }
57
58 PARSE_LANGOPT_BENIGN(Trigraphs);
59 PARSE_LANGOPT_BENIGN(BCPLComment);
60 PARSE_LANGOPT_BENIGN(DollarIdents);
61 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
62 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
63 PARSE_LANGOPT_BENIGN(ImplicitInt);
64 PARSE_LANGOPT_BENIGN(Digraphs);
65 PARSE_LANGOPT_BENIGN(HexFloats);
66 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
67 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
68 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
69 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
70 PARSE_LANGOPT_BENIGN(CXXOperatorName);
71 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
72 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
73 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
74 PARSE_LANGOPT_BENIGN(PascalStrings);
75 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000076 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000077 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000078 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000079 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
80 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
81 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
82 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000083 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000084 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000085 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000086 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
87 PARSE_LANGOPT_BENIGN(EmitAllDecls);
88 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
89 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000090 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000091 diag::warn_pch_heinous_extensions);
92 // FIXME: Most of the options below are benign if the macro wasn't
93 // used. Unfortunately, this means that a PCH compiled without
94 // optimization can't be used with optimization turned on, even
95 // though the only thing that changes is whether __OPTIMIZE__ was
96 // defined... but if __OPTIMIZE__ never showed up in the header, it
97 // doesn't matter. We could consider making this some special kind
98 // of check.
99 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
100 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
101 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
102 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
103 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
104 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
105 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
106 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
John Thompsona6fda122009-11-05 20:14:16 +0000107 PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000108 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000109 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000110 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
111 return true;
112 }
113 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000114 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
115 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000116 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000117 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000118 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000119#undef PARSE_LANGOPT_IRRELEVANT
120#undef PARSE_LANGOPT_BENIGN
121
122 return false;
123}
124
125bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000126 if (Triple != PP.getTargetInfo().getTriple().getTriple()) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000127 Reader.Diag(diag::warn_pch_target_triple)
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000128 << Triple << PP.getTargetInfo().getTriple().getTriple();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000129 return true;
130 }
131 return false;
132}
133
134/// \brief Split the given string into a vector of lines, eliminating
135/// any empty lines in the process.
136///
137/// \param Str the string to split.
138/// \param Len the length of Str.
139/// \param KeepEmptyLines true if empty lines should be included
140/// \returns a vector of lines, with the line endings removed
141static std::vector<std::string> splitLines(const char *Str, unsigned Len,
142 bool KeepEmptyLines = false) {
143 std::vector<std::string> Lines;
144 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
145 unsigned LineEnd = LineStart;
146 while (LineEnd < Len && Str[LineEnd] != '\n')
147 ++LineEnd;
148 if (LineStart != LineEnd || KeepEmptyLines)
149 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
150 LineStart = LineEnd;
151 }
152 return Lines;
153}
154
155/// \brief Determine whether the string Haystack starts with the
156/// substring Needle.
157static bool startsWith(const std::string &Haystack, const char *Needle) {
158 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
159 if (I == N)
160 return false;
161 if (Haystack[I] != Needle[I])
162 return false;
163 }
164
165 return true;
166}
167
168/// \brief Determine whether the string Haystack starts with the
169/// substring Needle.
170static inline bool startsWith(const std::string &Haystack,
171 const std::string &Needle) {
172 return startsWith(Haystack, Needle.c_str());
173}
174
Mike Stump1eb44332009-09-09 15:08:12 +0000175bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000176 unsigned PCHPredefLen,
177 FileID PCHBufferID,
178 std::string &SuggestedPredefines) {
179 const char *Predef = PP.getPredefines().c_str();
180 unsigned PredefLen = PP.getPredefines().size();
181
182 // If the two predefines buffers compare equal, we're done!
Mike Stump1eb44332009-09-09 15:08:12 +0000183 if (PredefLen == PCHPredefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000184 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
185 return false;
186
187 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000189 // The predefines buffers are different. Determine what the
190 // differences are, and whether they require us to reject the PCH
191 // file.
192 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
193 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
194
Mike Stump1eb44332009-09-09 15:08:12 +0000195 // Sort both sets of predefined buffer lines, since
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000196 std::sort(CmdLineLines.begin(), CmdLineLines.end());
197 std::sort(PCHLines.begin(), PCHLines.end());
198
199 // Determine which predefines that where used to build the PCH file
200 // are missing from the command line.
201 std::vector<std::string> MissingPredefines;
202 std::set_difference(PCHLines.begin(), PCHLines.end(),
203 CmdLineLines.begin(), CmdLineLines.end(),
204 std::back_inserter(MissingPredefines));
205
206 bool MissingDefines = false;
207 bool ConflictingDefines = false;
208 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
209 const std::string &Missing = MissingPredefines[I];
210 if (!startsWith(Missing, "#define ") != 0) {
211 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
212 return true;
213 }
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000215 // This is a macro definition. Determine the name of the macro
216 // we're defining.
217 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000218 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000219 = Missing.find_first_of("( \n\r", StartOfMacroName);
220 assert(EndOfMacroName != std::string::npos &&
221 "Couldn't find the end of the macro name");
222 std::string MacroName = Missing.substr(StartOfMacroName,
223 EndOfMacroName - StartOfMacroName);
224
225 // Determine whether this macro was given a different definition
226 // on the command line.
227 std::string MacroDefStart = "#define " + MacroName;
228 std::string::size_type MacroDefLen = MacroDefStart.size();
229 std::vector<std::string>::iterator ConflictPos
230 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
231 MacroDefStart);
232 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
233 if (!startsWith(*ConflictPos, MacroDefStart)) {
234 // Different macro; we're done.
235 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000236 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000237 }
Mike Stump1eb44332009-09-09 15:08:12 +0000238
239 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000240 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000241 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000242 (*ConflictPos)[MacroDefLen] != '(')
243 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000245 // We found a conflicting macro definition.
246 break;
247 }
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000249 if (ConflictPos != CmdLineLines.end()) {
250 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
251 << MacroName;
252
253 // Show the definition of this macro within the PCH file.
254 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
255 unsigned Offset = MissingDef - PCHPredef;
256 SourceLocation PCHMissingLoc
257 = SourceMgr.getLocForStartOfFile(PCHBufferID)
258 .getFileLocWithOffset(Offset);
259 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
260 << MacroName;
261
262 ConflictingDefines = true;
263 continue;
264 }
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000266 // If the macro doesn't conflict, then we'll just pick up the
267 // macro definition from the PCH file. Warn the user that they
268 // made a mistake.
269 if (ConflictingDefines)
270 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000272 if (!MissingDefines) {
273 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
274 MissingDefines = true;
275 }
276
277 // Show the definition of this macro within the PCH file.
278 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
279 unsigned Offset = MissingDef - PCHPredef;
280 SourceLocation PCHMissingLoc
281 = SourceMgr.getLocForStartOfFile(PCHBufferID)
282 .getFileLocWithOffset(Offset);
283 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
284 }
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000286 if (ConflictingDefines)
287 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000289 // Determine what predefines were introduced based on command-line
290 // parameters that were not present when building the PCH
291 // file. Extra #defines are okay, so long as the identifiers being
292 // defined were not used within the precompiled header.
293 std::vector<std::string> ExtraPredefines;
294 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
295 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000296 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000297 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
298 const std::string &Extra = ExtraPredefines[I];
299 if (!startsWith(Extra, "#define ") != 0) {
300 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
301 return true;
302 }
303
304 // This is an extra macro definition. Determine the name of the
305 // macro we're defining.
306 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000307 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000308 = Extra.find_first_of("( \n\r", StartOfMacroName);
309 assert(EndOfMacroName != std::string::npos &&
310 "Couldn't find the end of the macro name");
311 std::string MacroName = Extra.substr(StartOfMacroName,
312 EndOfMacroName - StartOfMacroName);
313
314 // Check whether this name was used somewhere in the PCH file. If
315 // so, defining it as a macro could change behavior, so we reject
316 // the PCH file.
317 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
318 MacroName.c_str() + MacroName.size())) {
319 Reader.Diag(diag::warn_macro_name_used_in_pch)
320 << II;
321 return true;
322 }
323
324 // Add this definition to the suggested predefines buffer.
325 SuggestedPredefines += Extra;
326 SuggestedPredefines += '\n';
327 }
328
329 // If we get here, it's because the predefines buffer had compatible
330 // contents. Accept the PCH file.
331 return false;
332}
333
334void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
335 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
336}
337
338void PCHValidator::ReadCounter(unsigned Value) {
339 PP.setCounterValue(Value);
340}
341
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000342//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000343// PCH reader implementation
344//===----------------------------------------------------------------------===//
345
Mike Stump1eb44332009-09-09 15:08:12 +0000346PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
347 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000348 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
349 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregor52e71082009-10-16 18:18:30 +0000350 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000351 IdentifierTableData(0), IdentifierLookupTable(0),
352 IdentifierOffsets(0),
353 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
354 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000355 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000356 NumStatHits(0), NumStatMisses(0),
357 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000358 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000359 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000360 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000361 RelocatablePCH = false;
362}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000363
364PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000365 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000366 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregor52e71082009-10-16 18:18:30 +0000367 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000368 IdentifierTableData(0), IdentifierLookupTable(0),
369 IdentifierOffsets(0),
370 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
371 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000372 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000373 NumStatHits(0), NumStatMisses(0),
374 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000375 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000376 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000377 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000378 RelocatablePCH = false;
379}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000380
381PCHReader::~PCHReader() {}
382
Chris Lattnerda930612009-04-27 05:58:23 +0000383Expr *PCHReader::ReadDeclExpr() {
384 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
385}
386
387Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor61d60ee2009-10-17 00:13:19 +0000388 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000389}
390
391
Douglas Gregor668c1a42009-04-21 22:25:48 +0000392namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000393class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
394 PCHReader &Reader;
395
396public:
397 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
398
399 typedef Selector external_key_type;
400 typedef external_key_type internal_key_type;
401
402 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000404 static bool EqualKey(const internal_key_type& a,
405 const internal_key_type& b) {
406 return a == b;
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000409 static unsigned ComputeHash(Selector Sel) {
410 unsigned N = Sel.getNumArgs();
411 if (N == 0)
412 ++N;
413 unsigned R = 5381;
414 for (unsigned I = 0; I != N; ++I)
415 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbar2596e422009-10-17 23:52:28 +0000416 R = llvm::HashString(II->getName(), R);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000417 return R;
418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000420 // This hopefully will just get inlined and removed by the optimizer.
421 static const internal_key_type&
422 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000424 static std::pair<unsigned, unsigned>
425 ReadKeyDataLength(const unsigned char*& d) {
426 using namespace clang::io;
427 unsigned KeyLen = ReadUnalignedLE16(d);
428 unsigned DataLen = ReadUnalignedLE16(d);
429 return std::make_pair(KeyLen, DataLen);
430 }
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Douglas Gregor83941df2009-04-25 17:48:32 +0000432 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000433 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000434 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000435 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000436 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000437 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
438 if (N == 0)
439 return SelTable.getNullarySelector(FirstII);
440 else if (N == 1)
441 return SelTable.getUnarySelector(FirstII);
442
443 llvm::SmallVector<IdentifierInfo *, 16> Args;
444 Args.push_back(FirstII);
445 for (unsigned I = 1; I != N; ++I)
446 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
447
Douglas Gregor75fdb232009-05-22 22:45:36 +0000448 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000449 }
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000451 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
452 using namespace clang::io;
453 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
454 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
455
456 data_type Result;
457
458 // Load instance methods
459 ObjCMethodList *Prev = 0;
460 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000461 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000462 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
463 if (!Result.first.Method) {
464 // This is the first method, which is the easy case.
465 Result.first.Method = Method;
466 Prev = &Result.first;
467 continue;
468 }
469
470 Prev->Next = new ObjCMethodList(Method, 0);
471 Prev = Prev->Next;
472 }
473
474 // Load factory methods
475 Prev = 0;
476 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000477 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000478 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
479 if (!Result.second.Method) {
480 // This is the first method, which is the easy case.
481 Result.second.Method = Method;
482 Prev = &Result.second;
483 continue;
484 }
485
486 Prev->Next = new ObjCMethodList(Method, 0);
487 Prev = Prev->Next;
488 }
489
490 return Result;
491 }
492};
Mike Stump1eb44332009-09-09 15:08:12 +0000493
494} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000495
496/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000497typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000498 PCHMethodPoolLookupTable;
499
500namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000501class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
502 PCHReader &Reader;
503
504 // If we know the IdentifierInfo in advance, it is here and we will
505 // not build a new one. Used when deserializing information about an
506 // identifier that was constructed before the PCH file was read.
507 IdentifierInfo *KnownII;
508
509public:
510 typedef IdentifierInfo * data_type;
511
512 typedef const std::pair<const char*, unsigned> external_key_type;
513
514 typedef external_key_type internal_key_type;
515
Mike Stump1eb44332009-09-09 15:08:12 +0000516 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000517 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Douglas Gregor668c1a42009-04-21 22:25:48 +0000519 static bool EqualKey(const internal_key_type& a,
520 const internal_key_type& b) {
521 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
522 : false;
523 }
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Douglas Gregor668c1a42009-04-21 22:25:48 +0000525 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000526 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregor668c1a42009-04-21 22:25:48 +0000529 // This hopefully will just get inlined and removed by the optimizer.
530 static const internal_key_type&
531 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Douglas Gregor668c1a42009-04-21 22:25:48 +0000533 static std::pair<unsigned, unsigned>
534 ReadKeyDataLength(const unsigned char*& d) {
535 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000536 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000537 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000538 return std::make_pair(KeyLen, DataLen);
539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregor668c1a42009-04-21 22:25:48 +0000541 static std::pair<const char*, unsigned>
542 ReadKey(const unsigned char* d, unsigned n) {
543 assert(n >= 2 && d[n-1] == '\0');
544 return std::make_pair((const char*) d, n-1);
545 }
Mike Stump1eb44332009-09-09 15:08:12 +0000546
547 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000548 const unsigned char* d,
549 unsigned DataLen) {
550 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000551 pch::IdentID ID = ReadUnalignedLE32(d);
552 bool IsInteresting = ID & 0x01;
553
554 // Wipe out the "is interesting" bit.
555 ID = ID >> 1;
556
557 if (!IsInteresting) {
558 // For unintersting identifiers, just build the IdentifierInfo
559 // and associate it with the persistent ID.
560 IdentifierInfo *II = KnownII;
561 if (!II)
562 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
563 k.first, k.first + k.second);
564 Reader.SetIdentifierInfo(ID, II);
565 return II;
566 }
567
Douglas Gregor5998da52009-04-28 21:32:13 +0000568 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000569 bool CPlusPlusOperatorKeyword = Bits & 0x01;
570 Bits >>= 1;
571 bool Poisoned = Bits & 0x01;
572 Bits >>= 1;
573 bool ExtensionToken = Bits & 0x01;
574 Bits >>= 1;
575 bool hasMacroDefinition = Bits & 0x01;
576 Bits >>= 1;
577 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
578 Bits >>= 10;
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Douglas Gregor2deaea32009-04-22 18:49:13 +0000580 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000581 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000582
583 // Build the IdentifierInfo itself and link the identifier ID with
584 // the new IdentifierInfo.
585 IdentifierInfo *II = KnownII;
586 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000587 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
588 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000589 Reader.SetIdentifierInfo(ID, II);
590
Douglas Gregor2deaea32009-04-22 18:49:13 +0000591 // Set or check the various bits in the IdentifierInfo structure.
592 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000593 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000594 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-04-22 18:49:13 +0000595 "Incorrect extension token flag");
596 (void)ExtensionToken;
597 II->setIsPoisoned(Poisoned);
598 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
599 "Incorrect C++ operator keyword flag");
600 (void)CPlusPlusOperatorKeyword;
601
Douglas Gregor37e26842009-04-21 23:56:24 +0000602 // If this identifier is a macro, deserialize the macro
603 // definition.
604 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000605 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000606 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000607 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000608 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000609
610 // Read all of the declarations visible at global scope with this
611 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000612 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000613 if (DataLen > 0) {
614 llvm::SmallVector<uint32_t, 4> DeclIDs;
615 for (; DataLen > 0; DataLen -= 4)
616 DeclIDs.push_back(ReadUnalignedLE32(d));
617 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000618 }
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Douglas Gregor668c1a42009-04-21 22:25:48 +0000620 return II;
621 }
622};
Mike Stump1eb44332009-09-09 15:08:12 +0000623
624} // end anonymous namespace
Douglas Gregor668c1a42009-04-21 22:25:48 +0000625
626/// \brief The on-disk hash table used to contain information about
627/// all of the identifiers in the program.
Mike Stump1eb44332009-09-09 15:08:12 +0000628typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000629 PCHIdentifierLookupTable;
630
Douglas Gregora02b1472009-04-28 21:53:25 +0000631bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000632 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
633 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000634 return true;
635}
636
Douglas Gregore1d918e2009-04-10 23:10:45 +0000637/// \brief Check the contents of the predefines buffer against the
638/// contents of the predefines buffer used to build the PCH file.
639///
640/// The contents of the two predefines buffers should be the same. If
641/// not, then some command-line option changed the preprocessor state
642/// and we must reject the PCH file.
643///
644/// \param PCHPredef The start of the predefines buffer in the PCH
645/// file.
646///
647/// \param PCHPredefLen The length of the predefines buffer in the PCH
648/// file.
649///
650/// \param PCHBufferID The FileID for the PCH predefines buffer.
651///
652/// \returns true if there was a mismatch (in which case the PCH file
653/// should be ignored), or false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +0000654bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000655 unsigned PCHPredefLen,
656 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000657 if (Listener)
658 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
659 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000660 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000661}
662
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000663//===----------------------------------------------------------------------===//
664// Source Manager Deserialization
665//===----------------------------------------------------------------------===//
666
Douglas Gregorbd945002009-04-13 16:31:14 +0000667/// \brief Read the line table in the source manager block.
668/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000669bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000670 unsigned Idx = 0;
671 LineTableInfo &LineTable = SourceMgr.getLineTable();
672
673 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000674 std::map<int, int> FileIDs;
675 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000676 // Extract the file name
677 unsigned FilenameLen = Record[Idx++];
678 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
679 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000680 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000681 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000682 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000683 }
684
685 // Parse the line entries
686 std::vector<LineEntry> Entries;
687 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000688 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000689
690 // Extract the line entries
691 unsigned NumEntries = Record[Idx++];
692 Entries.clear();
693 Entries.reserve(NumEntries);
694 for (unsigned I = 0; I != NumEntries; ++I) {
695 unsigned FileOffset = Record[Idx++];
696 unsigned LineNo = Record[Idx++];
697 int FilenameID = Record[Idx++];
Mike Stump1eb44332009-09-09 15:08:12 +0000698 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-04-13 16:31:14 +0000699 = (SrcMgr::CharacteristicKind)Record[Idx++];
700 unsigned IncludeOffset = Record[Idx++];
701 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
702 FileKind, IncludeOffset));
703 }
704 LineTable.AddEntry(FID, Entries);
705 }
706
707 return false;
708}
709
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000710namespace {
711
712class VISIBILITY_HIDDEN PCHStatData {
713public:
714 const bool hasStat;
715 const ino_t ino;
716 const dev_t dev;
717 const mode_t mode;
718 const time_t mtime;
719 const off_t size;
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000721 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000722 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
723
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000724 PCHStatData()
725 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
726};
727
728class VISIBILITY_HIDDEN PCHStatLookupTrait {
729 public:
730 typedef const char *external_key_type;
731 typedef const char *internal_key_type;
732
733 typedef PCHStatData data_type;
734
735 static unsigned ComputeHash(const char *path) {
Daniel Dunbar2596e422009-10-17 23:52:28 +0000736 return llvm::HashString(path);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000737 }
738
739 static internal_key_type GetInternalKey(const char *path) { return path; }
740
741 static bool EqualKey(internal_key_type a, internal_key_type b) {
742 return strcmp(a, b) == 0;
743 }
744
745 static std::pair<unsigned, unsigned>
746 ReadKeyDataLength(const unsigned char*& d) {
747 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
748 unsigned DataLen = (unsigned) *d++;
749 return std::make_pair(KeyLen + 1, DataLen);
750 }
751
752 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
753 return (const char *)d;
754 }
755
756 static data_type ReadData(const internal_key_type, const unsigned char *d,
757 unsigned /*DataLen*/) {
758 using namespace clang::io;
759
760 if (*d++ == 1)
761 return data_type();
762
763 ino_t ino = (ino_t) ReadUnalignedLE32(d);
764 dev_t dev = (dev_t) ReadUnalignedLE32(d);
765 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000766 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000767 off_t size = (off_t) ReadUnalignedLE64(d);
768 return data_type(ino, dev, mode, mtime, size);
769 }
770};
771
772/// \brief stat() cache for precompiled headers.
773///
774/// This cache is very similar to the stat cache used by pretokenized
775/// headers.
776class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
777 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
778 CacheTy *Cache;
779
780 unsigned &NumStatHits, &NumStatMisses;
Mike Stump1eb44332009-09-09 15:08:12 +0000781public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000782 PCHStatCache(const unsigned char *Buckets,
783 const unsigned char *Base,
784 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000785 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000786 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
787 Cache = CacheTy::Create(Buckets, Base);
788 }
789
790 ~PCHStatCache() { delete Cache; }
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000792 int stat(const char *path, struct stat *buf) {
793 // Do the lookup for the file's data in the PCH file.
794 CacheTy::iterator I = Cache->find(path);
795
796 // If we don't get a hit in the PCH file just forward to 'stat'.
797 if (I == Cache->end()) {
798 ++NumStatMisses;
Douglas Gregor52e71082009-10-16 18:18:30 +0000799 return StatSysCallCache::stat(path, buf);
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000800 }
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000802 ++NumStatHits;
803 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000805 if (!Data.hasStat)
806 return 1;
807
808 buf->st_ino = Data.ino;
809 buf->st_dev = Data.dev;
810 buf->st_mtime = Data.mtime;
811 buf->st_mode = Data.mode;
812 buf->st_size = Data.size;
813 return 0;
814 }
815};
816} // end anonymous namespace
817
818
Douglas Gregor14f79002009-04-10 03:52:48 +0000819/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000820PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000821 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000822
823 // Set the source-location entry cursor to the current position in
824 // the stream. This cursor will be used to read the contents of the
825 // source manager block initially, and then lazily read
826 // source-location entries as needed.
827 SLocEntryCursor = Stream;
828
829 // The stream itself is going to skip over the source manager block.
830 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000831 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000832 return Failure;
833 }
834
835 // Enter the source manager block.
836 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000837 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000838 return Failure;
839 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000840
Douglas Gregor14f79002009-04-10 03:52:48 +0000841 RecordData Record;
842 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000843 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000844 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000845 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000846 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000847 return Failure;
848 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000849 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregor14f79002009-04-10 03:52:48 +0000852 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
853 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000854 SLocEntryCursor.ReadSubBlockID();
855 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000856 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000857 return Failure;
858 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000859 continue;
860 }
Mike Stump1eb44332009-09-09 15:08:12 +0000861
Douglas Gregor14f79002009-04-10 03:52:48 +0000862 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000863 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000864 continue;
865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Douglas Gregor14f79002009-04-10 03:52:48 +0000867 // Read a record.
868 const char *BlobStart;
869 unsigned BlobLen;
870 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000871 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000872 default: // Default behavior: ignore.
873 break;
874
Chris Lattner2c78b872009-04-14 23:22:57 +0000875 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000876 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000877 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000878 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000879
880 case pch::SM_HEADER_FILE_INFO: {
881 HeaderFileInfo HFI;
882 HFI.isImport = Record[0];
883 HFI.DirInfo = Record[1];
884 HFI.NumIncludes = Record[2];
885 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000886 if (Listener)
887 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000888 break;
889 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000890
891 case pch::SM_SLOC_FILE_ENTRY:
892 case pch::SM_SLOC_BUFFER_ENTRY:
893 case pch::SM_SLOC_INSTANTIATION_ENTRY:
894 // Once we hit one of the source location entries, we're done.
895 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000896 }
897 }
898}
899
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000900/// \brief Read in the source location entry with the given ID.
901PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
902 if (ID == 0)
903 return Success;
904
905 if (ID > TotalNumSLocEntries) {
906 Error("source location entry ID out-of-range for PCH file");
907 return Failure;
908 }
909
910 ++NumSLocEntriesRead;
911 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
912 unsigned Code = SLocEntryCursor.ReadCode();
913 if (Code == llvm::bitc::END_BLOCK ||
914 Code == llvm::bitc::ENTER_SUBBLOCK ||
915 Code == llvm::bitc::DEFINE_ABBREV) {
916 Error("incorrectly-formatted source location entry in PCH file");
917 return Failure;
918 }
919
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000920 RecordData Record;
921 const char *BlobStart;
922 unsigned BlobLen;
923 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
924 default:
925 Error("incorrectly-formatted source location entry in PCH file");
926 return Failure;
927
928 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000929 std::string Filename(BlobStart, BlobStart + BlobLen);
930 MaybeAddSystemRootToFilename(Filename);
931 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000932 if (File == 0) {
933 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000934 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000935 ErrorStr += "' referenced by PCH file";
936 Error(ErrorStr.c_str());
937 return Failure;
938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000940 FileID FID = SourceMgr.createFileID(File,
941 SourceLocation::getFromRawEncoding(Record[1]),
942 (SrcMgr::CharacteristicKind)Record[2],
943 ID, Record[0]);
944 if (Record[3])
945 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
946 .setHasLineDirectives();
947
948 break;
949 }
950
951 case pch::SM_SLOC_BUFFER_ENTRY: {
952 const char *Name = BlobStart;
953 unsigned Offset = Record[0];
954 unsigned Code = SLocEntryCursor.ReadCode();
955 Record.clear();
Mike Stump1eb44332009-09-09 15:08:12 +0000956 unsigned RecCode
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000957 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
958 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
959 (void)RecCode;
960 llvm::MemoryBuffer *Buffer
Mike Stump1eb44332009-09-09 15:08:12 +0000961 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000962 BlobStart + BlobLen - 1,
963 Name);
964 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Douglas Gregor92b059e2009-04-28 20:33:11 +0000966 if (strcmp(Name, "<built-in>") == 0) {
967 PCHPredefinesBufferID = BufferID;
968 PCHPredefines = BlobStart;
969 PCHPredefinesLen = BlobLen - 1;
970 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000971
972 break;
973 }
974
975 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000976 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000977 = SourceLocation::getFromRawEncoding(Record[1]);
978 SourceMgr.createInstantiationLoc(SpellingLoc,
979 SourceLocation::getFromRawEncoding(Record[2]),
980 SourceLocation::getFromRawEncoding(Record[3]),
981 Record[4],
982 ID,
983 Record[0]);
984 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000985 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000986 }
987
988 return Success;
989}
990
Chris Lattner6367f6d2009-04-27 01:05:14 +0000991/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
992/// specified cursor. Read the abbreviations that are at the top of the block
993/// and then leave the cursor pointing into the block.
994bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
995 unsigned BlockID) {
996 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000997 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000998 return Failure;
999 }
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner6367f6d2009-04-27 01:05:14 +00001001 while (true) {
1002 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Chris Lattner6367f6d2009-04-27 01:05:14 +00001004 // We expect all abbrevs to be at the start of the block.
1005 if (Code != llvm::bitc::DEFINE_ABBREV)
1006 return false;
1007 Cursor.ReadAbbrevRecord();
1008 }
1009}
1010
Douglas Gregor37e26842009-04-21 23:56:24 +00001011void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001012 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Douglas Gregor37e26842009-04-21 23:56:24 +00001014 // Keep track of where we are in the stream, then jump back there
1015 // after reading this macro.
1016 SavedStreamPosition SavedPosition(Stream);
1017
1018 Stream.JumpToBit(Offset);
1019 RecordData Record;
1020 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1021 MacroInfo *Macro = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Douglas Gregor37e26842009-04-21 23:56:24 +00001023 while (true) {
1024 unsigned Code = Stream.ReadCode();
1025 switch (Code) {
1026 case llvm::bitc::END_BLOCK:
1027 return;
1028
1029 case llvm::bitc::ENTER_SUBBLOCK:
1030 // No known subblocks, always skip them.
1031 Stream.ReadSubBlockID();
1032 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001033 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001034 return;
1035 }
1036 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Douglas Gregor37e26842009-04-21 23:56:24 +00001038 case llvm::bitc::DEFINE_ABBREV:
1039 Stream.ReadAbbrevRecord();
1040 continue;
1041 default: break;
1042 }
1043
1044 // Read a record.
1045 Record.clear();
1046 pch::PreprocessorRecordTypes RecType =
1047 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1048 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001049 case pch::PP_MACRO_OBJECT_LIKE:
1050 case pch::PP_MACRO_FUNCTION_LIKE: {
1051 // If we already have a macro, that means that we've hit the end
1052 // of the definition of the macro we were looking for. We're
1053 // done.
1054 if (Macro)
1055 return;
1056
1057 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1058 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001059 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001060 return;
1061 }
1062 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1063 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001065 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001066 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Douglas Gregor37e26842009-04-21 23:56:24 +00001068 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1069 // Decode function-like macro info.
1070 bool isC99VarArgs = Record[3];
1071 bool isGNUVarArgs = Record[4];
1072 MacroArgs.clear();
1073 unsigned NumArgs = Record[5];
1074 for (unsigned i = 0; i != NumArgs; ++i)
1075 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1076
1077 // Install function-like macro info.
1078 MI->setIsFunctionLike();
1079 if (isC99VarArgs) MI->setIsC99Varargs();
1080 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001081 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001082 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001083 }
1084
1085 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001086 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001087
1088 // Remember that we saw this macro last so that we add the tokens that
1089 // form its body to it.
1090 Macro = MI;
1091 ++NumMacrosRead;
1092 break;
1093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Douglas Gregor37e26842009-04-21 23:56:24 +00001095 case pch::PP_TOKEN: {
1096 // If we see a TOKEN before a PP_MACRO_*, then the file is
1097 // erroneous, just pretend we didn't see this.
1098 if (Macro == 0) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Douglas Gregor37e26842009-04-21 23:56:24 +00001100 Token Tok;
1101 Tok.startToken();
1102 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1103 Tok.setLength(Record[1]);
1104 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1105 Tok.setIdentifierInfo(II);
1106 Tok.setKind((tok::TokenKind)Record[3]);
1107 Tok.setFlag((Token::TokenFlags)Record[4]);
1108 Macro->AddTokenToBody(Tok);
1109 break;
1110 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001111 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001112 }
1113}
1114
Douglas Gregore650c8c2009-07-07 00:12:59 +00001115/// \brief If we are loading a relocatable PCH file, and the filename is
1116/// not an absolute path, add the system root to the beginning of the file
1117/// name.
1118void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1119 // If this is not a relocatable PCH file, there's nothing to do.
1120 if (!RelocatablePCH)
1121 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Douglas Gregore650c8c2009-07-07 00:12:59 +00001123 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1124 return;
1125
1126 std::string FIXME = Filename;
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Douglas Gregore650c8c2009-07-07 00:12:59 +00001128 if (isysroot == 0) {
1129 // If no system root was given, default to '/'
1130 Filename.insert(Filename.begin(), '/');
1131 return;
1132 }
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Douglas Gregore650c8c2009-07-07 00:12:59 +00001134 unsigned Length = strlen(isysroot);
1135 if (isysroot[Length - 1] != '/')
1136 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Douglas Gregore650c8c2009-07-07 00:12:59 +00001138 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1139}
1140
Mike Stump1eb44332009-09-09 15:08:12 +00001141PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001142PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001143 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001144 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001145 return Failure;
1146 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001147
1148 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001149 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001150 while (!Stream.AtEndOfStream()) {
1151 unsigned Code = Stream.ReadCode();
1152 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001153 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001154 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001155 return Failure;
1156 }
Chris Lattner7356a312009-04-11 21:15:38 +00001157
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001158 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001159 }
1160
1161 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1162 switch (Stream.ReadSubBlockID()) {
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001163 case pch::DECLTYPES_BLOCK_ID:
Chris Lattner6367f6d2009-04-27 01:05:14 +00001164 // We lazily load the decls block, but we want to set up the
1165 // DeclsCursor cursor to point into it. Clone our current bitcode
1166 // cursor to it, enter the block and read the abbrevs in that block.
1167 // With the main cursor, we just skip over it.
1168 DeclsCursor = Stream;
1169 if (Stream.SkipBlock() || // Skip with the main cursor.
1170 // Read the abbrevs.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001171 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001172 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001173 return Failure;
1174 }
1175 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Chris Lattner7356a312009-04-11 21:15:38 +00001177 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001178 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001179 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001180 return Failure;
1181 }
1182 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001183
Douglas Gregor14f79002009-04-10 03:52:48 +00001184 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001185 switch (ReadSourceManagerBlock()) {
1186 case Success:
1187 break;
1188
1189 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001190 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001191 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001192
1193 case IgnorePCH:
1194 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001195 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001196 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001197 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001198 continue;
1199 }
1200
1201 if (Code == llvm::bitc::DEFINE_ABBREV) {
1202 Stream.ReadAbbrevRecord();
1203 continue;
1204 }
1205
1206 // Read and process a record.
1207 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001208 const char *BlobStart = 0;
1209 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001210 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001211 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001212 default: // Default behavior: ignore.
1213 break;
1214
1215 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001216 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001217 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001218 return Failure;
1219 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001220 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001221 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001222 break;
1223
1224 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001225 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001226 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001227 return Failure;
1228 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001229 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001230 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001231 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001232
1233 case pch::LANGUAGE_OPTIONS:
1234 if (ParseLanguageOptions(Record))
1235 return IgnorePCH;
1236 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001237
Douglas Gregorab41e632009-04-27 22:23:34 +00001238 case pch::METADATA: {
1239 if (Record[0] != pch::VERSION_MAJOR) {
1240 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1241 : diag::warn_pch_version_too_new);
1242 return IgnorePCH;
1243 }
1244
Douglas Gregore650c8c2009-07-07 00:12:59 +00001245 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001246 if (Listener) {
1247 std::string TargetTriple(BlobStart, BlobLen);
1248 if (Listener->ReadTargetTriple(TargetTriple))
1249 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001250 }
1251 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001252 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001253
1254 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001255 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001256 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001257 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001258 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001259 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001260 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001261 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001262 if (PP)
1263 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001264 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001265 break;
1266
1267 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001268 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001269 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001270 return Failure;
1271 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001272 IdentifierOffsets = (const uint32_t *)BlobStart;
1273 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001274 if (PP)
1275 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001276 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001277
1278 case pch::EXTERNAL_DEFINITIONS:
1279 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001280 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001281 return Failure;
1282 }
1283 ExternalDefinitions.swap(Record);
1284 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001285
Douglas Gregorad1de002009-04-18 05:55:16 +00001286 case pch::SPECIAL_TYPES:
1287 SpecialTypes.swap(Record);
1288 break;
1289
Douglas Gregor3e1af842009-04-17 22:13:46 +00001290 case pch::STATISTICS:
1291 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001292 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001293 TotalLexicalDeclContexts = Record[2];
1294 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001295 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001296
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001297 case pch::TENTATIVE_DEFINITIONS:
1298 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001299 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001300 return Failure;
1301 }
1302 TentativeDefinitions.swap(Record);
1303 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001304
1305 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1306 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001307 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001308 return Failure;
1309 }
1310 LocallyScopedExternalDecls.swap(Record);
1311 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001312
Douglas Gregor83941df2009-04-25 17:48:32 +00001313 case pch::SELECTOR_OFFSETS:
1314 SelectorOffsets = (const uint32_t *)BlobStart;
1315 TotalNumSelectors = Record[0];
1316 SelectorsLoaded.resize(TotalNumSelectors);
1317 break;
1318
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001319 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001320 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1321 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001322 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001323 = PCHMethodPoolLookupTable::Create(
1324 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001325 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001326 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001327 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001328 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001329
1330 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001331 if (!Record.empty() && Listener)
1332 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001333 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001334
1335 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001336 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001337 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001338 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001339 break;
1340
1341 case pch::SOURCE_LOCATION_PRELOADS:
1342 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1343 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1344 if (Result != Success)
1345 return Result;
1346 }
1347 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001348
Douglas Gregor52e71082009-10-16 18:18:30 +00001349 case pch::STAT_CACHE: {
1350 PCHStatCache *MyStatCache =
1351 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1352 (const unsigned char *)BlobStart,
1353 NumStatHits, NumStatMisses);
1354 FileMgr.addStatCache(MyStatCache);
1355 StatCache = MyStatCache;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001356 break;
Douglas Gregor52e71082009-10-16 18:18:30 +00001357 }
1358
Douglas Gregorb81c1702009-04-27 20:06:05 +00001359 case pch::EXT_VECTOR_DECLS:
1360 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001361 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001362 return Failure;
1363 }
1364 ExtVectorDecls.swap(Record);
1365 break;
1366
Douglas Gregorb64c1932009-05-12 01:31:05 +00001367 case pch::ORIGINAL_FILE_NAME:
1368 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001369 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001370 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Douglas Gregor2e222532009-07-02 17:08:52 +00001372 case pch::COMMENT_RANGES:
1373 Comments = (SourceRange *)BlobStart;
1374 NumComments = BlobLen / sizeof(SourceRange);
1375 break;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001376
1377 case pch::SVN_BRANCH_REVISION: {
1378 unsigned CurRevision = getClangSubversionRevision();
1379 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1380 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1381 : diag::warn_pch_version_too_new);
1382 return IgnorePCH;
1383 }
1384
1385 const char *CurBranch = getClangSubversionPath();
1386 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1387 std::string PCHBranch(BlobStart, BlobLen);
1388 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1389 return IgnorePCH;
1390 }
1391 break;
1392 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001393 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001394 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001395 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001396 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001397}
1398
Douglas Gregore1d918e2009-04-10 23:10:45 +00001399PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001400 // Set the PCH file name.
1401 this->FileName = FileName;
1402
Douglas Gregor2cf26342009-04-09 22:27:44 +00001403 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001404 //
1405 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001406 std::string ErrStr;
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001407 if (FileName == "-")
1408 Buffer.reset(llvm::MemoryBuffer::getSTDIN());
1409 else
1410 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001411 if (!Buffer) {
1412 Error(ErrStr.c_str());
1413 return IgnorePCH;
1414 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001415
1416 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001417 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001418 (const unsigned char *)Buffer->getBufferEnd());
1419 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001420
1421 // Sniff for the signature.
1422 if (Stream.Read(8) != 'C' ||
1423 Stream.Read(8) != 'P' ||
1424 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001425 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001426 Diag(diag::err_not_a_pch_file) << FileName;
1427 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001428 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001429
Douglas Gregor2cf26342009-04-09 22:27:44 +00001430 while (!Stream.AtEndOfStream()) {
1431 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Douglas Gregore1d918e2009-04-10 23:10:45 +00001433 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001434 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001435 return Failure;
1436 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001437
1438 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001439
Douglas Gregor2cf26342009-04-09 22:27:44 +00001440 // We only know the PCH subblock ID.
1441 switch (BlockID) {
1442 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001443 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001444 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001445 return Failure;
1446 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001447 break;
1448 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001449 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001450 case Success:
1451 break;
1452
1453 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001454 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001455
1456 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001457 // FIXME: We could consider reading through to the end of this
1458 // PCH block, skipping subblocks, to see if there are other
1459 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001460
1461 // Clear out any preallocated source location entries, so that
1462 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001463 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001464
1465 // Remove the stat cache.
Douglas Gregor52e71082009-10-16 18:18:30 +00001466 if (StatCache)
1467 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001468
Douglas Gregore1d918e2009-04-10 23:10:45 +00001469 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001470 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001471 break;
1472 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001473 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001474 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001475 return Failure;
1476 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001477 break;
1478 }
Mike Stump1eb44332009-09-09 15:08:12 +00001479 }
1480
Douglas Gregor92b059e2009-04-28 20:33:11 +00001481 // Check the predefines buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001482 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
Douglas Gregor92b059e2009-04-28 20:33:11 +00001483 PCHPredefinesBufferID))
1484 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001486 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001487 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001488 // PCH file is read, so there may be some identifiers that were
1489 // loaded into the IdentifierTable before we intercepted the
1490 // creation of identifiers. Iterate through the list of known
1491 // identifiers and determine whether we have to establish
1492 // preprocessor definitions or top-level identifier declaration
1493 // chains for those identifiers.
1494 //
1495 // We copy the IdentifierInfo pointers to a small vector first,
1496 // since de-serializing declarations or macro definitions can add
1497 // new entries into the identifier table, invalidating the
1498 // iterators.
1499 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1500 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1501 IdEnd = PP->getIdentifierTable().end();
1502 Id != IdEnd; ++Id)
1503 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001504 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001505 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1506 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1507 IdentifierInfo *II = Identifiers[I];
1508 // Look in the on-disk hash table for an entry for
1509 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbare013d682009-10-18 20:26:12 +00001510 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001511 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1512 if (Pos == IdTable->end())
1513 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001515 // Dereferencing the iterator has the effect of populating the
1516 // IdentifierInfo node with the various declarations it needs.
1517 (void)*Pos;
1518 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001519 }
1520
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001521 if (Context)
1522 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001523
Douglas Gregor668c1a42009-04-21 22:25:48 +00001524 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001525}
1526
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001527void PCHReader::InitializeContext(ASTContext &Ctx) {
1528 Context = &Ctx;
1529 assert(Context && "Passed null context!");
1530
1531 assert(PP && "Forgot to set Preprocessor ?");
1532 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1533 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001535 // Load the translation unit declaration
1536 ReadDeclRecord(DeclOffsets[0], 0);
1537
1538 // Load the special types.
1539 Context->setBuiltinVaListType(
1540 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1541 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1542 Context->setObjCIdType(GetType(Id));
1543 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1544 Context->setObjCSelType(GetType(Sel));
1545 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1546 Context->setObjCProtoType(GetType(Proto));
1547 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1548 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001549
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001550 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1551 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001552 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001553 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1554 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001555 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1556 QualType FileType = GetType(File);
1557 assert(!FileType.isNull() && "FILE type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001558 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001559 Context->setFILEDecl(Typedef->getDecl());
1560 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001561 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001562 assert(Tag && "Invalid FILE type in PCH file");
1563 Context->setFILEDecl(Tag->getDecl());
1564 }
1565 }
Mike Stump782fa302009-07-28 02:25:19 +00001566 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1567 QualType Jmp_bufType = GetType(Jmp_buf);
1568 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001569 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001570 Context->setjmp_bufDecl(Typedef->getDecl());
1571 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001572 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001573 assert(Tag && "Invalid jmp_bug type in PCH file");
1574 Context->setjmp_bufDecl(Tag->getDecl());
1575 }
1576 }
1577 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1578 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1579 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001580 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001581 Context->setsigjmp_bufDecl(Typedef->getDecl());
1582 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001583 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001584 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1585 Context->setsigjmp_bufDecl(Tag->getDecl());
1586 }
1587 }
Mike Stump1eb44332009-09-09 15:08:12 +00001588 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001589 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1590 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001591 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001592 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1593 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpadaaad32009-10-20 02:12:22 +00001594 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1595 Context->setBlockDescriptorType(GetType(String));
Mike Stump083c25e2009-10-22 00:49:09 +00001596 if (unsigned String
1597 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1598 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001599}
1600
Douglas Gregorb64c1932009-05-12 01:31:05 +00001601/// \brief Retrieve the name of the original source file name
1602/// directly from the PCH file, without actually loading the PCH
1603/// file.
1604std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1605 // Open the PCH file.
1606 std::string ErrStr;
1607 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1608 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1609 if (!Buffer) {
1610 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1611 return std::string();
1612 }
1613
1614 // Initialize the stream
1615 llvm::BitstreamReader StreamFile;
1616 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001617 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001618 (const unsigned char *)Buffer->getBufferEnd());
1619 Stream.init(StreamFile);
1620
1621 // Sniff for the signature.
1622 if (Stream.Read(8) != 'C' ||
1623 Stream.Read(8) != 'P' ||
1624 Stream.Read(8) != 'C' ||
1625 Stream.Read(8) != 'H') {
Mike Stump1eb44332009-09-09 15:08:12 +00001626 fprintf(stderr,
Douglas Gregorb64c1932009-05-12 01:31:05 +00001627 "error: '%s' does not appear to be a precompiled header file\n",
1628 PCHFileName.c_str());
1629 return std::string();
1630 }
1631
1632 RecordData Record;
1633 while (!Stream.AtEndOfStream()) {
1634 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Douglas Gregorb64c1932009-05-12 01:31:05 +00001636 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1637 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Douglas Gregorb64c1932009-05-12 01:31:05 +00001639 // We only know the PCH subblock ID.
1640 switch (BlockID) {
1641 case pch::PCH_BLOCK_ID:
1642 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1643 fprintf(stderr, "error: malformed block record in PCH file\n");
1644 return std::string();
1645 }
1646 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Douglas Gregorb64c1932009-05-12 01:31:05 +00001648 default:
1649 if (Stream.SkipBlock()) {
1650 fprintf(stderr, "error: malformed block record in PCH file\n");
1651 return std::string();
1652 }
1653 break;
1654 }
1655 continue;
1656 }
1657
1658 if (Code == llvm::bitc::END_BLOCK) {
1659 if (Stream.ReadBlockEnd()) {
1660 fprintf(stderr, "error: error at end of module block in PCH file\n");
1661 return std::string();
1662 }
1663 continue;
1664 }
1665
1666 if (Code == llvm::bitc::DEFINE_ABBREV) {
1667 Stream.ReadAbbrevRecord();
1668 continue;
1669 }
1670
1671 Record.clear();
1672 const char *BlobStart = 0;
1673 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001674 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001675 == pch::ORIGINAL_FILE_NAME)
1676 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001677 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001678
1679 return std::string();
1680}
1681
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001682/// \brief Parse the record that corresponds to a LangOptions data
1683/// structure.
1684///
1685/// This routine compares the language options used to generate the
1686/// PCH file against the language options set for the current
1687/// compilation. For each option, we classify differences between the
1688/// two compiler states as either "benign" or "important". Benign
1689/// differences don't matter, and we accept them without complaint
1690/// (and without modifying the language options). Differences between
1691/// the states for important options cause the PCH file to be
1692/// unusable, so we emit a warning and return true to indicate that
1693/// there was an error.
1694///
1695/// \returns true if the PCH file is unacceptable, false otherwise.
1696bool PCHReader::ParseLanguageOptions(
1697 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001698 if (Listener) {
1699 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001701 #define PARSE_LANGOPT(Option) \
1702 LangOpts.Option = Record[Idx]; \
1703 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001705 unsigned Idx = 0;
1706 PARSE_LANGOPT(Trigraphs);
1707 PARSE_LANGOPT(BCPLComment);
1708 PARSE_LANGOPT(DollarIdents);
1709 PARSE_LANGOPT(AsmPreprocessor);
1710 PARSE_LANGOPT(GNUMode);
1711 PARSE_LANGOPT(ImplicitInt);
1712 PARSE_LANGOPT(Digraphs);
1713 PARSE_LANGOPT(HexFloats);
1714 PARSE_LANGOPT(C99);
1715 PARSE_LANGOPT(Microsoft);
1716 PARSE_LANGOPT(CPlusPlus);
1717 PARSE_LANGOPT(CPlusPlus0x);
1718 PARSE_LANGOPT(CXXOperatorNames);
1719 PARSE_LANGOPT(ObjC1);
1720 PARSE_LANGOPT(ObjC2);
1721 PARSE_LANGOPT(ObjCNonFragileABI);
1722 PARSE_LANGOPT(PascalStrings);
1723 PARSE_LANGOPT(WritableStrings);
1724 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001725 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001726 PARSE_LANGOPT(Exceptions);
1727 PARSE_LANGOPT(NeXTRuntime);
1728 PARSE_LANGOPT(Freestanding);
1729 PARSE_LANGOPT(NoBuiltin);
1730 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001731 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001732 PARSE_LANGOPT(Blocks);
1733 PARSE_LANGOPT(EmitAllDecls);
1734 PARSE_LANGOPT(MathErrno);
1735 PARSE_LANGOPT(OverflowChecking);
1736 PARSE_LANGOPT(HeinousExtensions);
1737 PARSE_LANGOPT(Optimize);
1738 PARSE_LANGOPT(OptimizeSize);
1739 PARSE_LANGOPT(Static);
1740 PARSE_LANGOPT(PICLevel);
1741 PARSE_LANGOPT(GNUInline);
1742 PARSE_LANGOPT(NoInline);
1743 PARSE_LANGOPT(AccessControl);
1744 PARSE_LANGOPT(CharIsSigned);
John Thompsona6fda122009-11-05 20:14:16 +00001745 PARSE_LANGOPT(ShortWChar);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001746 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1747 ++Idx;
1748 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1749 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001750 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1751 Record[Idx]);
1752 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001753 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001754 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001755 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001756
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001757 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001758 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001759
1760 return false;
1761}
1762
Douglas Gregor2e222532009-07-02 17:08:52 +00001763void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1764 Comments.resize(NumComments);
1765 std::copy(this->Comments, this->Comments + NumComments,
1766 Comments.begin());
1767}
1768
Douglas Gregor2cf26342009-04-09 22:27:44 +00001769/// \brief Read and return the type at the given offset.
1770///
1771/// This routine actually reads the record corresponding to the type
1772/// at the given offset in the bitstream. It is a helper routine for
1773/// GetType, which deals with reading type IDs.
1774QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001775 // Keep track of where we are in the stream, then jump back there
1776 // after reading this type.
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001777 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001778
Douglas Gregord89275b2009-07-06 18:54:52 +00001779 // Note that we are loading a type record.
1780 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001782 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001783 RecordData Record;
Douglas Gregor61d60ee2009-10-17 00:13:19 +00001784 unsigned Code = DeclsCursor.ReadCode();
1785 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001786 case pch::TYPE_EXT_QUAL: {
John McCall0953e762009-09-24 19:53:00 +00001787 assert(Record.size() == 2 &&
Douglas Gregor6d473962009-04-15 22:00:08 +00001788 "Incorrect encoding of extended qualifier type");
1789 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00001790 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1791 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00001792 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001793
Douglas Gregor2cf26342009-04-09 22:27:44 +00001794 case pch::TYPE_FIXED_WIDTH_INT: {
1795 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001796 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001797 }
1798
1799 case pch::TYPE_COMPLEX: {
1800 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1801 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001802 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001803 }
1804
1805 case pch::TYPE_POINTER: {
1806 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1807 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001808 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001809 }
1810
1811 case pch::TYPE_BLOCK_POINTER: {
1812 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1813 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001814 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001815 }
1816
1817 case pch::TYPE_LVALUE_REFERENCE: {
1818 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1819 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001820 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001821 }
1822
1823 case pch::TYPE_RVALUE_REFERENCE: {
1824 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1825 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001826 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001827 }
1828
1829 case pch::TYPE_MEMBER_POINTER: {
1830 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1831 QualType PointeeType = GetType(Record[0]);
1832 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001833 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001834 }
1835
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001836 case pch::TYPE_CONSTANT_ARRAY: {
1837 QualType ElementType = GetType(Record[0]);
1838 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1839 unsigned IndexTypeQuals = Record[2];
1840 unsigned Idx = 3;
1841 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001842 return Context->getConstantArrayType(ElementType, Size,
1843 ASM, IndexTypeQuals);
1844 }
1845
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001846 case pch::TYPE_INCOMPLETE_ARRAY: {
1847 QualType ElementType = GetType(Record[0]);
1848 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1849 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001850 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001851 }
1852
1853 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001854 QualType ElementType = GetType(Record[0]);
1855 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1856 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001857 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1858 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001859 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001860 ASM, IndexTypeQuals,
1861 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001862 }
1863
1864 case pch::TYPE_VECTOR: {
1865 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001866 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001867 return QualType();
1868 }
1869
1870 QualType ElementType = GetType(Record[0]);
1871 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001872 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001873 }
1874
1875 case pch::TYPE_EXT_VECTOR: {
1876 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001877 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001878 return QualType();
1879 }
1880
1881 QualType ElementType = GetType(Record[0]);
1882 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001883 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001884 }
1885
1886 case pch::TYPE_FUNCTION_NO_PROTO: {
1887 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001888 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001889 return QualType();
1890 }
1891 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001892 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001893 }
1894
1895 case pch::TYPE_FUNCTION_PROTO: {
1896 QualType ResultType = GetType(Record[0]);
1897 unsigned Idx = 1;
1898 unsigned NumParams = Record[Idx++];
1899 llvm::SmallVector<QualType, 16> ParamTypes;
1900 for (unsigned I = 0; I != NumParams; ++I)
1901 ParamTypes.push_back(GetType(Record[Idx++]));
1902 bool isVariadic = Record[Idx++];
1903 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001904 bool hasExceptionSpec = Record[Idx++];
1905 bool hasAnyExceptionSpec = Record[Idx++];
1906 unsigned NumExceptions = Record[Idx++];
1907 llvm::SmallVector<QualType, 2> Exceptions;
1908 for (unsigned I = 0; I != NumExceptions; ++I)
1909 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001910 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001911 isVariadic, Quals, hasExceptionSpec,
1912 hasAnyExceptionSpec, NumExceptions,
1913 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001914 }
1915
1916 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001917 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001918 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001919
1920 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001921 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001922
1923 case pch::TYPE_TYPEOF: {
1924 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001925 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001926 return QualType();
1927 }
1928 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001929 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001930 }
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Anders Carlsson395b4752009-06-24 19:06:50 +00001932 case pch::TYPE_DECLTYPE:
1933 return Context->getDecltypeType(ReadTypeExpr());
1934
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001935 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001936 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001937 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001938
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001939 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001940 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001941 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001942
John McCall7da24312009-09-05 00:15:47 +00001943 case pch::TYPE_ELABORATED: {
1944 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1945 unsigned Tag = Record[1];
1946 return Context->getElaboratedType(GetType(Record[0]),
1947 (ElaboratedType::TagKind) Tag);
1948 }
1949
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001950 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001951 unsigned Idx = 0;
1952 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1953 unsigned NumProtos = Record[Idx++];
1954 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1955 for (unsigned I = 0; I != NumProtos; ++I)
1956 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001957 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001958 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001959
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001960 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001961 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001962 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001963 unsigned NumProtos = Record[Idx++];
1964 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1965 for (unsigned I = 0; I != NumProtos; ++I)
1966 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001967 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001968 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001969
John McCall49a832b2009-10-18 09:09:24 +00001970 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1971 unsigned Idx = 0;
1972 QualType Parm = GetType(Record[Idx++]);
1973 QualType Replacement = GetType(Record[Idx++]);
1974 return
1975 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1976 Replacement);
1977 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001978 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001979 // Suppress a GCC warning
1980 return QualType();
1981}
1982
John McCalla1ee0c52009-10-16 21:56:05 +00001983namespace {
1984
1985class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1986 PCHReader &Reader;
1987 const PCHReader::RecordData &Record;
1988 unsigned &Idx;
1989
1990public:
1991 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1992 unsigned &Idx)
1993 : Reader(Reader), Record(Record), Idx(Idx) { }
1994
John McCall51bd8032009-10-18 01:05:36 +00001995 // We want compile-time assurance that we've enumerated all of
1996 // these, so unfortunately we have to declare them first, then
1997 // define them out-of-line.
1998#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCalla1ee0c52009-10-16 21:56:05 +00001999#define TYPELOC(CLASS, PARENT) \
John McCall51bd8032009-10-18 01:05:36 +00002000 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002001#include "clang/AST/TypeLocNodes.def"
2002
John McCall51bd8032009-10-18 01:05:36 +00002003 void VisitFunctionTypeLoc(FunctionTypeLoc);
2004 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCalla1ee0c52009-10-16 21:56:05 +00002005};
2006
2007}
2008
John McCall51bd8032009-10-18 01:05:36 +00002009void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCalla1ee0c52009-10-16 21:56:05 +00002010 // nothing to do
2011}
John McCall51bd8032009-10-18 01:05:36 +00002012void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2013 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002014}
John McCall51bd8032009-10-18 01:05:36 +00002015void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
2016 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002017}
John McCall51bd8032009-10-18 01:05:36 +00002018void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2019 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002020}
John McCall51bd8032009-10-18 01:05:36 +00002021void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2022 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002023}
John McCall51bd8032009-10-18 01:05:36 +00002024void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2025 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002026}
John McCall51bd8032009-10-18 01:05:36 +00002027void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2028 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002029}
John McCall51bd8032009-10-18 01:05:36 +00002030void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2031 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002032}
John McCall51bd8032009-10-18 01:05:36 +00002033void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2034 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002035}
John McCall51bd8032009-10-18 01:05:36 +00002036void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2037 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2038 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002039 if (Record[Idx++])
John McCall51bd8032009-10-18 01:05:36 +00002040 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor61d60ee2009-10-17 00:13:19 +00002041 else
John McCall51bd8032009-10-18 01:05:36 +00002042 TL.setSizeExpr(0);
2043}
2044void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2045 VisitArrayTypeLoc(TL);
2046}
2047void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2048 VisitArrayTypeLoc(TL);
2049}
2050void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2051 VisitArrayTypeLoc(TL);
2052}
2053void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2054 DependentSizedArrayTypeLoc TL) {
2055 VisitArrayTypeLoc(TL);
2056}
2057void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2058 DependentSizedExtVectorTypeLoc TL) {
2059 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2060}
2061void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2062 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2063}
2064void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2065 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2066}
2067void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2068 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2069 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2070 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
John McCall86acc2a2009-10-23 01:28:53 +00002071 TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
John McCall51bd8032009-10-18 01:05:36 +00002072 }
2073}
2074void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2075 VisitFunctionTypeLoc(TL);
2076}
2077void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2078 VisitFunctionTypeLoc(TL);
2079}
2080void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2081 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2082}
2083void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2084 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2085}
2086void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2087 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2088}
2089void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2090 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2091}
2092void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2093 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2094}
2095void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2096 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2097}
2098void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2099 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2100}
2101void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2102 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2103}
John McCall49a832b2009-10-18 09:09:24 +00002104void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2105 SubstTemplateTypeParmTypeLoc TL) {
2106 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2107}
John McCall51bd8032009-10-18 01:05:36 +00002108void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2109 TemplateSpecializationTypeLoc TL) {
John McCall833ca992009-10-29 08:12:44 +00002110 TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2111 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2112 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2113 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2114 TL.setArgLocInfo(i,
2115 Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2116 Record, Idx));
John McCall51bd8032009-10-18 01:05:36 +00002117}
2118void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2119 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2120}
2121void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2122 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2123}
2124void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2125 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall51bd8032009-10-18 01:05:36 +00002126 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2127 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2128 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2129 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCalla1ee0c52009-10-16 21:56:05 +00002130}
John McCall54e14c42009-10-22 22:37:11 +00002131void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2132 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2133 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2134 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2135 TL.setHasBaseTypeAsWritten(Record[Idx++]);
2136 TL.setHasProtocolsAsWritten(Record[Idx++]);
2137 if (TL.hasProtocolsAsWritten())
2138 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2139 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2140}
John McCalla1ee0c52009-10-16 21:56:05 +00002141
2142DeclaratorInfo *PCHReader::GetDeclaratorInfo(const RecordData &Record,
2143 unsigned &Idx) {
2144 QualType InfoTy = GetType(Record[Idx++]);
2145 if (InfoTy.isNull())
2146 return 0;
2147
2148 DeclaratorInfo *DInfo = getContext()->CreateDeclaratorInfo(InfoTy);
2149 TypeLocReader TLR(*this, Record, Idx);
2150 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2151 TLR.Visit(TL);
2152 return DInfo;
2153}
Douglas Gregor2cf26342009-04-09 22:27:44 +00002154
Douglas Gregor8038d512009-04-10 17:25:41 +00002155QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002156 unsigned FastQuals = ID & Qualifiers::FastMask;
2157 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002158
2159 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2160 QualType T;
2161 switch ((pch::PredefinedTypeIDs)Index) {
2162 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002163 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2164 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002165
2166 case pch::PREDEF_TYPE_CHAR_U_ID:
2167 case pch::PREDEF_TYPE_CHAR_S_ID:
2168 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002169 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002170 break;
2171
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002172 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2173 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2174 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2175 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2176 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002177 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002178 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2179 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2180 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2181 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2182 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2183 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002184 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002185 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2186 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2187 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2188 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2189 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002190 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002191 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2192 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002193 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2194 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002195 }
2196
2197 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002198 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002199 }
2200
2201 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002202 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002203 if (TypesLoaded[Index].isNull())
2204 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
John McCall0953e762009-09-24 19:53:00 +00002206 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002207}
2208
John McCall833ca992009-10-29 08:12:44 +00002209TemplateArgumentLocInfo
2210PCHReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
2211 const RecordData &Record,
2212 unsigned &Index) {
2213 switch (Kind) {
2214 case TemplateArgument::Expression:
2215 return ReadDeclExpr();
2216 case TemplateArgument::Type:
2217 return GetDeclaratorInfo(Record, Index);
2218 case TemplateArgument::Null:
2219 case TemplateArgument::Integral:
2220 case TemplateArgument::Declaration:
2221 case TemplateArgument::Pack:
2222 return TemplateArgumentLocInfo();
2223 }
2224 llvm::llvm_unreachable("unexpected template argument loc");
2225 return TemplateArgumentLocInfo();
2226}
2227
Douglas Gregor8038d512009-04-10 17:25:41 +00002228Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002229 if (ID == 0)
2230 return 0;
2231
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002232 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002233 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002234 return 0;
2235 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002236
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002237 unsigned Index = ID - 1;
2238 if (!DeclsLoaded[Index])
2239 ReadDeclRecord(DeclOffsets[Index], Index);
2240
2241 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002242}
2243
Chris Lattner887e2b32009-04-27 05:46:25 +00002244/// \brief Resolve the offset of a statement into a statement.
2245///
2246/// This operation will read a new statement from the external
2247/// source each time it is called, and is meant to be used via a
2248/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2249Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002250 // Since we know tha this statement is part of a decl, make sure to use the
2251 // decl cursor to read it.
2252 DeclsCursor.JumpToBit(Offset);
2253 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002254}
2255
Douglas Gregor2cf26342009-04-09 22:27:44 +00002256bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002257 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002258 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002259 "DeclContext has no lexical decls in storage");
2260 uint64_t Offset = DeclContextOffsets[DC].first;
2261 assert(Offset && "DeclContext has no lexical decls in storage");
2262
Douglas Gregor0b748912009-04-14 21:18:50 +00002263 // Keep track of where we are in the stream, then jump back there
2264 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002265 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002266
Douglas Gregor2cf26342009-04-09 22:27:44 +00002267 // Load the record containing all of the declarations lexically in
2268 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002269 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002270 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002271 unsigned Code = DeclsCursor.ReadCode();
2272 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002273 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002274 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2275
2276 // Load all of the declaration IDs
2277 Decls.clear();
2278 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002279 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002280 return false;
2281}
2282
2283bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002284 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002285 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002286 "DeclContext has no visible decls in storage");
2287 uint64_t Offset = DeclContextOffsets[DC].second;
2288 assert(Offset && "DeclContext has no visible decls in storage");
2289
Douglas Gregor0b748912009-04-14 21:18:50 +00002290 // Keep track of where we are in the stream, then jump back there
2291 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002292 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002293
Douglas Gregor2cf26342009-04-09 22:27:44 +00002294 // Load the record containing all of the declarations visible in
2295 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002296 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002297 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002298 unsigned Code = DeclsCursor.ReadCode();
2299 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002300 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002301 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2302 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002303 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002304
2305 Decls.clear();
2306
2307 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002308 while (Idx < Record.size()) {
2309 Decls.push_back(VisibleDeclaration());
2310 Decls.back().Name = ReadDeclarationName(Record, Idx);
2311
Douglas Gregor2cf26342009-04-09 22:27:44 +00002312 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002313 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002314 LoadedDecls.reserve(Size);
2315 for (unsigned I = 0; I < Size; ++I)
2316 LoadedDecls.push_back(Record[Idx++]);
2317 }
2318
Douglas Gregor25123082009-04-22 22:34:57 +00002319 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002320 return false;
2321}
2322
Douglas Gregorfdd01722009-04-14 00:24:19 +00002323void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002324 this->Consumer = Consumer;
2325
Douglas Gregorfdd01722009-04-14 00:24:19 +00002326 if (!Consumer)
2327 return;
2328
2329 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002330 // Force deserialization of this decl, which will cause it to be passed to
2331 // the consumer (or queued).
2332 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002333 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002334
2335 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2336 DeclGroupRef DG(InterestingDecls[I]);
2337 Consumer->HandleTopLevelDecl(DG);
2338 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002339}
2340
Douglas Gregor2cf26342009-04-09 22:27:44 +00002341void PCHReader::PrintStats() {
2342 std::fprintf(stderr, "*** PCH Statistics:\n");
2343
Mike Stump1eb44332009-09-09 15:08:12 +00002344 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002345 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002346 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002347 unsigned NumDeclsLoaded
2348 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2349 (Decl *)0);
2350 unsigned NumIdentifiersLoaded
2351 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2352 IdentifiersLoaded.end(),
2353 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002354 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002355 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2356 SelectorsLoaded.end(),
2357 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002358
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002359 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2360 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002361 if (TotalNumSLocEntries)
2362 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2363 NumSLocEntriesRead, TotalNumSLocEntries,
2364 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002365 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002366 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002367 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2368 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2369 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002370 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002371 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2372 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002373 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002374 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002375 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2376 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002377 if (TotalNumSelectors)
2378 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2379 NumSelectorsLoaded, TotalNumSelectors,
2380 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2381 if (TotalNumStatements)
2382 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2383 NumStatementsRead, TotalNumStatements,
2384 ((float)NumStatementsRead/TotalNumStatements * 100));
2385 if (TotalNumMacros)
2386 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2387 NumMacrosRead, TotalNumMacros,
2388 ((float)NumMacrosRead/TotalNumMacros * 100));
2389 if (TotalLexicalDeclContexts)
2390 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2391 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2392 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2393 * 100));
2394 if (TotalVisibleDeclContexts)
2395 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2396 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2397 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2398 * 100));
2399 if (TotalSelectorsInMethodPool) {
2400 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2401 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2402 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2403 * 100));
2404 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2405 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002406 std::fprintf(stderr, "\n");
2407}
2408
Douglas Gregor668c1a42009-04-21 22:25:48 +00002409void PCHReader::InitializeSema(Sema &S) {
2410 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002411 S.ExternalSource = this;
2412
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002413 // Makes sure any declarations that were deserialized "too early"
2414 // still get added to the identifier's declaration chains.
2415 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2416 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2417 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002418 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002419 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002420
2421 // If there were any tentative definitions, deserialize them and add
2422 // them to Sema's table of tentative definitions.
2423 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2424 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2425 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner63d65f82009-09-08 18:19:27 +00002426 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002427 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002428
2429 // If there were any locally-scoped external declarations,
2430 // deserialize them and add them to Sema's table of locally-scoped
2431 // external declarations.
2432 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2433 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2434 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2435 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002436
2437 // If there were any ext_vector type declarations, deserialize them
2438 // and add them to Sema's vector of such declarations.
2439 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2440 SemaObj->ExtVectorDecls.push_back(
2441 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002442}
2443
2444IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2445 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002446 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002447 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2448 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2449 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2450 if (Pos == IdTable->end())
2451 return 0;
2452
2453 // Dereferencing the iterator has the effect of building the
2454 // IdentifierInfo node and populating it with the various
2455 // declarations it needs.
2456 return *Pos;
2457}
2458
Mike Stump1eb44332009-09-09 15:08:12 +00002459std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002460PCHReader::ReadMethodPool(Selector Sel) {
2461 if (!MethodPoolLookupTable)
2462 return std::pair<ObjCMethodList, ObjCMethodList>();
2463
2464 // Try to find this selector within our on-disk hash table.
2465 PCHMethodPoolLookupTable *PoolTable
2466 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2467 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002468 if (Pos == PoolTable->end()) {
2469 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002470 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002471 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002472
Douglas Gregor83941df2009-04-25 17:48:32 +00002473 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002474 return *Pos;
2475}
2476
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002477void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002478 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002479 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002480 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002481}
2482
Douglas Gregord89275b2009-07-06 18:54:52 +00002483/// \brief Set the globally-visible declarations associated with the given
2484/// identifier.
2485///
2486/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002487/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002488/// them.
2489///
2490/// \param II an IdentifierInfo that refers to one or more globally-visible
2491/// declarations.
2492///
2493/// \param DeclIDs the set of declaration IDs with the name @p II that are
2494/// visible at global scope.
2495///
2496/// \param Nonrecursive should be true to indicate that the caller knows that
2497/// this call is non-recursive, and therefore the globally-visible declarations
2498/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002499void
2500PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002501 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2502 bool Nonrecursive) {
2503 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2504 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2505 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2506 PII.II = II;
2507 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2508 PII.DeclIDs.push_back(DeclIDs[I]);
2509 return;
2510 }
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Douglas Gregord89275b2009-07-06 18:54:52 +00002512 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2513 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2514 if (SemaObj) {
2515 // Introduce this declaration into the translation-unit scope
2516 // and add it to the declaration chain for this identifier, so
2517 // that (unqualified) name lookup will find it.
2518 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2519 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2520 } else {
2521 // Queue this declaration so that it will be added to the
2522 // translation unit scope and identifier's declaration chain
2523 // once a Sema object is known.
2524 PreloadedDecls.push_back(D);
2525 }
2526 }
2527}
2528
Chris Lattner7356a312009-04-11 21:15:38 +00002529IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002530 if (ID == 0)
2531 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002533 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002534 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002535 return 0;
2536 }
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002538 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002539 if (!IdentifiersLoaded[ID - 1]) {
2540 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002541 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002542
Douglas Gregor02fc7512009-04-28 20:01:51 +00002543 // All of the strings in the PCH file are preceded by a 16-bit
2544 // length. Extract that 16-bit length to avoid having to execute
2545 // strlen().
Ted Kremenek231bc0b2009-10-23 04:45:31 +00002546 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
2547 // unsigned integers. This is important to avoid integer overflow when
2548 // we cast them to 'unsigned'.
Ted Kremenekff1ea462009-10-23 03:57:22 +00002549 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
Douglas Gregor02fc7512009-04-28 20:01:51 +00002550 unsigned StrLen = (((unsigned) StrLenPtr[0])
2551 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002552 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002553 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002554 }
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002556 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002557}
2558
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002559void PCHReader::ReadSLocEntry(unsigned ID) {
2560 ReadSLocEntryRecord(ID);
2561}
2562
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002563Selector PCHReader::DecodeSelector(unsigned ID) {
2564 if (ID == 0)
2565 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002566
Douglas Gregora02b1472009-04-28 21:53:25 +00002567 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002568 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002569
2570 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002571 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002572 return Selector();
2573 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002574
2575 unsigned Index = ID - 1;
2576 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2577 // Load this selector from the selector table.
2578 // FIXME: endianness portability issues with SelectorOffsets table
2579 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002580 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002581 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2582 }
2583
2584 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002585}
2586
Mike Stump1eb44332009-09-09 15:08:12 +00002587DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002588PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2589 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2590 switch (Kind) {
2591 case DeclarationName::Identifier:
2592 return DeclarationName(GetIdentifierInfo(Record, Idx));
2593
2594 case DeclarationName::ObjCZeroArgSelector:
2595 case DeclarationName::ObjCOneArgSelector:
2596 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002597 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002598
2599 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002600 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002601 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002602
2603 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002604 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002605 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002606
2607 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002608 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002609 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002610
2611 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002612 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002613 (OverloadedOperatorKind)Record[Idx++]);
2614
2615 case DeclarationName::CXXUsingDirective:
2616 return DeclarationName::getUsingDirectiveName();
2617 }
2618
2619 // Required to silence GCC warning
2620 return DeclarationName();
2621}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002622
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002623/// \brief Read an integral value
2624llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2625 unsigned BitWidth = Record[Idx++];
2626 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2627 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2628 Idx += NumWords;
2629 return Result;
2630}
2631
2632/// \brief Read a signed integral value
2633llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2634 bool isUnsigned = Record[Idx++];
2635 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2636}
2637
Douglas Gregor17fc2232009-04-14 21:55:33 +00002638/// \brief Read a floating-point value
2639llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002640 return llvm::APFloat(ReadAPInt(Record, Idx));
2641}
2642
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002643// \brief Read a string
2644std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2645 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002646 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002647 Idx += Len;
2648 return Result;
2649}
2650
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002651DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002652 return Diag(SourceLocation(), DiagID);
2653}
2654
2655DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002656 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002657}
Douglas Gregor025452f2009-04-17 00:04:06 +00002658
Douglas Gregor668c1a42009-04-21 22:25:48 +00002659/// \brief Retrieve the identifier table associated with the
2660/// preprocessor.
2661IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002662 assert(PP && "Forgot to set Preprocessor ?");
2663 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002664}
2665
Douglas Gregor025452f2009-04-17 00:04:06 +00002666/// \brief Record that the given ID maps to the given switch-case
2667/// statement.
2668void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2669 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2670 SwitchCaseStmts[ID] = SC;
2671}
2672
2673/// \brief Retrieve the switch-case statement with the given ID.
2674SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2675 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2676 return SwitchCaseStmts[ID];
2677}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002678
2679/// \brief Record that the given label statement has been
2680/// deserialized and has the given ID.
2681void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002682 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002683 "Deserialized label twice");
2684 LabelStmts[ID] = S;
2685
2686 // If we've already seen any goto statements that point to this
2687 // label, resolve them now.
2688 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2689 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2690 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2691 Goto->second->setLabel(S);
2692 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002693
2694 // If we've already seen any address-label statements that point to
2695 // this label, resolve them now.
2696 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002697 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002698 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002699 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002700 AddrLabel != AddrLabels.second; ++AddrLabel)
2701 AddrLabel->second->setLabel(S);
2702 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002703}
2704
2705/// \brief Set the label of the given statement to the label
2706/// identified by ID.
2707///
2708/// Depending on the order in which the label and other statements
2709/// referencing that label occur, this operation may complete
2710/// immediately (updating the statement) or it may queue the
2711/// statement to be back-patched later.
2712void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2713 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2714 if (Label != LabelStmts.end()) {
2715 // We've already seen this label, so set the label of the goto and
2716 // we're done.
2717 S->setLabel(Label->second);
2718 } else {
2719 // We haven't seen this label yet, so add this goto to the set of
2720 // unresolved goto statements.
2721 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2722 }
2723}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002724
2725/// \brief Set the label of the given expression to the label
2726/// identified by ID.
2727///
2728/// Depending on the order in which the label and other statements
2729/// referencing that label occur, this operation may complete
2730/// immediately (updating the statement) or it may queue the
2731/// statement to be back-patched later.
2732void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2733 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2734 if (Label != LabelStmts.end()) {
2735 // We've already seen this label, so set the label of the
2736 // label-address expression and we're done.
2737 S->setLabel(Label->second);
2738 } else {
2739 // We haven't seen this label yet, so add this label-address
2740 // expression to the set of unresolved label-address expressions.
2741 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2742 }
2743}
Douglas Gregord89275b2009-07-06 18:54:52 +00002744
2745
Mike Stump1eb44332009-09-09 15:08:12 +00002746PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00002747 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2748 Reader.CurrentlyLoadingTypeOrDecl = this;
2749}
2750
2751PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2752 if (!Parent) {
2753 // If any identifiers with corresponding top-level declarations have
2754 // been loaded, load those declarations now.
2755 while (!Reader.PendingIdentifierInfos.empty()) {
2756 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2757 Reader.PendingIdentifierInfos.front().DeclIDs,
2758 true);
2759 Reader.PendingIdentifierInfos.pop_front();
2760 }
2761 }
2762
Mike Stump1eb44332009-09-09 15:08:12 +00002763 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00002764}