blob: e61668dd31778a7e9e9ab60b4f8a752460c64111 [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregor445e23e2009-10-05 21:07:28 +000029#include "clang/Basic/Version.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000030#include "llvm/Bitcode/BitstreamReader.h"
31#include "llvm/Support/Compiler.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000034#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000035#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000036#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000037using namespace clang;
38
39//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000040// PCH reader validator implementation
41//===----------------------------------------------------------------------===//
42
43PCHReaderListener::~PCHReaderListener() {}
44
45bool
46PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
47 const LangOptions &PPLangOpts = PP.getLangOptions();
48#define PARSE_LANGOPT_BENIGN(Option)
49#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
50 if (PPLangOpts.Option != LangOpts.Option) { \
51 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
52 return true; \
53 }
54
55 PARSE_LANGOPT_BENIGN(Trigraphs);
56 PARSE_LANGOPT_BENIGN(BCPLComment);
57 PARSE_LANGOPT_BENIGN(DollarIdents);
58 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
59 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
60 PARSE_LANGOPT_BENIGN(ImplicitInt);
61 PARSE_LANGOPT_BENIGN(Digraphs);
62 PARSE_LANGOPT_BENIGN(HexFloats);
63 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
64 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
65 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
66 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
67 PARSE_LANGOPT_BENIGN(CXXOperatorName);
68 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
69 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
70 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
71 PARSE_LANGOPT_BENIGN(PascalStrings);
72 PARSE_LANGOPT_BENIGN(WritableStrings);
Mike Stump1eb44332009-09-09 15:08:12 +000073 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000074 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000075 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000076 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
77 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
78 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
79 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
Mike Stump1eb44332009-09-09 15:08:12 +000080 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000081 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000082 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000083 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
84 PARSE_LANGOPT_BENIGN(EmitAllDecls);
85 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
86 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
Mike Stump1eb44332009-09-09 15:08:12 +000087 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000088 diag::warn_pch_heinous_extensions);
89 // FIXME: Most of the options below are benign if the macro wasn't
90 // used. Unfortunately, this means that a PCH compiled without
91 // optimization can't be used with optimization turned on, even
92 // though the only thing that changes is whether __OPTIMIZE__ was
93 // defined... but if __OPTIMIZE__ never showed up in the header, it
94 // doesn't matter. We could consider making this some special kind
95 // of check.
96 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
97 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
98 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
99 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
100 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
101 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
102 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
103 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
104 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000105 Reader.Diag(diag::warn_pch_gc_mode)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000106 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
107 return true;
108 }
109 PARSE_LANGOPT_BENIGN(getVisibilityMode());
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000110 PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
111 diag::warn_pch_stack_protector);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000112 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000113 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Daniel Dunbarab8e2812009-09-21 04:16:19 +0000114 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000115#undef PARSE_LANGOPT_IRRELEVANT
116#undef PARSE_LANGOPT_BENIGN
117
118 return false;
119}
120
121bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000122 if (Triple != PP.getTargetInfo().getTriple().getTriple()) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000123 Reader.Diag(diag::warn_pch_target_triple)
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000124 << Triple << PP.getTargetInfo().getTriple().getTriple();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000125 return true;
126 }
127 return false;
128}
129
130/// \brief Split the given string into a vector of lines, eliminating
131/// any empty lines in the process.
132///
133/// \param Str the string to split.
134/// \param Len the length of Str.
135/// \param KeepEmptyLines true if empty lines should be included
136/// \returns a vector of lines, with the line endings removed
137static std::vector<std::string> splitLines(const char *Str, unsigned Len,
138 bool KeepEmptyLines = false) {
139 std::vector<std::string> Lines;
140 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
141 unsigned LineEnd = LineStart;
142 while (LineEnd < Len && Str[LineEnd] != '\n')
143 ++LineEnd;
144 if (LineStart != LineEnd || KeepEmptyLines)
145 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
146 LineStart = LineEnd;
147 }
148 return Lines;
149}
150
151/// \brief Determine whether the string Haystack starts with the
152/// substring Needle.
153static bool startsWith(const std::string &Haystack, const char *Needle) {
154 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
155 if (I == N)
156 return false;
157 if (Haystack[I] != Needle[I])
158 return false;
159 }
160
161 return true;
162}
163
164/// \brief Determine whether the string Haystack starts with the
165/// substring Needle.
166static inline bool startsWith(const std::string &Haystack,
167 const std::string &Needle) {
168 return startsWith(Haystack, Needle.c_str());
169}
170
Mike Stump1eb44332009-09-09 15:08:12 +0000171bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000172 unsigned PCHPredefLen,
173 FileID PCHBufferID,
174 std::string &SuggestedPredefines) {
175 const char *Predef = PP.getPredefines().c_str();
176 unsigned PredefLen = PP.getPredefines().size();
177
178 // If the two predefines buffers compare equal, we're done!
Mike Stump1eb44332009-09-09 15:08:12 +0000179 if (PredefLen == PCHPredefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000180 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
181 return false;
182
183 SourceManager &SourceMgr = PP.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000185 // The predefines buffers are different. Determine what the
186 // differences are, and whether they require us to reject the PCH
187 // file.
188 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
189 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
190
Mike Stump1eb44332009-09-09 15:08:12 +0000191 // Sort both sets of predefined buffer lines, since
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000192 std::sort(CmdLineLines.begin(), CmdLineLines.end());
193 std::sort(PCHLines.begin(), PCHLines.end());
194
195 // Determine which predefines that where used to build the PCH file
196 // are missing from the command line.
197 std::vector<std::string> MissingPredefines;
198 std::set_difference(PCHLines.begin(), PCHLines.end(),
199 CmdLineLines.begin(), CmdLineLines.end(),
200 std::back_inserter(MissingPredefines));
201
202 bool MissingDefines = false;
203 bool ConflictingDefines = false;
204 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
205 const std::string &Missing = MissingPredefines[I];
206 if (!startsWith(Missing, "#define ") != 0) {
207 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
208 return true;
209 }
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000211 // This is a macro definition. Determine the name of the macro
212 // we're defining.
213 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000214 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000215 = Missing.find_first_of("( \n\r", StartOfMacroName);
216 assert(EndOfMacroName != std::string::npos &&
217 "Couldn't find the end of the macro name");
218 std::string MacroName = Missing.substr(StartOfMacroName,
219 EndOfMacroName - StartOfMacroName);
220
221 // Determine whether this macro was given a different definition
222 // on the command line.
223 std::string MacroDefStart = "#define " + MacroName;
224 std::string::size_type MacroDefLen = MacroDefStart.size();
225 std::vector<std::string>::iterator ConflictPos
226 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
227 MacroDefStart);
228 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
229 if (!startsWith(*ConflictPos, MacroDefStart)) {
230 // Different macro; we're done.
231 ConflictPos = CmdLineLines.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000232 break;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000233 }
Mike Stump1eb44332009-09-09 15:08:12 +0000234
235 assert(ConflictPos->size() > MacroDefLen &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000236 "Invalid #define in predefines buffer?");
Mike Stump1eb44332009-09-09 15:08:12 +0000237 if ((*ConflictPos)[MacroDefLen] != ' ' &&
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000238 (*ConflictPos)[MacroDefLen] != '(')
239 continue; // Longer macro name; keep trying.
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000241 // We found a conflicting macro definition.
242 break;
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000245 if (ConflictPos != CmdLineLines.end()) {
246 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
247 << MacroName;
248
249 // Show the definition of this macro within the PCH file.
250 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
251 unsigned Offset = MissingDef - PCHPredef;
252 SourceLocation PCHMissingLoc
253 = SourceMgr.getLocForStartOfFile(PCHBufferID)
254 .getFileLocWithOffset(Offset);
255 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
256 << MacroName;
257
258 ConflictingDefines = true;
259 continue;
260 }
Mike Stump1eb44332009-09-09 15:08:12 +0000261
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000262 // If the macro doesn't conflict, then we'll just pick up the
263 // macro definition from the PCH file. Warn the user that they
264 // made a mistake.
265 if (ConflictingDefines)
266 continue; // Don't complain if there are already conflicting defs
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000268 if (!MissingDefines) {
269 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
270 MissingDefines = true;
271 }
272
273 // Show the definition of this macro within the PCH file.
274 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
275 unsigned Offset = MissingDef - PCHPredef;
276 SourceLocation PCHMissingLoc
277 = SourceMgr.getLocForStartOfFile(PCHBufferID)
278 .getFileLocWithOffset(Offset);
279 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
280 }
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000282 if (ConflictingDefines)
283 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000285 // Determine what predefines were introduced based on command-line
286 // parameters that were not present when building the PCH
287 // file. Extra #defines are okay, so long as the identifiers being
288 // defined were not used within the precompiled header.
289 std::vector<std::string> ExtraPredefines;
290 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
291 PCHLines.begin(), PCHLines.end(),
Mike Stump1eb44332009-09-09 15:08:12 +0000292 std::back_inserter(ExtraPredefines));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000293 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
294 const std::string &Extra = ExtraPredefines[I];
295 if (!startsWith(Extra, "#define ") != 0) {
296 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
297 return true;
298 }
299
300 // This is an extra macro definition. Determine the name of the
301 // macro we're defining.
302 std::string::size_type StartOfMacroName = strlen("#define ");
Mike Stump1eb44332009-09-09 15:08:12 +0000303 std::string::size_type EndOfMacroName
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000304 = Extra.find_first_of("( \n\r", StartOfMacroName);
305 assert(EndOfMacroName != std::string::npos &&
306 "Couldn't find the end of the macro name");
307 std::string MacroName = Extra.substr(StartOfMacroName,
308 EndOfMacroName - StartOfMacroName);
309
310 // Check whether this name was used somewhere in the PCH file. If
311 // so, defining it as a macro could change behavior, so we reject
312 // the PCH file.
313 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
314 MacroName.c_str() + MacroName.size())) {
315 Reader.Diag(diag::warn_macro_name_used_in_pch)
316 << II;
317 return true;
318 }
319
320 // Add this definition to the suggested predefines buffer.
321 SuggestedPredefines += Extra;
322 SuggestedPredefines += '\n';
323 }
324
325 // If we get here, it's because the predefines buffer had compatible
326 // contents. Accept the PCH file.
327 return false;
328}
329
330void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
331 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
332}
333
334void PCHValidator::ReadCounter(unsigned Value) {
335 PP.setCounterValue(Value);
336}
337
338
339
340//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000341// PCH reader implementation
342//===----------------------------------------------------------------------===//
343
Mike Stump1eb44332009-09-09 15:08:12 +0000344PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
345 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000346 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
347 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
348 SemaObj(0), PP(&PP), Context(Context), Consumer(0),
349 IdentifierTableData(0), IdentifierLookupTable(0),
350 IdentifierOffsets(0),
351 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
352 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000353 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000354 NumStatHits(0), NumStatMisses(0),
355 NumSLocEntriesRead(0), NumStatementsRead(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000356 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000357 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000358 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000359 RelocatablePCH = false;
360}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000361
362PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Mike Stump1eb44332009-09-09 15:08:12 +0000363 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000364 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Argyrios Kyrtzidis57102112009-06-19 07:55:35 +0000365 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000366 IdentifierTableData(0), IdentifierLookupTable(0),
367 IdentifierOffsets(0),
368 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
369 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000370 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Mike Stump1eb44332009-09-09 15:08:12 +0000371 NumStatHits(0), NumStatMisses(0),
372 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000373 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000374 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Mike Stump1eb44332009-09-09 15:08:12 +0000375 CurrentlyLoadingTypeOrDecl(0) {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000376 RelocatablePCH = false;
377}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000378
379PCHReader::~PCHReader() {}
380
Chris Lattnerda930612009-04-27 05:58:23 +0000381Expr *PCHReader::ReadDeclExpr() {
382 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
383}
384
385Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +0000386 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000387}
388
389
Douglas Gregor668c1a42009-04-21 22:25:48 +0000390namespace {
Douglas Gregorf0aaf7a2009-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 Stump1eb44332009-09-09 15:08:12 +0000401
Douglas Gregorf0aaf7a2009-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 Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorf0aaf7a2009-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))
414 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
415 return R;
416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Douglas Gregorf0aaf7a2009-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 Stump1eb44332009-09-09 15:08:12 +0000421
Douglas Gregorf0aaf7a2009-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 Stump1eb44332009-09-09 15:08:12 +0000429
Douglas Gregor83941df2009-04-25 17:48:32 +0000430 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000431 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000432 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000433 unsigned N = ReadUnalignedLE16(d);
Mike Stump1eb44332009-09-09 15:08:12 +0000434 IdentifierInfo *FirstII
Douglas Gregorf0aaf7a2009-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 Gregor75fdb232009-05-22 22:45:36 +0000446 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000447 }
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Douglas Gregorf0aaf7a2009-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 Stump1eb44332009-09-09 15:08:12 +0000459 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-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 Stump1eb44332009-09-09 15:08:12 +0000475 ObjCMethodDecl *Method
Douglas Gregorf0aaf7a2009-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 Stump1eb44332009-09-09 15:08:12 +0000491
492} // end anonymous namespace
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000493
494/// \brief The on-disk hash table used for the global method pool.
Mike Stump1eb44332009-09-09 15:08:12 +0000495typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000496 PCHMethodPoolLookupTable;
497
498namespace {
Douglas Gregor668c1a42009-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 Stump1eb44332009-09-09 15:08:12 +0000514 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
Douglas Gregor668c1a42009-04-21 22:25:48 +0000515 : Reader(Reader), KnownII(II) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Douglas Gregor668c1a42009-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 Stump1eb44332009-09-09 15:08:12 +0000522
Douglas Gregor668c1a42009-04-21 22:25:48 +0000523 static unsigned ComputeHash(const internal_key_type& a) {
524 return BernsteinHash(a.first, a.second);
525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Douglas Gregor668c1a42009-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 Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregor668c1a42009-04-21 22:25:48 +0000531 static std::pair<unsigned, unsigned>
532 ReadKeyDataLength(const unsigned char*& d) {
533 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000534 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000535 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000536 return std::make_pair(KeyLen, DataLen);
537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Douglas Gregor668c1a42009-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 Stump1eb44332009-09-09 15:08:12 +0000544
545 IdentifierInfo *ReadData(const internal_key_type& k,
Douglas Gregor668c1a42009-04-21 22:25:48 +0000546 const unsigned char* d,
547 unsigned DataLen) {
548 using namespace clang::io;
Douglas Gregora92193e2009-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 Gregor5998da52009-04-28 21:32:13 +0000566 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-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 Stump1eb44332009-09-09 15:08:12 +0000577
Douglas Gregor2deaea32009-04-22 18:49:13 +0000578 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000579 DataLen -= 6;
Douglas Gregor668c1a42009-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 Gregor5f8e3302009-04-25 20:26:24 +0000585 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
586 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000587 Reader.SetIdentifierInfo(ID, II);
588
Douglas Gregor2deaea32009-04-22 18:49:13 +0000589 // Set or check the various bits in the IdentifierInfo structure.
590 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000591 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
Mike Stump1eb44332009-09-09 15:08:12 +0000592 assert(II->isExtensionToken() == ExtensionToken &&
Douglas Gregor2deaea32009-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 Gregor37e26842009-04-21 23:56:24 +0000600 // If this identifier is a macro, deserialize the macro
601 // definition.
602 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000603 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000604 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000605 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000606 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000607
608 // Read all of the declarations visible at global scope with this
609 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000610 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-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 Gregor668c1a42009-04-21 22:25:48 +0000616 }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregor668c1a42009-04-21 22:25:48 +0000618 return II;
619 }
620};
Mike Stump1eb44332009-09-09 15:08:12 +0000621
622} // end anonymous namespace
Douglas Gregor668c1a42009-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 Stump1eb44332009-09-09 15:08:12 +0000626typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
Douglas Gregor668c1a42009-04-21 22:25:48 +0000627 PCHIdentifierLookupTable;
628
Douglas Gregora02b1472009-04-28 21:53:25 +0000629bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000630 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
631 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000632 return true;
633}
634
Douglas Gregore1d918e2009-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 Stump1eb44332009-09-09 15:08:12 +0000652bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
Douglas Gregore1d918e2009-04-10 23:10:45 +0000653 unsigned PCHPredefLen,
654 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000655 if (Listener)
656 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
657 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000658 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000659}
660
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000661//===----------------------------------------------------------------------===//
662// Source Manager Deserialization
663//===----------------------------------------------------------------------===//
664
Douglas Gregorbd945002009-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 Gregore650c8c2009-07-07 00:12:59 +0000667bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000668 unsigned Idx = 0;
669 LineTableInfo &LineTable = SourceMgr.getLineTable();
670
671 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000672 std::map<int, int> FileIDs;
673 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-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 Gregore650c8c2009-07-07 00:12:59 +0000678 MaybeAddSystemRootToFilename(Filename);
Mike Stump1eb44332009-09-09 15:08:12 +0000679 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
Douglas Gregorff0a9872009-04-13 17:12:42 +0000680 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000681 }
682
683 // Parse the line entries
684 std::vector<LineEntry> Entries;
685 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000686 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-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 Stump1eb44332009-09-09 15:08:12 +0000696 SrcMgr::CharacteristicKind FileKind
Douglas Gregorbd945002009-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 Gregor4fed3f42009-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 Stump1eb44332009-09-09 15:08:12 +0000718
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000719 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
Mike Stump1eb44332009-09-09 15:08:12 +0000720 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
721
Douglas Gregor4fed3f42009-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) {
734 return BernsteinHash(path);
735 }
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 Stump1eb44332009-09-09 15:08:12 +0000764 time_t mtime = (time_t) ReadUnalignedLE64(d);
Douglas Gregor4fed3f42009-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 Stump1eb44332009-09-09 15:08:12 +0000779public:
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000780 PCHStatCache(const unsigned char *Buckets,
781 const unsigned char *Base,
782 unsigned &NumStatHits,
Mike Stump1eb44332009-09-09 15:08:12 +0000783 unsigned &NumStatMisses)
Douglas Gregor4fed3f42009-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 Stump1eb44332009-09-09 15:08:12 +0000789
Douglas Gregor4fed3f42009-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;
797 return ::stat(path, buf);
798 }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000800 ++NumStatHits;
801 PCHStatData Data = *I;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Douglas Gregor4fed3f42009-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 Gregor14f79002009-04-10 03:52:48 +0000817/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000818PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000819 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-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 Gregora02b1472009-04-28 21:53:25 +0000829 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-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 Gregora02b1472009-04-28 21:53:25 +0000835 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000836 return Failure;
837 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000838
Douglas Gregor14f79002009-04-10 03:52:48 +0000839 RecordData Record;
840 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000841 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000842 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000843 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000844 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000845 return Failure;
846 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000847 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000848 }
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregor14f79002009-04-10 03:52:48 +0000850 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
851 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000852 SLocEntryCursor.ReadSubBlockID();
853 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000854 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000855 return Failure;
856 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000857 continue;
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregor14f79002009-04-10 03:52:48 +0000860 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000861 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000862 continue;
863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Douglas Gregor14f79002009-04-10 03:52:48 +0000865 // Read a record.
866 const char *BlobStart;
867 unsigned BlobLen;
868 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000869 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000870 default: // Default behavior: ignore.
871 break;
872
Chris Lattner2c78b872009-04-14 23:22:57 +0000873 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000874 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000875 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000876 break;
Douglas Gregor2eafc1b2009-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 Kyrtzidis11e51102009-06-19 00:03:23 +0000884 if (Listener)
885 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000886 break;
887 }
Douglas Gregor7f94b0b2009-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 Gregor14f79002009-04-10 03:52:48 +0000894 }
895 }
896}
897
Douglas Gregor7f94b0b2009-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 Gregor7f94b0b2009-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 Gregore650c8c2009-07-07 00:12:59 +0000927 std::string Filename(BlobStart, BlobStart + BlobLen);
928 MaybeAddSystemRootToFilename(Filename);
929 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000930 if (File == 0) {
931 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000932 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000933 ErrorStr += "' referenced by PCH file";
934 Error(ErrorStr.c_str());
935 return Failure;
936 }
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Douglas Gregor7f94b0b2009-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 Stump1eb44332009-09-09 15:08:12 +0000954 unsigned RecCode
Douglas Gregor7f94b0b2009-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 Stump1eb44332009-09-09 15:08:12 +0000959 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000960 BlobStart + BlobLen - 1,
961 Name);
962 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Douglas Gregor92b059e2009-04-28 20:33:11 +0000964 if (strcmp(Name, "<built-in>") == 0) {
965 PCHPredefinesBufferID = BufferID;
966 PCHPredefines = BlobStart;
967 PCHPredefinesLen = BlobLen - 1;
968 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000969
970 break;
971 }
972
973 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
Mike Stump1eb44332009-09-09 15:08:12 +0000974 SourceLocation SpellingLoc
Douglas Gregor7f94b0b2009-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 Stump1eb44332009-09-09 15:08:12 +0000983 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000984 }
985
986 return Success;
987}
988
Chris Lattner6367f6d2009-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 Gregora02b1472009-04-28 21:53:25 +0000995 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000996 return Failure;
997 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner6367f6d2009-04-27 01:05:14 +0000999 while (true) {
1000 unsigned Code = Cursor.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner6367f6d2009-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 Gregor37e26842009-04-21 23:56:24 +00001009void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001010 assert(PP && "Forgot to set Preprocessor ?");
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Douglas Gregor37e26842009-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 Stump1eb44332009-09-09 15:08:12 +00001020
Douglas Gregor37e26842009-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 Gregora02b1472009-04-28 21:53:25 +00001031 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001032 return;
1033 }
1034 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregor37e26842009-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 Gregor37e26842009-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 Gregora02b1472009-04-28 21:53:25 +00001057 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001058 return;
1059 }
1060 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1061 bool isUsed = Record[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001063 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001064 MI->setIsUsed(isUsed);
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregor37e26842009-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 Gregor75fdb232009-05-22 22:45:36 +00001079 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001080 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001081 }
1082
1083 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001084 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-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 Stump1eb44332009-09-09 15:08:12 +00001092
Douglas Gregor37e26842009-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 Stump1eb44332009-09-09 15:08:12 +00001097
Douglas Gregor37e26842009-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 Naroff83d63c72009-04-24 20:03:17 +00001109 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001110 }
1111}
1112
Douglas Gregore650c8c2009-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 Stump1eb44332009-09-09 15:08:12 +00001120
Douglas Gregore650c8c2009-07-07 00:12:59 +00001121 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1122 return;
1123
1124 std::string FIXME = Filename;
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Douglas Gregore650c8c2009-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 Stump1eb44332009-09-09 15:08:12 +00001131
Douglas Gregore650c8c2009-07-07 00:12:59 +00001132 unsigned Length = strlen(isysroot);
1133 if (isysroot[Length - 1] != '/')
1134 Filename.insert(Filename.begin(), '/');
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Douglas Gregore650c8c2009-07-07 00:12:59 +00001136 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1137}
1138
Mike Stump1eb44332009-09-09 15:08:12 +00001139PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001140PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001141 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001142 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001143 return Failure;
1144 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001145
1146 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001147 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001148 while (!Stream.AtEndOfStream()) {
1149 unsigned Code = Stream.ReadCode();
1150 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001151 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001152 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001153 return Failure;
1154 }
Chris Lattner7356a312009-04-11 21:15:38 +00001155
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001156 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001157 }
1158
1159 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1160 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001161 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1162 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001163 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001164 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001165 return Failure;
1166 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001167 break;
1168
Chris Lattner6367f6d2009-04-27 01:05:14 +00001169 case pch::DECLS_BLOCK_ID:
1170 // We lazily load the decls block, but we want to set up the
1171 // DeclsCursor cursor to point into it. Clone our current bitcode
1172 // cursor to it, enter the block and read the abbrevs in that block.
1173 // With the main cursor, we just skip over it.
1174 DeclsCursor = Stream;
1175 if (Stream.SkipBlock() || // Skip with the main cursor.
1176 // Read the abbrevs.
1177 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001178 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001179 return Failure;
1180 }
1181 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Chris Lattner7356a312009-04-11 21:15:38 +00001183 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001184 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001185 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001186 return Failure;
1187 }
1188 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001189
Douglas Gregor14f79002009-04-10 03:52:48 +00001190 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001191 switch (ReadSourceManagerBlock()) {
1192 case Success:
1193 break;
1194
1195 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001196 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001197 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001198
1199 case IgnorePCH:
1200 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001201 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001202 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001203 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001204 continue;
1205 }
1206
1207 if (Code == llvm::bitc::DEFINE_ABBREV) {
1208 Stream.ReadAbbrevRecord();
1209 continue;
1210 }
1211
1212 // Read and process a record.
1213 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001214 const char *BlobStart = 0;
1215 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001216 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
Douglas Gregor2bec0412009-04-10 21:16:55 +00001217 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001218 default: // Default behavior: ignore.
1219 break;
1220
1221 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001222 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001223 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001224 return Failure;
1225 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001226 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001227 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001228 break;
1229
1230 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001231 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001232 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001233 return Failure;
1234 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001235 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001236 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001237 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001238
1239 case pch::LANGUAGE_OPTIONS:
1240 if (ParseLanguageOptions(Record))
1241 return IgnorePCH;
1242 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001243
Douglas Gregorab41e632009-04-27 22:23:34 +00001244 case pch::METADATA: {
1245 if (Record[0] != pch::VERSION_MAJOR) {
1246 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1247 : diag::warn_pch_version_too_new);
1248 return IgnorePCH;
1249 }
1250
Douglas Gregore650c8c2009-07-07 00:12:59 +00001251 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001252 if (Listener) {
1253 std::string TargetTriple(BlobStart, BlobLen);
1254 if (Listener->ReadTargetTriple(TargetTriple))
1255 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001256 }
1257 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001258 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001259
1260 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001261 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001262 if (Record[0]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001263 IdentifierLookupTable
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001264 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001265 (const unsigned char *)IdentifierTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001266 (const unsigned char *)IdentifierTableData,
Douglas Gregor668c1a42009-04-21 22:25:48 +00001267 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001268 if (PP)
1269 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001270 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001271 break;
1272
1273 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001274 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001275 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001276 return Failure;
1277 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001278 IdentifierOffsets = (const uint32_t *)BlobStart;
1279 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001280 if (PP)
1281 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001282 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001283
1284 case pch::EXTERNAL_DEFINITIONS:
1285 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001286 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001287 return Failure;
1288 }
1289 ExternalDefinitions.swap(Record);
1290 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001291
Douglas Gregorad1de002009-04-18 05:55:16 +00001292 case pch::SPECIAL_TYPES:
1293 SpecialTypes.swap(Record);
1294 break;
1295
Douglas Gregor3e1af842009-04-17 22:13:46 +00001296 case pch::STATISTICS:
1297 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001298 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001299 TotalLexicalDeclContexts = Record[2];
1300 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001301 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001302
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001303 case pch::TENTATIVE_DEFINITIONS:
1304 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001305 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001306 return Failure;
1307 }
1308 TentativeDefinitions.swap(Record);
1309 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001310
1311 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1312 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001313 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001314 return Failure;
1315 }
1316 LocallyScopedExternalDecls.swap(Record);
1317 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001318
Douglas Gregor83941df2009-04-25 17:48:32 +00001319 case pch::SELECTOR_OFFSETS:
1320 SelectorOffsets = (const uint32_t *)BlobStart;
1321 TotalNumSelectors = Record[0];
1322 SelectorsLoaded.resize(TotalNumSelectors);
1323 break;
1324
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001325 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001326 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1327 if (Record[0])
Mike Stump1eb44332009-09-09 15:08:12 +00001328 MethodPoolLookupTable
Douglas Gregor83941df2009-04-25 17:48:32 +00001329 = PCHMethodPoolLookupTable::Create(
1330 MethodPoolLookupTableData + Record[0],
Mike Stump1eb44332009-09-09 15:08:12 +00001331 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001332 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001333 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001334 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001335
1336 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001337 if (!Record.empty() && Listener)
1338 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001339 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001340
1341 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001342 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001343 TotalNumSLocEntries = Record[0];
Douglas Gregor445e23e2009-10-05 21:07:28 +00001344 SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, Record[1]);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001345 break;
1346
1347 case pch::SOURCE_LOCATION_PRELOADS:
1348 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1349 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1350 if (Result != Success)
1351 return Result;
1352 }
1353 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001354
1355 case pch::STAT_CACHE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001356 FileMgr.setStatCache(
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001357 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1358 (const unsigned char *)BlobStart,
1359 NumStatHits, NumStatMisses));
1360 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001361
1362 case pch::EXT_VECTOR_DECLS:
1363 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001364 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001365 return Failure;
1366 }
1367 ExtVectorDecls.swap(Record);
1368 break;
1369
Douglas Gregorb64c1932009-05-12 01:31:05 +00001370 case pch::ORIGINAL_FILE_NAME:
1371 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001372 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001373 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Douglas Gregor2e222532009-07-02 17:08:52 +00001375 case pch::COMMENT_RANGES:
1376 Comments = (SourceRange *)BlobStart;
1377 NumComments = BlobLen / sizeof(SourceRange);
1378 break;
Douglas Gregor445e23e2009-10-05 21:07:28 +00001379
1380 case pch::SVN_BRANCH_REVISION: {
1381 unsigned CurRevision = getClangSubversionRevision();
1382 if (Record[0] && CurRevision && Record[0] != CurRevision) {
1383 Diag(Record[0] < CurRevision? diag::warn_pch_version_too_old
1384 : diag::warn_pch_version_too_new);
1385 return IgnorePCH;
1386 }
1387
1388 const char *CurBranch = getClangSubversionPath();
1389 if (strncmp(CurBranch, BlobStart, BlobLen)) {
1390 std::string PCHBranch(BlobStart, BlobLen);
1391 Diag(diag::warn_pch_different_branch) << PCHBranch << CurBranch;
1392 return IgnorePCH;
1393 }
1394 break;
1395 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001396 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001397 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001398 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001399 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001400}
1401
Douglas Gregore1d918e2009-04-10 23:10:45 +00001402PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001403 // Set the PCH file name.
1404 this->FileName = FileName;
1405
Douglas Gregor2cf26342009-04-09 22:27:44 +00001406 // Open the PCH file.
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001407 //
1408 // FIXME: This shouldn't be here, we should just take a raw_ostream.
Douglas Gregor2cf26342009-04-09 22:27:44 +00001409 std::string ErrStr;
Daniel Dunbarf3c740e2009-09-22 05:38:01 +00001410 if (FileName == "-")
1411 Buffer.reset(llvm::MemoryBuffer::getSTDIN());
1412 else
1413 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001414 if (!Buffer) {
1415 Error(ErrStr.c_str());
1416 return IgnorePCH;
1417 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001418
1419 // Initialize the stream
Mike Stump1eb44332009-09-09 15:08:12 +00001420 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001421 (const unsigned char *)Buffer->getBufferEnd());
1422 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001423
1424 // Sniff for the signature.
1425 if (Stream.Read(8) != 'C' ||
1426 Stream.Read(8) != 'P' ||
1427 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001428 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001429 Diag(diag::err_not_a_pch_file) << FileName;
1430 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001431 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001432
Douglas Gregor2cf26342009-04-09 22:27:44 +00001433 while (!Stream.AtEndOfStream()) {
1434 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Douglas Gregore1d918e2009-04-10 23:10:45 +00001436 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001437 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001438 return Failure;
1439 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001440
1441 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001442
Douglas Gregor2cf26342009-04-09 22:27:44 +00001443 // We only know the PCH subblock ID.
1444 switch (BlockID) {
1445 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001446 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001447 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001448 return Failure;
1449 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001450 break;
1451 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001452 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001453 case Success:
1454 break;
1455
1456 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001457 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001458
1459 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001460 // FIXME: We could consider reading through to the end of this
1461 // PCH block, skipping subblocks, to see if there are other
1462 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001463
1464 // Clear out any preallocated source location entries, so that
1465 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001466 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001467
1468 // Remove the stat cache.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001469 FileMgr.setStatCache(0);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001470
Douglas Gregore1d918e2009-04-10 23:10:45 +00001471 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001472 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001473 break;
1474 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001475 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001476 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001477 return Failure;
1478 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001479 break;
1480 }
Mike Stump1eb44332009-09-09 15:08:12 +00001481 }
1482
Douglas Gregor92b059e2009-04-28 20:33:11 +00001483 // Check the predefines buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001484 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
Douglas Gregor92b059e2009-04-28 20:33:11 +00001485 PCHPredefinesBufferID))
1486 return IgnorePCH;
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001488 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001489 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001490 // PCH file is read, so there may be some identifiers that were
1491 // loaded into the IdentifierTable before we intercepted the
1492 // creation of identifiers. Iterate through the list of known
1493 // identifiers and determine whether we have to establish
1494 // preprocessor definitions or top-level identifier declaration
1495 // chains for those identifiers.
1496 //
1497 // We copy the IdentifierInfo pointers to a small vector first,
1498 // since de-serializing declarations or macro definitions can add
1499 // new entries into the identifier table, invalidating the
1500 // iterators.
1501 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1502 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1503 IdEnd = PP->getIdentifierTable().end();
1504 Id != IdEnd; ++Id)
1505 Identifiers.push_back(Id->second);
Mike Stump1eb44332009-09-09 15:08:12 +00001506 PCHIdentifierLookupTable *IdTable
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001507 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1508 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1509 IdentifierInfo *II = Identifiers[I];
1510 // Look in the on-disk hash table for an entry for
1511 PCHIdentifierLookupTrait Info(*this, II);
1512 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1513 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1514 if (Pos == IdTable->end())
1515 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001517 // Dereferencing the iterator has the effect of populating the
1518 // IdentifierInfo node with the various declarations it needs.
1519 (void)*Pos;
1520 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001521 }
1522
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001523 if (Context)
1524 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001525
Douglas Gregor668c1a42009-04-21 22:25:48 +00001526 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001527}
1528
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001529void PCHReader::InitializeContext(ASTContext &Ctx) {
1530 Context = &Ctx;
1531 assert(Context && "Passed null context!");
1532
1533 assert(PP && "Forgot to set Preprocessor ?");
1534 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1535 PP->getHeaderSearchInfo().SetExternalLookup(this);
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001537 // Load the translation unit declaration
1538 ReadDeclRecord(DeclOffsets[0], 0);
1539
1540 // Load the special types.
1541 Context->setBuiltinVaListType(
1542 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1543 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1544 Context->setObjCIdType(GetType(Id));
1545 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1546 Context->setObjCSelType(GetType(Sel));
1547 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1548 Context->setObjCProtoType(GetType(Proto));
1549 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1550 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001551
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001552 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1553 Context->setCFConstantStringType(GetType(String));
Mike Stump1eb44332009-09-09 15:08:12 +00001554 if (unsigned FastEnum
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001555 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1556 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001557 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1558 QualType FileType = GetType(File);
1559 assert(!FileType.isNull() && "FILE type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001560 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001561 Context->setFILEDecl(Typedef->getDecl());
1562 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001563 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001564 assert(Tag && "Invalid FILE type in PCH file");
1565 Context->setFILEDecl(Tag->getDecl());
1566 }
1567 }
Mike Stump782fa302009-07-28 02:25:19 +00001568 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1569 QualType Jmp_bufType = GetType(Jmp_buf);
1570 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001571 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001572 Context->setjmp_bufDecl(Typedef->getDecl());
1573 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001574 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001575 assert(Tag && "Invalid jmp_bug type in PCH file");
1576 Context->setjmp_bufDecl(Tag->getDecl());
1577 }
1578 }
1579 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1580 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1581 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
John McCall183700f2009-09-21 23:43:11 +00001582 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Mike Stump782fa302009-07-28 02:25:19 +00001583 Context->setsigjmp_bufDecl(Typedef->getDecl());
1584 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001585 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001586 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1587 Context->setsigjmp_bufDecl(Tag->getDecl());
1588 }
1589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590 if (unsigned ObjCIdRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001591 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1592 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
Mike Stump1eb44332009-09-09 15:08:12 +00001593 if (unsigned ObjCClassRedef
Douglas Gregord1571ac2009-08-21 00:27:50 +00001594 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1595 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001596}
1597
Douglas Gregorb64c1932009-05-12 01:31:05 +00001598/// \brief Retrieve the name of the original source file name
1599/// directly from the PCH file, without actually loading the PCH
1600/// file.
1601std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1602 // Open the PCH file.
1603 std::string ErrStr;
1604 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1605 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1606 if (!Buffer) {
1607 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1608 return std::string();
1609 }
1610
1611 // Initialize the stream
1612 llvm::BitstreamReader StreamFile;
1613 llvm::BitstreamCursor Stream;
Mike Stump1eb44332009-09-09 15:08:12 +00001614 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
Douglas Gregorb64c1932009-05-12 01:31:05 +00001615 (const unsigned char *)Buffer->getBufferEnd());
1616 Stream.init(StreamFile);
1617
1618 // Sniff for the signature.
1619 if (Stream.Read(8) != 'C' ||
1620 Stream.Read(8) != 'P' ||
1621 Stream.Read(8) != 'C' ||
1622 Stream.Read(8) != 'H') {
Mike Stump1eb44332009-09-09 15:08:12 +00001623 fprintf(stderr,
Douglas Gregorb64c1932009-05-12 01:31:05 +00001624 "error: '%s' does not appear to be a precompiled header file\n",
1625 PCHFileName.c_str());
1626 return std::string();
1627 }
1628
1629 RecordData Record;
1630 while (!Stream.AtEndOfStream()) {
1631 unsigned Code = Stream.ReadCode();
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Douglas Gregorb64c1932009-05-12 01:31:05 +00001633 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1634 unsigned BlockID = Stream.ReadSubBlockID();
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Douglas Gregorb64c1932009-05-12 01:31:05 +00001636 // We only know the PCH subblock ID.
1637 switch (BlockID) {
1638 case pch::PCH_BLOCK_ID:
1639 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1640 fprintf(stderr, "error: malformed block record in PCH file\n");
1641 return std::string();
1642 }
1643 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Douglas Gregorb64c1932009-05-12 01:31:05 +00001645 default:
1646 if (Stream.SkipBlock()) {
1647 fprintf(stderr, "error: malformed block record in PCH file\n");
1648 return std::string();
1649 }
1650 break;
1651 }
1652 continue;
1653 }
1654
1655 if (Code == llvm::bitc::END_BLOCK) {
1656 if (Stream.ReadBlockEnd()) {
1657 fprintf(stderr, "error: error at end of module block in PCH file\n");
1658 return std::string();
1659 }
1660 continue;
1661 }
1662
1663 if (Code == llvm::bitc::DEFINE_ABBREV) {
1664 Stream.ReadAbbrevRecord();
1665 continue;
1666 }
1667
1668 Record.clear();
1669 const char *BlobStart = 0;
1670 unsigned BlobLen = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001671 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
Douglas Gregorb64c1932009-05-12 01:31:05 +00001672 == pch::ORIGINAL_FILE_NAME)
1673 return std::string(BlobStart, BlobLen);
Mike Stump1eb44332009-09-09 15:08:12 +00001674 }
Douglas Gregorb64c1932009-05-12 01:31:05 +00001675
1676 return std::string();
1677}
1678
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001679/// \brief Parse the record that corresponds to a LangOptions data
1680/// structure.
1681///
1682/// This routine compares the language options used to generate the
1683/// PCH file against the language options set for the current
1684/// compilation. For each option, we classify differences between the
1685/// two compiler states as either "benign" or "important". Benign
1686/// differences don't matter, and we accept them without complaint
1687/// (and without modifying the language options). Differences between
1688/// the states for important options cause the PCH file to be
1689/// unusable, so we emit a warning and return true to indicate that
1690/// there was an error.
1691///
1692/// \returns true if the PCH file is unacceptable, false otherwise.
1693bool PCHReader::ParseLanguageOptions(
1694 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001695 if (Listener) {
1696 LangOptions LangOpts;
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001698 #define PARSE_LANGOPT(Option) \
1699 LangOpts.Option = Record[Idx]; \
1700 ++Idx
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001702 unsigned Idx = 0;
1703 PARSE_LANGOPT(Trigraphs);
1704 PARSE_LANGOPT(BCPLComment);
1705 PARSE_LANGOPT(DollarIdents);
1706 PARSE_LANGOPT(AsmPreprocessor);
1707 PARSE_LANGOPT(GNUMode);
1708 PARSE_LANGOPT(ImplicitInt);
1709 PARSE_LANGOPT(Digraphs);
1710 PARSE_LANGOPT(HexFloats);
1711 PARSE_LANGOPT(C99);
1712 PARSE_LANGOPT(Microsoft);
1713 PARSE_LANGOPT(CPlusPlus);
1714 PARSE_LANGOPT(CPlusPlus0x);
1715 PARSE_LANGOPT(CXXOperatorNames);
1716 PARSE_LANGOPT(ObjC1);
1717 PARSE_LANGOPT(ObjC2);
1718 PARSE_LANGOPT(ObjCNonFragileABI);
1719 PARSE_LANGOPT(PascalStrings);
1720 PARSE_LANGOPT(WritableStrings);
1721 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001722 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001723 PARSE_LANGOPT(Exceptions);
1724 PARSE_LANGOPT(NeXTRuntime);
1725 PARSE_LANGOPT(Freestanding);
1726 PARSE_LANGOPT(NoBuiltin);
1727 PARSE_LANGOPT(ThreadsafeStatics);
Douglas Gregor972d9542009-09-03 14:36:33 +00001728 PARSE_LANGOPT(POSIXThreads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001729 PARSE_LANGOPT(Blocks);
1730 PARSE_LANGOPT(EmitAllDecls);
1731 PARSE_LANGOPT(MathErrno);
1732 PARSE_LANGOPT(OverflowChecking);
1733 PARSE_LANGOPT(HeinousExtensions);
1734 PARSE_LANGOPT(Optimize);
1735 PARSE_LANGOPT(OptimizeSize);
1736 PARSE_LANGOPT(Static);
1737 PARSE_LANGOPT(PICLevel);
1738 PARSE_LANGOPT(GNUInline);
1739 PARSE_LANGOPT(NoInline);
1740 PARSE_LANGOPT(AccessControl);
1741 PARSE_LANGOPT(CharIsSigned);
1742 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1743 ++Idx;
1744 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1745 ++Idx;
Daniel Dunbarab8e2812009-09-21 04:16:19 +00001746 LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
1747 Record[Idx]);
1748 ++Idx;
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001749 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001750 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001751 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001752
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001753 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001754 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001755
1756 return false;
1757}
1758
Douglas Gregor2e222532009-07-02 17:08:52 +00001759void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1760 Comments.resize(NumComments);
1761 std::copy(this->Comments, this->Comments + NumComments,
1762 Comments.begin());
1763}
1764
Douglas Gregor2cf26342009-04-09 22:27:44 +00001765/// \brief Read and return the type at the given offset.
1766///
1767/// This routine actually reads the record corresponding to the type
1768/// at the given offset in the bitstream. It is a helper routine for
1769/// GetType, which deals with reading type IDs.
1770QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001771 // Keep track of where we are in the stream, then jump back there
1772 // after reading this type.
1773 SavedStreamPosition SavedPosition(Stream);
1774
Douglas Gregord89275b2009-07-06 18:54:52 +00001775 // Note that we are loading a type record.
1776 LoadingTypeOrDecl Loading(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Douglas Gregor2cf26342009-04-09 22:27:44 +00001778 Stream.JumpToBit(Offset);
1779 RecordData Record;
1780 unsigned Code = Stream.ReadCode();
1781 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001782 case pch::TYPE_EXT_QUAL: {
John McCall0953e762009-09-24 19:53:00 +00001783 assert(Record.size() == 2 &&
Douglas Gregor6d473962009-04-15 22:00:08 +00001784 "Incorrect encoding of extended qualifier type");
1785 QualType Base = GetType(Record[0]);
John McCall0953e762009-09-24 19:53:00 +00001786 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
1787 return Context->getQualifiedType(Base, Quals);
Douglas Gregor6d473962009-04-15 22:00:08 +00001788 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001789
Douglas Gregor2cf26342009-04-09 22:27:44 +00001790 case pch::TYPE_FIXED_WIDTH_INT: {
1791 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001792 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001793 }
1794
1795 case pch::TYPE_COMPLEX: {
1796 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1797 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001798 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001799 }
1800
1801 case pch::TYPE_POINTER: {
1802 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1803 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001804 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001805 }
1806
1807 case pch::TYPE_BLOCK_POINTER: {
1808 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1809 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001810 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001811 }
1812
1813 case pch::TYPE_LVALUE_REFERENCE: {
1814 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1815 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001816 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001817 }
1818
1819 case pch::TYPE_RVALUE_REFERENCE: {
1820 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1821 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001822 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001823 }
1824
1825 case pch::TYPE_MEMBER_POINTER: {
1826 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1827 QualType PointeeType = GetType(Record[0]);
1828 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001829 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001830 }
1831
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001832 case pch::TYPE_CONSTANT_ARRAY: {
1833 QualType ElementType = GetType(Record[0]);
1834 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1835 unsigned IndexTypeQuals = Record[2];
1836 unsigned Idx = 3;
1837 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001838 return Context->getConstantArrayType(ElementType, Size,
1839 ASM, IndexTypeQuals);
1840 }
1841
1842 case pch::TYPE_CONSTANT_ARRAY_WITH_EXPR: {
1843 QualType ElementType = GetType(Record[0]);
1844 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1845 unsigned IndexTypeQuals = Record[2];
1846 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1847 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1848 unsigned Idx = 5;
1849 llvm::APInt Size = ReadAPInt(Record, Idx);
1850 return Context->getConstantArrayWithExprType(ElementType,
1851 Size, ReadTypeExpr(),
1852 ASM, IndexTypeQuals,
1853 SourceRange(LBLoc, RBLoc));
1854 }
1855
1856 case pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR: {
1857 QualType ElementType = GetType(Record[0]);
1858 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1859 unsigned IndexTypeQuals = Record[2];
1860 unsigned Idx = 3;
1861 llvm::APInt Size = ReadAPInt(Record, Idx);
1862 return Context->getConstantArrayWithoutExprType(ElementType, Size,
1863 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001864 }
1865
1866 case pch::TYPE_INCOMPLETE_ARRAY: {
1867 QualType ElementType = GetType(Record[0]);
1868 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1869 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001870 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001871 }
1872
1873 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001874 QualType ElementType = GetType(Record[0]);
1875 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1876 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001877 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1878 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001879 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001880 ASM, IndexTypeQuals,
1881 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001882 }
1883
1884 case pch::TYPE_VECTOR: {
1885 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001886 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001887 return QualType();
1888 }
1889
1890 QualType ElementType = GetType(Record[0]);
1891 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001892 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001893 }
1894
1895 case pch::TYPE_EXT_VECTOR: {
1896 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001897 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001898 return QualType();
1899 }
1900
1901 QualType ElementType = GetType(Record[0]);
1902 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001903 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001904 }
1905
1906 case pch::TYPE_FUNCTION_NO_PROTO: {
1907 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001908 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001909 return QualType();
1910 }
1911 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001912 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001913 }
1914
1915 case pch::TYPE_FUNCTION_PROTO: {
1916 QualType ResultType = GetType(Record[0]);
1917 unsigned Idx = 1;
1918 unsigned NumParams = Record[Idx++];
1919 llvm::SmallVector<QualType, 16> ParamTypes;
1920 for (unsigned I = 0; I != NumParams; ++I)
1921 ParamTypes.push_back(GetType(Record[Idx++]));
1922 bool isVariadic = Record[Idx++];
1923 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001924 bool hasExceptionSpec = Record[Idx++];
1925 bool hasAnyExceptionSpec = Record[Idx++];
1926 unsigned NumExceptions = Record[Idx++];
1927 llvm::SmallVector<QualType, 2> Exceptions;
1928 for (unsigned I = 0; I != NumExceptions; ++I)
1929 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001930 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001931 isVariadic, Quals, hasExceptionSpec,
1932 hasAnyExceptionSpec, NumExceptions,
1933 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001934 }
1935
1936 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001937 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001938 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001939
1940 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001941 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001942
1943 case pch::TYPE_TYPEOF: {
1944 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001945 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001946 return QualType();
1947 }
1948 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001949 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001950 }
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Anders Carlsson395b4752009-06-24 19:06:50 +00001952 case pch::TYPE_DECLTYPE:
1953 return Context->getDecltypeType(ReadTypeExpr());
1954
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001955 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001956 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001957 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001958
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001959 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001960 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001961 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001962
John McCall7da24312009-09-05 00:15:47 +00001963 case pch::TYPE_ELABORATED: {
1964 assert(Record.size() == 2 && "incorrect encoding of elaborated type");
1965 unsigned Tag = Record[1];
1966 return Context->getElaboratedType(GetType(Record[0]),
1967 (ElaboratedType::TagKind) Tag);
1968 }
1969
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001970 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001971 unsigned Idx = 0;
1972 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1973 unsigned NumProtos = Record[Idx++];
1974 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1975 for (unsigned I = 0; I != NumProtos; ++I)
1976 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001977 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001978 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001979
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001980 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001981 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001982 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001983 unsigned NumProtos = Record[Idx++];
1984 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1985 for (unsigned I = 0; I != NumProtos; ++I)
1986 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001987 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001988 }
Argyrios Kyrtzidis24fab412009-09-29 19:42:55 +00001989
1990 case pch::TYPE_OBJC_PROTOCOL_LIST: {
1991 unsigned Idx = 0;
1992 QualType OIT = GetType(Record[Idx++]);
1993 unsigned NumProtos = Record[Idx++];
1994 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1995 for (unsigned I = 0; I != NumProtos; ++I)
1996 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1997 return Context->getObjCProtocolListType(OIT, Protos.data(), NumProtos);
1998 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001999 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002000 // Suppress a GCC warning
2001 return QualType();
2002}
2003
Douglas Gregor2cf26342009-04-09 22:27:44 +00002004
Douglas Gregor8038d512009-04-10 17:25:41 +00002005QualType PCHReader::GetType(pch::TypeID ID) {
John McCall0953e762009-09-24 19:53:00 +00002006 unsigned FastQuals = ID & Qualifiers::FastMask;
2007 unsigned Index = ID >> Qualifiers::FastWidth;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002008
2009 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
2010 QualType T;
2011 switch ((pch::PredefinedTypeIDs)Index) {
2012 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002013 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
2014 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002015
2016 case pch::PREDEF_TYPE_CHAR_U_ID:
2017 case pch::PREDEF_TYPE_CHAR_S_ID:
2018 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002019 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002020 break;
2021
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002022 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
2023 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
2024 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
2025 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
2026 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002027 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002028 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
2029 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
2030 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
2031 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
2032 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
2033 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00002034 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002035 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
2036 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2037 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2038 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2039 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002040 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002041 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2042 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002043 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2044 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002045 }
2046
2047 assert(!T.isNull() && "Unknown predefined type");
John McCall0953e762009-09-24 19:53:00 +00002048 return T.withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002049 }
2050
2051 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002052 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
John McCall0953e762009-09-24 19:53:00 +00002053 if (TypesLoaded[Index].isNull())
2054 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]);
Mike Stump1eb44332009-09-09 15:08:12 +00002055
John McCall0953e762009-09-24 19:53:00 +00002056 return TypesLoaded[Index].withFastQualifiers(FastQuals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002057}
2058
Douglas Gregor8038d512009-04-10 17:25:41 +00002059Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002060 if (ID == 0)
2061 return 0;
2062
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002063 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002064 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002065 return 0;
2066 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002067
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002068 unsigned Index = ID - 1;
2069 if (!DeclsLoaded[Index])
2070 ReadDeclRecord(DeclOffsets[Index], Index);
2071
2072 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002073}
2074
Chris Lattner887e2b32009-04-27 05:46:25 +00002075/// \brief Resolve the offset of a statement into a statement.
2076///
2077/// This operation will read a new statement from the external
2078/// source each time it is called, and is meant to be used via a
2079/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2080Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002081 // Since we know tha this statement is part of a decl, make sure to use the
2082 // decl cursor to read it.
2083 DeclsCursor.JumpToBit(Offset);
2084 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002085}
2086
Douglas Gregor2cf26342009-04-09 22:27:44 +00002087bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002088 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002089 assert(DC->hasExternalLexicalStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002090 "DeclContext has no lexical decls in storage");
2091 uint64_t Offset = DeclContextOffsets[DC].first;
2092 assert(Offset && "DeclContext has no lexical decls in storage");
2093
Douglas Gregor0b748912009-04-14 21:18:50 +00002094 // Keep track of where we are in the stream, then jump back there
2095 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002096 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002097
Douglas Gregor2cf26342009-04-09 22:27:44 +00002098 // Load the record containing all of the declarations lexically in
2099 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002100 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002101 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002102 unsigned Code = DeclsCursor.ReadCode();
2103 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002104 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002105 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2106
2107 // Load all of the declaration IDs
2108 Decls.clear();
2109 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002110 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002111 return false;
2112}
2113
2114bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002115 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Mike Stump1eb44332009-09-09 15:08:12 +00002116 assert(DC->hasExternalVisibleStorage() &&
Douglas Gregor2cf26342009-04-09 22:27:44 +00002117 "DeclContext has no visible decls in storage");
2118 uint64_t Offset = DeclContextOffsets[DC].second;
2119 assert(Offset && "DeclContext has no visible decls in storage");
2120
Douglas Gregor0b748912009-04-14 21:18:50 +00002121 // Keep track of where we are in the stream, then jump back there
2122 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002123 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002124
Douglas Gregor2cf26342009-04-09 22:27:44 +00002125 // Load the record containing all of the declarations visible in
2126 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002127 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002128 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002129 unsigned Code = DeclsCursor.ReadCode();
2130 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002131 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002132 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2133 if (Record.size() == 0)
Mike Stump1eb44332009-09-09 15:08:12 +00002134 return false;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002135
2136 Decls.clear();
2137
2138 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002139 while (Idx < Record.size()) {
2140 Decls.push_back(VisibleDeclaration());
2141 Decls.back().Name = ReadDeclarationName(Record, Idx);
2142
Douglas Gregor2cf26342009-04-09 22:27:44 +00002143 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002144 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002145 LoadedDecls.reserve(Size);
2146 for (unsigned I = 0; I < Size; ++I)
2147 LoadedDecls.push_back(Record[Idx++]);
2148 }
2149
Douglas Gregor25123082009-04-22 22:34:57 +00002150 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002151 return false;
2152}
2153
Douglas Gregorfdd01722009-04-14 00:24:19 +00002154void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002155 this->Consumer = Consumer;
2156
Douglas Gregorfdd01722009-04-14 00:24:19 +00002157 if (!Consumer)
2158 return;
2159
2160 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
Daniel Dunbar04a0b502009-09-17 03:06:44 +00002161 // Force deserialization of this decl, which will cause it to be passed to
2162 // the consumer (or queued).
2163 GetDecl(ExternalDefinitions[I]);
Douglas Gregorfdd01722009-04-14 00:24:19 +00002164 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002165
2166 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2167 DeclGroupRef DG(InterestingDecls[I]);
2168 Consumer->HandleTopLevelDecl(DG);
2169 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002170}
2171
Douglas Gregor2cf26342009-04-09 22:27:44 +00002172void PCHReader::PrintStats() {
2173 std::fprintf(stderr, "*** PCH Statistics:\n");
2174
Mike Stump1eb44332009-09-09 15:08:12 +00002175 unsigned NumTypesLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002176 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
John McCall0953e762009-09-24 19:53:00 +00002177 QualType());
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002178 unsigned NumDeclsLoaded
2179 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2180 (Decl *)0);
2181 unsigned NumIdentifiersLoaded
2182 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2183 IdentifiersLoaded.end(),
2184 (IdentifierInfo *)0);
Mike Stump1eb44332009-09-09 15:08:12 +00002185 unsigned NumSelectorsLoaded
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002186 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2187 SelectorsLoaded.end(),
2188 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002189
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002190 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2191 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002192 if (TotalNumSLocEntries)
2193 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2194 NumSLocEntriesRead, TotalNumSLocEntries,
2195 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002196 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002197 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002198 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2199 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2200 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002201 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002202 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2203 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002204 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002205 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002206 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2207 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002208 if (TotalNumSelectors)
2209 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2210 NumSelectorsLoaded, TotalNumSelectors,
2211 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2212 if (TotalNumStatements)
2213 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2214 NumStatementsRead, TotalNumStatements,
2215 ((float)NumStatementsRead/TotalNumStatements * 100));
2216 if (TotalNumMacros)
2217 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2218 NumMacrosRead, TotalNumMacros,
2219 ((float)NumMacrosRead/TotalNumMacros * 100));
2220 if (TotalLexicalDeclContexts)
2221 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2222 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2223 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2224 * 100));
2225 if (TotalVisibleDeclContexts)
2226 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2227 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2228 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2229 * 100));
2230 if (TotalSelectorsInMethodPool) {
2231 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2232 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2233 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2234 * 100));
2235 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2236 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002237 std::fprintf(stderr, "\n");
2238}
2239
Douglas Gregor668c1a42009-04-21 22:25:48 +00002240void PCHReader::InitializeSema(Sema &S) {
2241 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002242 S.ExternalSource = this;
2243
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002244 // Makes sure any declarations that were deserialized "too early"
2245 // still get added to the identifier's declaration chains.
2246 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2247 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2248 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002249 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002250 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002251
2252 // If there were any tentative definitions, deserialize them and add
2253 // them to Sema's table of tentative definitions.
2254 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2255 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2256 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
Chris Lattner63d65f82009-09-08 18:19:27 +00002257 SemaObj->TentativeDefinitionList.push_back(Var->getDeclName());
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002258 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002259
2260 // If there were any locally-scoped external declarations,
2261 // deserialize them and add them to Sema's table of locally-scoped
2262 // external declarations.
2263 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2264 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2265 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2266 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002267
2268 // If there were any ext_vector type declarations, deserialize them
2269 // and add them to Sema's vector of such declarations.
2270 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2271 SemaObj->ExtVectorDecls.push_back(
2272 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002273}
2274
2275IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2276 // Try to find this name within our on-disk hash table
Mike Stump1eb44332009-09-09 15:08:12 +00002277 PCHIdentifierLookupTable *IdTable
Douglas Gregor668c1a42009-04-21 22:25:48 +00002278 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2279 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2280 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2281 if (Pos == IdTable->end())
2282 return 0;
2283
2284 // Dereferencing the iterator has the effect of building the
2285 // IdentifierInfo node and populating it with the various
2286 // declarations it needs.
2287 return *Pos;
2288}
2289
Mike Stump1eb44332009-09-09 15:08:12 +00002290std::pair<ObjCMethodList, ObjCMethodList>
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002291PCHReader::ReadMethodPool(Selector Sel) {
2292 if (!MethodPoolLookupTable)
2293 return std::pair<ObjCMethodList, ObjCMethodList>();
2294
2295 // Try to find this selector within our on-disk hash table.
2296 PCHMethodPoolLookupTable *PoolTable
2297 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2298 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002299 if (Pos == PoolTable->end()) {
2300 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002301 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002302 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002303
Douglas Gregor83941df2009-04-25 17:48:32 +00002304 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002305 return *Pos;
2306}
2307
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002308void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002309 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002310 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002311 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002312}
2313
Douglas Gregord89275b2009-07-06 18:54:52 +00002314/// \brief Set the globally-visible declarations associated with the given
2315/// identifier.
2316///
2317/// If the PCH reader is currently in a state where the given declaration IDs
Mike Stump1eb44332009-09-09 15:08:12 +00002318/// cannot safely be resolved, they are queued until it is safe to resolve
Douglas Gregord89275b2009-07-06 18:54:52 +00002319/// them.
2320///
2321/// \param II an IdentifierInfo that refers to one or more globally-visible
2322/// declarations.
2323///
2324/// \param DeclIDs the set of declaration IDs with the name @p II that are
2325/// visible at global scope.
2326///
2327/// \param Nonrecursive should be true to indicate that the caller knows that
2328/// this call is non-recursive, and therefore the globally-visible declarations
2329/// will not be placed onto the pending queue.
Mike Stump1eb44332009-09-09 15:08:12 +00002330void
2331PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
Douglas Gregord89275b2009-07-06 18:54:52 +00002332 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2333 bool Nonrecursive) {
2334 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2335 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2336 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2337 PII.II = II;
2338 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2339 PII.DeclIDs.push_back(DeclIDs[I]);
2340 return;
2341 }
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Douglas Gregord89275b2009-07-06 18:54:52 +00002343 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2344 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2345 if (SemaObj) {
2346 // Introduce this declaration into the translation-unit scope
2347 // and add it to the declaration chain for this identifier, so
2348 // that (unqualified) name lookup will find it.
2349 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2350 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2351 } else {
2352 // Queue this declaration so that it will be added to the
2353 // translation unit scope and identifier's declaration chain
2354 // once a Sema object is known.
2355 PreloadedDecls.push_back(D);
2356 }
2357 }
2358}
2359
Chris Lattner7356a312009-04-11 21:15:38 +00002360IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002361 if (ID == 0)
2362 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002364 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002365 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002366 return 0;
2367 }
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002369 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002370 if (!IdentifiersLoaded[ID - 1]) {
2371 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002372 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002373
Douglas Gregor02fc7512009-04-28 20:01:51 +00002374 // All of the strings in the PCH file are preceded by a 16-bit
2375 // length. Extract that 16-bit length to avoid having to execute
2376 // strlen().
2377 const char *StrLenPtr = Str - 2;
2378 unsigned StrLen = (((unsigned) StrLenPtr[0])
2379 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002380 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002381 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002382 }
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002384 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002385}
2386
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002387void PCHReader::ReadSLocEntry(unsigned ID) {
2388 ReadSLocEntryRecord(ID);
2389}
2390
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002391Selector PCHReader::DecodeSelector(unsigned ID) {
2392 if (ID == 0)
2393 return Selector();
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Douglas Gregora02b1472009-04-28 21:53:25 +00002395 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002396 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002397
2398 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002399 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002400 return Selector();
2401 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002402
2403 unsigned Index = ID - 1;
2404 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2405 // Load this selector from the selector table.
2406 // FIXME: endianness portability issues with SelectorOffsets table
2407 PCHMethodPoolLookupTrait Trait(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002408 SelectorsLoaded[Index]
Douglas Gregor83941df2009-04-25 17:48:32 +00002409 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2410 }
2411
2412 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002413}
2414
Mike Stump1eb44332009-09-09 15:08:12 +00002415DeclarationName
Douglas Gregor2cf26342009-04-09 22:27:44 +00002416PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2417 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2418 switch (Kind) {
2419 case DeclarationName::Identifier:
2420 return DeclarationName(GetIdentifierInfo(Record, Idx));
2421
2422 case DeclarationName::ObjCZeroArgSelector:
2423 case DeclarationName::ObjCOneArgSelector:
2424 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002425 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002426
2427 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002428 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002429 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002430
2431 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002432 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002433 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002434
2435 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002436 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002437 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002438
2439 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002440 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002441 (OverloadedOperatorKind)Record[Idx++]);
2442
2443 case DeclarationName::CXXUsingDirective:
2444 return DeclarationName::getUsingDirectiveName();
2445 }
2446
2447 // Required to silence GCC warning
2448 return DeclarationName();
2449}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002450
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002451/// \brief Read an integral value
2452llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2453 unsigned BitWidth = Record[Idx++];
2454 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2455 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2456 Idx += NumWords;
2457 return Result;
2458}
2459
2460/// \brief Read a signed integral value
2461llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2462 bool isUnsigned = Record[Idx++];
2463 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2464}
2465
Douglas Gregor17fc2232009-04-14 21:55:33 +00002466/// \brief Read a floating-point value
2467llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002468 return llvm::APFloat(ReadAPInt(Record, Idx));
2469}
2470
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002471// \brief Read a string
2472std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2473 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002474 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002475 Idx += Len;
2476 return Result;
2477}
2478
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002479DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002480 return Diag(SourceLocation(), DiagID);
2481}
2482
2483DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002484 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002485}
Douglas Gregor025452f2009-04-17 00:04:06 +00002486
Douglas Gregor668c1a42009-04-21 22:25:48 +00002487/// \brief Retrieve the identifier table associated with the
2488/// preprocessor.
2489IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002490 assert(PP && "Forgot to set Preprocessor ?");
2491 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002492}
2493
Douglas Gregor025452f2009-04-17 00:04:06 +00002494/// \brief Record that the given ID maps to the given switch-case
2495/// statement.
2496void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2497 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2498 SwitchCaseStmts[ID] = SC;
2499}
2500
2501/// \brief Retrieve the switch-case statement with the given ID.
2502SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2503 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2504 return SwitchCaseStmts[ID];
2505}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002506
2507/// \brief Record that the given label statement has been
2508/// deserialized and has the given ID.
2509void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
Mike Stump1eb44332009-09-09 15:08:12 +00002510 assert(LabelStmts.find(ID) == LabelStmts.end() &&
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002511 "Deserialized label twice");
2512 LabelStmts[ID] = S;
2513
2514 // If we've already seen any goto statements that point to this
2515 // label, resolve them now.
2516 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2517 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2518 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2519 Goto->second->setLabel(S);
2520 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002521
2522 // If we've already seen any address-label statements that point to
2523 // this label, resolve them now.
2524 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
Mike Stump1eb44332009-09-09 15:08:12 +00002525 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002526 = UnresolvedAddrLabelExprs.equal_range(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002527 for (AddrLabelIter AddrLabel = AddrLabels.first;
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002528 AddrLabel != AddrLabels.second; ++AddrLabel)
2529 AddrLabel->second->setLabel(S);
2530 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002531}
2532
2533/// \brief Set the label of the given statement to the label
2534/// identified by ID.
2535///
2536/// Depending on the order in which the label and other statements
2537/// referencing that label occur, this operation may complete
2538/// immediately (updating the statement) or it may queue the
2539/// statement to be back-patched later.
2540void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2541 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2542 if (Label != LabelStmts.end()) {
2543 // We've already seen this label, so set the label of the goto and
2544 // we're done.
2545 S->setLabel(Label->second);
2546 } else {
2547 // We haven't seen this label yet, so add this goto to the set of
2548 // unresolved goto statements.
2549 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2550 }
2551}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002552
2553/// \brief Set the label of the given expression to the label
2554/// identified by ID.
2555///
2556/// Depending on the order in which the label and other statements
2557/// referencing that label occur, this operation may complete
2558/// immediately (updating the statement) or it may queue the
2559/// statement to be back-patched later.
2560void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2561 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2562 if (Label != LabelStmts.end()) {
2563 // We've already seen this label, so set the label of the
2564 // label-address expression and we're done.
2565 S->setLabel(Label->second);
2566 } else {
2567 // We haven't seen this label yet, so add this label-address
2568 // expression to the set of unresolved label-address expressions.
2569 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2570 }
2571}
Douglas Gregord89275b2009-07-06 18:54:52 +00002572
2573
Mike Stump1eb44332009-09-09 15:08:12 +00002574PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
Douglas Gregord89275b2009-07-06 18:54:52 +00002575 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2576 Reader.CurrentlyLoadingTypeOrDecl = this;
2577}
2578
2579PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2580 if (!Parent) {
2581 // If any identifiers with corresponding top-level declarations have
2582 // been loaded, load those declarations now.
2583 while (!Reader.PendingIdentifierInfos.empty()) {
2584 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2585 Reader.PendingIdentifierInfos.front().DeclIDs,
2586 true);
2587 Reader.PendingIdentifierInfos.pop_front();
2588 }
2589 }
2590
Mike Stump1eb44332009-09-09 15:08:12 +00002591 Reader.CurrentlyLoadingTypeOrDecl = Parent;
Douglas Gregord89275b2009-07-06 18:54:52 +00002592}