blob: 55dbd978f1aa218cd5e7f1628c69f1885de87c9c [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 Gregor2cf26342009-04-09 22:27:44 +000029#include "llvm/Bitcode/BitstreamReader.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000039// PCH reader validator implementation
40//===----------------------------------------------------------------------===//
41
42PCHReaderListener::~PCHReaderListener() {}
43
44bool
45PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
46 const LangOptions &PPLangOpts = PP.getLangOptions();
47#define PARSE_LANGOPT_BENIGN(Option)
48#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
49 if (PPLangOpts.Option != LangOpts.Option) { \
50 Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option; \
51 return true; \
52 }
53
54 PARSE_LANGOPT_BENIGN(Trigraphs);
55 PARSE_LANGOPT_BENIGN(BCPLComment);
56 PARSE_LANGOPT_BENIGN(DollarIdents);
57 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
58 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
59 PARSE_LANGOPT_BENIGN(ImplicitInt);
60 PARSE_LANGOPT_BENIGN(Digraphs);
61 PARSE_LANGOPT_BENIGN(HexFloats);
62 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
63 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
64 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
65 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
66 PARSE_LANGOPT_BENIGN(CXXOperatorName);
67 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
68 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
69 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
70 PARSE_LANGOPT_BENIGN(PascalStrings);
71 PARSE_LANGOPT_BENIGN(WritableStrings);
72 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
73 diag::warn_pch_lax_vector_conversions);
Nate Begeman69cfb9b2009-06-25 22:57:40 +000074 PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000075 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
76 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
77 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
78 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
79 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
80 diag::warn_pch_thread_safe_statics);
Daniel Dunbar5345c392009-09-03 04:54:28 +000081 PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +000082 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
83 PARSE_LANGOPT_BENIGN(EmitAllDecls);
84 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
85 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
86 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
87 diag::warn_pch_heinous_extensions);
88 // FIXME: Most of the options below are benign if the macro wasn't
89 // used. Unfortunately, this means that a PCH compiled without
90 // optimization can't be used with optimization turned on, even
91 // though the only thing that changes is whether __OPTIMIZE__ was
92 // defined... but if __OPTIMIZE__ never showed up in the header, it
93 // doesn't matter. We could consider making this some special kind
94 // of check.
95 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
96 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
97 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
98 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
99 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
100 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
101 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
102 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
103 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
104 Reader.Diag(diag::warn_pch_gc_mode)
105 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
106 return true;
107 }
108 PARSE_LANGOPT_BENIGN(getVisibilityMode());
109 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000110 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Anders Carlsson92f58222009-08-22 22:30:33 +0000111 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000112#undef PARSE_LANGOPT_IRRELEVANT
113#undef PARSE_LANGOPT_BENIGN
114
115 return false;
116}
117
118bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000119 if (Triple != PP.getTargetInfo().getTriple().getTriple()) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000120 Reader.Diag(diag::warn_pch_target_triple)
Daniel Dunbar1752ee42009-08-24 09:10:05 +0000121 << Triple << PP.getTargetInfo().getTriple().getTriple();
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000122 return true;
123 }
124 return false;
125}
126
127/// \brief Split the given string into a vector of lines, eliminating
128/// any empty lines in the process.
129///
130/// \param Str the string to split.
131/// \param Len the length of Str.
132/// \param KeepEmptyLines true if empty lines should be included
133/// \returns a vector of lines, with the line endings removed
134static std::vector<std::string> splitLines(const char *Str, unsigned Len,
135 bool KeepEmptyLines = false) {
136 std::vector<std::string> Lines;
137 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
138 unsigned LineEnd = LineStart;
139 while (LineEnd < Len && Str[LineEnd] != '\n')
140 ++LineEnd;
141 if (LineStart != LineEnd || KeepEmptyLines)
142 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
143 LineStart = LineEnd;
144 }
145 return Lines;
146}
147
148/// \brief Determine whether the string Haystack starts with the
149/// substring Needle.
150static bool startsWith(const std::string &Haystack, const char *Needle) {
151 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
152 if (I == N)
153 return false;
154 if (Haystack[I] != Needle[I])
155 return false;
156 }
157
158 return true;
159}
160
161/// \brief Determine whether the string Haystack starts with the
162/// substring Needle.
163static inline bool startsWith(const std::string &Haystack,
164 const std::string &Needle) {
165 return startsWith(Haystack, Needle.c_str());
166}
167
168bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
169 unsigned PCHPredefLen,
170 FileID PCHBufferID,
171 std::string &SuggestedPredefines) {
172 const char *Predef = PP.getPredefines().c_str();
173 unsigned PredefLen = PP.getPredefines().size();
174
175 // If the two predefines buffers compare equal, we're done!
176 if (PredefLen == PCHPredefLen &&
177 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
178 return false;
179
180 SourceManager &SourceMgr = PP.getSourceManager();
181
182 // The predefines buffers are different. Determine what the
183 // differences are, and whether they require us to reject the PCH
184 // file.
185 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
186 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
187
188 // Sort both sets of predefined buffer lines, since
189 std::sort(CmdLineLines.begin(), CmdLineLines.end());
190 std::sort(PCHLines.begin(), PCHLines.end());
191
192 // Determine which predefines that where used to build the PCH file
193 // are missing from the command line.
194 std::vector<std::string> MissingPredefines;
195 std::set_difference(PCHLines.begin(), PCHLines.end(),
196 CmdLineLines.begin(), CmdLineLines.end(),
197 std::back_inserter(MissingPredefines));
198
199 bool MissingDefines = false;
200 bool ConflictingDefines = false;
201 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
202 const std::string &Missing = MissingPredefines[I];
203 if (!startsWith(Missing, "#define ") != 0) {
204 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
205 return true;
206 }
207
208 // This is a macro definition. Determine the name of the macro
209 // we're defining.
210 std::string::size_type StartOfMacroName = strlen("#define ");
211 std::string::size_type EndOfMacroName
212 = Missing.find_first_of("( \n\r", StartOfMacroName);
213 assert(EndOfMacroName != std::string::npos &&
214 "Couldn't find the end of the macro name");
215 std::string MacroName = Missing.substr(StartOfMacroName,
216 EndOfMacroName - StartOfMacroName);
217
218 // Determine whether this macro was given a different definition
219 // on the command line.
220 std::string MacroDefStart = "#define " + MacroName;
221 std::string::size_type MacroDefLen = MacroDefStart.size();
222 std::vector<std::string>::iterator ConflictPos
223 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
224 MacroDefStart);
225 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
226 if (!startsWith(*ConflictPos, MacroDefStart)) {
227 // Different macro; we're done.
228 ConflictPos = CmdLineLines.end();
229 break;
230 }
231
232 assert(ConflictPos->size() > MacroDefLen &&
233 "Invalid #define in predefines buffer?");
234 if ((*ConflictPos)[MacroDefLen] != ' ' &&
235 (*ConflictPos)[MacroDefLen] != '(')
236 continue; // Longer macro name; keep trying.
237
238 // We found a conflicting macro definition.
239 break;
240 }
241
242 if (ConflictPos != CmdLineLines.end()) {
243 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
244 << MacroName;
245
246 // Show the definition of this macro within the PCH file.
247 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
248 unsigned Offset = MissingDef - PCHPredef;
249 SourceLocation PCHMissingLoc
250 = SourceMgr.getLocForStartOfFile(PCHBufferID)
251 .getFileLocWithOffset(Offset);
252 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
253 << MacroName;
254
255 ConflictingDefines = true;
256 continue;
257 }
258
259 // If the macro doesn't conflict, then we'll just pick up the
260 // macro definition from the PCH file. Warn the user that they
261 // made a mistake.
262 if (ConflictingDefines)
263 continue; // Don't complain if there are already conflicting defs
264
265 if (!MissingDefines) {
266 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
267 MissingDefines = true;
268 }
269
270 // Show the definition of this macro within the PCH file.
271 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
272 unsigned Offset = MissingDef - PCHPredef;
273 SourceLocation PCHMissingLoc
274 = SourceMgr.getLocForStartOfFile(PCHBufferID)
275 .getFileLocWithOffset(Offset);
276 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
277 }
278
279 if (ConflictingDefines)
280 return true;
281
282 // Determine what predefines were introduced based on command-line
283 // parameters that were not present when building the PCH
284 // file. Extra #defines are okay, so long as the identifiers being
285 // defined were not used within the precompiled header.
286 std::vector<std::string> ExtraPredefines;
287 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
288 PCHLines.begin(), PCHLines.end(),
289 std::back_inserter(ExtraPredefines));
290 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
291 const std::string &Extra = ExtraPredefines[I];
292 if (!startsWith(Extra, "#define ") != 0) {
293 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
294 return true;
295 }
296
297 // This is an extra macro definition. Determine the name of the
298 // macro we're defining.
299 std::string::size_type StartOfMacroName = strlen("#define ");
300 std::string::size_type EndOfMacroName
301 = Extra.find_first_of("( \n\r", StartOfMacroName);
302 assert(EndOfMacroName != std::string::npos &&
303 "Couldn't find the end of the macro name");
304 std::string MacroName = Extra.substr(StartOfMacroName,
305 EndOfMacroName - StartOfMacroName);
306
307 // Check whether this name was used somewhere in the PCH file. If
308 // so, defining it as a macro could change behavior, so we reject
309 // the PCH file.
310 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
311 MacroName.c_str() + MacroName.size())) {
312 Reader.Diag(diag::warn_macro_name_used_in_pch)
313 << II;
314 return true;
315 }
316
317 // Add this definition to the suggested predefines buffer.
318 SuggestedPredefines += Extra;
319 SuggestedPredefines += '\n';
320 }
321
322 // If we get here, it's because the predefines buffer had compatible
323 // contents. Accept the PCH file.
324 return false;
325}
326
327void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
328 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
329}
330
331void PCHValidator::ReadCounter(unsigned Value) {
332 PP.setCounterValue(Value);
333}
334
335
336
337//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000338// PCH reader implementation
339//===----------------------------------------------------------------------===//
340
Douglas Gregore650c8c2009-07-07 00:12:59 +0000341PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
342 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000343 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
344 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
345 SemaObj(0), PP(&PP), Context(Context), Consumer(0),
346 IdentifierTableData(0), IdentifierLookupTable(0),
347 IdentifierOffsets(0),
348 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
349 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000350 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Douglas Gregor2e222532009-07-02 17:08:52 +0000351 NumStatHits(0), NumStatMisses(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000352 NumSLocEntriesRead(0), NumStatementsRead(0),
353 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000354 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
355 CurrentlyLoadingTypeOrDecl(0) {
356 RelocatablePCH = false;
357}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000358
359PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000360 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000361 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Argyrios Kyrtzidis57102112009-06-19 07:55:35 +0000362 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000363 IdentifierTableData(0), IdentifierLookupTable(0),
364 IdentifierOffsets(0),
365 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
366 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000367 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
368 NumStatHits(0), NumStatMisses(0),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000369 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000370 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000371 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000372 CurrentlyLoadingTypeOrDecl(0) {
373 RelocatablePCH = false;
374}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000375
376PCHReader::~PCHReader() {}
377
Chris Lattnerda930612009-04-27 05:58:23 +0000378Expr *PCHReader::ReadDeclExpr() {
379 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
380}
381
382Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +0000383 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000384}
385
386
Douglas Gregor668c1a42009-04-21 22:25:48 +0000387namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000388class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
389 PCHReader &Reader;
390
391public:
392 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
393
394 typedef Selector external_key_type;
395 typedef external_key_type internal_key_type;
396
397 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
398
399 static bool EqualKey(const internal_key_type& a,
400 const internal_key_type& b) {
401 return a == b;
402 }
403
404 static unsigned ComputeHash(Selector Sel) {
405 unsigned N = Sel.getNumArgs();
406 if (N == 0)
407 ++N;
408 unsigned R = 5381;
409 for (unsigned I = 0; I != N; ++I)
410 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
411 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
412 return R;
413 }
414
415 // This hopefully will just get inlined and removed by the optimizer.
416 static const internal_key_type&
417 GetInternalKey(const external_key_type& x) { return x; }
418
419 static std::pair<unsigned, unsigned>
420 ReadKeyDataLength(const unsigned char*& d) {
421 using namespace clang::io;
422 unsigned KeyLen = ReadUnalignedLE16(d);
423 unsigned DataLen = ReadUnalignedLE16(d);
424 return std::make_pair(KeyLen, DataLen);
425 }
426
Douglas Gregor83941df2009-04-25 17:48:32 +0000427 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000428 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000429 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000430 unsigned N = ReadUnalignedLE16(d);
431 IdentifierInfo *FirstII
432 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
433 if (N == 0)
434 return SelTable.getNullarySelector(FirstII);
435 else if (N == 1)
436 return SelTable.getUnarySelector(FirstII);
437
438 llvm::SmallVector<IdentifierInfo *, 16> Args;
439 Args.push_back(FirstII);
440 for (unsigned I = 1; I != N; ++I)
441 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
442
Douglas Gregor75fdb232009-05-22 22:45:36 +0000443 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000444 }
445
446 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
447 using namespace clang::io;
448 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
449 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
450
451 data_type Result;
452
453 // Load instance methods
454 ObjCMethodList *Prev = 0;
455 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
456 ObjCMethodDecl *Method
457 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
458 if (!Result.first.Method) {
459 // This is the first method, which is the easy case.
460 Result.first.Method = Method;
461 Prev = &Result.first;
462 continue;
463 }
464
465 Prev->Next = new ObjCMethodList(Method, 0);
466 Prev = Prev->Next;
467 }
468
469 // Load factory methods
470 Prev = 0;
471 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
472 ObjCMethodDecl *Method
473 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
474 if (!Result.second.Method) {
475 // This is the first method, which is the easy case.
476 Result.second.Method = Method;
477 Prev = &Result.second;
478 continue;
479 }
480
481 Prev->Next = new ObjCMethodList(Method, 0);
482 Prev = Prev->Next;
483 }
484
485 return Result;
486 }
487};
488
489} // end anonymous namespace
490
491/// \brief The on-disk hash table used for the global method pool.
492typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
493 PCHMethodPoolLookupTable;
494
495namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000496class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
497 PCHReader &Reader;
498
499 // If we know the IdentifierInfo in advance, it is here and we will
500 // not build a new one. Used when deserializing information about an
501 // identifier that was constructed before the PCH file was read.
502 IdentifierInfo *KnownII;
503
504public:
505 typedef IdentifierInfo * data_type;
506
507 typedef const std::pair<const char*, unsigned> external_key_type;
508
509 typedef external_key_type internal_key_type;
510
511 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
512 : Reader(Reader), KnownII(II) { }
513
514 static bool EqualKey(const internal_key_type& a,
515 const internal_key_type& b) {
516 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
517 : false;
518 }
519
520 static unsigned ComputeHash(const internal_key_type& a) {
521 return BernsteinHash(a.first, a.second);
522 }
523
524 // This hopefully will just get inlined and removed by the optimizer.
525 static const internal_key_type&
526 GetInternalKey(const external_key_type& x) { return x; }
527
528 static std::pair<unsigned, unsigned>
529 ReadKeyDataLength(const unsigned char*& d) {
530 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000531 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000532 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000533 return std::make_pair(KeyLen, DataLen);
534 }
535
536 static std::pair<const char*, unsigned>
537 ReadKey(const unsigned char* d, unsigned n) {
538 assert(n >= 2 && d[n-1] == '\0');
539 return std::make_pair((const char*) d, n-1);
540 }
541
542 IdentifierInfo *ReadData(const internal_key_type& k,
543 const unsigned char* d,
544 unsigned DataLen) {
545 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000546 pch::IdentID ID = ReadUnalignedLE32(d);
547 bool IsInteresting = ID & 0x01;
548
549 // Wipe out the "is interesting" bit.
550 ID = ID >> 1;
551
552 if (!IsInteresting) {
553 // For unintersting identifiers, just build the IdentifierInfo
554 // and associate it with the persistent ID.
555 IdentifierInfo *II = KnownII;
556 if (!II)
557 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
558 k.first, k.first + k.second);
559 Reader.SetIdentifierInfo(ID, II);
560 return II;
561 }
562
Douglas Gregor5998da52009-04-28 21:32:13 +0000563 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000564 bool CPlusPlusOperatorKeyword = Bits & 0x01;
565 Bits >>= 1;
566 bool Poisoned = Bits & 0x01;
567 Bits >>= 1;
568 bool ExtensionToken = Bits & 0x01;
569 Bits >>= 1;
570 bool hasMacroDefinition = Bits & 0x01;
571 Bits >>= 1;
572 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
573 Bits >>= 10;
Douglas Gregora92193e2009-04-28 21:18:29 +0000574
Douglas Gregor2deaea32009-04-22 18:49:13 +0000575 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000576 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000577
578 // Build the IdentifierInfo itself and link the identifier ID with
579 // the new IdentifierInfo.
580 IdentifierInfo *II = KnownII;
581 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000582 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
583 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000584 Reader.SetIdentifierInfo(ID, II);
585
Douglas Gregor2deaea32009-04-22 18:49:13 +0000586 // Set or check the various bits in the IdentifierInfo structure.
587 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000588 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
589 assert(II->isExtensionToken() == ExtensionToken &&
590 "Incorrect extension token flag");
591 (void)ExtensionToken;
592 II->setIsPoisoned(Poisoned);
593 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
594 "Incorrect C++ operator keyword flag");
595 (void)CPlusPlusOperatorKeyword;
596
Douglas Gregor37e26842009-04-21 23:56:24 +0000597 // If this identifier is a macro, deserialize the macro
598 // definition.
599 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000600 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000601 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000602 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000603 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000604
605 // Read all of the declarations visible at global scope with this
606 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000607 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000608 if (DataLen > 0) {
609 llvm::SmallVector<uint32_t, 4> DeclIDs;
610 for (; DataLen > 0; DataLen -= 4)
611 DeclIDs.push_back(ReadUnalignedLE32(d));
612 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000613 }
Douglas Gregord89275b2009-07-06 18:54:52 +0000614
Douglas Gregor668c1a42009-04-21 22:25:48 +0000615 return II;
616 }
617};
618
619} // end anonymous namespace
620
621/// \brief The on-disk hash table used to contain information about
622/// all of the identifiers in the program.
623typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
624 PCHIdentifierLookupTable;
625
Douglas Gregora02b1472009-04-28 21:53:25 +0000626bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000627 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
628 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000629 return true;
630}
631
Douglas Gregore1d918e2009-04-10 23:10:45 +0000632/// \brief Check the contents of the predefines buffer against the
633/// contents of the predefines buffer used to build the PCH file.
634///
635/// The contents of the two predefines buffers should be the same. If
636/// not, then some command-line option changed the preprocessor state
637/// and we must reject the PCH file.
638///
639/// \param PCHPredef The start of the predefines buffer in the PCH
640/// file.
641///
642/// \param PCHPredefLen The length of the predefines buffer in the PCH
643/// file.
644///
645/// \param PCHBufferID The FileID for the PCH predefines buffer.
646///
647/// \returns true if there was a mismatch (in which case the PCH file
648/// should be ignored), or false otherwise.
649bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
650 unsigned PCHPredefLen,
651 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000652 if (Listener)
653 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
654 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000655 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000656}
657
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000658//===----------------------------------------------------------------------===//
659// Source Manager Deserialization
660//===----------------------------------------------------------------------===//
661
Douglas Gregorbd945002009-04-13 16:31:14 +0000662/// \brief Read the line table in the source manager block.
663/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000664bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000665 unsigned Idx = 0;
666 LineTableInfo &LineTable = SourceMgr.getLineTable();
667
668 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000669 std::map<int, int> FileIDs;
670 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000671 // Extract the file name
672 unsigned FilenameLen = Record[Idx++];
673 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
674 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000675 MaybeAddSystemRootToFilename(Filename);
Douglas Gregorff0a9872009-04-13 17:12:42 +0000676 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
677 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000678 }
679
680 // Parse the line entries
681 std::vector<LineEntry> Entries;
682 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000683 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000684
685 // Extract the line entries
686 unsigned NumEntries = Record[Idx++];
687 Entries.clear();
688 Entries.reserve(NumEntries);
689 for (unsigned I = 0; I != NumEntries; ++I) {
690 unsigned FileOffset = Record[Idx++];
691 unsigned LineNo = Record[Idx++];
692 int FilenameID = Record[Idx++];
693 SrcMgr::CharacteristicKind FileKind
694 = (SrcMgr::CharacteristicKind)Record[Idx++];
695 unsigned IncludeOffset = Record[Idx++];
696 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
697 FileKind, IncludeOffset));
698 }
699 LineTable.AddEntry(FID, Entries);
700 }
701
702 return false;
703}
704
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000705namespace {
706
707class VISIBILITY_HIDDEN PCHStatData {
708public:
709 const bool hasStat;
710 const ino_t ino;
711 const dev_t dev;
712 const mode_t mode;
713 const time_t mtime;
714 const off_t size;
715
716 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
717 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
718
719 PCHStatData()
720 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
721};
722
723class VISIBILITY_HIDDEN PCHStatLookupTrait {
724 public:
725 typedef const char *external_key_type;
726 typedef const char *internal_key_type;
727
728 typedef PCHStatData data_type;
729
730 static unsigned ComputeHash(const char *path) {
731 return BernsteinHash(path);
732 }
733
734 static internal_key_type GetInternalKey(const char *path) { return path; }
735
736 static bool EqualKey(internal_key_type a, internal_key_type b) {
737 return strcmp(a, b) == 0;
738 }
739
740 static std::pair<unsigned, unsigned>
741 ReadKeyDataLength(const unsigned char*& d) {
742 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
743 unsigned DataLen = (unsigned) *d++;
744 return std::make_pair(KeyLen + 1, DataLen);
745 }
746
747 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
748 return (const char *)d;
749 }
750
751 static data_type ReadData(const internal_key_type, const unsigned char *d,
752 unsigned /*DataLen*/) {
753 using namespace clang::io;
754
755 if (*d++ == 1)
756 return data_type();
757
758 ino_t ino = (ino_t) ReadUnalignedLE32(d);
759 dev_t dev = (dev_t) ReadUnalignedLE32(d);
760 mode_t mode = (mode_t) ReadUnalignedLE16(d);
761 time_t mtime = (time_t) ReadUnalignedLE64(d);
762 off_t size = (off_t) ReadUnalignedLE64(d);
763 return data_type(ino, dev, mode, mtime, size);
764 }
765};
766
767/// \brief stat() cache for precompiled headers.
768///
769/// This cache is very similar to the stat cache used by pretokenized
770/// headers.
771class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
772 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
773 CacheTy *Cache;
774
775 unsigned &NumStatHits, &NumStatMisses;
776public:
777 PCHStatCache(const unsigned char *Buckets,
778 const unsigned char *Base,
779 unsigned &NumStatHits,
780 unsigned &NumStatMisses)
781 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
782 Cache = CacheTy::Create(Buckets, Base);
783 }
784
785 ~PCHStatCache() { delete Cache; }
786
787 int stat(const char *path, struct stat *buf) {
788 // Do the lookup for the file's data in the PCH file.
789 CacheTy::iterator I = Cache->find(path);
790
791 // If we don't get a hit in the PCH file just forward to 'stat'.
792 if (I == Cache->end()) {
793 ++NumStatMisses;
794 return ::stat(path, buf);
795 }
796
797 ++NumStatHits;
798 PCHStatData Data = *I;
799
800 if (!Data.hasStat)
801 return 1;
802
803 buf->st_ino = Data.ino;
804 buf->st_dev = Data.dev;
805 buf->st_mtime = Data.mtime;
806 buf->st_mode = Data.mode;
807 buf->st_size = Data.size;
808 return 0;
809 }
810};
811} // end anonymous namespace
812
813
Douglas Gregor14f79002009-04-10 03:52:48 +0000814/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000815PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000816 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000817
818 // Set the source-location entry cursor to the current position in
819 // the stream. This cursor will be used to read the contents of the
820 // source manager block initially, and then lazily read
821 // source-location entries as needed.
822 SLocEntryCursor = Stream;
823
824 // The stream itself is going to skip over the source manager block.
825 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000826 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000827 return Failure;
828 }
829
830 // Enter the source manager block.
831 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000832 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000833 return Failure;
834 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000835
Douglas Gregor14f79002009-04-10 03:52:48 +0000836 RecordData Record;
837 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000838 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000839 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000840 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000841 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000842 return Failure;
843 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000844 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000845 }
846
847 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
848 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000849 SLocEntryCursor.ReadSubBlockID();
850 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000851 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000852 return Failure;
853 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000854 continue;
855 }
856
857 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000858 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000859 continue;
860 }
861
862 // Read a record.
863 const char *BlobStart;
864 unsigned BlobLen;
865 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000866 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000867 default: // Default behavior: ignore.
868 break;
869
Chris Lattner2c78b872009-04-14 23:22:57 +0000870 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000871 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000872 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000873 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000874
875 case pch::SM_HEADER_FILE_INFO: {
876 HeaderFileInfo HFI;
877 HFI.isImport = Record[0];
878 HFI.DirInfo = Record[1];
879 HFI.NumIncludes = Record[2];
880 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000881 if (Listener)
882 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000883 break;
884 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000885
886 case pch::SM_SLOC_FILE_ENTRY:
887 case pch::SM_SLOC_BUFFER_ENTRY:
888 case pch::SM_SLOC_INSTANTIATION_ENTRY:
889 // Once we hit one of the source location entries, we're done.
890 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000891 }
892 }
893}
894
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000895/// \brief Read in the source location entry with the given ID.
896PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
897 if (ID == 0)
898 return Success;
899
900 if (ID > TotalNumSLocEntries) {
901 Error("source location entry ID out-of-range for PCH file");
902 return Failure;
903 }
904
905 ++NumSLocEntriesRead;
906 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
907 unsigned Code = SLocEntryCursor.ReadCode();
908 if (Code == llvm::bitc::END_BLOCK ||
909 Code == llvm::bitc::ENTER_SUBBLOCK ||
910 Code == llvm::bitc::DEFINE_ABBREV) {
911 Error("incorrectly-formatted source location entry in PCH file");
912 return Failure;
913 }
914
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000915 RecordData Record;
916 const char *BlobStart;
917 unsigned BlobLen;
918 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
919 default:
920 Error("incorrectly-formatted source location entry in PCH file");
921 return Failure;
922
923 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000924 std::string Filename(BlobStart, BlobStart + BlobLen);
925 MaybeAddSystemRootToFilename(Filename);
926 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000927 if (File == 0) {
928 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000929 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000930 ErrorStr += "' referenced by PCH file";
931 Error(ErrorStr.c_str());
932 return Failure;
933 }
934
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000935 FileID FID = SourceMgr.createFileID(File,
936 SourceLocation::getFromRawEncoding(Record[1]),
937 (SrcMgr::CharacteristicKind)Record[2],
938 ID, Record[0]);
939 if (Record[3])
940 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
941 .setHasLineDirectives();
942
943 break;
944 }
945
946 case pch::SM_SLOC_BUFFER_ENTRY: {
947 const char *Name = BlobStart;
948 unsigned Offset = Record[0];
949 unsigned Code = SLocEntryCursor.ReadCode();
950 Record.clear();
951 unsigned RecCode
952 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
953 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
954 (void)RecCode;
955 llvm::MemoryBuffer *Buffer
956 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
957 BlobStart + BlobLen - 1,
958 Name);
959 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
960
Douglas Gregor92b059e2009-04-28 20:33:11 +0000961 if (strcmp(Name, "<built-in>") == 0) {
962 PCHPredefinesBufferID = BufferID;
963 PCHPredefines = BlobStart;
964 PCHPredefinesLen = BlobLen - 1;
965 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000966
967 break;
968 }
969
970 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
971 SourceLocation SpellingLoc
972 = SourceLocation::getFromRawEncoding(Record[1]);
973 SourceMgr.createInstantiationLoc(SpellingLoc,
974 SourceLocation::getFromRawEncoding(Record[2]),
975 SourceLocation::getFromRawEncoding(Record[3]),
976 Record[4],
977 ID,
978 Record[0]);
979 break;
980 }
981 }
982
983 return Success;
984}
985
Chris Lattner6367f6d2009-04-27 01:05:14 +0000986/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
987/// specified cursor. Read the abbreviations that are at the top of the block
988/// and then leave the cursor pointing into the block.
989bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
990 unsigned BlockID) {
991 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000992 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000993 return Failure;
994 }
995
Chris Lattner6367f6d2009-04-27 01:05:14 +0000996 while (true) {
997 unsigned Code = Cursor.ReadCode();
998
999 // We expect all abbrevs to be at the start of the block.
1000 if (Code != llvm::bitc::DEFINE_ABBREV)
1001 return false;
1002 Cursor.ReadAbbrevRecord();
1003 }
1004}
1005
Douglas Gregor37e26842009-04-21 23:56:24 +00001006void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001007 assert(PP && "Forgot to set Preprocessor ?");
1008
Douglas Gregor37e26842009-04-21 23:56:24 +00001009 // Keep track of where we are in the stream, then jump back there
1010 // after reading this macro.
1011 SavedStreamPosition SavedPosition(Stream);
1012
1013 Stream.JumpToBit(Offset);
1014 RecordData Record;
1015 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1016 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +00001017
Douglas Gregor37e26842009-04-21 23:56:24 +00001018 while (true) {
1019 unsigned Code = Stream.ReadCode();
1020 switch (Code) {
1021 case llvm::bitc::END_BLOCK:
1022 return;
1023
1024 case llvm::bitc::ENTER_SUBBLOCK:
1025 // No known subblocks, always skip them.
1026 Stream.ReadSubBlockID();
1027 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001028 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001029 return;
1030 }
1031 continue;
1032
1033 case llvm::bitc::DEFINE_ABBREV:
1034 Stream.ReadAbbrevRecord();
1035 continue;
1036 default: break;
1037 }
1038
1039 // Read a record.
1040 Record.clear();
1041 pch::PreprocessorRecordTypes RecType =
1042 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1043 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001044 case pch::PP_MACRO_OBJECT_LIKE:
1045 case pch::PP_MACRO_FUNCTION_LIKE: {
1046 // If we already have a macro, that means that we've hit the end
1047 // of the definition of the macro we were looking for. We're
1048 // done.
1049 if (Macro)
1050 return;
1051
1052 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1053 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001054 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001055 return;
1056 }
1057 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1058 bool isUsed = Record[2];
1059
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001060 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001061 MI->setIsUsed(isUsed);
1062
1063 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1064 // Decode function-like macro info.
1065 bool isC99VarArgs = Record[3];
1066 bool isGNUVarArgs = Record[4];
1067 MacroArgs.clear();
1068 unsigned NumArgs = Record[5];
1069 for (unsigned i = 0; i != NumArgs; ++i)
1070 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1071
1072 // Install function-like macro info.
1073 MI->setIsFunctionLike();
1074 if (isC99VarArgs) MI->setIsC99Varargs();
1075 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001076 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001077 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001078 }
1079
1080 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001081 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001082
1083 // Remember that we saw this macro last so that we add the tokens that
1084 // form its body to it.
1085 Macro = MI;
1086 ++NumMacrosRead;
1087 break;
1088 }
1089
1090 case pch::PP_TOKEN: {
1091 // If we see a TOKEN before a PP_MACRO_*, then the file is
1092 // erroneous, just pretend we didn't see this.
1093 if (Macro == 0) break;
1094
1095 Token Tok;
1096 Tok.startToken();
1097 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1098 Tok.setLength(Record[1]);
1099 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1100 Tok.setIdentifierInfo(II);
1101 Tok.setKind((tok::TokenKind)Record[3]);
1102 Tok.setFlag((Token::TokenFlags)Record[4]);
1103 Macro->AddTokenToBody(Tok);
1104 break;
1105 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001106 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001107 }
1108}
1109
Douglas Gregore650c8c2009-07-07 00:12:59 +00001110/// \brief If we are loading a relocatable PCH file, and the filename is
1111/// not an absolute path, add the system root to the beginning of the file
1112/// name.
1113void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1114 // If this is not a relocatable PCH file, there's nothing to do.
1115 if (!RelocatablePCH)
1116 return;
1117
1118 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1119 return;
1120
1121 std::string FIXME = Filename;
1122
1123 if (isysroot == 0) {
1124 // If no system root was given, default to '/'
1125 Filename.insert(Filename.begin(), '/');
1126 return;
1127 }
1128
1129 unsigned Length = strlen(isysroot);
1130 if (isysroot[Length - 1] != '/')
1131 Filename.insert(Filename.begin(), '/');
1132
1133 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1134}
1135
Douglas Gregor668c1a42009-04-21 22:25:48 +00001136PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001137PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001138 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001139 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001140 return Failure;
1141 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001142
1143 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001144 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001145 while (!Stream.AtEndOfStream()) {
1146 unsigned Code = Stream.ReadCode();
1147 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001148 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001149 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001150 return Failure;
1151 }
Chris Lattner7356a312009-04-11 21:15:38 +00001152
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001153 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001154 }
1155
1156 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1157 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001158 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1159 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001160 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001161 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001162 return Failure;
1163 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001164 break;
1165
Chris Lattner6367f6d2009-04-27 01:05:14 +00001166 case pch::DECLS_BLOCK_ID:
1167 // We lazily load the decls block, but we want to set up the
1168 // DeclsCursor cursor to point into it. Clone our current bitcode
1169 // cursor to it, enter the block and read the abbrevs in that block.
1170 // With the main cursor, we just skip over it.
1171 DeclsCursor = Stream;
1172 if (Stream.SkipBlock() || // Skip with the main cursor.
1173 // Read the abbrevs.
1174 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001175 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001176 return Failure;
1177 }
1178 break;
1179
Chris Lattner7356a312009-04-11 21:15:38 +00001180 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001181 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001182 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001183 return Failure;
1184 }
1185 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001186
Douglas Gregor14f79002009-04-10 03:52:48 +00001187 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001188 switch (ReadSourceManagerBlock()) {
1189 case Success:
1190 break;
1191
1192 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001193 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001194 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001195
1196 case IgnorePCH:
1197 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001198 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001199 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001200 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001201 continue;
1202 }
1203
1204 if (Code == llvm::bitc::DEFINE_ABBREV) {
1205 Stream.ReadAbbrevRecord();
1206 continue;
1207 }
1208
1209 // Read and process a record.
1210 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001211 const char *BlobStart = 0;
1212 unsigned BlobLen = 0;
1213 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1214 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001215 default: // Default behavior: ignore.
1216 break;
1217
1218 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001219 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001220 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001221 return Failure;
1222 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001223 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001224 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001225 break;
1226
1227 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001228 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001229 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001230 return Failure;
1231 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001232 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001233 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001234 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001235
1236 case pch::LANGUAGE_OPTIONS:
1237 if (ParseLanguageOptions(Record))
1238 return IgnorePCH;
1239 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001240
Douglas Gregorab41e632009-04-27 22:23:34 +00001241 case pch::METADATA: {
1242 if (Record[0] != pch::VERSION_MAJOR) {
1243 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1244 : diag::warn_pch_version_too_new);
1245 return IgnorePCH;
1246 }
1247
Douglas Gregore650c8c2009-07-07 00:12:59 +00001248 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001249 if (Listener) {
1250 std::string TargetTriple(BlobStart, BlobLen);
1251 if (Listener->ReadTargetTriple(TargetTriple))
1252 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001253 }
1254 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001255 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001256
1257 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001258 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001259 if (Record[0]) {
1260 IdentifierLookupTable
1261 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001262 (const unsigned char *)IdentifierTableData + Record[0],
1263 (const unsigned char *)IdentifierTableData,
1264 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001265 if (PP)
1266 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001267 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001268 break;
1269
1270 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001271 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001272 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001273 return Failure;
1274 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001275 IdentifierOffsets = (const uint32_t *)BlobStart;
1276 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001277 if (PP)
1278 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001279 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001280
1281 case pch::EXTERNAL_DEFINITIONS:
1282 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001283 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001284 return Failure;
1285 }
1286 ExternalDefinitions.swap(Record);
1287 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001288
Douglas Gregorad1de002009-04-18 05:55:16 +00001289 case pch::SPECIAL_TYPES:
1290 SpecialTypes.swap(Record);
1291 break;
1292
Douglas Gregor3e1af842009-04-17 22:13:46 +00001293 case pch::STATISTICS:
1294 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001295 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001296 TotalLexicalDeclContexts = Record[2];
1297 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001298 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001299
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001300 case pch::TENTATIVE_DEFINITIONS:
1301 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001302 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001303 return Failure;
1304 }
1305 TentativeDefinitions.swap(Record);
1306 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001307
1308 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1309 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001310 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001311 return Failure;
1312 }
1313 LocallyScopedExternalDecls.swap(Record);
1314 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001315
Douglas Gregor83941df2009-04-25 17:48:32 +00001316 case pch::SELECTOR_OFFSETS:
1317 SelectorOffsets = (const uint32_t *)BlobStart;
1318 TotalNumSelectors = Record[0];
1319 SelectorsLoaded.resize(TotalNumSelectors);
1320 break;
1321
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001322 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001323 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1324 if (Record[0])
1325 MethodPoolLookupTable
1326 = PCHMethodPoolLookupTable::Create(
1327 MethodPoolLookupTableData + Record[0],
1328 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001329 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001330 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001331 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001332
1333 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001334 if (!Record.empty() && Listener)
1335 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001336 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001337
1338 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001339 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001340 TotalNumSLocEntries = Record[0];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001341 SourceMgr.PreallocateSLocEntries(this,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001342 TotalNumSLocEntries,
1343 Record[1]);
1344 break;
1345
1346 case pch::SOURCE_LOCATION_PRELOADS:
1347 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1348 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1349 if (Result != Success)
1350 return Result;
1351 }
1352 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001353
1354 case pch::STAT_CACHE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001355 FileMgr.setStatCache(
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001356 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1357 (const unsigned char *)BlobStart,
1358 NumStatHits, NumStatMisses));
1359 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001360
1361 case pch::EXT_VECTOR_DECLS:
1362 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001363 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001364 return Failure;
1365 }
1366 ExtVectorDecls.swap(Record);
1367 break;
1368
Douglas Gregorb64c1932009-05-12 01:31:05 +00001369 case pch::ORIGINAL_FILE_NAME:
1370 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001371 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001372 break;
Douglas Gregor2e222532009-07-02 17:08:52 +00001373
1374 case pch::COMMENT_RANGES:
1375 Comments = (SourceRange *)BlobStart;
1376 NumComments = BlobLen / sizeof(SourceRange);
1377 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001378 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001379 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001380 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001381 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001382}
1383
Douglas Gregore1d918e2009-04-10 23:10:45 +00001384PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001385 // Set the PCH file name.
1386 this->FileName = FileName;
1387
Douglas Gregor2cf26342009-04-09 22:27:44 +00001388 // Open the PCH file.
1389 std::string ErrStr;
1390 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001391 if (!Buffer) {
1392 Error(ErrStr.c_str());
1393 return IgnorePCH;
1394 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001395
1396 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001397 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1398 (const unsigned char *)Buffer->getBufferEnd());
1399 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001400
1401 // Sniff for the signature.
1402 if (Stream.Read(8) != 'C' ||
1403 Stream.Read(8) != 'P' ||
1404 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001405 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001406 Diag(diag::err_not_a_pch_file) << FileName;
1407 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001408 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001409
Douglas Gregor2cf26342009-04-09 22:27:44 +00001410 while (!Stream.AtEndOfStream()) {
1411 unsigned Code = Stream.ReadCode();
1412
Douglas Gregore1d918e2009-04-10 23:10:45 +00001413 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001414 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001415 return Failure;
1416 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001417
1418 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001419
Douglas Gregor2cf26342009-04-09 22:27:44 +00001420 // We only know the PCH subblock ID.
1421 switch (BlockID) {
1422 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001423 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001424 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001425 return Failure;
1426 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001427 break;
1428 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001429 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001430 case Success:
1431 break;
1432
1433 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001434 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001435
1436 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001437 // FIXME: We could consider reading through to the end of this
1438 // PCH block, skipping subblocks, to see if there are other
1439 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001440
1441 // Clear out any preallocated source location entries, so that
1442 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001443 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001444
1445 // Remove the stat cache.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001446 FileMgr.setStatCache(0);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001447
Douglas Gregore1d918e2009-04-10 23:10:45 +00001448 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001449 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001450 break;
1451 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001452 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001453 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001454 return Failure;
1455 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001456 break;
1457 }
1458 }
Douglas Gregor92b059e2009-04-28 20:33:11 +00001459
1460 // Check the predefines buffer.
1461 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1462 PCHPredefinesBufferID))
1463 return IgnorePCH;
1464
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001465 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001466 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001467 // PCH file is read, so there may be some identifiers that were
1468 // loaded into the IdentifierTable before we intercepted the
1469 // creation of identifiers. Iterate through the list of known
1470 // identifiers and determine whether we have to establish
1471 // preprocessor definitions or top-level identifier declaration
1472 // chains for those identifiers.
1473 //
1474 // We copy the IdentifierInfo pointers to a small vector first,
1475 // since de-serializing declarations or macro definitions can add
1476 // new entries into the identifier table, invalidating the
1477 // iterators.
1478 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1479 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1480 IdEnd = PP->getIdentifierTable().end();
1481 Id != IdEnd; ++Id)
1482 Identifiers.push_back(Id->second);
1483 PCHIdentifierLookupTable *IdTable
1484 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1485 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1486 IdentifierInfo *II = Identifiers[I];
1487 // Look in the on-disk hash table for an entry for
1488 PCHIdentifierLookupTrait Info(*this, II);
1489 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1490 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1491 if (Pos == IdTable->end())
1492 continue;
1493
1494 // Dereferencing the iterator has the effect of populating the
1495 // IdentifierInfo node with the various declarations it needs.
1496 (void)*Pos;
1497 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001498 }
1499
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001500 if (Context)
1501 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001502
Douglas Gregor668c1a42009-04-21 22:25:48 +00001503 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001504}
1505
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001506void PCHReader::InitializeContext(ASTContext &Ctx) {
1507 Context = &Ctx;
1508 assert(Context && "Passed null context!");
1509
1510 assert(PP && "Forgot to set Preprocessor ?");
1511 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1512 PP->getHeaderSearchInfo().SetExternalLookup(this);
1513
1514 // Load the translation unit declaration
1515 ReadDeclRecord(DeclOffsets[0], 0);
1516
1517 // Load the special types.
1518 Context->setBuiltinVaListType(
1519 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1520 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1521 Context->setObjCIdType(GetType(Id));
1522 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1523 Context->setObjCSelType(GetType(Sel));
1524 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1525 Context->setObjCProtoType(GetType(Proto));
1526 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1527 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001528
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001529 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1530 Context->setCFConstantStringType(GetType(String));
1531 if (unsigned FastEnum
1532 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1533 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001534 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1535 QualType FileType = GetType(File);
1536 assert(!FileType.isNull() && "FILE type is NULL");
1537 if (const TypedefType *Typedef = FileType->getAsTypedefType())
1538 Context->setFILEDecl(Typedef->getDecl());
1539 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001540 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001541 assert(Tag && "Invalid FILE type in PCH file");
1542 Context->setFILEDecl(Tag->getDecl());
1543 }
1544 }
Mike Stump782fa302009-07-28 02:25:19 +00001545 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1546 QualType Jmp_bufType = GetType(Jmp_buf);
1547 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
1548 if (const TypedefType *Typedef = Jmp_bufType->getAsTypedefType())
1549 Context->setjmp_bufDecl(Typedef->getDecl());
1550 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001551 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001552 assert(Tag && "Invalid jmp_bug type in PCH file");
1553 Context->setjmp_bufDecl(Tag->getDecl());
1554 }
1555 }
1556 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1557 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1558 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
1559 if (const TypedefType *Typedef = Sigjmp_bufType->getAsTypedefType())
1560 Context->setsigjmp_bufDecl(Typedef->getDecl());
1561 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001562 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001563 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1564 Context->setsigjmp_bufDecl(Tag->getDecl());
1565 }
1566 }
Douglas Gregord1571ac2009-08-21 00:27:50 +00001567 if (unsigned ObjCIdRedef
1568 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1569 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
1570 if (unsigned ObjCClassRedef
1571 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1572 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001573}
1574
Douglas Gregorb64c1932009-05-12 01:31:05 +00001575/// \brief Retrieve the name of the original source file name
1576/// directly from the PCH file, without actually loading the PCH
1577/// file.
1578std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1579 // Open the PCH file.
1580 std::string ErrStr;
1581 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1582 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1583 if (!Buffer) {
1584 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1585 return std::string();
1586 }
1587
1588 // Initialize the stream
1589 llvm::BitstreamReader StreamFile;
1590 llvm::BitstreamCursor Stream;
1591 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1592 (const unsigned char *)Buffer->getBufferEnd());
1593 Stream.init(StreamFile);
1594
1595 // Sniff for the signature.
1596 if (Stream.Read(8) != 'C' ||
1597 Stream.Read(8) != 'P' ||
1598 Stream.Read(8) != 'C' ||
1599 Stream.Read(8) != 'H') {
1600 fprintf(stderr,
1601 "error: '%s' does not appear to be a precompiled header file\n",
1602 PCHFileName.c_str());
1603 return std::string();
1604 }
1605
1606 RecordData Record;
1607 while (!Stream.AtEndOfStream()) {
1608 unsigned Code = Stream.ReadCode();
1609
1610 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1611 unsigned BlockID = Stream.ReadSubBlockID();
1612
1613 // We only know the PCH subblock ID.
1614 switch (BlockID) {
1615 case pch::PCH_BLOCK_ID:
1616 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1617 fprintf(stderr, "error: malformed block record in PCH file\n");
1618 return std::string();
1619 }
1620 break;
1621
1622 default:
1623 if (Stream.SkipBlock()) {
1624 fprintf(stderr, "error: malformed block record in PCH file\n");
1625 return std::string();
1626 }
1627 break;
1628 }
1629 continue;
1630 }
1631
1632 if (Code == llvm::bitc::END_BLOCK) {
1633 if (Stream.ReadBlockEnd()) {
1634 fprintf(stderr, "error: error at end of module block in PCH file\n");
1635 return std::string();
1636 }
1637 continue;
1638 }
1639
1640 if (Code == llvm::bitc::DEFINE_ABBREV) {
1641 Stream.ReadAbbrevRecord();
1642 continue;
1643 }
1644
1645 Record.clear();
1646 const char *BlobStart = 0;
1647 unsigned BlobLen = 0;
1648 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1649 == pch::ORIGINAL_FILE_NAME)
1650 return std::string(BlobStart, BlobLen);
1651 }
1652
1653 return std::string();
1654}
1655
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001656/// \brief Parse the record that corresponds to a LangOptions data
1657/// structure.
1658///
1659/// This routine compares the language options used to generate the
1660/// PCH file against the language options set for the current
1661/// compilation. For each option, we classify differences between the
1662/// two compiler states as either "benign" or "important". Benign
1663/// differences don't matter, and we accept them without complaint
1664/// (and without modifying the language options). Differences between
1665/// the states for important options cause the PCH file to be
1666/// unusable, so we emit a warning and return true to indicate that
1667/// there was an error.
1668///
1669/// \returns true if the PCH file is unacceptable, false otherwise.
1670bool PCHReader::ParseLanguageOptions(
1671 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001672 if (Listener) {
1673 LangOptions LangOpts;
1674
1675 #define PARSE_LANGOPT(Option) \
1676 LangOpts.Option = Record[Idx]; \
1677 ++Idx
1678
1679 unsigned Idx = 0;
1680 PARSE_LANGOPT(Trigraphs);
1681 PARSE_LANGOPT(BCPLComment);
1682 PARSE_LANGOPT(DollarIdents);
1683 PARSE_LANGOPT(AsmPreprocessor);
1684 PARSE_LANGOPT(GNUMode);
1685 PARSE_LANGOPT(ImplicitInt);
1686 PARSE_LANGOPT(Digraphs);
1687 PARSE_LANGOPT(HexFloats);
1688 PARSE_LANGOPT(C99);
1689 PARSE_LANGOPT(Microsoft);
1690 PARSE_LANGOPT(CPlusPlus);
1691 PARSE_LANGOPT(CPlusPlus0x);
1692 PARSE_LANGOPT(CXXOperatorNames);
1693 PARSE_LANGOPT(ObjC1);
1694 PARSE_LANGOPT(ObjC2);
1695 PARSE_LANGOPT(ObjCNonFragileABI);
1696 PARSE_LANGOPT(PascalStrings);
1697 PARSE_LANGOPT(WritableStrings);
1698 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001699 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001700 PARSE_LANGOPT(Exceptions);
1701 PARSE_LANGOPT(NeXTRuntime);
1702 PARSE_LANGOPT(Freestanding);
1703 PARSE_LANGOPT(NoBuiltin);
1704 PARSE_LANGOPT(ThreadsafeStatics);
1705 PARSE_LANGOPT(Blocks);
1706 PARSE_LANGOPT(EmitAllDecls);
1707 PARSE_LANGOPT(MathErrno);
1708 PARSE_LANGOPT(OverflowChecking);
1709 PARSE_LANGOPT(HeinousExtensions);
1710 PARSE_LANGOPT(Optimize);
1711 PARSE_LANGOPT(OptimizeSize);
1712 PARSE_LANGOPT(Static);
1713 PARSE_LANGOPT(PICLevel);
1714 PARSE_LANGOPT(GNUInline);
1715 PARSE_LANGOPT(NoInline);
1716 PARSE_LANGOPT(AccessControl);
1717 PARSE_LANGOPT(CharIsSigned);
1718 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1719 ++Idx;
1720 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1721 ++Idx;
1722 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001723 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001724 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001725
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001726 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001727 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001728
1729 return false;
1730}
1731
Douglas Gregor2e222532009-07-02 17:08:52 +00001732void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1733 Comments.resize(NumComments);
1734 std::copy(this->Comments, this->Comments + NumComments,
1735 Comments.begin());
1736}
1737
Douglas Gregor2cf26342009-04-09 22:27:44 +00001738/// \brief Read and return the type at the given offset.
1739///
1740/// This routine actually reads the record corresponding to the type
1741/// at the given offset in the bitstream. It is a helper routine for
1742/// GetType, which deals with reading type IDs.
1743QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001744 // Keep track of where we are in the stream, then jump back there
1745 // after reading this type.
1746 SavedStreamPosition SavedPosition(Stream);
1747
Douglas Gregord89275b2009-07-06 18:54:52 +00001748 // Note that we are loading a type record.
1749 LoadingTypeOrDecl Loading(*this);
1750
Douglas Gregor2cf26342009-04-09 22:27:44 +00001751 Stream.JumpToBit(Offset);
1752 RecordData Record;
1753 unsigned Code = Stream.ReadCode();
1754 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001755 case pch::TYPE_EXT_QUAL: {
1756 assert(Record.size() == 3 &&
1757 "Incorrect encoding of extended qualifier type");
1758 QualType Base = GetType(Record[0]);
1759 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1760 unsigned AddressSpace = Record[2];
1761
1762 QualType T = Base;
1763 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001764 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001765 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001766 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001767 return T;
1768 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001769
Douglas Gregor2cf26342009-04-09 22:27:44 +00001770 case pch::TYPE_FIXED_WIDTH_INT: {
1771 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001772 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001773 }
1774
1775 case pch::TYPE_COMPLEX: {
1776 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1777 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001778 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001779 }
1780
1781 case pch::TYPE_POINTER: {
1782 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1783 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001784 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001785 }
1786
1787 case pch::TYPE_BLOCK_POINTER: {
1788 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1789 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001790 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001791 }
1792
1793 case pch::TYPE_LVALUE_REFERENCE: {
1794 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1795 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001796 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001797 }
1798
1799 case pch::TYPE_RVALUE_REFERENCE: {
1800 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1801 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001802 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001803 }
1804
1805 case pch::TYPE_MEMBER_POINTER: {
1806 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1807 QualType PointeeType = GetType(Record[0]);
1808 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001809 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001810 }
1811
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001812 case pch::TYPE_CONSTANT_ARRAY: {
1813 QualType ElementType = GetType(Record[0]);
1814 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1815 unsigned IndexTypeQuals = Record[2];
1816 unsigned Idx = 3;
1817 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001818 return Context->getConstantArrayType(ElementType, Size,
1819 ASM, IndexTypeQuals);
1820 }
1821
1822 case pch::TYPE_CONSTANT_ARRAY_WITH_EXPR: {
1823 QualType ElementType = GetType(Record[0]);
1824 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1825 unsigned IndexTypeQuals = Record[2];
1826 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1827 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1828 unsigned Idx = 5;
1829 llvm::APInt Size = ReadAPInt(Record, Idx);
1830 return Context->getConstantArrayWithExprType(ElementType,
1831 Size, ReadTypeExpr(),
1832 ASM, IndexTypeQuals,
1833 SourceRange(LBLoc, RBLoc));
1834 }
1835
1836 case pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR: {
1837 QualType ElementType = GetType(Record[0]);
1838 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1839 unsigned IndexTypeQuals = Record[2];
1840 unsigned Idx = 3;
1841 llvm::APInt Size = ReadAPInt(Record, Idx);
1842 return Context->getConstantArrayWithoutExprType(ElementType, Size,
1843 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001844 }
1845
1846 case pch::TYPE_INCOMPLETE_ARRAY: {
1847 QualType ElementType = GetType(Record[0]);
1848 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1849 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001850 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001851 }
1852
1853 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001854 QualType ElementType = GetType(Record[0]);
1855 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1856 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001857 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1858 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001859 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001860 ASM, IndexTypeQuals,
1861 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001862 }
1863
1864 case pch::TYPE_VECTOR: {
1865 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001866 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001867 return QualType();
1868 }
1869
1870 QualType ElementType = GetType(Record[0]);
1871 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001872 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001873 }
1874
1875 case pch::TYPE_EXT_VECTOR: {
1876 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001877 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001878 return QualType();
1879 }
1880
1881 QualType ElementType = GetType(Record[0]);
1882 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001883 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001884 }
1885
1886 case pch::TYPE_FUNCTION_NO_PROTO: {
1887 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001888 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001889 return QualType();
1890 }
1891 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001892 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001893 }
1894
1895 case pch::TYPE_FUNCTION_PROTO: {
1896 QualType ResultType = GetType(Record[0]);
1897 unsigned Idx = 1;
1898 unsigned NumParams = Record[Idx++];
1899 llvm::SmallVector<QualType, 16> ParamTypes;
1900 for (unsigned I = 0; I != NumParams; ++I)
1901 ParamTypes.push_back(GetType(Record[Idx++]));
1902 bool isVariadic = Record[Idx++];
1903 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001904 bool hasExceptionSpec = Record[Idx++];
1905 bool hasAnyExceptionSpec = Record[Idx++];
1906 unsigned NumExceptions = Record[Idx++];
1907 llvm::SmallVector<QualType, 2> Exceptions;
1908 for (unsigned I = 0; I != NumExceptions; ++I)
1909 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001910 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001911 isVariadic, Quals, hasExceptionSpec,
1912 hasAnyExceptionSpec, NumExceptions,
1913 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001914 }
1915
1916 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001917 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001918 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001919
1920 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001921 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001922
1923 case pch::TYPE_TYPEOF: {
1924 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001925 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001926 return QualType();
1927 }
1928 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001929 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001930 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001931
1932 case pch::TYPE_DECLTYPE:
1933 return Context->getDecltypeType(ReadTypeExpr());
1934
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001935 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001936 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001937 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001938
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001939 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001940 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001941 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001942
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001943 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001944 unsigned Idx = 0;
1945 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1946 unsigned NumProtos = Record[Idx++];
1947 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1948 for (unsigned I = 0; I != NumProtos; ++I)
1949 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001950 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001951 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001952
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001953 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001954 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001955 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001956 unsigned NumProtos = Record[Idx++];
1957 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1958 for (unsigned I = 0; I != NumProtos; ++I)
1959 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001960 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001961 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001962 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001963 // Suppress a GCC warning
1964 return QualType();
1965}
1966
Douglas Gregor2cf26342009-04-09 22:27:44 +00001967
Douglas Gregor8038d512009-04-10 17:25:41 +00001968QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001969 unsigned Quals = ID & 0x07;
1970 unsigned Index = ID >> 3;
1971
1972 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1973 QualType T;
1974 switch ((pch::PredefinedTypeIDs)Index) {
1975 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001976 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1977 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001978
1979 case pch::PREDEF_TYPE_CHAR_U_ID:
1980 case pch::PREDEF_TYPE_CHAR_S_ID:
1981 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001982 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001983 break;
1984
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001985 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1986 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1987 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1988 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1989 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001990 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001991 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1992 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1993 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1994 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1995 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1996 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001997 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001998 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1999 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
2000 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2001 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2002 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002003 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002004 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2005 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002006 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2007 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002008 }
2009
2010 assert(!T.isNull() && "Unknown predefined type");
2011 return T.getQualifiedType(Quals);
2012 }
2013
2014 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002015 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002016 if (!TypesLoaded[Index])
2017 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00002018
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002019 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002020}
2021
Douglas Gregor8038d512009-04-10 17:25:41 +00002022Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002023 if (ID == 0)
2024 return 0;
2025
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002026 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002027 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002028 return 0;
2029 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002030
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002031 unsigned Index = ID - 1;
2032 if (!DeclsLoaded[Index])
2033 ReadDeclRecord(DeclOffsets[Index], Index);
2034
2035 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002036}
2037
Chris Lattner887e2b32009-04-27 05:46:25 +00002038/// \brief Resolve the offset of a statement into a statement.
2039///
2040/// This operation will read a new statement from the external
2041/// source each time it is called, and is meant to be used via a
2042/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2043Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002044 // Since we know tha this statement is part of a decl, make sure to use the
2045 // decl cursor to read it.
2046 DeclsCursor.JumpToBit(Offset);
2047 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002048}
2049
Douglas Gregor2cf26342009-04-09 22:27:44 +00002050bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002051 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002052 assert(DC->hasExternalLexicalStorage() &&
2053 "DeclContext has no lexical decls in storage");
2054 uint64_t Offset = DeclContextOffsets[DC].first;
2055 assert(Offset && "DeclContext has no lexical decls in storage");
2056
Douglas Gregor0b748912009-04-14 21:18:50 +00002057 // Keep track of where we are in the stream, then jump back there
2058 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002059 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002060
Douglas Gregor2cf26342009-04-09 22:27:44 +00002061 // Load the record containing all of the declarations lexically in
2062 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002063 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002064 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002065 unsigned Code = DeclsCursor.ReadCode();
2066 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002067 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002068 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2069
2070 // Load all of the declaration IDs
2071 Decls.clear();
2072 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002073 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002074 return false;
2075}
2076
2077bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002078 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002079 assert(DC->hasExternalVisibleStorage() &&
2080 "DeclContext has no visible decls in storage");
2081 uint64_t Offset = DeclContextOffsets[DC].second;
2082 assert(Offset && "DeclContext has no visible decls in storage");
2083
Douglas Gregor0b748912009-04-14 21:18:50 +00002084 // Keep track of where we are in the stream, then jump back there
2085 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002086 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002087
Douglas Gregor2cf26342009-04-09 22:27:44 +00002088 // Load the record containing all of the declarations visible in
2089 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002090 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002091 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002092 unsigned Code = DeclsCursor.ReadCode();
2093 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002094 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002095 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2096 if (Record.size() == 0)
2097 return false;
2098
2099 Decls.clear();
2100
2101 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002102 while (Idx < Record.size()) {
2103 Decls.push_back(VisibleDeclaration());
2104 Decls.back().Name = ReadDeclarationName(Record, Idx);
2105
Douglas Gregor2cf26342009-04-09 22:27:44 +00002106 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002107 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002108 LoadedDecls.reserve(Size);
2109 for (unsigned I = 0; I < Size; ++I)
2110 LoadedDecls.push_back(Record[Idx++]);
2111 }
2112
Douglas Gregor25123082009-04-22 22:34:57 +00002113 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002114 return false;
2115}
2116
Douglas Gregorfdd01722009-04-14 00:24:19 +00002117void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002118 this->Consumer = Consumer;
2119
Douglas Gregorfdd01722009-04-14 00:24:19 +00002120 if (!Consumer)
2121 return;
2122
2123 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2124 Decl *D = GetDecl(ExternalDefinitions[I]);
2125 DeclGroupRef DG(D);
2126 Consumer->HandleTopLevelDecl(DG);
2127 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002128
2129 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2130 DeclGroupRef DG(InterestingDecls[I]);
2131 Consumer->HandleTopLevelDecl(DG);
2132 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002133}
2134
Douglas Gregor2cf26342009-04-09 22:27:44 +00002135void PCHReader::PrintStats() {
2136 std::fprintf(stderr, "*** PCH Statistics:\n");
2137
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002138 unsigned NumTypesLoaded
2139 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2140 (Type *)0);
2141 unsigned NumDeclsLoaded
2142 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2143 (Decl *)0);
2144 unsigned NumIdentifiersLoaded
2145 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2146 IdentifiersLoaded.end(),
2147 (IdentifierInfo *)0);
2148 unsigned NumSelectorsLoaded
2149 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2150 SelectorsLoaded.end(),
2151 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002152
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002153 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2154 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002155 if (TotalNumSLocEntries)
2156 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2157 NumSLocEntriesRead, TotalNumSLocEntries,
2158 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002159 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002160 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002161 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2162 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2163 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002164 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002165 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2166 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002167 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002168 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002169 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2170 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002171 if (TotalNumSelectors)
2172 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2173 NumSelectorsLoaded, TotalNumSelectors,
2174 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2175 if (TotalNumStatements)
2176 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2177 NumStatementsRead, TotalNumStatements,
2178 ((float)NumStatementsRead/TotalNumStatements * 100));
2179 if (TotalNumMacros)
2180 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2181 NumMacrosRead, TotalNumMacros,
2182 ((float)NumMacrosRead/TotalNumMacros * 100));
2183 if (TotalLexicalDeclContexts)
2184 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2185 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2186 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2187 * 100));
2188 if (TotalVisibleDeclContexts)
2189 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2190 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2191 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2192 * 100));
2193 if (TotalSelectorsInMethodPool) {
2194 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2195 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2196 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2197 * 100));
2198 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2199 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002200 std::fprintf(stderr, "\n");
2201}
2202
Douglas Gregor668c1a42009-04-21 22:25:48 +00002203void PCHReader::InitializeSema(Sema &S) {
2204 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002205 S.ExternalSource = this;
2206
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002207 // Makes sure any declarations that were deserialized "too early"
2208 // still get added to the identifier's declaration chains.
2209 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2210 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2211 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002212 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002213 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002214
2215 // If there were any tentative definitions, deserialize them and add
2216 // them to Sema's table of tentative definitions.
2217 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2218 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2219 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2220 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002221
2222 // If there were any locally-scoped external declarations,
2223 // deserialize them and add them to Sema's table of locally-scoped
2224 // external declarations.
2225 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2226 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2227 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2228 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002229
2230 // If there were any ext_vector type declarations, deserialize them
2231 // and add them to Sema's vector of such declarations.
2232 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2233 SemaObj->ExtVectorDecls.push_back(
2234 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002235}
2236
2237IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2238 // Try to find this name within our on-disk hash table
2239 PCHIdentifierLookupTable *IdTable
2240 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2241 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2242 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2243 if (Pos == IdTable->end())
2244 return 0;
2245
2246 // Dereferencing the iterator has the effect of building the
2247 // IdentifierInfo node and populating it with the various
2248 // declarations it needs.
2249 return *Pos;
2250}
2251
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002252std::pair<ObjCMethodList, ObjCMethodList>
2253PCHReader::ReadMethodPool(Selector Sel) {
2254 if (!MethodPoolLookupTable)
2255 return std::pair<ObjCMethodList, ObjCMethodList>();
2256
2257 // Try to find this selector within our on-disk hash table.
2258 PCHMethodPoolLookupTable *PoolTable
2259 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2260 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002261 if (Pos == PoolTable->end()) {
2262 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002263 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002264 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002265
Douglas Gregor83941df2009-04-25 17:48:32 +00002266 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002267 return *Pos;
2268}
2269
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002270void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002271 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002272 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002273 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002274}
2275
Douglas Gregord89275b2009-07-06 18:54:52 +00002276/// \brief Set the globally-visible declarations associated with the given
2277/// identifier.
2278///
2279/// If the PCH reader is currently in a state where the given declaration IDs
2280/// cannot safely be resolved, they are queued until it is safe to resolve
2281/// them.
2282///
2283/// \param II an IdentifierInfo that refers to one or more globally-visible
2284/// declarations.
2285///
2286/// \param DeclIDs the set of declaration IDs with the name @p II that are
2287/// visible at global scope.
2288///
2289/// \param Nonrecursive should be true to indicate that the caller knows that
2290/// this call is non-recursive, and therefore the globally-visible declarations
2291/// will not be placed onto the pending queue.
2292void
2293PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
2294 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2295 bool Nonrecursive) {
2296 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2297 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2298 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2299 PII.II = II;
2300 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2301 PII.DeclIDs.push_back(DeclIDs[I]);
2302 return;
2303 }
2304
2305 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2306 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2307 if (SemaObj) {
2308 // Introduce this declaration into the translation-unit scope
2309 // and add it to the declaration chain for this identifier, so
2310 // that (unqualified) name lookup will find it.
2311 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2312 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2313 } else {
2314 // Queue this declaration so that it will be added to the
2315 // translation unit scope and identifier's declaration chain
2316 // once a Sema object is known.
2317 PreloadedDecls.push_back(D);
2318 }
2319 }
2320}
2321
Chris Lattner7356a312009-04-11 21:15:38 +00002322IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002323 if (ID == 0)
2324 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00002325
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002326 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002327 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002328 return 0;
2329 }
Chris Lattner7356a312009-04-11 21:15:38 +00002330
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002331 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002332 if (!IdentifiersLoaded[ID - 1]) {
2333 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002334 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002335
Douglas Gregor02fc7512009-04-28 20:01:51 +00002336 // All of the strings in the PCH file are preceded by a 16-bit
2337 // length. Extract that 16-bit length to avoid having to execute
2338 // strlen().
2339 const char *StrLenPtr = Str - 2;
2340 unsigned StrLen = (((unsigned) StrLenPtr[0])
2341 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2342 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002343 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002344 }
Chris Lattner7356a312009-04-11 21:15:38 +00002345
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002346 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002347}
2348
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002349void PCHReader::ReadSLocEntry(unsigned ID) {
2350 ReadSLocEntryRecord(ID);
2351}
2352
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002353Selector PCHReader::DecodeSelector(unsigned ID) {
2354 if (ID == 0)
2355 return Selector();
2356
Douglas Gregora02b1472009-04-28 21:53:25 +00002357 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002358 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002359
2360 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002361 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002362 return Selector();
2363 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002364
2365 unsigned Index = ID - 1;
2366 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2367 // Load this selector from the selector table.
2368 // FIXME: endianness portability issues with SelectorOffsets table
2369 PCHMethodPoolLookupTrait Trait(*this);
2370 SelectorsLoaded[Index]
2371 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2372 }
2373
2374 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002375}
2376
Douglas Gregor2cf26342009-04-09 22:27:44 +00002377DeclarationName
2378PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2379 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2380 switch (Kind) {
2381 case DeclarationName::Identifier:
2382 return DeclarationName(GetIdentifierInfo(Record, Idx));
2383
2384 case DeclarationName::ObjCZeroArgSelector:
2385 case DeclarationName::ObjCOneArgSelector:
2386 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002387 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002388
2389 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002390 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002391 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002392
2393 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002394 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002395 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002396
2397 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002398 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002399 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002400
2401 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002402 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002403 (OverloadedOperatorKind)Record[Idx++]);
2404
2405 case DeclarationName::CXXUsingDirective:
2406 return DeclarationName::getUsingDirectiveName();
2407 }
2408
2409 // Required to silence GCC warning
2410 return DeclarationName();
2411}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002412
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002413/// \brief Read an integral value
2414llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2415 unsigned BitWidth = Record[Idx++];
2416 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2417 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2418 Idx += NumWords;
2419 return Result;
2420}
2421
2422/// \brief Read a signed integral value
2423llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2424 bool isUnsigned = Record[Idx++];
2425 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2426}
2427
Douglas Gregor17fc2232009-04-14 21:55:33 +00002428/// \brief Read a floating-point value
2429llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002430 return llvm::APFloat(ReadAPInt(Record, Idx));
2431}
2432
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002433// \brief Read a string
2434std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2435 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002436 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002437 Idx += Len;
2438 return Result;
2439}
2440
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002441DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002442 return Diag(SourceLocation(), DiagID);
2443}
2444
2445DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002446 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002447}
Douglas Gregor025452f2009-04-17 00:04:06 +00002448
Douglas Gregor668c1a42009-04-21 22:25:48 +00002449/// \brief Retrieve the identifier table associated with the
2450/// preprocessor.
2451IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002452 assert(PP && "Forgot to set Preprocessor ?");
2453 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002454}
2455
Douglas Gregor025452f2009-04-17 00:04:06 +00002456/// \brief Record that the given ID maps to the given switch-case
2457/// statement.
2458void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2459 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2460 SwitchCaseStmts[ID] = SC;
2461}
2462
2463/// \brief Retrieve the switch-case statement with the given ID.
2464SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2465 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2466 return SwitchCaseStmts[ID];
2467}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002468
2469/// \brief Record that the given label statement has been
2470/// deserialized and has the given ID.
2471void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2472 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2473 "Deserialized label twice");
2474 LabelStmts[ID] = S;
2475
2476 // If we've already seen any goto statements that point to this
2477 // label, resolve them now.
2478 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2479 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2480 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2481 Goto->second->setLabel(S);
2482 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002483
2484 // If we've already seen any address-label statements that point to
2485 // this label, resolve them now.
2486 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2487 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2488 = UnresolvedAddrLabelExprs.equal_range(ID);
2489 for (AddrLabelIter AddrLabel = AddrLabels.first;
2490 AddrLabel != AddrLabels.second; ++AddrLabel)
2491 AddrLabel->second->setLabel(S);
2492 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002493}
2494
2495/// \brief Set the label of the given statement to the label
2496/// identified by ID.
2497///
2498/// Depending on the order in which the label and other statements
2499/// referencing that label occur, this operation may complete
2500/// immediately (updating the statement) or it may queue the
2501/// statement to be back-patched later.
2502void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2503 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2504 if (Label != LabelStmts.end()) {
2505 // We've already seen this label, so set the label of the goto and
2506 // we're done.
2507 S->setLabel(Label->second);
2508 } else {
2509 // We haven't seen this label yet, so add this goto to the set of
2510 // unresolved goto statements.
2511 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2512 }
2513}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002514
2515/// \brief Set the label of the given expression to the label
2516/// identified by ID.
2517///
2518/// Depending on the order in which the label and other statements
2519/// referencing that label occur, this operation may complete
2520/// immediately (updating the statement) or it may queue the
2521/// statement to be back-patched later.
2522void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2523 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2524 if (Label != LabelStmts.end()) {
2525 // We've already seen this label, so set the label of the
2526 // label-address expression and we're done.
2527 S->setLabel(Label->second);
2528 } else {
2529 // We haven't seen this label yet, so add this label-address
2530 // expression to the set of unresolved label-address expressions.
2531 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2532 }
2533}
Douglas Gregord89275b2009-07-06 18:54:52 +00002534
2535
2536PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
2537 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2538 Reader.CurrentlyLoadingTypeOrDecl = this;
2539}
2540
2541PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2542 if (!Parent) {
2543 // If any identifiers with corresponding top-level declarations have
2544 // been loaded, load those declarations now.
2545 while (!Reader.PendingIdentifierInfos.empty()) {
2546 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2547 Reader.PendingIdentifierInfos.front().DeclIDs,
2548 true);
2549 Reader.PendingIdentifierInfos.pop_front();
2550 }
2551 }
2552
2553 Reader.CurrentlyLoadingTypeOrDecl = Parent;
2554}