blob: c025fcd1aa4ae55603c1c295f931507ce51861bb [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);
81 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
82 PARSE_LANGOPT_BENIGN(EmitAllDecls);
83 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
84 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
85 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
86 diag::warn_pch_heinous_extensions);
87 // FIXME: Most of the options below are benign if the macro wasn't
88 // used. Unfortunately, this means that a PCH compiled without
89 // optimization can't be used with optimization turned on, even
90 // though the only thing that changes is whether __OPTIMIZE__ was
91 // defined... but if __OPTIMIZE__ never showed up in the header, it
92 // doesn't matter. We could consider making this some special kind
93 // of check.
94 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
95 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
96 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
97 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
98 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
99 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
100 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
101 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
102 if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
103 Reader.Diag(diag::warn_pch_gc_mode)
104 << LangOpts.getGCMode() << PPLangOpts.getGCMode();
105 return true;
106 }
107 PARSE_LANGOPT_BENIGN(getVisibilityMode());
108 PARSE_LANGOPT_BENIGN(InstantiationDepth);
Nate Begeman69cfb9b2009-06-25 22:57:40 +0000109 PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
Anders Carlsson92f58222009-08-22 22:30:33 +0000110 PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_elide_constructors);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000111#undef PARSE_LANGOPT_IRRELEVANT
112#undef PARSE_LANGOPT_BENIGN
113
114 return false;
115}
116
117bool PCHValidator::ReadTargetTriple(const std::string &Triple) {
118 if (Triple != PP.getTargetInfo().getTargetTriple()) {
119 Reader.Diag(diag::warn_pch_target_triple)
120 << Triple << PP.getTargetInfo().getTargetTriple();
121 return true;
122 }
123 return false;
124}
125
126/// \brief Split the given string into a vector of lines, eliminating
127/// any empty lines in the process.
128///
129/// \param Str the string to split.
130/// \param Len the length of Str.
131/// \param KeepEmptyLines true if empty lines should be included
132/// \returns a vector of lines, with the line endings removed
133static std::vector<std::string> splitLines(const char *Str, unsigned Len,
134 bool KeepEmptyLines = false) {
135 std::vector<std::string> Lines;
136 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
137 unsigned LineEnd = LineStart;
138 while (LineEnd < Len && Str[LineEnd] != '\n')
139 ++LineEnd;
140 if (LineStart != LineEnd || KeepEmptyLines)
141 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
142 LineStart = LineEnd;
143 }
144 return Lines;
145}
146
147/// \brief Determine whether the string Haystack starts with the
148/// substring Needle.
149static bool startsWith(const std::string &Haystack, const char *Needle) {
150 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
151 if (I == N)
152 return false;
153 if (Haystack[I] != Needle[I])
154 return false;
155 }
156
157 return true;
158}
159
160/// \brief Determine whether the string Haystack starts with the
161/// substring Needle.
162static inline bool startsWith(const std::string &Haystack,
163 const std::string &Needle) {
164 return startsWith(Haystack, Needle.c_str());
165}
166
167bool PCHValidator::ReadPredefinesBuffer(const char *PCHPredef,
168 unsigned PCHPredefLen,
169 FileID PCHBufferID,
170 std::string &SuggestedPredefines) {
171 const char *Predef = PP.getPredefines().c_str();
172 unsigned PredefLen = PP.getPredefines().size();
173
174 // If the two predefines buffers compare equal, we're done!
175 if (PredefLen == PCHPredefLen &&
176 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
177 return false;
178
179 SourceManager &SourceMgr = PP.getSourceManager();
180
181 // The predefines buffers are different. Determine what the
182 // differences are, and whether they require us to reject the PCH
183 // file.
184 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
185 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
186
187 // Sort both sets of predefined buffer lines, since
188 std::sort(CmdLineLines.begin(), CmdLineLines.end());
189 std::sort(PCHLines.begin(), PCHLines.end());
190
191 // Determine which predefines that where used to build the PCH file
192 // are missing from the command line.
193 std::vector<std::string> MissingPredefines;
194 std::set_difference(PCHLines.begin(), PCHLines.end(),
195 CmdLineLines.begin(), CmdLineLines.end(),
196 std::back_inserter(MissingPredefines));
197
198 bool MissingDefines = false;
199 bool ConflictingDefines = false;
200 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
201 const std::string &Missing = MissingPredefines[I];
202 if (!startsWith(Missing, "#define ") != 0) {
203 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
204 return true;
205 }
206
207 // This is a macro definition. Determine the name of the macro
208 // we're defining.
209 std::string::size_type StartOfMacroName = strlen("#define ");
210 std::string::size_type EndOfMacroName
211 = Missing.find_first_of("( \n\r", StartOfMacroName);
212 assert(EndOfMacroName != std::string::npos &&
213 "Couldn't find the end of the macro name");
214 std::string MacroName = Missing.substr(StartOfMacroName,
215 EndOfMacroName - StartOfMacroName);
216
217 // Determine whether this macro was given a different definition
218 // on the command line.
219 std::string MacroDefStart = "#define " + MacroName;
220 std::string::size_type MacroDefLen = MacroDefStart.size();
221 std::vector<std::string>::iterator ConflictPos
222 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
223 MacroDefStart);
224 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
225 if (!startsWith(*ConflictPos, MacroDefStart)) {
226 // Different macro; we're done.
227 ConflictPos = CmdLineLines.end();
228 break;
229 }
230
231 assert(ConflictPos->size() > MacroDefLen &&
232 "Invalid #define in predefines buffer?");
233 if ((*ConflictPos)[MacroDefLen] != ' ' &&
234 (*ConflictPos)[MacroDefLen] != '(')
235 continue; // Longer macro name; keep trying.
236
237 // We found a conflicting macro definition.
238 break;
239 }
240
241 if (ConflictPos != CmdLineLines.end()) {
242 Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
243 << MacroName;
244
245 // Show the definition of this macro within the PCH file.
246 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
247 unsigned Offset = MissingDef - PCHPredef;
248 SourceLocation PCHMissingLoc
249 = SourceMgr.getLocForStartOfFile(PCHBufferID)
250 .getFileLocWithOffset(Offset);
251 Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
252 << MacroName;
253
254 ConflictingDefines = true;
255 continue;
256 }
257
258 // If the macro doesn't conflict, then we'll just pick up the
259 // macro definition from the PCH file. Warn the user that they
260 // made a mistake.
261 if (ConflictingDefines)
262 continue; // Don't complain if there are already conflicting defs
263
264 if (!MissingDefines) {
265 Reader.Diag(diag::warn_cmdline_missing_macro_defs);
266 MissingDefines = true;
267 }
268
269 // Show the definition of this macro within the PCH file.
270 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
271 unsigned Offset = MissingDef - PCHPredef;
272 SourceLocation PCHMissingLoc
273 = SourceMgr.getLocForStartOfFile(PCHBufferID)
274 .getFileLocWithOffset(Offset);
275 Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
276 }
277
278 if (ConflictingDefines)
279 return true;
280
281 // Determine what predefines were introduced based on command-line
282 // parameters that were not present when building the PCH
283 // file. Extra #defines are okay, so long as the identifiers being
284 // defined were not used within the precompiled header.
285 std::vector<std::string> ExtraPredefines;
286 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
287 PCHLines.begin(), PCHLines.end(),
288 std::back_inserter(ExtraPredefines));
289 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
290 const std::string &Extra = ExtraPredefines[I];
291 if (!startsWith(Extra, "#define ") != 0) {
292 Reader.Diag(diag::warn_pch_compiler_options_mismatch);
293 return true;
294 }
295
296 // This is an extra macro definition. Determine the name of the
297 // macro we're defining.
298 std::string::size_type StartOfMacroName = strlen("#define ");
299 std::string::size_type EndOfMacroName
300 = Extra.find_first_of("( \n\r", StartOfMacroName);
301 assert(EndOfMacroName != std::string::npos &&
302 "Couldn't find the end of the macro name");
303 std::string MacroName = Extra.substr(StartOfMacroName,
304 EndOfMacroName - StartOfMacroName);
305
306 // Check whether this name was used somewhere in the PCH file. If
307 // so, defining it as a macro could change behavior, so we reject
308 // the PCH file.
309 if (IdentifierInfo *II = Reader.get(MacroName.c_str(),
310 MacroName.c_str() + MacroName.size())) {
311 Reader.Diag(diag::warn_macro_name_used_in_pch)
312 << II;
313 return true;
314 }
315
316 // Add this definition to the suggested predefines buffer.
317 SuggestedPredefines += Extra;
318 SuggestedPredefines += '\n';
319 }
320
321 // If we get here, it's because the predefines buffer had compatible
322 // contents. Accept the PCH file.
323 return false;
324}
325
326void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
327 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
328}
329
330void PCHValidator::ReadCounter(unsigned Value) {
331 PP.setCounterValue(Value);
332}
333
334
335
336//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +0000337// PCH reader implementation
338//===----------------------------------------------------------------------===//
339
Douglas Gregore650c8c2009-07-07 00:12:59 +0000340PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context,
341 const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000342 : Listener(new PCHValidator(PP, *this)), SourceMgr(PP.getSourceManager()),
343 FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
344 SemaObj(0), PP(&PP), Context(Context), Consumer(0),
345 IdentifierTableData(0), IdentifierLookupTable(0),
346 IdentifierOffsets(0),
347 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
348 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000349 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
Douglas Gregor2e222532009-07-02 17:08:52 +0000350 NumStatHits(0), NumStatMisses(0),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000351 NumSLocEntriesRead(0), NumStatementsRead(0),
352 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000353 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
354 CurrentlyLoadingTypeOrDecl(0) {
355 RelocatablePCH = false;
356}
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000357
358PCHReader::PCHReader(SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregore650c8c2009-07-07 00:12:59 +0000359 Diagnostic &Diags, const char *isysroot)
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000360 : SourceMgr(SourceMgr), FileMgr(FileMgr), Diags(Diags),
Argyrios Kyrtzidis57102112009-06-19 07:55:35 +0000361 SemaObj(0), PP(0), Context(0), Consumer(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +0000362 IdentifierTableData(0), IdentifierLookupTable(0),
363 IdentifierOffsets(0),
364 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
365 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000366 TotalNumSelectors(0), Comments(0), NumComments(0), isysroot(isysroot),
367 NumStatHits(0), NumStatMisses(0),
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000368 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000369 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Douglas Gregord89275b2009-07-06 18:54:52 +0000370 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0),
Douglas Gregore650c8c2009-07-07 00:12:59 +0000371 CurrentlyLoadingTypeOrDecl(0) {
372 RelocatablePCH = false;
373}
Chris Lattner4c6f9522009-04-27 05:14:47 +0000374
375PCHReader::~PCHReader() {}
376
Chris Lattnerda930612009-04-27 05:58:23 +0000377Expr *PCHReader::ReadDeclExpr() {
378 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
379}
380
381Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +0000382 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +0000383}
384
385
Douglas Gregor668c1a42009-04-21 22:25:48 +0000386namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000387class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
388 PCHReader &Reader;
389
390public:
391 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
392
393 typedef Selector external_key_type;
394 typedef external_key_type internal_key_type;
395
396 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
397
398 static bool EqualKey(const internal_key_type& a,
399 const internal_key_type& b) {
400 return a == b;
401 }
402
403 static unsigned ComputeHash(Selector Sel) {
404 unsigned N = Sel.getNumArgs();
405 if (N == 0)
406 ++N;
407 unsigned R = 5381;
408 for (unsigned I = 0; I != N; ++I)
409 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
410 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
411 return R;
412 }
413
414 // This hopefully will just get inlined and removed by the optimizer.
415 static const internal_key_type&
416 GetInternalKey(const external_key_type& x) { return x; }
417
418 static std::pair<unsigned, unsigned>
419 ReadKeyDataLength(const unsigned char*& d) {
420 using namespace clang::io;
421 unsigned KeyLen = ReadUnalignedLE16(d);
422 unsigned DataLen = ReadUnalignedLE16(d);
423 return std::make_pair(KeyLen, DataLen);
424 }
425
Douglas Gregor83941df2009-04-25 17:48:32 +0000426 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000427 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000428 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000429 unsigned N = ReadUnalignedLE16(d);
430 IdentifierInfo *FirstII
431 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
432 if (N == 0)
433 return SelTable.getNullarySelector(FirstII);
434 else if (N == 1)
435 return SelTable.getUnarySelector(FirstII);
436
437 llvm::SmallVector<IdentifierInfo *, 16> Args;
438 Args.push_back(FirstII);
439 for (unsigned I = 1; I != N; ++I)
440 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
441
Douglas Gregor75fdb232009-05-22 22:45:36 +0000442 return SelTable.getSelector(N, Args.data());
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000443 }
444
445 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
446 using namespace clang::io;
447 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
448 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
449
450 data_type Result;
451
452 // Load instance methods
453 ObjCMethodList *Prev = 0;
454 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
455 ObjCMethodDecl *Method
456 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
457 if (!Result.first.Method) {
458 // This is the first method, which is the easy case.
459 Result.first.Method = Method;
460 Prev = &Result.first;
461 continue;
462 }
463
464 Prev->Next = new ObjCMethodList(Method, 0);
465 Prev = Prev->Next;
466 }
467
468 // Load factory methods
469 Prev = 0;
470 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
471 ObjCMethodDecl *Method
472 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
473 if (!Result.second.Method) {
474 // This is the first method, which is the easy case.
475 Result.second.Method = Method;
476 Prev = &Result.second;
477 continue;
478 }
479
480 Prev->Next = new ObjCMethodList(Method, 0);
481 Prev = Prev->Next;
482 }
483
484 return Result;
485 }
486};
487
488} // end anonymous namespace
489
490/// \brief The on-disk hash table used for the global method pool.
491typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
492 PCHMethodPoolLookupTable;
493
494namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000495class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
496 PCHReader &Reader;
497
498 // If we know the IdentifierInfo in advance, it is here and we will
499 // not build a new one. Used when deserializing information about an
500 // identifier that was constructed before the PCH file was read.
501 IdentifierInfo *KnownII;
502
503public:
504 typedef IdentifierInfo * data_type;
505
506 typedef const std::pair<const char*, unsigned> external_key_type;
507
508 typedef external_key_type internal_key_type;
509
510 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
511 : Reader(Reader), KnownII(II) { }
512
513 static bool EqualKey(const internal_key_type& a,
514 const internal_key_type& b) {
515 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
516 : false;
517 }
518
519 static unsigned ComputeHash(const internal_key_type& a) {
520 return BernsteinHash(a.first, a.second);
521 }
522
523 // This hopefully will just get inlined and removed by the optimizer.
524 static const internal_key_type&
525 GetInternalKey(const external_key_type& x) { return x; }
526
527 static std::pair<unsigned, unsigned>
528 ReadKeyDataLength(const unsigned char*& d) {
529 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000530 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000531 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000532 return std::make_pair(KeyLen, DataLen);
533 }
534
535 static std::pair<const char*, unsigned>
536 ReadKey(const unsigned char* d, unsigned n) {
537 assert(n >= 2 && d[n-1] == '\0');
538 return std::make_pair((const char*) d, n-1);
539 }
540
541 IdentifierInfo *ReadData(const internal_key_type& k,
542 const unsigned char* d,
543 unsigned DataLen) {
544 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000545 pch::IdentID ID = ReadUnalignedLE32(d);
546 bool IsInteresting = ID & 0x01;
547
548 // Wipe out the "is interesting" bit.
549 ID = ID >> 1;
550
551 if (!IsInteresting) {
552 // For unintersting identifiers, just build the IdentifierInfo
553 // and associate it with the persistent ID.
554 IdentifierInfo *II = KnownII;
555 if (!II)
556 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
557 k.first, k.first + k.second);
558 Reader.SetIdentifierInfo(ID, II);
559 return II;
560 }
561
Douglas Gregor5998da52009-04-28 21:32:13 +0000562 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000563 bool CPlusPlusOperatorKeyword = Bits & 0x01;
564 Bits >>= 1;
565 bool Poisoned = Bits & 0x01;
566 Bits >>= 1;
567 bool ExtensionToken = Bits & 0x01;
568 Bits >>= 1;
569 bool hasMacroDefinition = Bits & 0x01;
570 Bits >>= 1;
571 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
572 Bits >>= 10;
Douglas Gregora92193e2009-04-28 21:18:29 +0000573
Douglas Gregor2deaea32009-04-22 18:49:13 +0000574 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000575 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000576
577 // Build the IdentifierInfo itself and link the identifier ID with
578 // the new IdentifierInfo.
579 IdentifierInfo *II = KnownII;
580 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000581 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
582 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000583 Reader.SetIdentifierInfo(ID, II);
584
Douglas Gregor2deaea32009-04-22 18:49:13 +0000585 // Set or check the various bits in the IdentifierInfo structure.
586 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000587 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
588 assert(II->isExtensionToken() == ExtensionToken &&
589 "Incorrect extension token flag");
590 (void)ExtensionToken;
591 II->setIsPoisoned(Poisoned);
592 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
593 "Incorrect C++ operator keyword flag");
594 (void)CPlusPlusOperatorKeyword;
595
Douglas Gregor37e26842009-04-21 23:56:24 +0000596 // If this identifier is a macro, deserialize the macro
597 // definition.
598 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000599 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000600 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000601 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000602 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000603
604 // Read all of the declarations visible at global scope with this
605 // name.
Chris Lattner6bf690f2009-04-27 22:17:41 +0000606 if (Reader.getContext() == 0) return II;
Douglas Gregord89275b2009-07-06 18:54:52 +0000607 if (DataLen > 0) {
608 llvm::SmallVector<uint32_t, 4> DeclIDs;
609 for (; DataLen > 0; DataLen -= 4)
610 DeclIDs.push_back(ReadUnalignedLE32(d));
611 Reader.SetGloballyVisibleDecls(II, DeclIDs);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000612 }
Douglas Gregord89275b2009-07-06 18:54:52 +0000613
Douglas Gregor668c1a42009-04-21 22:25:48 +0000614 return II;
615 }
616};
617
618} // end anonymous namespace
619
620/// \brief The on-disk hash table used to contain information about
621/// all of the identifiers in the program.
622typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
623 PCHIdentifierLookupTable;
624
Douglas Gregora02b1472009-04-28 21:53:25 +0000625bool PCHReader::Error(const char *Msg) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000626 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
627 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000628 return true;
629}
630
Douglas Gregore1d918e2009-04-10 23:10:45 +0000631/// \brief Check the contents of the predefines buffer against the
632/// contents of the predefines buffer used to build the PCH file.
633///
634/// The contents of the two predefines buffers should be the same. If
635/// not, then some command-line option changed the preprocessor state
636/// and we must reject the PCH file.
637///
638/// \param PCHPredef The start of the predefines buffer in the PCH
639/// file.
640///
641/// \param PCHPredefLen The length of the predefines buffer in the PCH
642/// file.
643///
644/// \param PCHBufferID The FileID for the PCH predefines buffer.
645///
646/// \returns true if there was a mismatch (in which case the PCH file
647/// should be ignored), or false otherwise.
648bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
649 unsigned PCHPredefLen,
650 FileID PCHBufferID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000651 if (Listener)
652 return Listener->ReadPredefinesBuffer(PCHPredef, PCHPredefLen, PCHBufferID,
653 SuggestedPredefines);
Douglas Gregore721f952009-04-28 18:58:38 +0000654 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000655}
656
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000657//===----------------------------------------------------------------------===//
658// Source Manager Deserialization
659//===----------------------------------------------------------------------===//
660
Douglas Gregorbd945002009-04-13 16:31:14 +0000661/// \brief Read the line table in the source manager block.
662/// \returns true if ther was an error.
Douglas Gregore650c8c2009-07-07 00:12:59 +0000663bool PCHReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000664 unsigned Idx = 0;
665 LineTableInfo &LineTable = SourceMgr.getLineTable();
666
667 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000668 std::map<int, int> FileIDs;
669 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000670 // Extract the file name
671 unsigned FilenameLen = Record[Idx++];
672 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
673 Idx += FilenameLen;
Douglas Gregore650c8c2009-07-07 00:12:59 +0000674 MaybeAddSystemRootToFilename(Filename);
Douglas Gregorff0a9872009-04-13 17:12:42 +0000675 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
676 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000677 }
678
679 // Parse the line entries
680 std::vector<LineEntry> Entries;
681 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000682 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000683
684 // Extract the line entries
685 unsigned NumEntries = Record[Idx++];
686 Entries.clear();
687 Entries.reserve(NumEntries);
688 for (unsigned I = 0; I != NumEntries; ++I) {
689 unsigned FileOffset = Record[Idx++];
690 unsigned LineNo = Record[Idx++];
691 int FilenameID = Record[Idx++];
692 SrcMgr::CharacteristicKind FileKind
693 = (SrcMgr::CharacteristicKind)Record[Idx++];
694 unsigned IncludeOffset = Record[Idx++];
695 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
696 FileKind, IncludeOffset));
697 }
698 LineTable.AddEntry(FID, Entries);
699 }
700
701 return false;
702}
703
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000704namespace {
705
706class VISIBILITY_HIDDEN PCHStatData {
707public:
708 const bool hasStat;
709 const ino_t ino;
710 const dev_t dev;
711 const mode_t mode;
712 const time_t mtime;
713 const off_t size;
714
715 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
716 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
717
718 PCHStatData()
719 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
720};
721
722class VISIBILITY_HIDDEN PCHStatLookupTrait {
723 public:
724 typedef const char *external_key_type;
725 typedef const char *internal_key_type;
726
727 typedef PCHStatData data_type;
728
729 static unsigned ComputeHash(const char *path) {
730 return BernsteinHash(path);
731 }
732
733 static internal_key_type GetInternalKey(const char *path) { return path; }
734
735 static bool EqualKey(internal_key_type a, internal_key_type b) {
736 return strcmp(a, b) == 0;
737 }
738
739 static std::pair<unsigned, unsigned>
740 ReadKeyDataLength(const unsigned char*& d) {
741 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
742 unsigned DataLen = (unsigned) *d++;
743 return std::make_pair(KeyLen + 1, DataLen);
744 }
745
746 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
747 return (const char *)d;
748 }
749
750 static data_type ReadData(const internal_key_type, const unsigned char *d,
751 unsigned /*DataLen*/) {
752 using namespace clang::io;
753
754 if (*d++ == 1)
755 return data_type();
756
757 ino_t ino = (ino_t) ReadUnalignedLE32(d);
758 dev_t dev = (dev_t) ReadUnalignedLE32(d);
759 mode_t mode = (mode_t) ReadUnalignedLE16(d);
760 time_t mtime = (time_t) ReadUnalignedLE64(d);
761 off_t size = (off_t) ReadUnalignedLE64(d);
762 return data_type(ino, dev, mode, mtime, size);
763 }
764};
765
766/// \brief stat() cache for precompiled headers.
767///
768/// This cache is very similar to the stat cache used by pretokenized
769/// headers.
770class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
771 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
772 CacheTy *Cache;
773
774 unsigned &NumStatHits, &NumStatMisses;
775public:
776 PCHStatCache(const unsigned char *Buckets,
777 const unsigned char *Base,
778 unsigned &NumStatHits,
779 unsigned &NumStatMisses)
780 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
781 Cache = CacheTy::Create(Buckets, Base);
782 }
783
784 ~PCHStatCache() { delete Cache; }
785
786 int stat(const char *path, struct stat *buf) {
787 // Do the lookup for the file's data in the PCH file.
788 CacheTy::iterator I = Cache->find(path);
789
790 // If we don't get a hit in the PCH file just forward to 'stat'.
791 if (I == Cache->end()) {
792 ++NumStatMisses;
793 return ::stat(path, buf);
794 }
795
796 ++NumStatHits;
797 PCHStatData Data = *I;
798
799 if (!Data.hasStat)
800 return 1;
801
802 buf->st_ino = Data.ino;
803 buf->st_dev = Data.dev;
804 buf->st_mtime = Data.mtime;
805 buf->st_mode = Data.mode;
806 buf->st_size = Data.size;
807 return 0;
808 }
809};
810} // end anonymous namespace
811
812
Douglas Gregor14f79002009-04-10 03:52:48 +0000813/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000814PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000815 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000816
817 // Set the source-location entry cursor to the current position in
818 // the stream. This cursor will be used to read the contents of the
819 // source manager block initially, and then lazily read
820 // source-location entries as needed.
821 SLocEntryCursor = Stream;
822
823 // The stream itself is going to skip over the source manager block.
824 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000825 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000826 return Failure;
827 }
828
829 // Enter the source manager block.
830 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000831 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000832 return Failure;
833 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000834
Douglas Gregor14f79002009-04-10 03:52:48 +0000835 RecordData Record;
836 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000837 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000838 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000839 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000840 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000841 return Failure;
842 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000843 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000844 }
845
846 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
847 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000848 SLocEntryCursor.ReadSubBlockID();
849 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000850 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000851 return Failure;
852 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000853 continue;
854 }
855
856 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000857 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000858 continue;
859 }
860
861 // Read a record.
862 const char *BlobStart;
863 unsigned BlobLen;
864 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000865 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000866 default: // Default behavior: ignore.
867 break;
868
Chris Lattner2c78b872009-04-14 23:22:57 +0000869 case pch::SM_LINE_TABLE:
Douglas Gregore650c8c2009-07-07 00:12:59 +0000870 if (ParseLineTable(Record))
Douglas Gregorbd945002009-04-13 16:31:14 +0000871 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000872 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000873
874 case pch::SM_HEADER_FILE_INFO: {
875 HeaderFileInfo HFI;
876 HFI.isImport = Record[0];
877 HFI.DirInfo = Record[1];
878 HFI.NumIncludes = Record[2];
879 HFI.ControllingMacroID = Record[3];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +0000880 if (Listener)
881 Listener->ReadHeaderFileInfo(HFI);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000882 break;
883 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000884
885 case pch::SM_SLOC_FILE_ENTRY:
886 case pch::SM_SLOC_BUFFER_ENTRY:
887 case pch::SM_SLOC_INSTANTIATION_ENTRY:
888 // Once we hit one of the source location entries, we're done.
889 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000890 }
891 }
892}
893
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000894/// \brief Read in the source location entry with the given ID.
895PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
896 if (ID == 0)
897 return Success;
898
899 if (ID > TotalNumSLocEntries) {
900 Error("source location entry ID out-of-range for PCH file");
901 return Failure;
902 }
903
904 ++NumSLocEntriesRead;
905 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
906 unsigned Code = SLocEntryCursor.ReadCode();
907 if (Code == llvm::bitc::END_BLOCK ||
908 Code == llvm::bitc::ENTER_SUBBLOCK ||
909 Code == llvm::bitc::DEFINE_ABBREV) {
910 Error("incorrectly-formatted source location entry in PCH file");
911 return Failure;
912 }
913
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000914 RecordData Record;
915 const char *BlobStart;
916 unsigned BlobLen;
917 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
918 default:
919 Error("incorrectly-formatted source location entry in PCH file");
920 return Failure;
921
922 case pch::SM_SLOC_FILE_ENTRY: {
Douglas Gregore650c8c2009-07-07 00:12:59 +0000923 std::string Filename(BlobStart, BlobStart + BlobLen);
924 MaybeAddSystemRootToFilename(Filename);
925 const FileEntry *File = FileMgr.getFile(Filename);
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000926 if (File == 0) {
927 std::string ErrorStr = "could not find file '";
Douglas Gregore650c8c2009-07-07 00:12:59 +0000928 ErrorStr += Filename;
Chris Lattnerd3555ae2009-06-15 04:35:16 +0000929 ErrorStr += "' referenced by PCH file";
930 Error(ErrorStr.c_str());
931 return Failure;
932 }
933
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000934 FileID FID = SourceMgr.createFileID(File,
935 SourceLocation::getFromRawEncoding(Record[1]),
936 (SrcMgr::CharacteristicKind)Record[2],
937 ID, Record[0]);
938 if (Record[3])
939 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
940 .setHasLineDirectives();
941
942 break;
943 }
944
945 case pch::SM_SLOC_BUFFER_ENTRY: {
946 const char *Name = BlobStart;
947 unsigned Offset = Record[0];
948 unsigned Code = SLocEntryCursor.ReadCode();
949 Record.clear();
950 unsigned RecCode
951 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
952 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
953 (void)RecCode;
954 llvm::MemoryBuffer *Buffer
955 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
956 BlobStart + BlobLen - 1,
957 Name);
958 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
959
Douglas Gregor92b059e2009-04-28 20:33:11 +0000960 if (strcmp(Name, "<built-in>") == 0) {
961 PCHPredefinesBufferID = BufferID;
962 PCHPredefines = BlobStart;
963 PCHPredefinesLen = BlobLen - 1;
964 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000965
966 break;
967 }
968
969 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
970 SourceLocation SpellingLoc
971 = SourceLocation::getFromRawEncoding(Record[1]);
972 SourceMgr.createInstantiationLoc(SpellingLoc,
973 SourceLocation::getFromRawEncoding(Record[2]),
974 SourceLocation::getFromRawEncoding(Record[3]),
975 Record[4],
976 ID,
977 Record[0]);
978 break;
979 }
980 }
981
982 return Success;
983}
984
Chris Lattner6367f6d2009-04-27 01:05:14 +0000985/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
986/// specified cursor. Read the abbreviations that are at the top of the block
987/// and then leave the cursor pointing into the block.
988bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
989 unsigned BlockID) {
990 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000991 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000992 return Failure;
993 }
994
Chris Lattner6367f6d2009-04-27 01:05:14 +0000995 while (true) {
996 unsigned Code = Cursor.ReadCode();
997
998 // We expect all abbrevs to be at the start of the block.
999 if (Code != llvm::bitc::DEFINE_ABBREV)
1000 return false;
1001 Cursor.ReadAbbrevRecord();
1002 }
1003}
1004
Douglas Gregor37e26842009-04-21 23:56:24 +00001005void PCHReader::ReadMacroRecord(uint64_t Offset) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001006 assert(PP && "Forgot to set Preprocessor ?");
1007
Douglas Gregor37e26842009-04-21 23:56:24 +00001008 // Keep track of where we are in the stream, then jump back there
1009 // after reading this macro.
1010 SavedStreamPosition SavedPosition(Stream);
1011
1012 Stream.JumpToBit(Offset);
1013 RecordData Record;
1014 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1015 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +00001016
Douglas Gregor37e26842009-04-21 23:56:24 +00001017 while (true) {
1018 unsigned Code = Stream.ReadCode();
1019 switch (Code) {
1020 case llvm::bitc::END_BLOCK:
1021 return;
1022
1023 case llvm::bitc::ENTER_SUBBLOCK:
1024 // No known subblocks, always skip them.
1025 Stream.ReadSubBlockID();
1026 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001027 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001028 return;
1029 }
1030 continue;
1031
1032 case llvm::bitc::DEFINE_ABBREV:
1033 Stream.ReadAbbrevRecord();
1034 continue;
1035 default: break;
1036 }
1037
1038 // Read a record.
1039 Record.clear();
1040 pch::PreprocessorRecordTypes RecType =
1041 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1042 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +00001043 case pch::PP_MACRO_OBJECT_LIKE:
1044 case pch::PP_MACRO_FUNCTION_LIKE: {
1045 // If we already have a macro, that means that we've hit the end
1046 // of the definition of the macro we were looking for. We're
1047 // done.
1048 if (Macro)
1049 return;
1050
1051 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1052 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001053 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +00001054 return;
1055 }
1056 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1057 bool isUsed = Record[2];
1058
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001059 MacroInfo *MI = PP->AllocateMacroInfo(Loc);
Douglas Gregor37e26842009-04-21 23:56:24 +00001060 MI->setIsUsed(isUsed);
1061
1062 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
1063 // Decode function-like macro info.
1064 bool isC99VarArgs = Record[3];
1065 bool isGNUVarArgs = Record[4];
1066 MacroArgs.clear();
1067 unsigned NumArgs = Record[5];
1068 for (unsigned i = 0; i != NumArgs; ++i)
1069 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1070
1071 // Install function-like macro info.
1072 MI->setIsFunctionLike();
1073 if (isC99VarArgs) MI->setIsC99Varargs();
1074 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor75fdb232009-05-22 22:45:36 +00001075 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001076 PP->getPreprocessorAllocator());
Douglas Gregor37e26842009-04-21 23:56:24 +00001077 }
1078
1079 // Finally, install the macro.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001080 PP->setMacroInfo(II, MI);
Douglas Gregor37e26842009-04-21 23:56:24 +00001081
1082 // Remember that we saw this macro last so that we add the tokens that
1083 // form its body to it.
1084 Macro = MI;
1085 ++NumMacrosRead;
1086 break;
1087 }
1088
1089 case pch::PP_TOKEN: {
1090 // If we see a TOKEN before a PP_MACRO_*, then the file is
1091 // erroneous, just pretend we didn't see this.
1092 if (Macro == 0) break;
1093
1094 Token Tok;
1095 Tok.startToken();
1096 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1097 Tok.setLength(Record[1]);
1098 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1099 Tok.setIdentifierInfo(II);
1100 Tok.setKind((tok::TokenKind)Record[3]);
1101 Tok.setFlag((Token::TokenFlags)Record[4]);
1102 Macro->AddTokenToBody(Tok);
1103 break;
1104 }
Steve Naroff83d63c72009-04-24 20:03:17 +00001105 }
Douglas Gregor37e26842009-04-21 23:56:24 +00001106 }
1107}
1108
Douglas Gregore650c8c2009-07-07 00:12:59 +00001109/// \brief If we are loading a relocatable PCH file, and the filename is
1110/// not an absolute path, add the system root to the beginning of the file
1111/// name.
1112void PCHReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1113 // If this is not a relocatable PCH file, there's nothing to do.
1114 if (!RelocatablePCH)
1115 return;
1116
1117 if (Filename.empty() || Filename[0] == '/' || Filename[0] == '<')
1118 return;
1119
1120 std::string FIXME = Filename;
1121
1122 if (isysroot == 0) {
1123 // If no system root was given, default to '/'
1124 Filename.insert(Filename.begin(), '/');
1125 return;
1126 }
1127
1128 unsigned Length = strlen(isysroot);
1129 if (isysroot[Length - 1] != '/')
1130 Filename.insert(Filename.begin(), '/');
1131
1132 Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1133}
1134
Douglas Gregor668c1a42009-04-21 22:25:48 +00001135PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001136PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001137 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001138 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001139 return Failure;
1140 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001141
1142 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +00001143 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001144 while (!Stream.AtEndOfStream()) {
1145 unsigned Code = Stream.ReadCode();
1146 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001147 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001148 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001149 return Failure;
1150 }
Chris Lattner7356a312009-04-11 21:15:38 +00001151
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001152 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001153 }
1154
1155 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1156 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001157 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1158 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001159 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001160 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001161 return Failure;
1162 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001163 break;
1164
Chris Lattner6367f6d2009-04-27 01:05:14 +00001165 case pch::DECLS_BLOCK_ID:
1166 // We lazily load the decls block, but we want to set up the
1167 // DeclsCursor cursor to point into it. Clone our current bitcode
1168 // cursor to it, enter the block and read the abbrevs in that block.
1169 // With the main cursor, we just skip over it.
1170 DeclsCursor = Stream;
1171 if (Stream.SkipBlock() || // Skip with the main cursor.
1172 // Read the abbrevs.
1173 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001174 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001175 return Failure;
1176 }
1177 break;
1178
Chris Lattner7356a312009-04-11 21:15:38 +00001179 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001180 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001181 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001182 return Failure;
1183 }
1184 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001185
Douglas Gregor14f79002009-04-10 03:52:48 +00001186 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001187 switch (ReadSourceManagerBlock()) {
1188 case Success:
1189 break;
1190
1191 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001192 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001193 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001194
1195 case IgnorePCH:
1196 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001197 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001198 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001199 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001200 continue;
1201 }
1202
1203 if (Code == llvm::bitc::DEFINE_ABBREV) {
1204 Stream.ReadAbbrevRecord();
1205 continue;
1206 }
1207
1208 // Read and process a record.
1209 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001210 const char *BlobStart = 0;
1211 unsigned BlobLen = 0;
1212 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1213 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001214 default: // Default behavior: ignore.
1215 break;
1216
1217 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001218 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001219 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001220 return Failure;
1221 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001222 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001223 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001224 break;
1225
1226 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001227 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001228 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001229 return Failure;
1230 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001231 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001232 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001233 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001234
1235 case pch::LANGUAGE_OPTIONS:
1236 if (ParseLanguageOptions(Record))
1237 return IgnorePCH;
1238 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001239
Douglas Gregorab41e632009-04-27 22:23:34 +00001240 case pch::METADATA: {
1241 if (Record[0] != pch::VERSION_MAJOR) {
1242 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1243 : diag::warn_pch_version_too_new);
1244 return IgnorePCH;
1245 }
1246
Douglas Gregore650c8c2009-07-07 00:12:59 +00001247 RelocatablePCH = Record[4];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001248 if (Listener) {
1249 std::string TargetTriple(BlobStart, BlobLen);
1250 if (Listener->ReadTargetTriple(TargetTriple))
1251 return IgnorePCH;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001252 }
1253 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001254 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001255
1256 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001257 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001258 if (Record[0]) {
1259 IdentifierLookupTable
1260 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001261 (const unsigned char *)IdentifierTableData + Record[0],
1262 (const unsigned char *)IdentifierTableData,
1263 PCHIdentifierLookupTrait(*this));
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001264 if (PP)
1265 PP->getIdentifierTable().setExternalIdentifierLookup(this);
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001266 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001267 break;
1268
1269 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001270 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001271 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001272 return Failure;
1273 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001274 IdentifierOffsets = (const uint32_t *)BlobStart;
1275 IdentifiersLoaded.resize(Record[0]);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001276 if (PP)
1277 PP->getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001278 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001279
1280 case pch::EXTERNAL_DEFINITIONS:
1281 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001282 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001283 return Failure;
1284 }
1285 ExternalDefinitions.swap(Record);
1286 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001287
Douglas Gregorad1de002009-04-18 05:55:16 +00001288 case pch::SPECIAL_TYPES:
1289 SpecialTypes.swap(Record);
1290 break;
1291
Douglas Gregor3e1af842009-04-17 22:13:46 +00001292 case pch::STATISTICS:
1293 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001294 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001295 TotalLexicalDeclContexts = Record[2];
1296 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001297 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001298
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001299 case pch::TENTATIVE_DEFINITIONS:
1300 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001301 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001302 return Failure;
1303 }
1304 TentativeDefinitions.swap(Record);
1305 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001306
1307 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1308 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001309 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001310 return Failure;
1311 }
1312 LocallyScopedExternalDecls.swap(Record);
1313 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001314
Douglas Gregor83941df2009-04-25 17:48:32 +00001315 case pch::SELECTOR_OFFSETS:
1316 SelectorOffsets = (const uint32_t *)BlobStart;
1317 TotalNumSelectors = Record[0];
1318 SelectorsLoaded.resize(TotalNumSelectors);
1319 break;
1320
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001321 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001322 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1323 if (Record[0])
1324 MethodPoolLookupTable
1325 = PCHMethodPoolLookupTable::Create(
1326 MethodPoolLookupTableData + Record[0],
1327 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001328 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001329 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001330 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001331
1332 case pch::PP_COUNTER_VALUE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001333 if (!Record.empty() && Listener)
1334 Listener->ReadCounter(Record[0]);
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001335 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001336
1337 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001338 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001339 TotalNumSLocEntries = Record[0];
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001340 SourceMgr.PreallocateSLocEntries(this,
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001341 TotalNumSLocEntries,
1342 Record[1]);
1343 break;
1344
1345 case pch::SOURCE_LOCATION_PRELOADS:
1346 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1347 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1348 if (Result != Success)
1349 return Result;
1350 }
1351 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001352
1353 case pch::STAT_CACHE:
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001354 FileMgr.setStatCache(
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001355 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1356 (const unsigned char *)BlobStart,
1357 NumStatHits, NumStatMisses));
1358 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001359
1360 case pch::EXT_VECTOR_DECLS:
1361 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001362 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001363 return Failure;
1364 }
1365 ExtVectorDecls.swap(Record);
1366 break;
1367
Douglas Gregorb64c1932009-05-12 01:31:05 +00001368 case pch::ORIGINAL_FILE_NAME:
1369 OriginalFileName.assign(BlobStart, BlobLen);
Douglas Gregore650c8c2009-07-07 00:12:59 +00001370 MaybeAddSystemRootToFilename(OriginalFileName);
Douglas Gregorb64c1932009-05-12 01:31:05 +00001371 break;
Douglas Gregor2e222532009-07-02 17:08:52 +00001372
1373 case pch::COMMENT_RANGES:
1374 Comments = (SourceRange *)BlobStart;
1375 NumComments = BlobLen / sizeof(SourceRange);
1376 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001377 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001378 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001379 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001380 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001381}
1382
Douglas Gregore1d918e2009-04-10 23:10:45 +00001383PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001384 // Set the PCH file name.
1385 this->FileName = FileName;
1386
Douglas Gregor2cf26342009-04-09 22:27:44 +00001387 // Open the PCH file.
1388 std::string ErrStr;
1389 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001390 if (!Buffer) {
1391 Error(ErrStr.c_str());
1392 return IgnorePCH;
1393 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001394
1395 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001396 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1397 (const unsigned char *)Buffer->getBufferEnd());
1398 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001399
1400 // Sniff for the signature.
1401 if (Stream.Read(8) != 'C' ||
1402 Stream.Read(8) != 'P' ||
1403 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001404 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001405 Diag(diag::err_not_a_pch_file) << FileName;
1406 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001407 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001408
Douglas Gregor2cf26342009-04-09 22:27:44 +00001409 while (!Stream.AtEndOfStream()) {
1410 unsigned Code = Stream.ReadCode();
1411
Douglas Gregore1d918e2009-04-10 23:10:45 +00001412 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001413 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001414 return Failure;
1415 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001416
1417 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001418
Douglas Gregor2cf26342009-04-09 22:27:44 +00001419 // We only know the PCH subblock ID.
1420 switch (BlockID) {
1421 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001422 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001423 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001424 return Failure;
1425 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001426 break;
1427 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001428 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001429 case Success:
1430 break;
1431
1432 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001433 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001434
1435 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001436 // FIXME: We could consider reading through to the end of this
1437 // PCH block, skipping subblocks, to see if there are other
1438 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001439
1440 // Clear out any preallocated source location entries, so that
1441 // the source manager does not try to resolve them later.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001442 SourceMgr.ClearPreallocatedSLocEntries();
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001443
1444 // Remove the stat cache.
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001445 FileMgr.setStatCache(0);
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001446
Douglas Gregore1d918e2009-04-10 23:10:45 +00001447 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001448 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001449 break;
1450 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001451 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001452 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001453 return Failure;
1454 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001455 break;
1456 }
1457 }
Douglas Gregor92b059e2009-04-28 20:33:11 +00001458
1459 // Check the predefines buffer.
1460 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1461 PCHPredefinesBufferID))
1462 return IgnorePCH;
1463
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001464 if (PP) {
Zhongxing Xu08996212009-07-18 09:26:51 +00001465 // Initialization of keywords and pragmas occurs before the
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001466 // PCH file is read, so there may be some identifiers that were
1467 // loaded into the IdentifierTable before we intercepted the
1468 // creation of identifiers. Iterate through the list of known
1469 // identifiers and determine whether we have to establish
1470 // preprocessor definitions or top-level identifier declaration
1471 // chains for those identifiers.
1472 //
1473 // We copy the IdentifierInfo pointers to a small vector first,
1474 // since de-serializing declarations or macro definitions can add
1475 // new entries into the identifier table, invalidating the
1476 // iterators.
1477 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1478 for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
1479 IdEnd = PP->getIdentifierTable().end();
1480 Id != IdEnd; ++Id)
1481 Identifiers.push_back(Id->second);
1482 PCHIdentifierLookupTable *IdTable
1483 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1484 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1485 IdentifierInfo *II = Identifiers[I];
1486 // Look in the on-disk hash table for an entry for
1487 PCHIdentifierLookupTrait Info(*this, II);
1488 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1489 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1490 if (Pos == IdTable->end())
1491 continue;
1492
1493 // Dereferencing the iterator has the effect of populating the
1494 // IdentifierInfo node with the various declarations it needs.
1495 (void)*Pos;
1496 }
Douglas Gregor668c1a42009-04-21 22:25:48 +00001497 }
1498
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001499 if (Context)
1500 InitializeContext(*Context);
Douglas Gregor0b748912009-04-14 21:18:50 +00001501
Douglas Gregor668c1a42009-04-21 22:25:48 +00001502 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001503}
1504
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001505void PCHReader::InitializeContext(ASTContext &Ctx) {
1506 Context = &Ctx;
1507 assert(Context && "Passed null context!");
1508
1509 assert(PP && "Forgot to set Preprocessor ?");
1510 PP->getIdentifierTable().setExternalIdentifierLookup(this);
1511 PP->getHeaderSearchInfo().SetExternalLookup(this);
1512
1513 // Load the translation unit declaration
1514 ReadDeclRecord(DeclOffsets[0], 0);
1515
1516 // Load the special types.
1517 Context->setBuiltinVaListType(
1518 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1519 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1520 Context->setObjCIdType(GetType(Id));
1521 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1522 Context->setObjCSelType(GetType(Sel));
1523 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1524 Context->setObjCProtoType(GetType(Proto));
1525 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1526 Context->setObjCClassType(GetType(Class));
Steve Naroff14108da2009-07-10 23:34:53 +00001527
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001528 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1529 Context->setCFConstantStringType(GetType(String));
1530 if (unsigned FastEnum
1531 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1532 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001533 if (unsigned File = SpecialTypes[pch::SPECIAL_TYPE_FILE]) {
1534 QualType FileType = GetType(File);
1535 assert(!FileType.isNull() && "FILE type is NULL");
1536 if (const TypedefType *Typedef = FileType->getAsTypedefType())
1537 Context->setFILEDecl(Typedef->getDecl());
1538 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001539 const TagType *Tag = FileType->getAs<TagType>();
Douglas Gregorc29f77b2009-07-07 16:35:42 +00001540 assert(Tag && "Invalid FILE type in PCH file");
1541 Context->setFILEDecl(Tag->getDecl());
1542 }
1543 }
Mike Stump782fa302009-07-28 02:25:19 +00001544 if (unsigned Jmp_buf = SpecialTypes[pch::SPECIAL_TYPE_jmp_buf]) {
1545 QualType Jmp_bufType = GetType(Jmp_buf);
1546 assert(!Jmp_bufType.isNull() && "jmp_bug type is NULL");
1547 if (const TypedefType *Typedef = Jmp_bufType->getAsTypedefType())
1548 Context->setjmp_bufDecl(Typedef->getDecl());
1549 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001550 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001551 assert(Tag && "Invalid jmp_bug type in PCH file");
1552 Context->setjmp_bufDecl(Tag->getDecl());
1553 }
1554 }
1555 if (unsigned Sigjmp_buf = SpecialTypes[pch::SPECIAL_TYPE_sigjmp_buf]) {
1556 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
1557 assert(!Sigjmp_bufType.isNull() && "sigjmp_buf type is NULL");
1558 if (const TypedefType *Typedef = Sigjmp_bufType->getAsTypedefType())
1559 Context->setsigjmp_bufDecl(Typedef->getDecl());
1560 else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001561 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Mike Stump782fa302009-07-28 02:25:19 +00001562 assert(Tag && "Invalid sigjmp_buf type in PCH file");
1563 Context->setsigjmp_bufDecl(Tag->getDecl());
1564 }
1565 }
Douglas Gregord1571ac2009-08-21 00:27:50 +00001566 if (unsigned ObjCIdRedef
1567 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID_REDEFINITION])
1568 Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
1569 if (unsigned ObjCClassRedef
1570 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
1571 Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001572}
1573
Douglas Gregorb64c1932009-05-12 01:31:05 +00001574/// \brief Retrieve the name of the original source file name
1575/// directly from the PCH file, without actually loading the PCH
1576/// file.
1577std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1578 // Open the PCH file.
1579 std::string ErrStr;
1580 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1581 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1582 if (!Buffer) {
1583 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1584 return std::string();
1585 }
1586
1587 // Initialize the stream
1588 llvm::BitstreamReader StreamFile;
1589 llvm::BitstreamCursor Stream;
1590 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1591 (const unsigned char *)Buffer->getBufferEnd());
1592 Stream.init(StreamFile);
1593
1594 // Sniff for the signature.
1595 if (Stream.Read(8) != 'C' ||
1596 Stream.Read(8) != 'P' ||
1597 Stream.Read(8) != 'C' ||
1598 Stream.Read(8) != 'H') {
1599 fprintf(stderr,
1600 "error: '%s' does not appear to be a precompiled header file\n",
1601 PCHFileName.c_str());
1602 return std::string();
1603 }
1604
1605 RecordData Record;
1606 while (!Stream.AtEndOfStream()) {
1607 unsigned Code = Stream.ReadCode();
1608
1609 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1610 unsigned BlockID = Stream.ReadSubBlockID();
1611
1612 // We only know the PCH subblock ID.
1613 switch (BlockID) {
1614 case pch::PCH_BLOCK_ID:
1615 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1616 fprintf(stderr, "error: malformed block record in PCH file\n");
1617 return std::string();
1618 }
1619 break;
1620
1621 default:
1622 if (Stream.SkipBlock()) {
1623 fprintf(stderr, "error: malformed block record in PCH file\n");
1624 return std::string();
1625 }
1626 break;
1627 }
1628 continue;
1629 }
1630
1631 if (Code == llvm::bitc::END_BLOCK) {
1632 if (Stream.ReadBlockEnd()) {
1633 fprintf(stderr, "error: error at end of module block in PCH file\n");
1634 return std::string();
1635 }
1636 continue;
1637 }
1638
1639 if (Code == llvm::bitc::DEFINE_ABBREV) {
1640 Stream.ReadAbbrevRecord();
1641 continue;
1642 }
1643
1644 Record.clear();
1645 const char *BlobStart = 0;
1646 unsigned BlobLen = 0;
1647 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1648 == pch::ORIGINAL_FILE_NAME)
1649 return std::string(BlobStart, BlobLen);
1650 }
1651
1652 return std::string();
1653}
1654
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001655/// \brief Parse the record that corresponds to a LangOptions data
1656/// structure.
1657///
1658/// This routine compares the language options used to generate the
1659/// PCH file against the language options set for the current
1660/// compilation. For each option, we classify differences between the
1661/// two compiler states as either "benign" or "important". Benign
1662/// differences don't matter, and we accept them without complaint
1663/// (and without modifying the language options). Differences between
1664/// the states for important options cause the PCH file to be
1665/// unusable, so we emit a warning and return true to indicate that
1666/// there was an error.
1667///
1668/// \returns true if the PCH file is unacceptable, false otherwise.
1669bool PCHReader::ParseLanguageOptions(
1670 const llvm::SmallVectorImpl<uint64_t> &Record) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001671 if (Listener) {
1672 LangOptions LangOpts;
1673
1674 #define PARSE_LANGOPT(Option) \
1675 LangOpts.Option = Record[Idx]; \
1676 ++Idx
1677
1678 unsigned Idx = 0;
1679 PARSE_LANGOPT(Trigraphs);
1680 PARSE_LANGOPT(BCPLComment);
1681 PARSE_LANGOPT(DollarIdents);
1682 PARSE_LANGOPT(AsmPreprocessor);
1683 PARSE_LANGOPT(GNUMode);
1684 PARSE_LANGOPT(ImplicitInt);
1685 PARSE_LANGOPT(Digraphs);
1686 PARSE_LANGOPT(HexFloats);
1687 PARSE_LANGOPT(C99);
1688 PARSE_LANGOPT(Microsoft);
1689 PARSE_LANGOPT(CPlusPlus);
1690 PARSE_LANGOPT(CPlusPlus0x);
1691 PARSE_LANGOPT(CXXOperatorNames);
1692 PARSE_LANGOPT(ObjC1);
1693 PARSE_LANGOPT(ObjC2);
1694 PARSE_LANGOPT(ObjCNonFragileABI);
1695 PARSE_LANGOPT(PascalStrings);
1696 PARSE_LANGOPT(WritableStrings);
1697 PARSE_LANGOPT(LaxVectorConversions);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001698 PARSE_LANGOPT(AltiVec);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001699 PARSE_LANGOPT(Exceptions);
1700 PARSE_LANGOPT(NeXTRuntime);
1701 PARSE_LANGOPT(Freestanding);
1702 PARSE_LANGOPT(NoBuiltin);
1703 PARSE_LANGOPT(ThreadsafeStatics);
1704 PARSE_LANGOPT(Blocks);
1705 PARSE_LANGOPT(EmitAllDecls);
1706 PARSE_LANGOPT(MathErrno);
1707 PARSE_LANGOPT(OverflowChecking);
1708 PARSE_LANGOPT(HeinousExtensions);
1709 PARSE_LANGOPT(Optimize);
1710 PARSE_LANGOPT(OptimizeSize);
1711 PARSE_LANGOPT(Static);
1712 PARSE_LANGOPT(PICLevel);
1713 PARSE_LANGOPT(GNUInline);
1714 PARSE_LANGOPT(NoInline);
1715 PARSE_LANGOPT(AccessControl);
1716 PARSE_LANGOPT(CharIsSigned);
1717 LangOpts.setGCMode((LangOptions::GCMode)Record[Idx]);
1718 ++Idx;
1719 LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx]);
1720 ++Idx;
1721 PARSE_LANGOPT(InstantiationDepth);
Nate Begemanb9e7e632009-06-25 23:01:11 +00001722 PARSE_LANGOPT(OpenCL);
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001723 #undef PARSE_LANGOPT
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001724
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00001725 return Listener->ReadLanguageOptions(LangOpts);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001726 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001727
1728 return false;
1729}
1730
Douglas Gregor2e222532009-07-02 17:08:52 +00001731void PCHReader::ReadComments(std::vector<SourceRange> &Comments) {
1732 Comments.resize(NumComments);
1733 std::copy(this->Comments, this->Comments + NumComments,
1734 Comments.begin());
1735}
1736
Douglas Gregor2cf26342009-04-09 22:27:44 +00001737/// \brief Read and return the type at the given offset.
1738///
1739/// This routine actually reads the record corresponding to the type
1740/// at the given offset in the bitstream. It is a helper routine for
1741/// GetType, which deals with reading type IDs.
1742QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001743 // Keep track of where we are in the stream, then jump back there
1744 // after reading this type.
1745 SavedStreamPosition SavedPosition(Stream);
1746
Douglas Gregord89275b2009-07-06 18:54:52 +00001747 // Note that we are loading a type record.
1748 LoadingTypeOrDecl Loading(*this);
1749
Douglas Gregor2cf26342009-04-09 22:27:44 +00001750 Stream.JumpToBit(Offset);
1751 RecordData Record;
1752 unsigned Code = Stream.ReadCode();
1753 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001754 case pch::TYPE_EXT_QUAL: {
1755 assert(Record.size() == 3 &&
1756 "Incorrect encoding of extended qualifier type");
1757 QualType Base = GetType(Record[0]);
1758 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1759 unsigned AddressSpace = Record[2];
1760
1761 QualType T = Base;
1762 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001763 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001764 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001765 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001766 return T;
1767 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001768
Douglas Gregor2cf26342009-04-09 22:27:44 +00001769 case pch::TYPE_FIXED_WIDTH_INT: {
1770 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001771 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001772 }
1773
1774 case pch::TYPE_COMPLEX: {
1775 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1776 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001777 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001778 }
1779
1780 case pch::TYPE_POINTER: {
1781 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1782 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001783 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001784 }
1785
1786 case pch::TYPE_BLOCK_POINTER: {
1787 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1788 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001789 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001790 }
1791
1792 case pch::TYPE_LVALUE_REFERENCE: {
1793 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1794 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001795 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001796 }
1797
1798 case pch::TYPE_RVALUE_REFERENCE: {
1799 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1800 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001801 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001802 }
1803
1804 case pch::TYPE_MEMBER_POINTER: {
1805 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1806 QualType PointeeType = GetType(Record[0]);
1807 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001808 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001809 }
1810
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001811 case pch::TYPE_CONSTANT_ARRAY: {
1812 QualType ElementType = GetType(Record[0]);
1813 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1814 unsigned IndexTypeQuals = Record[2];
1815 unsigned Idx = 3;
1816 llvm::APInt Size = ReadAPInt(Record, Idx);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001817 return Context->getConstantArrayType(ElementType, Size,
1818 ASM, IndexTypeQuals);
1819 }
1820
1821 case pch::TYPE_CONSTANT_ARRAY_WITH_EXPR: {
1822 QualType ElementType = GetType(Record[0]);
1823 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1824 unsigned IndexTypeQuals = Record[2];
1825 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1826 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
1827 unsigned Idx = 5;
1828 llvm::APInt Size = ReadAPInt(Record, Idx);
1829 return Context->getConstantArrayWithExprType(ElementType,
1830 Size, ReadTypeExpr(),
1831 ASM, IndexTypeQuals,
1832 SourceRange(LBLoc, RBLoc));
1833 }
1834
1835 case pch::TYPE_CONSTANT_ARRAY_WITHOUT_EXPR: {
1836 QualType ElementType = GetType(Record[0]);
1837 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1838 unsigned IndexTypeQuals = Record[2];
1839 unsigned Idx = 3;
1840 llvm::APInt Size = ReadAPInt(Record, Idx);
1841 return Context->getConstantArrayWithoutExprType(ElementType, Size,
1842 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001843 }
1844
1845 case pch::TYPE_INCOMPLETE_ARRAY: {
1846 QualType ElementType = GetType(Record[0]);
1847 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1848 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001849 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001850 }
1851
1852 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001853 QualType ElementType = GetType(Record[0]);
1854 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1855 unsigned IndexTypeQuals = Record[2];
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001856 SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
1857 SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001858 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001859 ASM, IndexTypeQuals,
1860 SourceRange(LBLoc, RBLoc));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001861 }
1862
1863 case pch::TYPE_VECTOR: {
1864 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001865 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001866 return QualType();
1867 }
1868
1869 QualType ElementType = GetType(Record[0]);
1870 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001871 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001872 }
1873
1874 case pch::TYPE_EXT_VECTOR: {
1875 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001876 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001877 return QualType();
1878 }
1879
1880 QualType ElementType = GetType(Record[0]);
1881 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001882 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001883 }
1884
1885 case pch::TYPE_FUNCTION_NO_PROTO: {
1886 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001887 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001888 return QualType();
1889 }
1890 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001891 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001892 }
1893
1894 case pch::TYPE_FUNCTION_PROTO: {
1895 QualType ResultType = GetType(Record[0]);
1896 unsigned Idx = 1;
1897 unsigned NumParams = Record[Idx++];
1898 llvm::SmallVector<QualType, 16> ParamTypes;
1899 for (unsigned I = 0; I != NumParams; ++I)
1900 ParamTypes.push_back(GetType(Record[Idx++]));
1901 bool isVariadic = Record[Idx++];
1902 unsigned Quals = Record[Idx++];
Sebastian Redl465226e2009-05-27 22:11:52 +00001903 bool hasExceptionSpec = Record[Idx++];
1904 bool hasAnyExceptionSpec = Record[Idx++];
1905 unsigned NumExceptions = Record[Idx++];
1906 llvm::SmallVector<QualType, 2> Exceptions;
1907 for (unsigned I = 0; I != NumExceptions; ++I)
1908 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foadbeaaccd2009-05-21 09:52:38 +00001909 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl465226e2009-05-27 22:11:52 +00001910 isVariadic, Quals, hasExceptionSpec,
1911 hasAnyExceptionSpec, NumExceptions,
1912 Exceptions.data());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001913 }
1914
1915 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001916 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001917 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001918
1919 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001920 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001921
1922 case pch::TYPE_TYPEOF: {
1923 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001924 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001925 return QualType();
1926 }
1927 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001928 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001929 }
Anders Carlsson395b4752009-06-24 19:06:50 +00001930
1931 case pch::TYPE_DECLTYPE:
1932 return Context->getDecltypeType(ReadTypeExpr());
1933
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001934 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001935 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001936 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001937
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001938 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001939 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001940 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001941
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001942 case pch::TYPE_OBJC_INTERFACE: {
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001943 unsigned Idx = 0;
1944 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1945 unsigned NumProtos = Record[Idx++];
1946 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1947 for (unsigned I = 0; I != NumProtos; ++I)
1948 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001949 return Context->getObjCInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001950 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001951
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001952 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001953 unsigned Idx = 0;
Steve Naroff14108da2009-07-10 23:34:53 +00001954 QualType OIT = GetType(Record[Idx++]);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001955 unsigned NumProtos = Record[Idx++];
1956 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1957 for (unsigned I = 0; I != NumProtos; ++I)
1958 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroff14108da2009-07-10 23:34:53 +00001959 return Context->getObjCObjectPointerType(OIT, Protos.data(), NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001960 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001961 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001962 // Suppress a GCC warning
1963 return QualType();
1964}
1965
Douglas Gregor2cf26342009-04-09 22:27:44 +00001966
Douglas Gregor8038d512009-04-10 17:25:41 +00001967QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001968 unsigned Quals = ID & 0x07;
1969 unsigned Index = ID >> 3;
1970
1971 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1972 QualType T;
1973 switch ((pch::PredefinedTypeIDs)Index) {
1974 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001975 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1976 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001977
1978 case pch::PREDEF_TYPE_CHAR_U_ID:
1979 case pch::PREDEF_TYPE_CHAR_S_ID:
1980 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001981 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001982 break;
1983
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001984 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1985 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1986 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1987 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1988 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001989 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001990 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1991 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1992 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1993 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1994 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1995 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001996 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001997 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1998 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1999 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
2000 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
2001 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002002 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002003 case pch::PREDEF_TYPE_CHAR16_ID: T = Context->Char16Ty; break;
2004 case pch::PREDEF_TYPE_CHAR32_ID: T = Context->Char32Ty; break;
Steve Naroffde2e22d2009-07-15 18:40:39 +00002005 case pch::PREDEF_TYPE_OBJC_ID: T = Context->ObjCBuiltinIdTy; break;
2006 case pch::PREDEF_TYPE_OBJC_CLASS: T = Context->ObjCBuiltinClassTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002007 }
2008
2009 assert(!T.isNull() && "Unknown predefined type");
2010 return T.getQualifiedType(Quals);
2011 }
2012
2013 Index -= pch::NUM_PREDEF_TYPE_IDS;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002014 //assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002015 if (!TypesLoaded[Index])
2016 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00002017
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002018 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002019}
2020
Douglas Gregor8038d512009-04-10 17:25:41 +00002021Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002022 if (ID == 0)
2023 return 0;
2024
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002025 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002026 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002027 return 0;
2028 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002029
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002030 unsigned Index = ID - 1;
2031 if (!DeclsLoaded[Index])
2032 ReadDeclRecord(DeclOffsets[Index], Index);
2033
2034 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002035}
2036
Chris Lattner887e2b32009-04-27 05:46:25 +00002037/// \brief Resolve the offset of a statement into a statement.
2038///
2039/// This operation will read a new statement from the external
2040/// source each time it is called, and is meant to be used via a
2041/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
2042Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00002043 // Since we know tha this statement is part of a decl, make sure to use the
2044 // decl cursor to read it.
2045 DeclsCursor.JumpToBit(Offset);
2046 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00002047}
2048
Douglas Gregor2cf26342009-04-09 22:27:44 +00002049bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00002050 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002051 assert(DC->hasExternalLexicalStorage() &&
2052 "DeclContext has no lexical decls in storage");
2053 uint64_t Offset = DeclContextOffsets[DC].first;
2054 assert(Offset && "DeclContext has no lexical decls in storage");
2055
Douglas Gregor0b748912009-04-14 21:18:50 +00002056 // Keep track of where we are in the stream, then jump back there
2057 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002058 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002059
Douglas Gregor2cf26342009-04-09 22:27:44 +00002060 // Load the record containing all of the declarations lexically in
2061 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002062 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002063 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002064 unsigned Code = DeclsCursor.ReadCode();
2065 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002066 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002067 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
2068
2069 // Load all of the declaration IDs
2070 Decls.clear();
2071 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00002072 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002073 return false;
2074}
2075
2076bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002077 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00002078 assert(DC->hasExternalVisibleStorage() &&
2079 "DeclContext has no visible decls in storage");
2080 uint64_t Offset = DeclContextOffsets[DC].second;
2081 assert(Offset && "DeclContext has no visible decls in storage");
2082
Douglas Gregor0b748912009-04-14 21:18:50 +00002083 // Keep track of where we are in the stream, then jump back there
2084 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002085 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00002086
Douglas Gregor2cf26342009-04-09 22:27:44 +00002087 // Load the record containing all of the declarations visible in
2088 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002089 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00002090 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002091 unsigned Code = DeclsCursor.ReadCode();
2092 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00002093 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002094 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
2095 if (Record.size() == 0)
2096 return false;
2097
2098 Decls.clear();
2099
2100 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002101 while (Idx < Record.size()) {
2102 Decls.push_back(VisibleDeclaration());
2103 Decls.back().Name = ReadDeclarationName(Record, Idx);
2104
Douglas Gregor2cf26342009-04-09 22:27:44 +00002105 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00002106 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002107 LoadedDecls.reserve(Size);
2108 for (unsigned I = 0; I < Size; ++I)
2109 LoadedDecls.push_back(Record[Idx++]);
2110 }
2111
Douglas Gregor25123082009-04-22 22:34:57 +00002112 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00002113 return false;
2114}
2115
Douglas Gregorfdd01722009-04-14 00:24:19 +00002116void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00002117 this->Consumer = Consumer;
2118
Douglas Gregorfdd01722009-04-14 00:24:19 +00002119 if (!Consumer)
2120 return;
2121
2122 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
2123 Decl *D = GetDecl(ExternalDefinitions[I]);
2124 DeclGroupRef DG(D);
2125 Consumer->HandleTopLevelDecl(DG);
2126 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00002127
2128 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
2129 DeclGroupRef DG(InterestingDecls[I]);
2130 Consumer->HandleTopLevelDecl(DG);
2131 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00002132}
2133
Douglas Gregor2cf26342009-04-09 22:27:44 +00002134void PCHReader::PrintStats() {
2135 std::fprintf(stderr, "*** PCH Statistics:\n");
2136
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002137 unsigned NumTypesLoaded
2138 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
2139 (Type *)0);
2140 unsigned NumDeclsLoaded
2141 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
2142 (Decl *)0);
2143 unsigned NumIdentifiersLoaded
2144 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
2145 IdentifiersLoaded.end(),
2146 (IdentifierInfo *)0);
2147 unsigned NumSelectorsLoaded
2148 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
2149 SelectorsLoaded.end(),
2150 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00002151
Douglas Gregor4fed3f42009-04-27 18:38:38 +00002152 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
2153 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002154 if (TotalNumSLocEntries)
2155 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
2156 NumSLocEntriesRead, TotalNumSLocEntries,
2157 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002158 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002159 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002160 NumTypesLoaded, (unsigned)TypesLoaded.size(),
2161 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
2162 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002163 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00002164 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
2165 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002166 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00002167 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002168 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
2169 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00002170 if (TotalNumSelectors)
2171 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
2172 NumSelectorsLoaded, TotalNumSelectors,
2173 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
2174 if (TotalNumStatements)
2175 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
2176 NumStatementsRead, TotalNumStatements,
2177 ((float)NumStatementsRead/TotalNumStatements * 100));
2178 if (TotalNumMacros)
2179 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
2180 NumMacrosRead, TotalNumMacros,
2181 ((float)NumMacrosRead/TotalNumMacros * 100));
2182 if (TotalLexicalDeclContexts)
2183 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
2184 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
2185 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
2186 * 100));
2187 if (TotalVisibleDeclContexts)
2188 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
2189 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
2190 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
2191 * 100));
2192 if (TotalSelectorsInMethodPool) {
2193 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
2194 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
2195 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
2196 * 100));
2197 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
2198 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00002199 std::fprintf(stderr, "\n");
2200}
2201
Douglas Gregor668c1a42009-04-21 22:25:48 +00002202void PCHReader::InitializeSema(Sema &S) {
2203 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002204 S.ExternalSource = this;
2205
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002206 // Makes sure any declarations that were deserialized "too early"
2207 // still get added to the identifier's declaration chains.
2208 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
2209 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
2210 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00002211 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00002212 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00002213
2214 // If there were any tentative definitions, deserialize them and add
2215 // them to Sema's table of tentative definitions.
2216 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
2217 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
2218 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
2219 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00002220
2221 // If there were any locally-scoped external declarations,
2222 // deserialize them and add them to Sema's table of locally-scoped
2223 // external declarations.
2224 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2225 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2226 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2227 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00002228
2229 // If there were any ext_vector type declarations, deserialize them
2230 // and add them to Sema's vector of such declarations.
2231 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2232 SemaObj->ExtVectorDecls.push_back(
2233 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002234}
2235
2236IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2237 // Try to find this name within our on-disk hash table
2238 PCHIdentifierLookupTable *IdTable
2239 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2240 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2241 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2242 if (Pos == IdTable->end())
2243 return 0;
2244
2245 // Dereferencing the iterator has the effect of building the
2246 // IdentifierInfo node and populating it with the various
2247 // declarations it needs.
2248 return *Pos;
2249}
2250
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002251std::pair<ObjCMethodList, ObjCMethodList>
2252PCHReader::ReadMethodPool(Selector Sel) {
2253 if (!MethodPoolLookupTable)
2254 return std::pair<ObjCMethodList, ObjCMethodList>();
2255
2256 // Try to find this selector within our on-disk hash table.
2257 PCHMethodPoolLookupTable *PoolTable
2258 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2259 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002260 if (Pos == PoolTable->end()) {
2261 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002262 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002263 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002264
Douglas Gregor83941df2009-04-25 17:48:32 +00002265 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002266 return *Pos;
2267}
2268
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002269void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002270 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002271 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002272 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002273}
2274
Douglas Gregord89275b2009-07-06 18:54:52 +00002275/// \brief Set the globally-visible declarations associated with the given
2276/// identifier.
2277///
2278/// If the PCH reader is currently in a state where the given declaration IDs
2279/// cannot safely be resolved, they are queued until it is safe to resolve
2280/// them.
2281///
2282/// \param II an IdentifierInfo that refers to one or more globally-visible
2283/// declarations.
2284///
2285/// \param DeclIDs the set of declaration IDs with the name @p II that are
2286/// visible at global scope.
2287///
2288/// \param Nonrecursive should be true to indicate that the caller knows that
2289/// this call is non-recursive, and therefore the globally-visible declarations
2290/// will not be placed onto the pending queue.
2291void
2292PCHReader::SetGloballyVisibleDecls(IdentifierInfo *II,
2293 const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
2294 bool Nonrecursive) {
2295 if (CurrentlyLoadingTypeOrDecl && !Nonrecursive) {
2296 PendingIdentifierInfos.push_back(PendingIdentifierInfo());
2297 PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
2298 PII.II = II;
2299 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I)
2300 PII.DeclIDs.push_back(DeclIDs[I]);
2301 return;
2302 }
2303
2304 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
2305 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
2306 if (SemaObj) {
2307 // Introduce this declaration into the translation-unit scope
2308 // and add it to the declaration chain for this identifier, so
2309 // that (unqualified) name lookup will find it.
2310 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
2311 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
2312 } else {
2313 // Queue this declaration so that it will be added to the
2314 // translation unit scope and identifier's declaration chain
2315 // once a Sema object is known.
2316 PreloadedDecls.push_back(D);
2317 }
2318 }
2319}
2320
Chris Lattner7356a312009-04-11 21:15:38 +00002321IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002322 if (ID == 0)
2323 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00002324
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002325 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002326 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002327 return 0;
2328 }
Chris Lattner7356a312009-04-11 21:15:38 +00002329
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002330 assert(PP && "Forgot to set Preprocessor ?");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002331 if (!IdentifiersLoaded[ID - 1]) {
2332 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002333 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002334
Douglas Gregor02fc7512009-04-28 20:01:51 +00002335 // All of the strings in the PCH file are preceded by a 16-bit
2336 // length. Extract that 16-bit length to avoid having to execute
2337 // strlen().
2338 const char *StrLenPtr = Str - 2;
2339 unsigned StrLen = (((unsigned) StrLenPtr[0])
2340 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2341 IdentifiersLoaded[ID - 1]
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002342 = &PP->getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002343 }
Chris Lattner7356a312009-04-11 21:15:38 +00002344
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002345 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002346}
2347
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002348void PCHReader::ReadSLocEntry(unsigned ID) {
2349 ReadSLocEntryRecord(ID);
2350}
2351
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002352Selector PCHReader::DecodeSelector(unsigned ID) {
2353 if (ID == 0)
2354 return Selector();
2355
Douglas Gregora02b1472009-04-28 21:53:25 +00002356 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002357 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002358
2359 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002360 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002361 return Selector();
2362 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002363
2364 unsigned Index = ID - 1;
2365 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2366 // Load this selector from the selector table.
2367 // FIXME: endianness portability issues with SelectorOffsets table
2368 PCHMethodPoolLookupTrait Trait(*this);
2369 SelectorsLoaded[Index]
2370 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2371 }
2372
2373 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002374}
2375
Douglas Gregor2cf26342009-04-09 22:27:44 +00002376DeclarationName
2377PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2378 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2379 switch (Kind) {
2380 case DeclarationName::Identifier:
2381 return DeclarationName(GetIdentifierInfo(Record, Idx));
2382
2383 case DeclarationName::ObjCZeroArgSelector:
2384 case DeclarationName::ObjCOneArgSelector:
2385 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002386 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002387
2388 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002389 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002390 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002391
2392 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002393 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002394 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002395
2396 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002397 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor50d62d12009-08-05 05:36:45 +00002398 Context->getCanonicalType(GetType(Record[Idx++])));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002399
2400 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002401 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002402 (OverloadedOperatorKind)Record[Idx++]);
2403
2404 case DeclarationName::CXXUsingDirective:
2405 return DeclarationName::getUsingDirectiveName();
2406 }
2407
2408 // Required to silence GCC warning
2409 return DeclarationName();
2410}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002411
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002412/// \brief Read an integral value
2413llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2414 unsigned BitWidth = Record[Idx++];
2415 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2416 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2417 Idx += NumWords;
2418 return Result;
2419}
2420
2421/// \brief Read a signed integral value
2422llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2423 bool isUnsigned = Record[Idx++];
2424 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2425}
2426
Douglas Gregor17fc2232009-04-14 21:55:33 +00002427/// \brief Read a floating-point value
2428llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002429 return llvm::APFloat(ReadAPInt(Record, Idx));
2430}
2431
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002432// \brief Read a string
2433std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2434 unsigned Len = Record[Idx++];
Jay Foadbeaaccd2009-05-21 09:52:38 +00002435 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002436 Idx += Len;
2437 return Result;
2438}
2439
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002440DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002441 return Diag(SourceLocation(), DiagID);
2442}
2443
2444DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002445 return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002446}
Douglas Gregor025452f2009-04-17 00:04:06 +00002447
Douglas Gregor668c1a42009-04-21 22:25:48 +00002448/// \brief Retrieve the identifier table associated with the
2449/// preprocessor.
2450IdentifierTable &PCHReader::getIdentifierTable() {
Argyrios Kyrtzidis11e51102009-06-19 00:03:23 +00002451 assert(PP && "Forgot to set Preprocessor ?");
2452 return PP->getIdentifierTable();
Douglas Gregor668c1a42009-04-21 22:25:48 +00002453}
2454
Douglas Gregor025452f2009-04-17 00:04:06 +00002455/// \brief Record that the given ID maps to the given switch-case
2456/// statement.
2457void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2458 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2459 SwitchCaseStmts[ID] = SC;
2460}
2461
2462/// \brief Retrieve the switch-case statement with the given ID.
2463SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2464 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2465 return SwitchCaseStmts[ID];
2466}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002467
2468/// \brief Record that the given label statement has been
2469/// deserialized and has the given ID.
2470void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2471 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2472 "Deserialized label twice");
2473 LabelStmts[ID] = S;
2474
2475 // If we've already seen any goto statements that point to this
2476 // label, resolve them now.
2477 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2478 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2479 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2480 Goto->second->setLabel(S);
2481 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002482
2483 // If we've already seen any address-label statements that point to
2484 // this label, resolve them now.
2485 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2486 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2487 = UnresolvedAddrLabelExprs.equal_range(ID);
2488 for (AddrLabelIter AddrLabel = AddrLabels.first;
2489 AddrLabel != AddrLabels.second; ++AddrLabel)
2490 AddrLabel->second->setLabel(S);
2491 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002492}
2493
2494/// \brief Set the label of the given statement to the label
2495/// identified by ID.
2496///
2497/// Depending on the order in which the label and other statements
2498/// referencing that label occur, this operation may complete
2499/// immediately (updating the statement) or it may queue the
2500/// statement to be back-patched later.
2501void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2502 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2503 if (Label != LabelStmts.end()) {
2504 // We've already seen this label, so set the label of the goto and
2505 // we're done.
2506 S->setLabel(Label->second);
2507 } else {
2508 // We haven't seen this label yet, so add this goto to the set of
2509 // unresolved goto statements.
2510 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2511 }
2512}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002513
2514/// \brief Set the label of the given expression to the label
2515/// identified by ID.
2516///
2517/// Depending on the order in which the label and other statements
2518/// referencing that label occur, this operation may complete
2519/// immediately (updating the statement) or it may queue the
2520/// statement to be back-patched later.
2521void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2522 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2523 if (Label != LabelStmts.end()) {
2524 // We've already seen this label, so set the label of the
2525 // label-address expression and we're done.
2526 S->setLabel(Label->second);
2527 } else {
2528 // We haven't seen this label yet, so add this label-address
2529 // expression to the set of unresolved label-address expressions.
2530 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2531 }
2532}
Douglas Gregord89275b2009-07-06 18:54:52 +00002533
2534
2535PCHReader::LoadingTypeOrDecl::LoadingTypeOrDecl(PCHReader &Reader)
2536 : Reader(Reader), Parent(Reader.CurrentlyLoadingTypeOrDecl) {
2537 Reader.CurrentlyLoadingTypeOrDecl = this;
2538}
2539
2540PCHReader::LoadingTypeOrDecl::~LoadingTypeOrDecl() {
2541 if (!Parent) {
2542 // If any identifiers with corresponding top-level declarations have
2543 // been loaded, load those declarations now.
2544 while (!Reader.PendingIdentifierInfos.empty()) {
2545 Reader.SetGloballyVisibleDecls(Reader.PendingIdentifierInfos.front().II,
2546 Reader.PendingIdentifierInfos.front().DeclIDs,
2547 true);
2548 Reader.PendingIdentifierInfos.pop_front();
2549 }
2550 }
2551
2552 Reader.CurrentlyLoadingTypeOrDecl = Parent;
2553}