blob: c02959f2cc790d3d029cc96adffb8574aabfdafc [file] [log] [blame]
Douglas Gregoref84c4b2009-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 Lattner92ba5ff2009-04-27 05:14:47 +000013
Douglas Gregoref84c4b2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor55abb232009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor1a0d0b92009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000021#include "clang/AST/TypeLocVisitor.h"
Chris Lattner34321bc2009-04-10 21:41:48 +000022#include "clang/Lex/MacroInfo.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000023#include "clang/Lex/Preprocessor.h"
Steve Naroff3fa455a2009-04-24 20:03:17 +000024#include "clang/Lex/HeaderSearch.h"
Douglas Gregora868bbd2009-04-21 22:25:48 +000025#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000026#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000027#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000028#include "clang/Basic/FileManager.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000029#include "clang/Basic/TargetInfo.h"
Douglas Gregord54f3a12009-10-05 21:07:28 +000030#include "clang/Basic/Version.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000031#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000032#include "llvm/Bitcode/BitstreamReader.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include <algorithm>
Douglas Gregorc379c072009-04-28 18:58:38 +000036#include <iterator>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000037#include <cstdio>
Douglas Gregorc5046832009-04-27 18:38:38 +000038#include <sys/stat.h>
Douglas Gregoref84c4b2009-04-09 22:27:44 +000039using namespace clang;
40
41//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000042// PCH reader validator implementation
43//===----------------------------------------------------------------------===//
44
45PCHReaderListener::~PCHReaderListener() {}
46
47bool
48PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
49 const LangOptions &PPLangOpts = PP.getLangOptions();
50#define PARSE_LANGOPT_BENIGN(Option)
51#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
52 if (PPLangOpts.Option != LangOpts.Option) { \
53 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
54 return true; \
55 }
56
57 PARSE_LANGOPT_BENIGN(Trigraphs);
58 PARSE_LANGOPT_BENIGN(BCPLComment);
59 PARSE_LANGOPT_BENIGN(DollarIdents);
60 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
61 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
62 PARSE_LANGOPT_BENIGN(ImplicitInt);
63 PARSE_LANGOPT_BENIGN(Digraphs);
64 PARSE_LANGOPT_BENIGN(HexFloats);
65 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
66 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
67 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
68 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
69 PARSE_LANGOPT_BENIGN(CXXOperatorName);
70 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
71 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
72 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
73 PARSE_LANGOPT_BENIGN(PascalStrings);
74 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump11289f42009-09-09 15:08:12 +000075 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000076 diag::warn_pch_lax_vector_conversions);
Nate Begeman9d905792009-06-25 22:57:40 +000077 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000078 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
79 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
80 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
81 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump11289f42009-09-09 15:08:12 +000082 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000083 diag::warn_pch_thread_safe_statics);
Daniel Dunbara77eaeb2009-09-03 04:54:28 +000084 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000085 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
86 PARSE_LANGOPT_BENIGN(EmitAllDecls);
87 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
88 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump11289f42009-09-09 15:08:12 +000089 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +000090 diag::warn_pch_heinous_extensions);
91 // FIXME: Most of the options below are benign if the macro wasn't
92 // used. Unfortunately, this means that a PCH compiled without
93 // optimization can't be used with optimization turned on, even
94 // though the only thing that changes is whether __OPTIMIZE__ was
95 // defined... but if __OPTIMIZE__ never showed up in the header, it
96 // doesn't matter. We could consider making this some special kind
97 // of check.
98 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
99 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
100 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
101 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
102 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
103 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
104 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
105 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
106 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump11289f42009-09-09 15:08:12 +0000107 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000108 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
109 return true;
110 }
111 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbar143021e2009-09-21 04:16:19 +0000112 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
113 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000114 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman9d905792009-06-25 22:57:40 +0000115 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbar143021e2009-09-21 04:16:19 +0000116 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000117#undef PARSE_LANGOPT_IRRELEVANT
118#undef PARSE_LANGOPT_BENIGN
119
120 return false;
121}
122
123bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
Daniel Dunbar40165182009-08-24 09:10:05 +0000124 if (Triple != PP.getTargetInfo().getTriple().getTriple()) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000125 Reader.Diag(diag::warn_pch_target_triple)
Daniel Dunbar40165182009-08-24 09:10:05 +0000126 << Triple << PP.getTargetInfo().getTriple().getTriple();
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000127 return true;
128 }
129 return false;
130}
131
132/// \brief Split the given string into a vector of lines, eliminating
133/// any empty lines in the process.
134///
135/// \param Str the string to split.
136/// \param Len the length of Str.
137/// \param KeepEmptyLines true if empty lines should be included
138/// \returns a vector of lines, with the line endings removed
139static std::vector<std::string> splitLines(const char *Str, unsigned Len,
140 bool KeepEmptyLines = false) {
141 std::vector<std::string> Lines;
142 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
143 unsigned LineEnd = LineStart;
144 while (LineEnd < Len && Str[LineEnd] != '\n')
145 ++LineEnd;
146 if (LineStart != LineEnd || KeepEmptyLines)
147 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
148 LineStart = LineEnd;
149 }
150 return Lines;
151}
152
153/// \brief Determine whether the string Haystack starts with the
154/// substring Needle.
155static bool startsWith(const std::string &Haystack, const char *Needle) {
156 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
157 if (I == N)
158 return false;
159 if (Haystack[I] != Needle[I])
160 return false;
161 }
162
163 return true;
164}
165
166/// \brief Determine whether the string Haystack starts with the
167/// substring Needle.
168static inline bool startsWith(const std::string &Haystack,
169 const std::string &Needle) {
170 return startsWith(Haystack, Needle.c_str());
171}
172
Mike Stump11289f42009-09-09 15:08:12 +0000173bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000174 unsigned PCHPredefLen,
175 FileID PCHBufferID,
176 std::string &SuggestedPredefines) {
177 const char *Predef = PP.getPredefines().c_str();
178 unsigned PredefLen = PP.getPredefines().size();
179
180 // If the two predefines buffers compare equal, we're done!
Mike Stump11289f42009-09-09 15:08:12 +0000181 if (PredefLen == PCHPredefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000182 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
183 return false;
184
185 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +0000186
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000187 // The predefines buffers are different. Determine what the
188 // differences are, and whether they require us to reject the PCH
189 // file.
190 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
191 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
192
Mike Stump11289f42009-09-09 15:08:12 +0000193 // Sort both sets of predefined buffer lines, since
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000194 std::sort(CmdLineLines.begin(), CmdLineLines.end());
195 std::sort(PCHLines.begin(), PCHLines.end());
196
197 // Determine which predefines that where used to build the PCH file
198 // are missing from the command line.
199 std::vector<std::string> MissingPredefines;
200 std::set_difference(PCHLines.begin(), PCHLines.end(),
201 CmdLineLines.begin(), CmdLineLines.end(),
202 std::back_inserter(MissingPredefines));
203
204 bool MissingDefines = false;
205 bool ConflictingDefines = false;
206 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
207 const std::string &Missing = MissingPredefines[I];
208 if (!startsWith(Missing, "#define ") != 0) {
209 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
210 return true;
211 }
Mike Stump11289f42009-09-09 15:08:12 +0000212
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000213 // This is a macro definition. Determine the name of the macro
214 // we're defining.
215 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000216 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000217 = Missing.find_first_of("( \n\r", StartOfMacroName);
218 assert(EndOfMacroName != std::string::npos &&
219 "Couldn't find the end of the macro name");
220 std::string MacroName = Missing.substr(StartOfMacroName,
221 EndOfMacroName - StartOfMacroName);
222
223 // Determine whether this macro was given a different definition
224 // on the command line.
225 std::string MacroDefStart = "#define " + MacroName;
226 std::string::size_type MacroDefLen = MacroDefStart.size();
227 std::vector<std::string>::iterator ConflictPos
228 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
229 MacroDefStart);
230 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
231 if (!startsWith(*ConflictPos, MacroDefStart)) {
232 // Different macro; we're done.
233 ConflictPos = CmdLineLines.end();
Mike Stump11289f42009-09-09 15:08:12 +0000234 break;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000235 }
Mike Stump11289f42009-09-09 15:08:12 +0000236
237 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000238 "Invalid #define in predefines buffer?");
Mike Stump11289f42009-09-09 15:08:12 +0000239 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000240 (*ConflictPos)[MacroDefLen] != '(')
241 continue; // Longer macro name; keep trying.
Mike Stump11289f42009-09-09 15:08:12 +0000242
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000243 // We found a conflicting macro definition.
244 break;
245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000247 if (ConflictPos != CmdLineLines.end()) {
248 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
249 << MacroName;
250
251 // Show the definition of this macro within the PCH file.
252 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
253 unsigned Offset = MissingDef - PCHPredef;
254 SourceLocation PCHMissingLoc
255 = SourceMgr.getLocForStartOfFile(PCHBufferID)
256 .getFileLocWithOffset(Offset);
257 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
258 << MacroName;
259
260 ConflictingDefines = true;
261 continue;
262 }
Mike Stump11289f42009-09-09 15:08:12 +0000263
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000264 // If the macro doesn't conflict, then we'll just pick up the
265 // macro definition from the PCH file. Warn the user that they
266 // made a mistake.
267 if (ConflictingDefines)
268 continue; // Don't complain if there are already conflicting defs
Mike Stump11289f42009-09-09 15:08:12 +0000269
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000270 if (!MissingDefines) {
271 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
272 MissingDefines = true;
273 }
274
275 // Show the definition of this macro within the PCH file.
276 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
277 unsigned Offset = MissingDef - PCHPredef;
278 SourceLocation PCHMissingLoc
279 = SourceMgr.getLocForStartOfFile(PCHBufferID)
280 .getFileLocWithOffset(Offset);
281 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
282 }
Mike Stump11289f42009-09-09 15:08:12 +0000283
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000284 if (ConflictingDefines)
285 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000286
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000287 // Determine what predefines were introduced based on command-line
288 // parameters that were not present when building the PCH
289 // file. Extra #defines are okay, so long as the identifiers being
290 // defined were not used within the precompiled header.
291 std::vector<std::string> ExtraPredefines;
292 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
293 PCHLines.begin(), PCHLines.end(),
Mike Stump11289f42009-09-09 15:08:12 +0000294 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000295 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
296 const std::string &Extra = ExtraPredefines[I];
297 if (!startsWith(Extra, "#define ") != 0) {
298 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
299 return true;
300 }
301
302 // This is an extra macro definition. Determine the name of the
303 // macro we're defining.
304 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump11289f42009-09-09 15:08:12 +0000305 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000306 = Extra.find_first_of("( \n\r", StartOfMacroName);
307 assert(EndOfMacroName != std::string::npos &&
308 "Couldn't find the end of the macro name");
309 std::string MacroName = Extra.substr(StartOfMacroName,
310 EndOfMacroName - StartOfMacroName);
311
312 // Check whether this name was used somewhere in the PCH file. If
313 // so, defining it as a macro could change behavior, so we reject
314 // the PCH file.
315 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
316 MacroName.c_str() + MacroName.size())) {
317 Reader.Diag(diag::warn_macro_name_used_in_pch)
318 << II;
319 return true;
320 }
321
322 // Add this definition to the suggested predefines buffer.
323 SuggestedPredefines += Extra;
324 SuggestedPredefines += '\n';
325 }
326
327 // If we get here, it's because the predefines buffer had compatible
328 // contents. Accept the PCH file.
329 return false;
330}
331
332void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
333 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
334}
335
336void PCHValidator::ReadCounter(unsigned Value) {
337 PP.setCounterValue(Value);
338}
339
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000340//===----------------------------------------------------------------------===//
Douglas Gregora868bbd2009-04-21 22:25:48 +0000341// PCH reader implementation
342//===----------------------------------------------------------------------===//
343
Mike Stump11289f42009-09-09 15:08:12 +0000344PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
345 const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000346 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
347 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000348 SemaObj(0), PP(&PP), Context(Context), StatCache(0), Consumer(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000349 IdentifierTableData(0), IdentifierLookupTable(0),
350 IdentifierOffsets(0),
351 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
352 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000353 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000354 NumStatHits(0), NumStatMisses(0),
355 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000356 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000357 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000358 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000359 RelocatablePCH = false;
360}
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000361
362PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump11289f42009-09-09 15:08:12 +0000363 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000364 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000365 SemaObj(0), PP(0), Context(0), StatCache(0), Consumer(0),
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000366 IdentifierTableData(0), IdentifierLookupTable(0),
367 IdentifierOffsets(0),
368 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
369 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000370 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump11289f42009-09-09 15:08:12 +0000371 NumStatHits(0), NumStatMisses(0),
372 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor258ae542009-04-27 06:38:32 +0000373 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregor1342e842009-07-06 18:54:52 +0000374 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump11289f42009-09-09 15:08:12 +0000375 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000376 RelocatablePCH = false;
377}
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000378
379PCHReader::~PCHReader() {}
380
Chris Lattner1de76db2009-04-27 05:58:23 +0000381Expr *PCHReader::ReadDeclExpr() {
382 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
383}
384
385Expr *PCHReader::ReadTypeExpr() {
Douglas Gregor12bfa382009-10-17 00:13:19 +0000386 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
Chris Lattner92ba5ff2009-04-27 05:14:47 +0000387}
388
389
Douglas Gregora868bbd2009-04-21 22:25:48 +0000390namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000391class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
392 PCHReader &Reader;
393
394public:
395 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
396
397 typedef Selector external_key_type;
398 typedef external_key_type internal_key_type;
399
400 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
Mike Stump11289f42009-09-09 15:08:12 +0000401
Douglas Gregorc78d3462009-04-24 21:10:55 +0000402 static bool EqualKey(const internal_key_type& a,
403 const internal_key_type& b) {
404 return a == b;
405 }
Mike Stump11289f42009-09-09 15:08:12 +0000406
Douglas Gregorc78d3462009-04-24 21:10:55 +0000407 static unsigned ComputeHash(Selector Sel) {
408 unsigned N = Sel.getNumArgs();
409 if (N == 0)
410 ++N;
411 unsigned R = 5381;
412 for (unsigned I = 0; I != N; ++I)
413 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000414 R = llvm::HashString(II->getName(), R);
Douglas Gregorc78d3462009-04-24 21:10:55 +0000415 return R;
416 }
Mike Stump11289f42009-09-09 15:08:12 +0000417
Douglas Gregorc78d3462009-04-24 21:10:55 +0000418 // This hopefully will just get inlined and removed by the optimizer.
419 static const internal_key_type&
420 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000421
Douglas Gregorc78d3462009-04-24 21:10:55 +0000422 static std::pair<unsigned, unsigned>
423 ReadKeyDataLength(const unsigned char*& d) {
424 using namespace clang::io;
425 unsigned KeyLen = ReadUnalignedLE16(d);
426 unsigned DataLen = ReadUnalignedLE16(d);
427 return std::make_pair(KeyLen, DataLen);
428 }
Mike Stump11289f42009-09-09 15:08:12 +0000429
Douglas Gregor95c13f52009-04-25 17:48:32 +0000430 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc78d3462009-04-24 21:10:55 +0000431 using namespace clang::io;
Chris Lattner8575daa2009-04-27 21:45:14 +0000432 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc78d3462009-04-24 21:10:55 +0000433 unsigned N = ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000434 IdentifierInfo *FirstII
Douglas Gregorc78d3462009-04-24 21:10:55 +0000435 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
436 if (N == 0)
437 return SelTable.getNullarySelector(FirstII);
438 else if (N == 1)
439 return SelTable.getUnarySelector(FirstII);
440
441 llvm::SmallVector<IdentifierInfo *, 16> Args;
442 Args.push_back(FirstII);
443 for (unsigned I = 1; I != N; ++I)
444 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
445
Douglas Gregor038c3382009-05-22 22:45:36 +0000446 return SelTable.getSelector(N, Args.data());
Douglas Gregorc78d3462009-04-24 21:10:55 +0000447 }
Mike Stump11289f42009-09-09 15:08:12 +0000448
Douglas Gregorc78d3462009-04-24 21:10:55 +0000449 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
450 using namespace clang::io;
451 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
452 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
453
454 data_type Result;
455
456 // Load instance methods
457 ObjCMethodList *Prev = 0;
458 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000459 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000460 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
461 if (!Result.first.Method) {
462 // This is the first method, which is the easy case.
463 Result.first.Method = Method;
464 Prev = &Result.first;
465 continue;
466 }
467
468 Prev->Next = new ObjCMethodList(Method, 0);
469 Prev = Prev->Next;
470 }
471
472 // Load factory methods
473 Prev = 0;
474 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000475 ObjCMethodDecl *Method
Douglas Gregorc78d3462009-04-24 21:10:55 +0000476 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
477 if (!Result.second.Method) {
478 // This is the first method, which is the easy case.
479 Result.second.Method = Method;
480 Prev = &Result.second;
481 continue;
482 }
483
484 Prev->Next = new ObjCMethodList(Method, 0);
485 Prev = Prev->Next;
486 }
487
488 return Result;
489 }
490};
Mike Stump11289f42009-09-09 15:08:12 +0000491
492} // end anonymous namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +0000493
494/// \brief The on-disk hash table used for the global method pool.
Mike Stump11289f42009-09-09 15:08:12 +0000495typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorc78d3462009-04-24 21:10:55 +0000496 PCHMethodPoolLookupTable;
497
498namespace {
Douglas Gregora868bbd2009-04-21 22:25:48 +0000499class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
500 PCHReader &Reader;
501
502 // If we know the IdentifierInfo in advance, it is here and we will
503 // not build a new one. Used when deserializing information about an
504 // identifier that was constructed before the PCH file was read.
505 IdentifierInfo *KnownII;
506
507public:
508 typedef IdentifierInfo * data_type;
509
510 typedef const std::pair<const char*, unsigned> external_key_type;
511
512 typedef external_key_type internal_key_type;
513
Mike Stump11289f42009-09-09 15:08:12 +0000514 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregora868bbd2009-04-21 22:25:48 +0000515 : Reader(Reader), KnownII(II) { }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Douglas Gregora868bbd2009-04-21 22:25:48 +0000517 static bool EqualKey(const internal_key_type& a,
518 const internal_key_type& b) {
519 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
520 : false;
521 }
Mike Stump11289f42009-09-09 15:08:12 +0000522
Douglas Gregora868bbd2009-04-21 22:25:48 +0000523 static unsigned ComputeHash(const internal_key_type& a) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000524 return llvm::HashString(llvm::StringRef(a.first, a.second));
Douglas Gregora868bbd2009-04-21 22:25:48 +0000525 }
Mike Stump11289f42009-09-09 15:08:12 +0000526
Douglas Gregora868bbd2009-04-21 22:25:48 +0000527 // This hopefully will just get inlined and removed by the optimizer.
528 static const internal_key_type&
529 GetInternalKey(const external_key_type& x) { return x; }
Mike Stump11289f42009-09-09 15:08:12 +0000530
Douglas Gregora868bbd2009-04-21 22:25:48 +0000531 static std::pair<unsigned, unsigned>
532 ReadKeyDataLength(const unsigned char*& d) {
533 using namespace clang::io;
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000534 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor5287b4e2009-04-25 21:04:17 +0000535 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000536 return std::make_pair(KeyLen, DataLen);
537 }
Mike Stump11289f42009-09-09 15:08:12 +0000538
Douglas Gregora868bbd2009-04-21 22:25:48 +0000539 static std::pair<const char*, unsigned>
540 ReadKey(const unsigned char* d, unsigned n) {
541 assert(n >= 2 && d[n-1] == '\0');
542 return std::make_pair((const char*) d, n-1);
543 }
Mike Stump11289f42009-09-09 15:08:12 +0000544
545 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregora868bbd2009-04-21 22:25:48 +0000546 const unsigned char* d,
547 unsigned DataLen) {
548 using namespace clang::io;
Douglas Gregor1d583f22009-04-28 21:18:29 +0000549 pch::IdentID ID = ReadUnalignedLE32(d);
550 bool IsInteresting = ID & 0x01;
551
552 // Wipe out the "is interesting" bit.
553 ID = ID >> 1;
554
555 if (!IsInteresting) {
556 // For unintersting identifiers, just build the IdentifierInfo
557 // and associate it with the persistent ID.
558 IdentifierInfo *II = KnownII;
559 if (!II)
560 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
561 k.first, k.first + k.second);
562 Reader.SetIdentifierInfo(ID, II);
563 return II;
564 }
565
Douglas Gregorb9256522009-04-28 21:32:13 +0000566 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000567 bool CPlusPlusOperatorKeyword = Bits & 0x01;
568 Bits >>= 1;
569 bool Poisoned = Bits & 0x01;
570 Bits >>= 1;
571 bool ExtensionToken = Bits & 0x01;
572 Bits >>= 1;
573 bool hasMacroDefinition = Bits & 0x01;
574 Bits >>= 1;
575 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
576 Bits >>= 10;
Mike Stump11289f42009-09-09 15:08:12 +0000577
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000578 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorb9256522009-04-28 21:32:13 +0000579 DataLen -= 6;
Douglas Gregora868bbd2009-04-21 22:25:48 +0000580
581 // Build the IdentifierInfo itself and link the identifier ID with
582 // the new IdentifierInfo.
583 IdentifierInfo *II = KnownII;
584 if (!II)
Douglas Gregor6b7bf5a2009-04-25 20:26:24 +0000585 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
586 k.first, k.first + k.second);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000587 Reader.SetIdentifierInfo(ID, II);
588
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000589 // Set or check the various bits in the IdentifierInfo structure.
590 // FIXME: Load token IDs lazily, too?
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000591 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump11289f42009-09-09 15:08:12 +0000592 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor4621c6a2009-04-22 18:49:13 +0000593 "Incorrect extension token flag");
594 (void)ExtensionToken;
595 II->setIsPoisoned(Poisoned);
596 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
597 "Incorrect C++ operator keyword flag");
598 (void)CPlusPlusOperatorKeyword;
599
Douglas Gregorc3366a52009-04-21 23:56:24 +0000600 // If this identifier is a macro, deserialize the macro
601 // definition.
602 if (hasMacroDefinition) {
Douglas Gregorb9256522009-04-28 21:32:13 +0000603 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregorc3366a52009-04-21 23:56:24 +0000604 Reader.ReadMacroRecord(Offset);
Douglas Gregorb9256522009-04-28 21:32:13 +0000605 DataLen -= 4;
Douglas Gregorc3366a52009-04-21 23:56:24 +0000606 }
Douglas Gregora868bbd2009-04-21 22:25:48 +0000607
608 // Read all of the declarations visible at global scope with this
609 // name.
Chris Lattner1d728882009-04-27 22:17:41 +0000610 if (Reader.getContext() == 0) return II;
Douglas Gregor1342e842009-07-06 18:54:52 +0000611 if (DataLen > 0) {
612 llvm::SmallVector<uint32_t, 4> DeclIDs;
613 for (; DataLen > 0; DataLen -= 4)
614 DeclIDs.push_back(ReadUnalignedLE32(d));
615 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregora868bbd2009-04-21 22:25:48 +0000616 }
Mike Stump11289f42009-09-09 15:08:12 +0000617
Douglas Gregora868bbd2009-04-21 22:25:48 +0000618 return II;
619 }
620};
Mike Stump11289f42009-09-09 15:08:12 +0000621
622} // end anonymous namespace
Douglas Gregora868bbd2009-04-21 22:25:48 +0000623
624/// \brief The on-disk hash table used to contain information about
625/// all of the identifiers in the program.
Mike Stump11289f42009-09-09 15:08:12 +0000626typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregora868bbd2009-04-21 22:25:48 +0000627 PCHIdentifierLookupTable;
628
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000629bool PCHReader::Error(const char *Msg) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000630 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
631 Diag(DiagID);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000632 return true;
633}
634
Douglas Gregor92863e42009-04-10 23:10:45 +0000635/// \brief Check the contents of the predefines buffer against the
636/// contents of the predefines buffer used to build the PCH file.
637///
638/// The contents of the two predefines buffers should be the same. If
639/// not, then some command-line option changed the preprocessor state
640/// and we must reject the PCH file.
641///
642/// \param PCHPredef The start of the predefines buffer in the PCH
643/// file.
644///
645/// \param PCHPredefLen The length of the predefines buffer in the PCH
646/// file.
647///
648/// \param PCHBufferID The FileID for the PCH predefines buffer.
649///
650/// \returns true if there was a mismatch (in which case the PCH file
651/// should be ignored), or false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +0000652bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
Douglas Gregor92863e42009-04-10 23:10:45 +0000653 unsigned PCHPredefLen,
654 FileID PCHBufferID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000655 if (Listener)
656 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
657 SuggestedPredefines);
Douglas Gregorc379c072009-04-28 18:58:38 +0000658 return false;
Douglas Gregor92863e42009-04-10 23:10:45 +0000659}
660
Douglas Gregorc5046832009-04-27 18:38:38 +0000661//===----------------------------------------------------------------------===//
662// Source Manager Deserialization
663//===----------------------------------------------------------------------===//
664
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000665/// \brief Read the line table in the source manager block.
666/// \returns true if ther was an error.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000667bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000668 unsigned Idx = 0;
669 LineTableInfo &LineTable = SourceMgr.getLineTable();
670
671 // Parse the file names
Douglas Gregora8854652009-04-13 17:12:42 +0000672 std::map<int, int> FileIDs;
673 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000674 // Extract the file name
675 unsigned FilenameLen = Record[Idx++];
676 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
677 Idx += FilenameLen;
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000678 MaybeAddSystemRootToFilename(Filename);
Mike Stump11289f42009-09-09 15:08:12 +0000679 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregora8854652009-04-13 17:12:42 +0000680 Filename.size());
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000681 }
682
683 // Parse the line entries
684 std::vector<LineEntry> Entries;
685 while (Idx < Record.size()) {
Douglas Gregora8854652009-04-13 17:12:42 +0000686 int FID = FileIDs[Record[Idx++]];
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000687
688 // Extract the line entries
689 unsigned NumEntries = Record[Idx++];
690 Entries.clear();
691 Entries.reserve(NumEntries);
692 for (unsigned I = 0; I != NumEntries; ++I) {
693 unsigned FileOffset = Record[Idx++];
694 unsigned LineNo = Record[Idx++];
695 int FilenameID = Record[Idx++];
Mike Stump11289f42009-09-09 15:08:12 +0000696 SrcMgr::CharacteristicKind FileKind
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000697 = (SrcMgr::CharacteristicKind)Record[Idx++];
698 unsigned IncludeOffset = Record[Idx++];
699 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
700 FileKind, IncludeOffset));
701 }
702 LineTable.AddEntry(FID, Entries);
703 }
704
705 return false;
706}
707
Douglas Gregorc5046832009-04-27 18:38:38 +0000708namespace {
709
710class VISIBILITY_HIDDEN PCHStatData {
711public:
712 const bool hasStat;
713 const ino_t ino;
714 const dev_t dev;
715 const mode_t mode;
716 const time_t mtime;
717 const off_t size;
Mike Stump11289f42009-09-09 15:08:12 +0000718
Douglas Gregorc5046832009-04-27 18:38:38 +0000719 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump11289f42009-09-09 15:08:12 +0000720 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
721
Douglas Gregorc5046832009-04-27 18:38:38 +0000722 PCHStatData()
723 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
724};
725
726class VISIBILITY_HIDDEN PCHStatLookupTrait {
727 public:
728 typedef const char *external_key_type;
729 typedef const char *internal_key_type;
730
731 typedef PCHStatData data_type;
732
733 static unsigned ComputeHash(const char *path) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +0000734 return llvm::HashString(path);
Douglas Gregorc5046832009-04-27 18:38:38 +0000735 }
736
737 static internal_key_type GetInternalKey(const char *path) { return path; }
738
739 static bool EqualKey(internal_key_type a, internal_key_type b) {
740 return strcmp(a, b) == 0;
741 }
742
743 static std::pair<unsigned, unsigned>
744 ReadKeyDataLength(const unsigned char*& d) {
745 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
746 unsigned DataLen = (unsigned) *d++;
747 return std::make_pair(KeyLen + 1, DataLen);
748 }
749
750 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
751 return (const char *)d;
752 }
753
754 static data_type ReadData(const internal_key_type, const unsigned char *d,
755 unsigned /*DataLen*/) {
756 using namespace clang::io;
757
758 if (*d++ == 1)
759 return data_type();
760
761 ino_t ino = (ino_t) ReadUnalignedLE32(d);
762 dev_t dev = (dev_t) ReadUnalignedLE32(d);
763 mode_t mode = (mode_t) ReadUnalignedLE16(d);
Mike Stump11289f42009-09-09 15:08:12 +0000764 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregorc5046832009-04-27 18:38:38 +0000765 off_t size = (off_t) ReadUnalignedLE64(d);
766 return data_type(ino, dev, mode, mtime, size);
767 }
768};
769
770/// \brief stat() cache for precompiled headers.
771///
772/// This cache is very similar to the stat cache used by pretokenized
773/// headers.
774class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
775 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
776 CacheTy *Cache;
777
778 unsigned &NumStatHits, &NumStatMisses;
Mike Stump11289f42009-09-09 15:08:12 +0000779public:
Douglas Gregorc5046832009-04-27 18:38:38 +0000780 PCHStatCache(const unsigned char *Buckets,
781 const unsigned char *Base,
782 unsigned &NumStatHits,
Mike Stump11289f42009-09-09 15:08:12 +0000783 unsigned &NumStatMisses)
Douglas Gregorc5046832009-04-27 18:38:38 +0000784 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
785 Cache = CacheTy::Create(Buckets, Base);
786 }
787
788 ~PCHStatCache() { delete Cache; }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Douglas Gregorc5046832009-04-27 18:38:38 +0000790 int stat(const char *path, struct stat *buf) {
791 // Do the lookup for the file's data in the PCH file.
792 CacheTy::iterator I = Cache->find(path);
793
794 // If we don't get a hit in the PCH file just forward to 'stat'.
795 if (I == Cache->end()) {
796 ++NumStatMisses;
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000797 return StatSysCallCache::stat(path, buf);
Douglas Gregorc5046832009-04-27 18:38:38 +0000798 }
Mike Stump11289f42009-09-09 15:08:12 +0000799
Douglas Gregorc5046832009-04-27 18:38:38 +0000800 ++NumStatHits;
801 PCHStatData Data = *I;
Mike Stump11289f42009-09-09 15:08:12 +0000802
Douglas Gregorc5046832009-04-27 18:38:38 +0000803 if (!Data.hasStat)
804 return 1;
805
806 buf->st_ino = Data.ino;
807 buf->st_dev = Data.dev;
808 buf->st_mtime = Data.mtime;
809 buf->st_mode = Data.mode;
810 buf->st_size = Data.size;
811 return 0;
812 }
813};
814} // end anonymous namespace
815
816
Douglas Gregora7f71a92009-04-10 03:52:48 +0000817/// \brief Read the source manager block
Douglas Gregor92863e42009-04-10 23:10:45 +0000818PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000819 using namespace SrcMgr;
Douglas Gregor258ae542009-04-27 06:38:32 +0000820
821 // Set the source-location entry cursor to the current position in
822 // the stream. This cursor will be used to read the contents of the
823 // source manager block initially, and then lazily read
824 // source-location entries as needed.
825 SLocEntryCursor = Stream;
826
827 // The stream itself is going to skip over the source manager block.
828 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000829 Error("malformed block record in PCH file");
Douglas Gregor258ae542009-04-27 06:38:32 +0000830 return Failure;
831 }
832
833 // Enter the source manager block.
834 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000835 Error("malformed source manager block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000836 return Failure;
837 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000838
Douglas Gregora7f71a92009-04-10 03:52:48 +0000839 RecordData Record;
840 while (true) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000841 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000842 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000843 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000844 Error("error at end of Source Manager block in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000845 return Failure;
846 }
Douglas Gregor92863e42009-04-10 23:10:45 +0000847 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000848 }
Mike Stump11289f42009-09-09 15:08:12 +0000849
Douglas Gregora7f71a92009-04-10 03:52:48 +0000850 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
851 // No known subblocks, always skip them.
Douglas Gregor258ae542009-04-27 06:38:32 +0000852 SLocEntryCursor.ReadSubBlockID();
853 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000854 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +0000855 return Failure;
856 }
Douglas Gregora7f71a92009-04-10 03:52:48 +0000857 continue;
858 }
Mike Stump11289f42009-09-09 15:08:12 +0000859
Douglas Gregora7f71a92009-04-10 03:52:48 +0000860 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor258ae542009-04-27 06:38:32 +0000861 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregora7f71a92009-04-10 03:52:48 +0000862 continue;
863 }
Mike Stump11289f42009-09-09 15:08:12 +0000864
Douglas Gregora7f71a92009-04-10 03:52:48 +0000865 // Read a record.
866 const char *BlobStart;
867 unsigned BlobLen;
868 Record.clear();
Douglas Gregor258ae542009-04-27 06:38:32 +0000869 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregora7f71a92009-04-10 03:52:48 +0000870 default: // Default behavior: ignore.
871 break;
872
Chris Lattner184e65d2009-04-14 23:22:57 +0000873 case pch::SM_LINE_TABLE:
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000874 if (ParseLineTable(Record))
Douglas Gregor4c7626e2009-04-13 16:31:14 +0000875 return Failure;
Chris Lattner184e65d2009-04-14 23:22:57 +0000876 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +0000877
878 case pch::SM_HEADER_FILE_INFO: {
879 HeaderFileInfo HFI;
880 HFI.isImport = Record[0];
881 HFI.DirInfo = Record[1];
882 HFI.NumIncludes = Record[2];
883 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +0000884 if (Listener)
885 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregoreda6a892009-04-26 00:07:37 +0000886 break;
887 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000888
889 case pch::SM_SLOC_FILE_ENTRY:
890 case pch::SM_SLOC_BUFFER_ENTRY:
891 case pch::SM_SLOC_INSTANTIATION_ENTRY:
892 // Once we hit one of the source location entries, we're done.
893 return Success;
Douglas Gregora7f71a92009-04-10 03:52:48 +0000894 }
895 }
896}
897
Douglas Gregor258ae542009-04-27 06:38:32 +0000898/// \brief Read in the source location entry with the given ID.
899PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
900 if (ID == 0)
901 return Success;
902
903 if (ID > TotalNumSLocEntries) {
904 Error("source location entry ID out-of-range for PCH file");
905 return Failure;
906 }
907
908 ++NumSLocEntriesRead;
909 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
910 unsigned Code = SLocEntryCursor.ReadCode();
911 if (Code == llvm::bitc::END_BLOCK ||
912 Code == llvm::bitc::ENTER_SUBBLOCK ||
913 Code == llvm::bitc::DEFINE_ABBREV) {
914 Error("incorrectly-formatted source location entry in PCH file");
915 return Failure;
916 }
917
Douglas Gregor258ae542009-04-27 06:38:32 +0000918 RecordData Record;
919 const char *BlobStart;
920 unsigned BlobLen;
921 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
922 default:
923 Error("incorrectly-formatted source location entry in PCH file");
924 return Failure;
925
926 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000927 std::string Filename(BlobStart, BlobStart + BlobLen);
928 MaybeAddSystemRootToFilename(Filename);
929 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd20dc872009-06-15 04:35:16 +0000930 if (File == 0) {
931 std::string ErrorStr = "could not find file '";
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000932 ErrorStr += Filename;
Chris Lattnerd20dc872009-06-15 04:35:16 +0000933 ErrorStr += "' referenced by PCH file";
934 Error(ErrorStr.c_str());
935 return Failure;
936 }
Mike Stump11289f42009-09-09 15:08:12 +0000937
Douglas Gregor258ae542009-04-27 06:38:32 +0000938 FileID FID = SourceMgr.createFileID(File,
939 SourceLocation::getFromRawEncoding(Record[1]),
940 (SrcMgr::CharacteristicKind)Record[2],
941 ID, Record[0]);
942 if (Record[3])
943 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
944 .setHasLineDirectives();
945
946 break;
947 }
948
949 case pch::SM_SLOC_BUFFER_ENTRY: {
950 const char *Name = BlobStart;
951 unsigned Offset = Record[0];
952 unsigned Code = SLocEntryCursor.ReadCode();
953 Record.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000954 unsigned RecCode
Douglas Gregor258ae542009-04-27 06:38:32 +0000955 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
956 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
957 (void)RecCode;
958 llvm::MemoryBuffer *Buffer
Mike Stump11289f42009-09-09 15:08:12 +0000959 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor258ae542009-04-27 06:38:32 +0000960 BlobStart + BlobLen - 1,
961 Name);
962 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump11289f42009-09-09 15:08:12 +0000963
Douglas Gregore6648fb2009-04-28 20:33:11 +0000964 if (strcmp(Name, "<built-in>") == 0) {
965 PCHPredefinesBufferID = BufferID;
966 PCHPredefines = BlobStart;
967 PCHPredefinesLen = BlobLen - 1;
968 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000969
970 break;
971 }
972
973 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump11289f42009-09-09 15:08:12 +0000974 SourceLocation SpellingLoc
Douglas Gregor258ae542009-04-27 06:38:32 +0000975 = SourceLocation::getFromRawEncoding(Record[1]);
976 SourceMgr.createInstantiationLoc(SpellingLoc,
977 SourceLocation::getFromRawEncoding(Record[2]),
978 SourceLocation::getFromRawEncoding(Record[3]),
979 Record[4],
980 ID,
981 Record[0]);
982 break;
Mike Stump11289f42009-09-09 15:08:12 +0000983 }
Douglas Gregor258ae542009-04-27 06:38:32 +0000984 }
985
986 return Success;
987}
988
Chris Lattnere78a6be2009-04-27 01:05:14 +0000989/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
990/// specified cursor. Read the abbreviations that are at the top of the block
991/// and then leave the cursor pointing into the block.
992bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
993 unsigned BlockID) {
994 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +0000995 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +0000996 return Failure;
997 }
Mike Stump11289f42009-09-09 15:08:12 +0000998
Chris Lattnere78a6be2009-04-27 01:05:14 +0000999 while (true) {
1000 unsigned Code = Cursor.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001001
Chris Lattnere78a6be2009-04-27 01:05:14 +00001002 // We expect all abbrevs to be at the start of the block.
1003 if (Code != llvm::bitc::DEFINE_ABBREV)
1004 return false;
1005 Cursor.ReadAbbrevRecord();
1006 }
1007}
1008
Douglas Gregorc3366a52009-04-21 23:56:24 +00001009void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001010 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump11289f42009-09-09 15:08:12 +00001011
Douglas Gregorc3366a52009-04-21 23:56:24 +00001012 // Keep track of where we are in the stream, then jump back there
1013 // after reading this macro.
1014 SavedStreamPosition SavedPosition(Stream);
1015
1016 Stream.JumpToBit(Offset);
1017 RecordData Record;
1018 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1019 MacroInfo *Macro = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001020
Douglas Gregorc3366a52009-04-21 23:56:24 +00001021 while (true) {
1022 unsigned Code = Stream.ReadCode();
1023 switch (Code) {
1024 case llvm::bitc::END_BLOCK:
1025 return;
1026
1027 case llvm::bitc::ENTER_SUBBLOCK:
1028 // No known subblocks, always skip them.
1029 Stream.ReadSubBlockID();
1030 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001031 Error("malformed block record in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001032 return;
1033 }
1034 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001035
Douglas Gregorc3366a52009-04-21 23:56:24 +00001036 case llvm::bitc::DEFINE_ABBREV:
1037 Stream.ReadAbbrevRecord();
1038 continue;
1039 default: break;
1040 }
1041
1042 // Read a record.
1043 Record.clear();
1044 pch::PreprocessorRecordTypes RecType =
1045 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1046 switch (RecType) {
Douglas Gregorc3366a52009-04-21 23:56:24 +00001047 case pch::PP_MACRO_OBJECT_LIKE:
1048 case pch::PP_MACRO_FUNCTION_LIKE: {
1049 // If we already have a macro, that means that we've hit the end
1050 // of the definition of the macro we were looking for. We're
1051 // done.
1052 if (Macro)
1053 return;
1054
1055 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1056 if (II == 0) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001057 Error("macro must have a name in PCH file");
Douglas Gregorc3366a52009-04-21 23:56:24 +00001058 return;
1059 }
1060 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1061 bool isUsed = Record[2];
Mike Stump11289f42009-09-09 15:08:12 +00001062
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001063 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001064 MI->setIsUsed(isUsed);
Mike Stump11289f42009-09-09 15:08:12 +00001065
Douglas Gregorc3366a52009-04-21 23:56:24 +00001066 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1067 // Decode function-like macro info.
1068 bool isC99VarArgs = Record[3];
1069 bool isGNUVarArgs = Record[4];
1070 MacroArgs.clear();
1071 unsigned NumArgs = Record[5];
1072 for (unsigned i = 0; i != NumArgs; ++i)
1073 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1074
1075 // Install function-like macro info.
1076 MI->setIsFunctionLike();
1077 if (isC99VarArgs) MI->setIsC99Varargs();
1078 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor038c3382009-05-22 22:45:36 +00001079 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001080 PP->getPreprocessorAllocator());
Douglas Gregorc3366a52009-04-21 23:56:24 +00001081 }
1082
1083 // Finally, install the macro.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001084 PP->setMacroInfo(II, MI);
Douglas Gregorc3366a52009-04-21 23:56:24 +00001085
1086 // Remember that we saw this macro last so that we add the tokens that
1087 // form its body to it.
1088 Macro = MI;
1089 ++NumMacrosRead;
1090 break;
1091 }
Mike Stump11289f42009-09-09 15:08:12 +00001092
Douglas Gregorc3366a52009-04-21 23:56:24 +00001093 case pch::PP_TOKEN: {
1094 // If we see a TOKEN before a PP_MACRO_*, then the file is
1095 // erroneous, just pretend we didn't see this.
1096 if (Macro == 0) break;
Mike Stump11289f42009-09-09 15:08:12 +00001097
Douglas Gregorc3366a52009-04-21 23:56:24 +00001098 Token Tok;
1099 Tok.startToken();
1100 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1101 Tok.setLength(Record[1]);
1102 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1103 Tok.setIdentifierInfo(II);
1104 Tok.setKind((tok::TokenKind)Record[3]);
1105 Tok.setFlag((Token::TokenFlags)Record[4]);
1106 Macro->AddTokenToBody(Tok);
1107 break;
1108 }
Steve Naroff3fa455a2009-04-24 20:03:17 +00001109 }
Douglas Gregorc3366a52009-04-21 23:56:24 +00001110 }
1111}
1112
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001113/// \brief If we are loading a relocatable PCH file, and the filename is
1114/// not an absolute path, add the system root to the beginning of the file
1115/// name.
1116void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1117 // If this is not a relocatable PCH file, there's nothing to do.
1118 if (!RelocatablePCH)
1119 return;
Mike Stump11289f42009-09-09 15:08:12 +00001120
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001121 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1122 return;
1123
1124 std::string FIXME = Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001125
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001126 if (isysroot == 0) {
1127 // If no system root was given, default to '/'
1128 Filename.insert(Filename.begin(), '/');
1129 return;
1130 }
Mike Stump11289f42009-09-09 15:08:12 +00001131
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001132 unsigned Length = strlen(isysroot);
1133 if (isysroot[Length - 1] != '/')
1134 Filename.insert(Filename.begin(), '/');
Mike Stump11289f42009-09-09 15:08:12 +00001135
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001136 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1137}
1138
Mike Stump11289f42009-09-09 15:08:12 +00001139PCHReader::PCHReadResult
Douglas Gregoreda6a892009-04-26 00:07:37 +00001140PCHReader::ReadPCHBlock() {
Douglas Gregor55abb232009-04-10 20:39:37 +00001141 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001142 Error("malformed block record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001143 return Failure;
1144 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001145
1146 // Read all of the records and blocks for the PCH file.
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001147 RecordData Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001148 while (!Stream.AtEndOfStream()) {
1149 unsigned Code = Stream.ReadCode();
1150 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001151 if (Stream.ReadBlockEnd()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001152 Error("error at end of module block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001153 return Failure;
1154 }
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001155
Douglas Gregor55abb232009-04-10 20:39:37 +00001156 return Success;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001157 }
1158
1159 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1160 switch (Stream.ReadSubBlockID()) {
Douglas Gregor12bfa382009-10-17 00:13:19 +00001161 case pch::DECLTYPES_BLOCK_ID:
Chris Lattnere78a6be2009-04-27 01:05:14 +00001162 // We lazily load the decls block, but we want to set up the
1163 // DeclsCursor cursor to point into it. Clone our current bitcode
1164 // cursor to it, enter the block and read the abbrevs in that block.
1165 // With the main cursor, we just skip over it.
1166 DeclsCursor = Stream;
1167 if (Stream.SkipBlock() || // Skip with the main cursor.
1168 // Read the abbrevs.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001169 ReadBlockAbbrevs(DeclsCursor, pch::DECLTYPES_BLOCK_ID)) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001170 Error("malformed block record in PCH file");
Chris Lattnere78a6be2009-04-27 01:05:14 +00001171 return Failure;
1172 }
1173 break;
Mike Stump11289f42009-09-09 15:08:12 +00001174
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001175 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001176 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001177 Error("malformed block record in PCH file");
Chris Lattnerc523d8e2009-04-11 21:15:38 +00001178 return Failure;
1179 }
1180 break;
Steve Naroff2ddea052009-04-23 10:39:46 +00001181
Douglas Gregora7f71a92009-04-10 03:52:48 +00001182 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001183 switch (ReadSourceManagerBlock()) {
1184 case Success:
1185 break;
1186
1187 case Failure:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001188 Error("malformed source manager block in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001189 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001190
1191 case IgnorePCH:
1192 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001193 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00001194 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001195 }
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001196 continue;
1197 }
1198
1199 if (Code == llvm::bitc::DEFINE_ABBREV) {
1200 Stream.ReadAbbrevRecord();
1201 continue;
1202 }
1203
1204 // Read and process a record.
1205 Record.clear();
Douglas Gregorbfbde532009-04-10 21:16:55 +00001206 const char *BlobStart = 0;
1207 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001208 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregorbfbde532009-04-10 21:16:55 +00001209 &BlobStart, &BlobLen)) {
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001210 default: // Default behavior: ignore.
1211 break;
1212
1213 case pch::TYPE_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001214 if (!TypesLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001215 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001216 return Failure;
1217 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001218 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001219 TypesLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001220 break;
1221
1222 case pch::DECL_OFFSET:
Douglas Gregor745ed142009-04-25 18:35:21 +00001223 if (!DeclsLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001224 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001225 return Failure;
1226 }
Chris Lattnereeb05692009-04-27 18:24:17 +00001227 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor745ed142009-04-25 18:35:21 +00001228 DeclsLoaded.resize(Record[0]);
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00001229 break;
Douglas Gregor55abb232009-04-10 20:39:37 +00001230
1231 case pch::LANGUAGE_OPTIONS:
1232 if (ParseLanguageOptions(Record))
1233 return IgnorePCH;
1234 break;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001235
Douglas Gregor7b71e632009-04-27 22:23:34 +00001236 case pch::METADATA: {
1237 if (Record[0] != pch::VERSION_MAJOR) {
1238 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1239 : diag::warn_pch_version_too_new);
1240 return IgnorePCH;
1241 }
1242
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001243 RelocatablePCH = Record[4];
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001244 if (Listener) {
1245 std::string TargetTriple(BlobStart, BlobLen);
1246 if (Listener->ReadTargetTriple(TargetTriple))
1247 return IgnorePCH;
Douglas Gregorbfbde532009-04-10 21:16:55 +00001248 }
1249 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001250 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001251
1252 case pch::IDENTIFIER_TABLE:
Douglas Gregora868bbd2009-04-21 22:25:48 +00001253 IdentifierTableData = BlobStart;
Douglas Gregor0e149972009-04-25 19:10:14 +00001254 if (Record[0]) {
Mike Stump11289f42009-09-09 15:08:12 +00001255 IdentifierLookupTable
Douglas Gregor0e149972009-04-25 19:10:14 +00001256 = PCHIdentifierLookupTable::Create(
Douglas Gregora868bbd2009-04-21 22:25:48 +00001257 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001258 (const unsigned char *)IdentifierTableData,
Douglas Gregora868bbd2009-04-21 22:25:48 +00001259 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001260 if (PP)
1261 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor0e149972009-04-25 19:10:14 +00001262 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001263 break;
1264
1265 case pch::IDENTIFIER_OFFSET:
Douglas Gregor0e149972009-04-25 19:10:14 +00001266 if (!IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001267 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001268 return Failure;
1269 }
Douglas Gregor0e149972009-04-25 19:10:14 +00001270 IdentifierOffsets = (const uint32_t *)BlobStart;
1271 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001272 if (PP)
1273 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001274 break;
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001275
1276 case pch::EXTERNAL_DEFINITIONS:
1277 if (!ExternalDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001278 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00001279 return Failure;
1280 }
1281 ExternalDefinitions.swap(Record);
1282 break;
Douglas Gregor08f01292009-04-17 22:13:46 +00001283
Douglas Gregor652d82a2009-04-18 05:55:16 +00001284 case pch::SPECIAL_TYPES:
1285 SpecialTypes.swap(Record);
1286 break;
1287
Douglas Gregor08f01292009-04-17 22:13:46 +00001288 case pch::STATISTICS:
1289 TotalNumStatements = Record[0];
Douglas Gregorc3366a52009-04-21 23:56:24 +00001290 TotalNumMacros = Record[1];
Douglas Gregora57c3ab2009-04-22 22:34:57 +00001291 TotalLexicalDeclContexts = Record[2];
1292 TotalVisibleDeclContexts = Record[3];
Douglas Gregor08f01292009-04-17 22:13:46 +00001293 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001294
Douglas Gregord4df8652009-04-22 22:02:47 +00001295 case pch::TENTATIVE_DEFINITIONS:
1296 if (!TentativeDefinitions.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001297 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregord4df8652009-04-22 22:02:47 +00001298 return Failure;
1299 }
1300 TentativeDefinitions.swap(Record);
1301 break;
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001302
1303 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1304 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001305 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregoracfc76c2009-04-22 22:18:58 +00001306 return Failure;
1307 }
1308 LocallyScopedExternalDecls.swap(Record);
1309 break;
Douglas Gregorc78d3462009-04-24 21:10:55 +00001310
Douglas Gregor95c13f52009-04-25 17:48:32 +00001311 case pch::SELECTOR_OFFSETS:
1312 SelectorOffsets = (const uint32_t *)BlobStart;
1313 TotalNumSelectors = Record[0];
1314 SelectorsLoaded.resize(TotalNumSelectors);
1315 break;
1316
Douglas Gregorc78d3462009-04-24 21:10:55 +00001317 case pch::METHOD_POOL:
Douglas Gregor95c13f52009-04-25 17:48:32 +00001318 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1319 if (Record[0])
Mike Stump11289f42009-09-09 15:08:12 +00001320 MethodPoolLookupTable
Douglas Gregor95c13f52009-04-25 17:48:32 +00001321 = PCHMethodPoolLookupTable::Create(
1322 MethodPoolLookupTableData + Record[0],
Mike Stump11289f42009-09-09 15:08:12 +00001323 MethodPoolLookupTableData,
Douglas Gregorc78d3462009-04-24 21:10:55 +00001324 PCHMethodPoolLookupTrait(*this));
Douglas Gregor95c13f52009-04-25 17:48:32 +00001325 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc78d3462009-04-24 21:10:55 +00001326 break;
Douglas Gregoreda6a892009-04-26 00:07:37 +00001327
1328 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001329 if (!Record.empty() && Listener)
1330 Listener->ReadCounter(Record[0]);
Douglas Gregoreda6a892009-04-26 00:07:37 +00001331 break;
Douglas Gregor258ae542009-04-27 06:38:32 +00001332
1333 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner12d61d32009-04-27 19:01:47 +00001334 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor258ae542009-04-27 06:38:32 +00001335 TotalNumSLocEntries = Record[0];
Douglas Gregord54f3a12009-10-05 21:07:28 +00001336 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor258ae542009-04-27 06:38:32 +00001337 break;
1338
1339 case pch::SOURCE_LOCATION_PRELOADS:
1340 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1341 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1342 if (Result != Success)
1343 return Result;
1344 }
1345 break;
Douglas Gregorc5046832009-04-27 18:38:38 +00001346
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001347 case pch::STAT_CACHE: {
1348 PCHStatCache *MyStatCache =
1349 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1350 (const unsigned char *)BlobStart,
1351 NumStatHits, NumStatMisses);
1352 FileMgr.addStatCache(MyStatCache);
1353 StatCache = MyStatCache;
Douglas Gregorc5046832009-04-27 18:38:38 +00001354 break;
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001355 }
1356
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001357 case pch::EXT_VECTOR_DECLS:
1358 if (!ExtVectorDecls.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001359 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001360 return Failure;
1361 }
1362 ExtVectorDecls.swap(Record);
1363 break;
1364
Douglas Gregor45fe0362009-05-12 01:31:05 +00001365 case pch::ORIGINAL_FILE_NAME:
1366 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001367 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001368 break;
Mike Stump11289f42009-09-09 15:08:12 +00001369
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001370 case pch::COMMENT_RANGES:
1371 Comments = (SourceRange *)BlobStart;
1372 NumComments = BlobLen / sizeof(SourceRange);
1373 break;
Douglas Gregord54f3a12009-10-05 21:07:28 +00001374
1375 case pch::SVN_BRANCH_REVISION: {
1376 unsigned CurRevision = getClangSubversionRevision();
1377 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1378 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1379 : diag::warn_pch_version_too_new);
1380 return IgnorePCH;
1381 }
1382
1383 const char *CurBranch = getClangSubversionPath();
1384 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1385 std::string PCHBranch(BlobStart, BlobLen);
1386 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1387 return IgnorePCH;
1388 }
1389 break;
1390 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00001391 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001392 }
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001393 Error("premature end of bitstream in PCH file");
Douglas Gregor55abb232009-04-10 20:39:37 +00001394 return Failure;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001395}
1396
Douglas Gregor92863e42009-04-10 23:10:45 +00001397PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001398 // Set the PCH file name.
1399 this->FileName = FileName;
1400
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001401 // Open the PCH file.
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001402 //
1403 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001404 std::string ErrStr;
Daniel Dunbar2d925eb2009-09-22 05:38:01 +00001405 if (FileName == "-")
1406 Buffer.reset(llvm::MemoryBuffer::getSTDIN());
1407 else
1408 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregor92863e42009-04-10 23:10:45 +00001409 if (!Buffer) {
1410 Error(ErrStr.c_str());
1411 return IgnorePCH;
1412 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001413
1414 // Initialize the stream
Mike Stump11289f42009-09-09 15:08:12 +00001415 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattner9356ace2009-04-26 20:59:20 +00001416 (const unsigned char *)Buffer->getBufferEnd());
1417 Stream.init(StreamFile);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001418
1419 // Sniff for the signature.
1420 if (Stream.Read(8) != 'C' ||
1421 Stream.Read(8) != 'P' ||
1422 Stream.Read(8) != 'C' ||
Douglas Gregor92863e42009-04-10 23:10:45 +00001423 Stream.Read(8) != 'H') {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001424 Diag(diag::err_not_a_pch_file) << FileName;
1425 return Failure;
Douglas Gregor92863e42009-04-10 23:10:45 +00001426 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001427
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001428 while (!Stream.AtEndOfStream()) {
1429 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001430
Douglas Gregor92863e42009-04-10 23:10:45 +00001431 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001432 Error("invalid record at top-level of PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001433 return Failure;
1434 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001435
1436 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregora868bbd2009-04-21 22:25:48 +00001437
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001438 // We only know the PCH subblock ID.
1439 switch (BlockID) {
1440 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregor92863e42009-04-10 23:10:45 +00001441 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001442 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001443 return Failure;
1444 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001445 break;
1446 case pch::PCH_BLOCK_ID:
Douglas Gregoreda6a892009-04-26 00:07:37 +00001447 switch (ReadPCHBlock()) {
Douglas Gregor55abb232009-04-10 20:39:37 +00001448 case Success:
1449 break;
1450
1451 case Failure:
Douglas Gregor92863e42009-04-10 23:10:45 +00001452 return Failure;
Douglas Gregor55abb232009-04-10 20:39:37 +00001453
1454 case IgnorePCH:
Douglas Gregorbfbde532009-04-10 21:16:55 +00001455 // FIXME: We could consider reading through to the end of this
1456 // PCH block, skipping subblocks, to see if there are other
1457 // PCH blocks elsewhere.
Douglas Gregor0bc12932009-04-27 21:28:04 +00001458
1459 // Clear out any preallocated source location entries, so that
1460 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001461 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor0bc12932009-04-27 21:28:04 +00001462
1463 // Remove the stat cache.
Douglas Gregord2eb58a2009-10-16 18:18:30 +00001464 if (StatCache)
1465 FileMgr.removeStatCache((PCHStatCache*)StatCache);
Douglas Gregor0bc12932009-04-27 21:28:04 +00001466
Douglas Gregor92863e42009-04-10 23:10:45 +00001467 return IgnorePCH;
Douglas Gregor55abb232009-04-10 20:39:37 +00001468 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001469 break;
1470 default:
Douglas Gregor92863e42009-04-10 23:10:45 +00001471 if (Stream.SkipBlock()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001472 Error("malformed block record in PCH file");
Douglas Gregor92863e42009-04-10 23:10:45 +00001473 return Failure;
1474 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001475 break;
1476 }
Mike Stump11289f42009-09-09 15:08:12 +00001477 }
1478
Douglas Gregore6648fb2009-04-28 20:33:11 +00001479 // Check the predefines buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001480 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
Douglas Gregore6648fb2009-04-28 20:33:11 +00001481 PCHPredefinesBufferID))
1482 return IgnorePCH;
Mike Stump11289f42009-09-09 15:08:12 +00001483
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001484 if (PP) {
Zhongxing Xu3f51f412009-07-18 09:26:51 +00001485 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001486 // PCH file is read, so there may be some identifiers that were
1487 // loaded into the IdentifierTable before we intercepted the
1488 // creation of identifiers. Iterate through the list of known
1489 // identifiers and determine whether we have to establish
1490 // preprocessor definitions or top-level identifier declaration
1491 // chains for those identifiers.
1492 //
1493 // We copy the IdentifierInfo pointers to a small vector first,
1494 // since de-serializing declarations or macro definitions can add
1495 // new entries into the identifier table, invalidating the
1496 // iterators.
1497 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1498 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1499 IdEnd = PP->getIdentifierTable().end();
1500 Id != IdEnd; ++Id)
1501 Identifiers.push_back(Id->second);
Mike Stump11289f42009-09-09 15:08:12 +00001502 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001503 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1504 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1505 IdentifierInfo *II = Identifiers[I];
1506 // Look in the on-disk hash table for an entry for
1507 PCHIdentifierLookupTrait Info(*this, II);
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001508 std::pair<const char*, unsigned> Key(II->getNameStart(), II->getLength());
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001509 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1510 if (Pos == IdTable->end())
1511 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001512
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001513 // Dereferencing the iterator has the effect of populating the
1514 // IdentifierInfo node with the various declarations it needs.
1515 (void)*Pos;
1516 }
Douglas Gregora868bbd2009-04-21 22:25:48 +00001517 }
1518
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001519 if (Context)
1520 InitializeContext(*Context);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001521
Douglas Gregora868bbd2009-04-21 22:25:48 +00001522 return Success;
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001523}
1524
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001525void PCHReader::InitializeContext(ASTContext &Ctx) {
1526 Context = &Ctx;
1527 assert(Context && "Passed null context!");
1528
1529 assert(PP && "Forgot to set Preprocessor ?");
1530 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1531 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump11289f42009-09-09 15:08:12 +00001532
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001533 // Load the translation unit declaration
1534 ReadDeclRecord(DeclOffsets[0], 0);
1535
1536 // Load the special types.
1537 Context->setBuiltinVaListType(
1538 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1539 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1540 Context->setObjCIdType(GetType(Id));
1541 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1542 Context->setObjCSelType(GetType(Sel));
1543 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1544 Context->setObjCProtoType(GetType(Proto));
1545 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1546 Context->setObjCClassType(GetType(Class));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001547
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001548 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1549 Context->setCFConstantStringType(GetType(String));
Mike Stump11289f42009-09-09 15:08:12 +00001550 if (unsigned FastEnum
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001551 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1552 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregor27821ce2009-07-07 16:35:42 +00001553 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1554 QualType FileType = GetType(File);
1555 assert(!FileType.isNull() && "FILE type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001556 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregor27821ce2009-07-07 16:35:42 +00001557 Context->setFILEDecl(Typedef->getDecl());
1558 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001559 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregor27821ce2009-07-07 16:35:42 +00001560 assert(Tag && "Invalid FILE type in PCH file");
1561 Context->setFILEDecl(Tag->getDecl());
1562 }
1563 }
Mike Stumpa4de80b2009-07-28 02:25:19 +00001564 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1565 QualType Jmp_bufType = GetType(Jmp_buf);
1566 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001567 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001568 Context->setjmp_bufDecl(Typedef->getDecl());
1569 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001570 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001571 assert(Tag && "Invalid jmp_bug type in PCH file");
1572 Context->setjmp_bufDecl(Tag->getDecl());
1573 }
1574 }
1575 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1576 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1577 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall9dd450b2009-09-21 23:43:11 +00001578 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stumpa4de80b2009-07-28 02:25:19 +00001579 Context->setsigjmp_bufDecl(Typedef->getDecl());
1580 else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001581 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stumpa4de80b2009-07-28 02:25:19 +00001582 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1583 Context->setsigjmp_bufDecl(Tag->getDecl());
1584 }
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586 if (unsigned ObjCIdRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001587 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1588 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump11289f42009-09-09 15:08:12 +00001589 if (unsigned ObjCClassRedef
Douglas Gregora8eed7d2009-08-21 00:27:50 +00001590 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1591 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Mike Stumpd0153282009-10-20 02:12:22 +00001592 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_DESCRIPTOR])
1593 Context->setBlockDescriptorType(GetType(String));
Mike Stumpe1b19ba2009-10-22 00:49:09 +00001594 if (unsigned String
1595 = SpecialTypes[pch::SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
1596 Context->setBlockDescriptorExtendedType(GetType(String));
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001597}
1598
Douglas Gregor45fe0362009-05-12 01:31:05 +00001599/// \brief Retrieve the name of the original source file name
1600/// directly from the PCH file, without actually loading the PCH
1601/// file.
1602std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1603 // Open the PCH file.
1604 std::string ErrStr;
1605 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1606 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1607 if (!Buffer) {
1608 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1609 return std::string();
1610 }
1611
1612 // Initialize the stream
1613 llvm::BitstreamReader StreamFile;
1614 llvm::BitstreamCursor Stream;
Mike Stump11289f42009-09-09 15:08:12 +00001615 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregor45fe0362009-05-12 01:31:05 +00001616 (const unsigned char *)Buffer->getBufferEnd());
1617 Stream.init(StreamFile);
1618
1619 // Sniff for the signature.
1620 if (Stream.Read(8) != 'C' ||
1621 Stream.Read(8) != 'P' ||
1622 Stream.Read(8) != 'C' ||
1623 Stream.Read(8) != 'H') {
Mike Stump11289f42009-09-09 15:08:12 +00001624 fprintf(stderr,
Douglas Gregor45fe0362009-05-12 01:31:05 +00001625 "error: '%s' does not appear to be a precompiled header file\n",
1626 PCHFileName.c_str());
1627 return std::string();
1628 }
1629
1630 RecordData Record;
1631 while (!Stream.AtEndOfStream()) {
1632 unsigned Code = Stream.ReadCode();
Mike Stump11289f42009-09-09 15:08:12 +00001633
Douglas Gregor45fe0362009-05-12 01:31:05 +00001634 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1635 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump11289f42009-09-09 15:08:12 +00001636
Douglas Gregor45fe0362009-05-12 01:31:05 +00001637 // We only know the PCH subblock ID.
1638 switch (BlockID) {
1639 case pch::PCH_BLOCK_ID:
1640 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1641 fprintf(stderr, "error: malformed block record in PCH file\n");
1642 return std::string();
1643 }
1644 break;
Mike Stump11289f42009-09-09 15:08:12 +00001645
Douglas Gregor45fe0362009-05-12 01:31:05 +00001646 default:
1647 if (Stream.SkipBlock()) {
1648 fprintf(stderr, "error: malformed block record in PCH file\n");
1649 return std::string();
1650 }
1651 break;
1652 }
1653 continue;
1654 }
1655
1656 if (Code == llvm::bitc::END_BLOCK) {
1657 if (Stream.ReadBlockEnd()) {
1658 fprintf(stderr, "error: error at end of module block in PCH file\n");
1659 return std::string();
1660 }
1661 continue;
1662 }
1663
1664 if (Code == llvm::bitc::DEFINE_ABBREV) {
1665 Stream.ReadAbbrevRecord();
1666 continue;
1667 }
1668
1669 Record.clear();
1670 const char *BlobStart = 0;
1671 unsigned BlobLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001672 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregor45fe0362009-05-12 01:31:05 +00001673 == pch::ORIGINAL_FILE_NAME)
1674 return std::string(BlobStart, BlobLen);
Mike Stump11289f42009-09-09 15:08:12 +00001675 }
Douglas Gregor45fe0362009-05-12 01:31:05 +00001676
1677 return std::string();
1678}
1679
Douglas Gregor55abb232009-04-10 20:39:37 +00001680/// \brief Parse the record that corresponds to a LangOptions data
1681/// structure.
1682///
1683/// This routine compares the language options used to generate the
1684/// PCH file against the language options set for the current
1685/// compilation. For each option, we classify differences between the
1686/// two compiler states as either "benign" or "important". Benign
1687/// differences don't matter, and we accept them without complaint
1688/// (and without modifying the language options). Differences between
1689/// the states for important options cause the PCH file to be
1690/// unusable, so we emit a warning and return true to indicate that
1691/// there was an error.
1692///
1693/// \returns true if the PCH file is unacceptable, false otherwise.
1694bool PCHReader::ParseLanguageOptions(
1695 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001696 if (Listener) {
1697 LangOptions LangOpts;
Mike Stump11289f42009-09-09 15:08:12 +00001698
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001699 #define PARSE_LANGOPT(Option) \
1700 LangOpts.Option = Record[Idx]; \
1701 ++Idx
Mike Stump11289f42009-09-09 15:08:12 +00001702
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001703 unsigned Idx = 0;
1704 PARSE_LANGOPT(Trigraphs);
1705 PARSE_LANGOPT(BCPLComment);
1706 PARSE_LANGOPT(DollarIdents);
1707 PARSE_LANGOPT(AsmPreprocessor);
1708 PARSE_LANGOPT(GNUMode);
1709 PARSE_LANGOPT(ImplicitInt);
1710 PARSE_LANGOPT(Digraphs);
1711 PARSE_LANGOPT(HexFloats);
1712 PARSE_LANGOPT(C99);
1713 PARSE_LANGOPT(Microsoft);
1714 PARSE_LANGOPT(CPlusPlus);
1715 PARSE_LANGOPT(CPlusPlus0x);
1716 PARSE_LANGOPT(CXXOperatorNames);
1717 PARSE_LANGOPT(ObjC1);
1718 PARSE_LANGOPT(ObjC2);
1719 PARSE_LANGOPT(ObjCNonFragileABI);
1720 PARSE_LANGOPT(PascalStrings);
1721 PARSE_LANGOPT(WritableStrings);
1722 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanf2911662009-06-25 23:01:11 +00001723 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001724 PARSE_LANGOPT(Exceptions);
1725 PARSE_LANGOPT(NeXTRuntime);
1726 PARSE_LANGOPT(Freestanding);
1727 PARSE_LANGOPT(NoBuiltin);
1728 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregorb3286fe2009-09-03 14:36:33 +00001729 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001730 PARSE_LANGOPT(Blocks);
1731 PARSE_LANGOPT(EmitAllDecls);
1732 PARSE_LANGOPT(MathErrno);
1733 PARSE_LANGOPT(OverflowChecking);
1734 PARSE_LANGOPT(HeinousExtensions);
1735 PARSE_LANGOPT(Optimize);
1736 PARSE_LANGOPT(OptimizeSize);
1737 PARSE_LANGOPT(Static);
1738 PARSE_LANGOPT(PICLevel);
1739 PARSE_LANGOPT(GNUInline);
1740 PARSE_LANGOPT(NoInline);
1741 PARSE_LANGOPT(AccessControl);
1742 PARSE_LANGOPT(CharIsSigned);
1743 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1744 ++Idx;
1745 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1746 ++Idx;
Daniel Dunbar143021e2009-09-21 04:16:19 +00001747 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1748 Record[Idx]);
1749 ++Idx;
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001750 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanf2911662009-06-25 23:01:11 +00001751 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001752 #undef PARSE_LANGOPT
Douglas Gregor55abb232009-04-10 20:39:37 +00001753
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00001754 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor55abb232009-04-10 20:39:37 +00001755 }
Douglas Gregor55abb232009-04-10 20:39:37 +00001756
1757 return false;
1758}
1759
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001760void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1761 Comments.resize(NumComments);
1762 std::copy(this->Comments, this->Comments + NumComments,
1763 Comments.begin());
1764}
1765
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001766/// \brief Read and return the type at the given offset.
1767///
1768/// This routine actually reads the record corresponding to the type
1769/// at the given offset in the bitstream. It is a helper routine for
1770/// GetType, which deals with reading type IDs.
1771QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001772 // Keep track of where we are in the stream, then jump back there
1773 // after reading this type.
Douglas Gregor12bfa382009-10-17 00:13:19 +00001774 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001775
Douglas Gregor1342e842009-07-06 18:54:52 +00001776 // Note that we are loading a type record.
1777 LoadingTypeOrDecl Loading(*this);
Mike Stump11289f42009-09-09 15:08:12 +00001778
Douglas Gregor12bfa382009-10-17 00:13:19 +00001779 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001780 RecordData Record;
Douglas Gregor12bfa382009-10-17 00:13:19 +00001781 unsigned Code = DeclsCursor.ReadCode();
1782 switch ((pch::TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
Douglas Gregor455b8f42009-04-15 22:00:08 +00001783 case pch::TYPE_EXT_QUAL: {
John McCall8ccfcb52009-09-24 19:53:00 +00001784 assert(Record.size() == 2 &&
Douglas Gregor455b8f42009-04-15 22:00:08 +00001785 "Incorrect encoding of extended qualifier type");
1786 QualType Base = GetType(Record[0]);
John McCall8ccfcb52009-09-24 19:53:00 +00001787 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1788 return Context->getQualifiedType(Base, Quals);
Douglas Gregor455b8f42009-04-15 22:00:08 +00001789 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001790
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001791 case pch::TYPE_FIXED_WIDTH_INT: {
1792 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001793 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001794 }
1795
1796 case pch::TYPE_COMPLEX: {
1797 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1798 QualType ElemType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001799 return Context->getComplexType(ElemType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001800 }
1801
1802 case pch::TYPE_POINTER: {
1803 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1804 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001805 return Context->getPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001806 }
1807
1808 case pch::TYPE_BLOCK_POINTER: {
1809 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1810 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001811 return Context->getBlockPointerType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001812 }
1813
1814 case pch::TYPE_LVALUE_REFERENCE: {
1815 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1816 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001817 return Context->getLValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001818 }
1819
1820 case pch::TYPE_RVALUE_REFERENCE: {
1821 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1822 QualType PointeeType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001823 return Context->getRValueReferenceType(PointeeType);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001824 }
1825
1826 case pch::TYPE_MEMBER_POINTER: {
1827 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1828 QualType PointeeType = GetType(Record[0]);
1829 QualType ClassType = GetType(Record[1]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001830 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001831 }
1832
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001833 case pch::TYPE_CONSTANT_ARRAY: {
1834 QualType ElementType = GetType(Record[0]);
1835 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1836 unsigned IndexTypeQuals = Record[2];
1837 unsigned Idx = 3;
1838 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor04318252009-07-06 15:59:29 +00001839 return Context->getConstantArrayType(ElementType, Size,
1840 ASM, IndexTypeQuals);
1841 }
1842
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001843 case pch::TYPE_INCOMPLETE_ARRAY: {
1844 QualType ElementType = GetType(Record[0]);
1845 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1846 unsigned IndexTypeQuals = Record[2];
Chris Lattner8575daa2009-04-27 21:45:14 +00001847 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001848 }
1849
1850 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorfeb84b02009-04-14 21:18:50 +00001851 QualType ElementType = GetType(Record[0]);
1852 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1853 unsigned IndexTypeQuals = Record[2];
Douglas Gregor04318252009-07-06 15:59:29 +00001854 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1855 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001856 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor04318252009-07-06 15:59:29 +00001857 ASM, IndexTypeQuals,
1858 SourceRange(LBLoc, RBLoc));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001859 }
1860
1861 case pch::TYPE_VECTOR: {
1862 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001863 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001864 return QualType();
1865 }
1866
1867 QualType ElementType = GetType(Record[0]);
1868 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001869 return Context->getVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001870 }
1871
1872 case pch::TYPE_EXT_VECTOR: {
1873 if (Record.size() != 2) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001874 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001875 return QualType();
1876 }
1877
1878 QualType ElementType = GetType(Record[0]);
1879 unsigned NumElements = Record[1];
Chris Lattner8575daa2009-04-27 21:45:14 +00001880 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001881 }
1882
1883 case pch::TYPE_FUNCTION_NO_PROTO: {
1884 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001885 Error("incorrect encoding of no-proto function type");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001886 return QualType();
1887 }
1888 QualType ResultType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001889 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001890 }
1891
1892 case pch::TYPE_FUNCTION_PROTO: {
1893 QualType ResultType = GetType(Record[0]);
1894 unsigned Idx = 1;
1895 unsigned NumParams = Record[Idx++];
1896 llvm::SmallVector<QualType, 16> ParamTypes;
1897 for (unsigned I = 0; I != NumParams; ++I)
1898 ParamTypes.push_back(GetType(Record[Idx++]));
1899 bool isVariadic = Record[Idx++];
1900 unsigned Quals = Record[Idx++];
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001901 bool hasExceptionSpec = Record[Idx++];
1902 bool hasAnyExceptionSpec = Record[Idx++];
1903 unsigned NumExceptions = Record[Idx++];
1904 llvm::SmallVector<QualType, 2> Exceptions;
1905 for (unsigned I = 0; I != NumExceptions; ++I)
1906 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad7d0479f2009-05-21 09:52:38 +00001907 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001908 isVariadic, Quals, hasExceptionSpec,
1909 hasAnyExceptionSpec, NumExceptions,
1910 Exceptions.data());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001911 }
1912
1913 case pch::TYPE_TYPEDEF:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001914 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001915 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001916
1917 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner8575daa2009-04-27 21:45:14 +00001918 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001919
1920 case pch::TYPE_TYPEOF: {
1921 if (Record.size() != 1) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001922 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001923 return QualType();
1924 }
1925 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner8575daa2009-04-27 21:45:14 +00001926 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001927 }
Mike Stump11289f42009-09-09 15:08:12 +00001928
Anders Carlsson81df7b82009-06-24 19:06:50 +00001929 case pch::TYPE_DECLTYPE:
1930 return Context->getDecltypeType(ReadTypeExpr());
1931
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001932 case pch::TYPE_RECORD:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001933 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001934 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001935
Douglas Gregor1daeb692009-04-13 18:14:40 +00001936 case pch::TYPE_ENUM:
Douglas Gregor6f00bf82009-04-28 21:53:25 +00001937 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner8575daa2009-04-27 21:45:14 +00001938 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor1daeb692009-04-13 18:14:40 +00001939
John McCallfcc33b02009-09-05 00:15:47 +00001940 case pch::TYPE_ELABORATED: {
1941 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1942 unsigned Tag = Record[1];
1943 return Context->getElaboratedType(GetType(Record[0]),
1944 (ElaboratedType::TagKind) Tag);
1945 }
1946
Steve Naroffc277ad12009-07-18 15:33:26 +00001947 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattner587cbe12009-04-22 06:45:28 +00001948 unsigned Idx = 0;
1949 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1950 unsigned NumProtos = Record[Idx++];
1951 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1952 for (unsigned I = 0; I != NumProtos; ++I)
1953 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc277ad12009-07-18 15:33:26 +00001954 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattner587cbe12009-04-22 06:45:28 +00001955 }
Douglas Gregor85c0fcd2009-04-13 20:46:52 +00001956
Steve Narofffb4330f2009-06-17 22:40:22 +00001957 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner6e054af2009-04-22 06:40:03 +00001958 unsigned Idx = 0;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001959 QualType OIT = GetType(Record[Idx++]);
Chris Lattner6e054af2009-04-22 06:40:03 +00001960 unsigned NumProtos = Record[Idx++];
1961 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1962 for (unsigned I = 0; I != NumProtos; ++I)
1963 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff7cae42b2009-07-10 23:34:53 +00001964 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattner6e054af2009-04-22 06:40:03 +00001965 }
Argyrios Kyrtzidisa7a36df2009-09-29 19:42:55 +00001966
1967 case pch::TYPE_OBJC_PROTOCOL_LIST: {
1968 unsigned Idx = 0;
1969 QualType OIT = GetType(Record[Idx++]);
1970 unsigned NumProtos = Record[Idx++];
1971 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1972 for (unsigned I = 0; I != NumProtos; ++I)
1973 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1974 return Context->getObjCProtocolListType(OIT, Protos.data(), NumProtos);
1975 }
John McCallcebee162009-10-18 09:09:24 +00001976
1977 case pch::TYPE_SUBST_TEMPLATE_TYPE_PARM: {
1978 unsigned Idx = 0;
1979 QualType Parm = GetType(Record[Idx++]);
1980 QualType Replacement = GetType(Record[Idx++]);
1981 return
1982 Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
1983 Replacement);
1984 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001985 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001986 // Suppress a GCC warning
1987 return QualType();
1988}
1989
John McCall8f115c62009-10-16 21:56:05 +00001990namespace {
1991
1992class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
1993 PCHReader &Reader;
1994 const PCHReader::RecordData &Record;
1995 unsigned &Idx;
1996
1997public:
1998 TypeLocReader(PCHReader &Reader, const PCHReader::RecordData &Record,
1999 unsigned &Idx)
2000 : Reader(Reader), Record(Record), Idx(Idx) { }
2001
John McCall17001972009-10-18 01:05:36 +00002002 // We want compile-time assurance that we've enumerated all of
2003 // these, so unfortunately we have to declare them first, then
2004 // define them out-of-line.
2005#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +00002006#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +00002007 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +00002008#include "clang/AST/TypeLocNodes.def"
2009
John McCall17001972009-10-18 01:05:36 +00002010 void VisitFunctionTypeLoc(FunctionTypeLoc);
2011 void VisitArrayTypeLoc(ArrayTypeLoc);
John McCall8f115c62009-10-16 21:56:05 +00002012};
2013
2014}
2015
John McCall17001972009-10-18 01:05:36 +00002016void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
John McCall8f115c62009-10-16 21:56:05 +00002017 // nothing to do
2018}
John McCall17001972009-10-18 01:05:36 +00002019void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2020 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002021}
John McCall17001972009-10-18 01:05:36 +00002022void TypeLocReader::VisitFixedWidthIntTypeLoc(FixedWidthIntTypeLoc TL) {
2023 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002024}
John McCall17001972009-10-18 01:05:36 +00002025void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2026 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002027}
John McCall17001972009-10-18 01:05:36 +00002028void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2029 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002030}
John McCall17001972009-10-18 01:05:36 +00002031void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2032 TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002033}
John McCall17001972009-10-18 01:05:36 +00002034void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2035 TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002036}
John McCall17001972009-10-18 01:05:36 +00002037void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2038 TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002039}
John McCall17001972009-10-18 01:05:36 +00002040void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2041 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002042}
John McCall17001972009-10-18 01:05:36 +00002043void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2044 TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2045 TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002046 if (Record[Idx++])
John McCall17001972009-10-18 01:05:36 +00002047 TL.setSizeExpr(Reader.ReadDeclExpr());
Douglas Gregor12bfa382009-10-17 00:13:19 +00002048 else
John McCall17001972009-10-18 01:05:36 +00002049 TL.setSizeExpr(0);
2050}
2051void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2052 VisitArrayTypeLoc(TL);
2053}
2054void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2055 VisitArrayTypeLoc(TL);
2056}
2057void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2058 VisitArrayTypeLoc(TL);
2059}
2060void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2061 DependentSizedArrayTypeLoc TL) {
2062 VisitArrayTypeLoc(TL);
2063}
2064void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2065 DependentSizedExtVectorTypeLoc TL) {
2066 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2067}
2068void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2069 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2070}
2071void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2072 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2073}
2074void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2075 TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2076 TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2077 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
2078 TL.setArg(i, cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
2079 }
2080}
2081void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2082 VisitFunctionTypeLoc(TL);
2083}
2084void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2085 VisitFunctionTypeLoc(TL);
2086}
2087void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2088 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2089}
2090void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2091 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2092}
2093void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2094 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2095}
2096void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2097 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2098}
2099void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2100 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2101}
2102void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2103 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2104}
2105void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2106 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2107}
2108void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2109 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2110}
John McCallcebee162009-10-18 09:09:24 +00002111void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2112 SubstTemplateTypeParmTypeLoc TL) {
2113 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2114}
John McCall17001972009-10-18 01:05:36 +00002115void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2116 TemplateSpecializationTypeLoc TL) {
2117 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2118}
2119void TypeLocReader::VisitQualifiedNameTypeLoc(QualifiedNameTypeLoc TL) {
2120 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2121}
2122void TypeLocReader::VisitTypenameTypeLoc(TypenameTypeLoc TL) {
2123 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2124}
2125void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2126 TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2127}
2128void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2129 TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2130}
2131void TypeLocReader::VisitObjCProtocolListTypeLoc(ObjCProtocolListTypeLoc TL) {
2132 TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2133 TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2134 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2135 TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
John McCall8f115c62009-10-16 21:56:05 +00002136}
2137
2138DeclaratorInfo *PCHReader::GetDeclaratorInfo(const RecordData &Record,
2139 unsigned &Idx) {
2140 QualType InfoTy = GetType(Record[Idx++]);
2141 if (InfoTy.isNull())
2142 return 0;
2143
2144 DeclaratorInfo *DInfo = getContext()->CreateDeclaratorInfo(InfoTy);
2145 TypeLocReader TLR(*this, Record, Idx);
2146 for (TypeLoc TL = DInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2147 TLR.Visit(TL);
2148 return DInfo;
2149}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002150
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002151QualType PCHReader::GetType(pch::TypeID ID) {
John McCall8ccfcb52009-09-24 19:53:00 +00002152 unsigned FastQuals = ID & Qualifiers::FastMask;
2153 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002154
2155 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2156 QualType T;
2157 switch ((pch::PredefinedTypeIDs)Index) {
2158 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner8575daa2009-04-27 21:45:14 +00002159 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2160 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002161
2162 case pch::PREDEF_TYPE_CHAR_U_ID:
2163 case pch::PREDEF_TYPE_CHAR_S_ID:
2164 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner8575daa2009-04-27 21:45:14 +00002165 T = Context->CharTy;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002166 break;
2167
Chris Lattner8575daa2009-04-27 21:45:14 +00002168 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2169 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2170 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2171 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2172 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002173 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002174 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2175 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2176 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2177 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2178 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2179 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattnerf122cef2009-04-30 02:43:43 +00002180 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner8575daa2009-04-27 21:45:14 +00002181 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2182 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2183 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2184 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2185 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002186 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002187 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2188 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroff1329fa02009-07-15 18:40:39 +00002189 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2190 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002191 }
2192
2193 assert(!T.isNull() && "Unknown predefined type");
John McCall8ccfcb52009-09-24 19:53:00 +00002194 return T.withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002195 }
2196
2197 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc277ad12009-07-18 15:33:26 +00002198 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall8ccfcb52009-09-24 19:53:00 +00002199 if (TypesLoaded[Index].isNull())
2200 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump11289f42009-09-09 15:08:12 +00002201
John McCall8ccfcb52009-09-24 19:53:00 +00002202 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002203}
2204
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002205Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002206 if (ID == 0)
2207 return 0;
2208
Douglas Gregor745ed142009-04-25 18:35:21 +00002209 if (ID > DeclsLoaded.size()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002210 Error("declaration ID out-of-range for PCH file");
Douglas Gregor745ed142009-04-25 18:35:21 +00002211 return 0;
2212 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002213
Douglas Gregor745ed142009-04-25 18:35:21 +00002214 unsigned Index = ID - 1;
2215 if (!DeclsLoaded[Index])
2216 ReadDeclRecord(DeclOffsets[Index], Index);
2217
2218 return DeclsLoaded[Index];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002219}
2220
Chris Lattner9c28af02009-04-27 05:46:25 +00002221/// \brief Resolve the offset of a statement into a statement.
2222///
2223/// This operation will read a new statement from the external
2224/// source each time it is called, and is meant to be used via a
2225/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2226Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner1de76db2009-04-27 05:58:23 +00002227 // Since we know tha this statement is part of a decl, make sure to use the
2228 // decl cursor to read it.
2229 DeclsCursor.JumpToBit(Offset);
2230 return ReadStmt(DeclsCursor);
Douglas Gregor3c3aa612009-04-18 00:07:54 +00002231}
2232
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002233bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor1e9bf3b2009-04-10 17:25:41 +00002234 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002235 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002236 "DeclContext has no lexical decls in storage");
2237 uint64_t Offset = DeclContextOffsets[DC].first;
2238 assert(Offset && "DeclContext has no lexical decls in storage");
2239
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002240 // Keep track of where we are in the stream, then jump back there
2241 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002242 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002243
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002244 // Load the record containing all of the declarations lexically in
2245 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002246 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002247 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002248 unsigned Code = DeclsCursor.ReadCode();
2249 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002250 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002251 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2252
2253 // Load all of the declaration IDs
2254 Decls.clear();
2255 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002256 ++NumLexicalDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002257 return false;
2258}
2259
2260bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner72405d62009-04-27 07:35:40 +00002261 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump11289f42009-09-09 15:08:12 +00002262 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002263 "DeclContext has no visible decls in storage");
2264 uint64_t Offset = DeclContextOffsets[DC].second;
2265 assert(Offset && "DeclContext has no visible decls in storage");
2266
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002267 // Keep track of where we are in the stream, then jump back there
2268 // after reading this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002269 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002270
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002271 // Load the record containing all of the declarations visible in
2272 // this context.
Chris Lattner72405d62009-04-27 07:35:40 +00002273 DeclsCursor.JumpToBit(Offset);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002274 RecordData Record;
Chris Lattner72405d62009-04-27 07:35:40 +00002275 unsigned Code = DeclsCursor.ReadCode();
2276 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregore95304a2009-04-15 18:43:11 +00002277 (void)RecCode;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002278 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2279 if (Record.size() == 0)
Mike Stump11289f42009-09-09 15:08:12 +00002280 return false;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002281
2282 Decls.clear();
2283
2284 unsigned Idx = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002285 while (Idx < Record.size()) {
2286 Decls.push_back(VisibleDeclaration());
2287 Decls.back().Name = ReadDeclarationName(Record, Idx);
2288
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002289 unsigned Size = Record[Idx++];
Chris Lattner72405d62009-04-27 07:35:40 +00002290 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002291 LoadedDecls.reserve(Size);
2292 for (unsigned I = 0; I < Size; ++I)
2293 LoadedDecls.push_back(Record[Idx++]);
2294 }
2295
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002296 ++NumVisibleDeclContextsRead;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002297 return false;
2298}
2299
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002300void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregorb985eeb2009-04-22 19:09:20 +00002301 this->Consumer = Consumer;
2302
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002303 if (!Consumer)
2304 return;
2305
2306 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar865c2a72009-09-17 03:06:44 +00002307 // Force deserialization of this decl, which will cause it to be passed to
2308 // the consumer (or queued).
2309 GetDecl(ExternalDefinitions[I]);
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002310 }
Douglas Gregorf005eac2009-04-25 00:41:30 +00002311
2312 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2313 DeclGroupRef DG(InterestingDecls[I]);
2314 Consumer->HandleTopLevelDecl(DG);
2315 }
Douglas Gregor1a0d0b92009-04-14 00:24:19 +00002316}
2317
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002318void PCHReader::PrintStats() {
2319 std::fprintf(stderr, "*** PCH Statistics:\n");
2320
Mike Stump11289f42009-09-09 15:08:12 +00002321 unsigned NumTypesLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002322 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall8ccfcb52009-09-24 19:53:00 +00002323 QualType());
Douglas Gregor0e149972009-04-25 19:10:14 +00002324 unsigned NumDeclsLoaded
2325 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2326 (Decl *)0);
2327 unsigned NumIdentifiersLoaded
2328 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2329 IdentifiersLoaded.end(),
2330 (IdentifierInfo *)0);
Mike Stump11289f42009-09-09 15:08:12 +00002331 unsigned NumSelectorsLoaded
Douglas Gregor0e149972009-04-25 19:10:14 +00002332 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2333 SelectorsLoaded.end(),
2334 Selector());
Douglas Gregorc3b1dd12009-04-13 20:50:16 +00002335
Douglas Gregorc5046832009-04-27 18:38:38 +00002336 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2337 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor258ae542009-04-27 06:38:32 +00002338 if (TotalNumSLocEntries)
2339 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2340 NumSLocEntriesRead, TotalNumSLocEntries,
2341 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor745ed142009-04-25 18:35:21 +00002342 if (!TypesLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002343 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002344 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2345 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2346 if (!DeclsLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002347 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor745ed142009-04-25 18:35:21 +00002348 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2349 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor0e149972009-04-25 19:10:14 +00002350 if (!IdentifiersLoaded.empty())
Douglas Gregor95c13f52009-04-25 17:48:32 +00002351 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor0e149972009-04-25 19:10:14 +00002352 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2353 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor95c13f52009-04-25 17:48:32 +00002354 if (TotalNumSelectors)
2355 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2356 NumSelectorsLoaded, TotalNumSelectors,
2357 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2358 if (TotalNumStatements)
2359 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2360 NumStatementsRead, TotalNumStatements,
2361 ((float)NumStatementsRead/TotalNumStatements * 100));
2362 if (TotalNumMacros)
2363 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2364 NumMacrosRead, TotalNumMacros,
2365 ((float)NumMacrosRead/TotalNumMacros * 100));
2366 if (TotalLexicalDeclContexts)
2367 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2368 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2369 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2370 * 100));
2371 if (TotalVisibleDeclContexts)
2372 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2373 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2374 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2375 * 100));
2376 if (TotalSelectorsInMethodPool) {
2377 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2378 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2379 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2380 * 100));
2381 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2382 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002383 std::fprintf(stderr, "\n");
2384}
2385
Douglas Gregora868bbd2009-04-21 22:25:48 +00002386void PCHReader::InitializeSema(Sema &S) {
2387 SemaObj = &S;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002388 S.ExternalSource = this;
2389
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002390 // Makes sure any declarations that were deserialized "too early"
2391 // still get added to the identifier's declaration chains.
2392 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2393 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2394 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregora868bbd2009-04-21 22:25:48 +00002395 }
Douglas Gregor7cd60f72009-04-22 21:15:06 +00002396 PreloadedDecls.clear();
Douglas Gregord4df8652009-04-22 22:02:47 +00002397
2398 // If there were any tentative definitions, deserialize them and add
2399 // them to Sema's table of tentative definitions.
2400 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2401 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2402 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner0c797362009-09-08 18:19:27 +00002403 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregord4df8652009-04-22 22:02:47 +00002404 }
Douglas Gregoracfc76c2009-04-22 22:18:58 +00002405
2406 // If there were any locally-scoped external declarations,
2407 // deserialize them and add them to Sema's table of locally-scoped
2408 // external declarations.
2409 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2410 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2411 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2412 }
Douglas Gregor61cac2b2009-04-27 20:06:05 +00002413
2414 // If there were any ext_vector type declarations, deserialize them
2415 // and add them to Sema's vector of such declarations.
2416 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2417 SemaObj->ExtVectorDecls.push_back(
2418 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregora868bbd2009-04-21 22:25:48 +00002419}
2420
2421IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2422 // Try to find this name within our on-disk hash table
Mike Stump11289f42009-09-09 15:08:12 +00002423 PCHIdentifierLookupTable *IdTable
Douglas Gregora868bbd2009-04-21 22:25:48 +00002424 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2425 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2426 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2427 if (Pos == IdTable->end())
2428 return 0;
2429
2430 // Dereferencing the iterator has the effect of building the
2431 // IdentifierInfo node and populating it with the various
2432 // declarations it needs.
2433 return *Pos;
2434}
2435
Mike Stump11289f42009-09-09 15:08:12 +00002436std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorc78d3462009-04-24 21:10:55 +00002437PCHReader::ReadMethodPool(Selector Sel) {
2438 if (!MethodPoolLookupTable)
2439 return std::pair<ObjCMethodList, ObjCMethodList>();
2440
2441 // Try to find this selector within our on-disk hash table.
2442 PCHMethodPoolLookupTable *PoolTable
2443 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2444 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor95c13f52009-04-25 17:48:32 +00002445 if (Pos == PoolTable->end()) {
2446 ++NumMethodPoolMisses;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002447 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor95c13f52009-04-25 17:48:32 +00002448 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002449
Douglas Gregor95c13f52009-04-25 17:48:32 +00002450 ++NumMethodPoolSelectorsRead;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002451 return *Pos;
2452}
2453
Douglas Gregor0e149972009-04-25 19:10:14 +00002454void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregora868bbd2009-04-21 22:25:48 +00002455 assert(ID && "Non-zero identifier ID required");
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002456 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor0e149972009-04-25 19:10:14 +00002457 IdentifiersLoaded[ID - 1] = II;
Douglas Gregora868bbd2009-04-21 22:25:48 +00002458}
2459
Douglas Gregor1342e842009-07-06 18:54:52 +00002460/// \brief Set the globally-visible declarations associated with the given
2461/// identifier.
2462///
2463/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump11289f42009-09-09 15:08:12 +00002464/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregor1342e842009-07-06 18:54:52 +00002465/// them.
2466///
2467/// \param II an IdentifierInfo that refers to one or more globally-visible
2468/// declarations.
2469///
2470/// \param DeclIDs the set of declaration IDs with the name @p II that are
2471/// visible at global scope.
2472///
2473/// \param Nonrecursive should be true to indicate that the caller knows that
2474/// this call is non-recursive, and therefore the globally-visible declarations
2475/// will not be placed onto the pending queue.
Mike Stump11289f42009-09-09 15:08:12 +00002476void
2477PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregor1342e842009-07-06 18:54:52 +00002478 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2479 bool Nonrecursive) {
2480 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2481 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2482 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2483 PII.II = II;
2484 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2485 PII.DeclIDs.push_back(DeclIDs[I]);
2486 return;
2487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregor1342e842009-07-06 18:54:52 +00002489 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2490 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2491 if (SemaObj) {
2492 // Introduce this declaration into the translation-unit scope
2493 // and add it to the declaration chain for this identifier, so
2494 // that (unqualified) name lookup will find it.
2495 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2496 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2497 } else {
2498 // Queue this declaration so that it will be added to the
2499 // translation unit scope and identifier's declaration chain
2500 // once a Sema object is known.
2501 PreloadedDecls.push_back(D);
2502 }
2503 }
2504}
2505
Chris Lattnerc523d8e2009-04-11 21:15:38 +00002506IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002507 if (ID == 0)
2508 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002509
Douglas Gregor0e149972009-04-25 19:10:14 +00002510 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002511 Error("no identifier table in PCH file");
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002512 return 0;
2513 }
Mike Stump11289f42009-09-09 15:08:12 +00002514
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002515 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor0e149972009-04-25 19:10:14 +00002516 if (!IdentifiersLoaded[ID - 1]) {
2517 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor95272492009-04-25 21:21:38 +00002518 const char *Str = IdentifierTableData + Offset;
Douglas Gregor5287b4e2009-04-25 21:04:17 +00002519
Douglas Gregorab4df582009-04-28 20:01:51 +00002520 // All of the strings in the PCH file are preceded by a 16-bit
2521 // length. Extract that 16-bit length to avoid having to execute
2522 // strlen().
2523 const char *StrLenPtr = Str - 2;
2524 unsigned StrLen = (((unsigned) StrLenPtr[0])
2525 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump11289f42009-09-09 15:08:12 +00002526 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002527 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00002528 }
Mike Stump11289f42009-09-09 15:08:12 +00002529
Douglas Gregor0e149972009-04-25 19:10:14 +00002530 return IdentifiersLoaded[ID - 1];
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002531}
2532
Douglas Gregor258ae542009-04-27 06:38:32 +00002533void PCHReader::ReadSLocEntry(unsigned ID) {
2534 ReadSLocEntryRecord(ID);
2535}
2536
Steve Naroff2ddea052009-04-23 10:39:46 +00002537Selector PCHReader::DecodeSelector(unsigned ID) {
2538 if (ID == 0)
2539 return Selector();
Mike Stump11289f42009-09-09 15:08:12 +00002540
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002541 if (!MethodPoolLookupTableData)
Steve Naroff2ddea052009-04-23 10:39:46 +00002542 return Selector();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002543
2544 if (ID > TotalNumSelectors) {
Douglas Gregor6f00bf82009-04-28 21:53:25 +00002545 Error("selector ID out of range in PCH file");
Steve Naroff2ddea052009-04-23 10:39:46 +00002546 return Selector();
2547 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00002548
2549 unsigned Index = ID - 1;
2550 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2551 // Load this selector from the selector table.
2552 // FIXME: endianness portability issues with SelectorOffsets table
2553 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002554 SelectorsLoaded[Index]
Douglas Gregor95c13f52009-04-25 17:48:32 +00002555 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2556 }
2557
2558 return SelectorsLoaded[Index];
Steve Naroff2ddea052009-04-23 10:39:46 +00002559}
2560
Mike Stump11289f42009-09-09 15:08:12 +00002561DeclarationName
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002562PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2563 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2564 switch (Kind) {
2565 case DeclarationName::Identifier:
2566 return DeclarationName(GetIdentifierInfo(Record, Idx));
2567
2568 case DeclarationName::ObjCZeroArgSelector:
2569 case DeclarationName::ObjCOneArgSelector:
2570 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff3c301dc2009-04-23 15:15:40 +00002571 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002572
2573 case DeclarationName::CXXConstructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002574 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002575 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002576
2577 case DeclarationName::CXXDestructorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002578 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002579 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002580
2581 case DeclarationName::CXXConversionFunctionName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002582 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2211d342009-08-05 05:36:45 +00002583 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002584
2585 case DeclarationName::CXXOperatorName:
Chris Lattner8575daa2009-04-27 21:45:14 +00002586 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002587 (OverloadedOperatorKind)Record[Idx++]);
2588
2589 case DeclarationName::CXXUsingDirective:
2590 return DeclarationName::getUsingDirectiveName();
2591 }
2592
2593 // Required to silence GCC warning
2594 return DeclarationName();
2595}
Douglas Gregor55abb232009-04-10 20:39:37 +00002596
Douglas Gregor1daeb692009-04-13 18:14:40 +00002597/// \brief Read an integral value
2598llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2599 unsigned BitWidth = Record[Idx++];
2600 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2601 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2602 Idx += NumWords;
2603 return Result;
2604}
2605
2606/// \brief Read a signed integral value
2607llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2608 bool isUnsigned = Record[Idx++];
2609 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2610}
2611
Douglas Gregore0a3a512009-04-14 21:55:33 +00002612/// \brief Read a floating-point value
2613llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00002614 return llvm::APFloat(ReadAPInt(Record, Idx));
2615}
2616
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002617// \brief Read a string
2618std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2619 unsigned Len = Record[Idx++];
Jay Foad7d0479f2009-05-21 09:52:38 +00002620 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00002621 Idx += Len;
2622 return Result;
2623}
2624
Douglas Gregor55abb232009-04-10 20:39:37 +00002625DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregor92863e42009-04-10 23:10:45 +00002626 return Diag(SourceLocation(), DiagID);
2627}
2628
2629DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002630 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor55abb232009-04-10 20:39:37 +00002631}
Douglas Gregora9af1d12009-04-17 00:04:06 +00002632
Douglas Gregora868bbd2009-04-21 22:25:48 +00002633/// \brief Retrieve the identifier table associated with the
2634/// preprocessor.
2635IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis366985d2009-06-19 00:03:23 +00002636 assert(PP && "Forgot to set Preprocessor ?");
2637 return PP->getIdentifierTable();
Douglas Gregora868bbd2009-04-21 22:25:48 +00002638}
2639
Douglas Gregora9af1d12009-04-17 00:04:06 +00002640/// \brief Record that the given ID maps to the given switch-case
2641/// statement.
2642void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2643 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2644 SwitchCaseStmts[ID] = SC;
2645}
2646
2647/// \brief Retrieve the switch-case statement with the given ID.
2648SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2649 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2650 return SwitchCaseStmts[ID];
2651}
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002652
2653/// \brief Record that the given label statement has been
2654/// deserialized and has the given ID.
2655void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump11289f42009-09-09 15:08:12 +00002656 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002657 "Deserialized label twice");
2658 LabelStmts[ID] = S;
2659
2660 // If we've already seen any goto statements that point to this
2661 // label, resolve them now.
2662 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2663 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2664 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2665 Goto->second->setLabel(S);
2666 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor779d8652009-04-17 18:58:21 +00002667
2668 // If we've already seen any address-label statements that point to
2669 // this label, resolve them now.
2670 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump11289f42009-09-09 15:08:12 +00002671 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor779d8652009-04-17 18:58:21 +00002672 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump11289f42009-09-09 15:08:12 +00002673 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor779d8652009-04-17 18:58:21 +00002674 AddrLabel != AddrLabels.second; ++AddrLabel)
2675 AddrLabel->second->setLabel(S);
2676 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6cc68a42009-04-17 18:18:49 +00002677}
2678
2679/// \brief Set the label of the given statement to the label
2680/// identified by ID.
2681///
2682/// Depending on the order in which the label and other statements
2683/// referencing that label occur, this operation may complete
2684/// immediately (updating the statement) or it may queue the
2685/// statement to be back-patched later.
2686void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2687 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2688 if (Label != LabelStmts.end()) {
2689 // We've already seen this label, so set the label of the goto and
2690 // we're done.
2691 S->setLabel(Label->second);
2692 } else {
2693 // We haven't seen this label yet, so add this goto to the set of
2694 // unresolved goto statements.
2695 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2696 }
2697}
Douglas Gregor779d8652009-04-17 18:58:21 +00002698
2699/// \brief Set the label of the given expression to the label
2700/// identified by ID.
2701///
2702/// Depending on the order in which the label and other statements
2703/// referencing that label occur, this operation may complete
2704/// immediately (updating the statement) or it may queue the
2705/// statement to be back-patched later.
2706void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2707 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2708 if (Label != LabelStmts.end()) {
2709 // We've already seen this label, so set the label of the
2710 // label-address expression and we're done.
2711 S->setLabel(Label->second);
2712 } else {
2713 // We haven't seen this label yet, so add this label-address
2714 // expression to the set of unresolved label-address expressions.
2715 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2716 }
2717}
Douglas Gregor1342e842009-07-06 18:54:52 +00002718
2719
Mike Stump11289f42009-09-09 15:08:12 +00002720PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregor1342e842009-07-06 18:54:52 +00002721 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2722 Reader.CurrentlyLoadingTypeOrDecl = this;
2723}
2724
2725PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2726 if (!Parent) {
2727 // If any identifiers with corresponding top-level declarations have
2728 // been loaded, load those declarations now.
2729 while (!Reader.PendingIdentifierInfos.empty()) {
2730 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2731 Reader.PendingIdentifierInfos.front().DeclIDs,
2732 true);
2733 Reader.PendingIdentifierInfos.pop_front();
2734 }
2735 }
2736
Mike Stump11289f42009-09-09 15:08:12 +00002737 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregor1342e842009-07-06 18:54:52 +00002738}