blob: 3ba1f80e4049af43be177adcb90435cfe3c739f3 [file] [log] [blame]
Douglas Gregorc34897d2009-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 Lattner09547942009-04-27 05:14:47 +000013
Douglas Gregorc34897d2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor179cfb12009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregorc713da92009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor631f6c62009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregorc713da92009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-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 Gregor32de6312009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregorc34897d2009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregor6cc5d192009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregorc34897d2009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Douglas Gregorc713da92009-04-21 22:25:48 +000039// PCH reader implementation
40//===----------------------------------------------------------------------===//
41
Chris Lattner270d29a2009-04-27 21:45:14 +000042PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context)
Chris Lattner09547942009-04-27 05:14:47 +000043 : SemaObj(0), PP(PP), Context(Context), Consumer(0),
44 IdentifierTableData(0), IdentifierLookupTable(0),
45 IdentifierOffsets(0),
46 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
47 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor6cc5d192009-04-27 18:38:38 +000048 TotalNumSelectors(0), NumStatHits(0), NumStatMisses(0),
49 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor32e231c2009-04-27 06:38:32 +000050 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Chris Lattner09547942009-04-27 05:14:47 +000051 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
52
53PCHReader::~PCHReader() {}
54
Chris Lattner3ef21962009-04-27 05:58:23 +000055Expr *PCHReader::ReadDeclExpr() {
56 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
57}
58
59Expr *PCHReader::ReadTypeExpr() {
Chris Lattner3282c392009-04-27 05:41:06 +000060 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner09547942009-04-27 05:14:47 +000061}
62
63
Douglas Gregorc713da92009-04-21 22:25:48 +000064namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +000065class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
66 PCHReader &Reader;
67
68public:
69 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
70
71 typedef Selector external_key_type;
72 typedef external_key_type internal_key_type;
73
74 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
75
76 static bool EqualKey(const internal_key_type& a,
77 const internal_key_type& b) {
78 return a == b;
79 }
80
81 static unsigned ComputeHash(Selector Sel) {
82 unsigned N = Sel.getNumArgs();
83 if (N == 0)
84 ++N;
85 unsigned R = 5381;
86 for (unsigned I = 0; I != N; ++I)
87 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
88 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
89 return R;
90 }
91
92 // This hopefully will just get inlined and removed by the optimizer.
93 static const internal_key_type&
94 GetInternalKey(const external_key_type& x) { return x; }
95
96 static std::pair<unsigned, unsigned>
97 ReadKeyDataLength(const unsigned char*& d) {
98 using namespace clang::io;
99 unsigned KeyLen = ReadUnalignedLE16(d);
100 unsigned DataLen = ReadUnalignedLE16(d);
101 return std::make_pair(KeyLen, DataLen);
102 }
103
Douglas Gregor2d711832009-04-25 17:48:32 +0000104 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000105 using namespace clang::io;
Chris Lattner270d29a2009-04-27 21:45:14 +0000106 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000107 unsigned N = ReadUnalignedLE16(d);
108 IdentifierInfo *FirstII
109 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
110 if (N == 0)
111 return SelTable.getNullarySelector(FirstII);
112 else if (N == 1)
113 return SelTable.getUnarySelector(FirstII);
114
115 llvm::SmallVector<IdentifierInfo *, 16> Args;
116 Args.push_back(FirstII);
117 for (unsigned I = 1; I != N; ++I)
118 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
119
Douglas Gregor4e284192009-05-22 22:45:36 +0000120 return SelTable.getSelector(N, Args.data());
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000121 }
122
123 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
124 using namespace clang::io;
125 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
126 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
127
128 data_type Result;
129
130 // Load instance methods
131 ObjCMethodList *Prev = 0;
132 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
133 ObjCMethodDecl *Method
134 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
135 if (!Result.first.Method) {
136 // This is the first method, which is the easy case.
137 Result.first.Method = Method;
138 Prev = &Result.first;
139 continue;
140 }
141
142 Prev->Next = new ObjCMethodList(Method, 0);
143 Prev = Prev->Next;
144 }
145
146 // Load factory methods
147 Prev = 0;
148 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
149 ObjCMethodDecl *Method
150 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
151 if (!Result.second.Method) {
152 // This is the first method, which is the easy case.
153 Result.second.Method = Method;
154 Prev = &Result.second;
155 continue;
156 }
157
158 Prev->Next = new ObjCMethodList(Method, 0);
159 Prev = Prev->Next;
160 }
161
162 return Result;
163 }
164};
165
166} // end anonymous namespace
167
168/// \brief The on-disk hash table used for the global method pool.
169typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
170 PCHMethodPoolLookupTable;
171
172namespace {
Douglas Gregorc713da92009-04-21 22:25:48 +0000173class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
174 PCHReader &Reader;
175
176 // If we know the IdentifierInfo in advance, it is here and we will
177 // not build a new one. Used when deserializing information about an
178 // identifier that was constructed before the PCH file was read.
179 IdentifierInfo *KnownII;
180
181public:
182 typedef IdentifierInfo * data_type;
183
184 typedef const std::pair<const char*, unsigned> external_key_type;
185
186 typedef external_key_type internal_key_type;
187
188 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
189 : Reader(Reader), KnownII(II) { }
190
191 static bool EqualKey(const internal_key_type& a,
192 const internal_key_type& b) {
193 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
194 : false;
195 }
196
197 static unsigned ComputeHash(const internal_key_type& a) {
198 return BernsteinHash(a.first, a.second);
199 }
200
201 // This hopefully will just get inlined and removed by the optimizer.
202 static const internal_key_type&
203 GetInternalKey(const external_key_type& x) { return x; }
204
205 static std::pair<unsigned, unsigned>
206 ReadKeyDataLength(const unsigned char*& d) {
207 using namespace clang::io;
Douglas Gregor4bb24882009-04-25 20:26:24 +0000208 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor85c4a872009-04-25 21:04:17 +0000209 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregorc713da92009-04-21 22:25:48 +0000210 return std::make_pair(KeyLen, DataLen);
211 }
212
213 static std::pair<const char*, unsigned>
214 ReadKey(const unsigned char* d, unsigned n) {
215 assert(n >= 2 && d[n-1] == '\0');
216 return std::make_pair((const char*) d, n-1);
217 }
218
219 IdentifierInfo *ReadData(const internal_key_type& k,
220 const unsigned char* d,
221 unsigned DataLen) {
222 using namespace clang::io;
Douglas Gregor2c09dad2009-04-28 21:18:29 +0000223 pch::IdentID ID = ReadUnalignedLE32(d);
224 bool IsInteresting = ID & 0x01;
225
226 // Wipe out the "is interesting" bit.
227 ID = ID >> 1;
228
229 if (!IsInteresting) {
230 // For unintersting identifiers, just build the IdentifierInfo
231 // and associate it with the persistent ID.
232 IdentifierInfo *II = KnownII;
233 if (!II)
234 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
235 k.first, k.first + k.second);
236 Reader.SetIdentifierInfo(ID, II);
237 return II;
238 }
239
Douglas Gregor67d91172009-04-28 21:32:13 +0000240 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000241 bool CPlusPlusOperatorKeyword = Bits & 0x01;
242 Bits >>= 1;
243 bool Poisoned = Bits & 0x01;
244 Bits >>= 1;
245 bool ExtensionToken = Bits & 0x01;
246 Bits >>= 1;
247 bool hasMacroDefinition = Bits & 0x01;
248 Bits >>= 1;
249 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
250 Bits >>= 10;
Douglas Gregor2c09dad2009-04-28 21:18:29 +0000251
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000252 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor67d91172009-04-28 21:32:13 +0000253 DataLen -= 6;
Douglas Gregorc713da92009-04-21 22:25:48 +0000254
255 // Build the IdentifierInfo itself and link the identifier ID with
256 // the new IdentifierInfo.
257 IdentifierInfo *II = KnownII;
258 if (!II)
Douglas Gregor4bb24882009-04-25 20:26:24 +0000259 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
260 k.first, k.first + k.second);
Douglas Gregorc713da92009-04-21 22:25:48 +0000261 Reader.SetIdentifierInfo(ID, II);
262
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000263 // Set or check the various bits in the IdentifierInfo structure.
264 // FIXME: Load token IDs lazily, too?
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000265 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
266 assert(II->isExtensionToken() == ExtensionToken &&
267 "Incorrect extension token flag");
268 (void)ExtensionToken;
269 II->setIsPoisoned(Poisoned);
270 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
271 "Incorrect C++ operator keyword flag");
272 (void)CPlusPlusOperatorKeyword;
273
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000274 // If this identifier is a macro, deserialize the macro
275 // definition.
276 if (hasMacroDefinition) {
Douglas Gregor67d91172009-04-28 21:32:13 +0000277 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000278 Reader.ReadMacroRecord(Offset);
Douglas Gregor67d91172009-04-28 21:32:13 +0000279 DataLen -= 4;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000280 }
Douglas Gregorc713da92009-04-21 22:25:48 +0000281
282 // Read all of the declarations visible at global scope with this
283 // name.
284 Sema *SemaObj = Reader.getSema();
Chris Lattnerea436b82009-04-27 22:17:41 +0000285 if (Reader.getContext() == 0) return II;
Chris Lattner772a7c12009-04-27 22:02:30 +0000286
Douglas Gregorc713da92009-04-21 22:25:48 +0000287 while (DataLen > 0) {
288 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregorc713da92009-04-21 22:25:48 +0000289 if (SemaObj) {
290 // Introduce this declaration into the translation-unit scope
291 // and add it to the declaration chain for this identifier, so
292 // that (unqualified) name lookup will find it.
293 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
294 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
295 } else {
296 // Queue this declaration so that it will be added to the
297 // translation unit scope and identifier's declaration chain
298 // once a Sema object is known.
Douglas Gregor2554cf22009-04-22 21:15:06 +0000299 Reader.PreloadedDecls.push_back(D);
Douglas Gregorc713da92009-04-21 22:25:48 +0000300 }
301
302 DataLen -= 4;
303 }
304 return II;
305 }
306};
307
308} // end anonymous namespace
309
310/// \brief The on-disk hash table used to contain information about
311/// all of the identifiers in the program.
312typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
313 PCHIdentifierLookupTable;
314
Douglas Gregorc34897d2009-04-09 22:27:44 +0000315// FIXME: use the diagnostics machinery
Douglas Gregoreae710d2009-04-28 21:53:25 +0000316bool PCHReader::Error(const char *Msg) {
317 Diagnostic &Diags = PP.getDiagnostics();
318 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
319 Diag(DiagID);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000320 return true;
321}
322
Douglas Gregor32de6312009-04-28 18:58:38 +0000323/// \brief Split the given string into a vector of lines, eliminating
324/// any empty lines in the process.
325///
326/// \param Str the string to split.
327/// \param Len the length of Str.
328/// \param KeepEmptyLines true if empty lines should be included
329/// \returns a vector of lines, with the line endings removed
330std::vector<std::string> splitLines(const char *Str, unsigned Len,
331 bool KeepEmptyLines = false) {
332 std::vector<std::string> Lines;
333 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
334 unsigned LineEnd = LineStart;
335 while (LineEnd < Len && Str[LineEnd] != '\n')
336 ++LineEnd;
337 if (LineStart != LineEnd || KeepEmptyLines)
338 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
339 LineStart = LineEnd;
340 }
341 return Lines;
342}
343
344/// \brief Determine whether the string Haystack starts with the
345/// substring Needle.
346static bool startsWith(const std::string &Haystack, const char *Needle) {
347 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
348 if (I == N)
349 return false;
350 if (Haystack[I] != Needle[I])
351 return false;
352 }
353
354 return true;
355}
356
357/// \brief Determine whether the string Haystack starts with the
358/// substring Needle.
359static inline bool startsWith(const std::string &Haystack,
360 const std::string &Needle) {
361 return startsWith(Haystack, Needle.c_str());
362}
363
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000364/// \brief Check the contents of the predefines buffer against the
365/// contents of the predefines buffer used to build the PCH file.
366///
367/// The contents of the two predefines buffers should be the same. If
368/// not, then some command-line option changed the preprocessor state
369/// and we must reject the PCH file.
370///
371/// \param PCHPredef The start of the predefines buffer in the PCH
372/// file.
373///
374/// \param PCHPredefLen The length of the predefines buffer in the PCH
375/// file.
376///
377/// \param PCHBufferID The FileID for the PCH predefines buffer.
378///
379/// \returns true if there was a mismatch (in which case the PCH file
380/// should be ignored), or false otherwise.
381bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
382 unsigned PCHPredefLen,
383 FileID PCHBufferID) {
384 const char *Predef = PP.getPredefines().c_str();
385 unsigned PredefLen = PP.getPredefines().size();
386
Douglas Gregor32de6312009-04-28 18:58:38 +0000387 // If the two predefines buffers compare equal, we're done!
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000388 if (PredefLen == PCHPredefLen &&
389 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
390 return false;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000391
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000392 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor32de6312009-04-28 18:58:38 +0000393
394 // The predefines buffers are different. Determine what the
395 // differences are, and whether they require us to reject the PCH
396 // file.
397 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
398 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000399
Douglas Gregor32de6312009-04-28 18:58:38 +0000400 // Sort both sets of predefined buffer lines, since
401 std::sort(CmdLineLines.begin(), CmdLineLines.end());
402 std::sort(PCHLines.begin(), PCHLines.end());
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000403
Douglas Gregor32de6312009-04-28 18:58:38 +0000404 // Determine which predefines that where used to build the PCH file
405 // are missing from the command line.
406 std::vector<std::string> MissingPredefines;
407 std::set_difference(PCHLines.begin(), PCHLines.end(),
408 CmdLineLines.begin(), CmdLineLines.end(),
409 std::back_inserter(MissingPredefines));
410
411 bool MissingDefines = false;
412 bool ConflictingDefines = false;
413 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
414 const std::string &Missing = MissingPredefines[I];
415 if (!startsWith(Missing, "#define ") != 0) {
Douglas Gregor1c6d8cc2009-04-28 20:36:16 +0000416 Diag(diag::warn_pch_compiler_options_mismatch);
Douglas Gregor32de6312009-04-28 18:58:38 +0000417 return true;
418 }
419
420 // This is a macro definition. Determine the name of the macro
421 // we're defining.
422 std::string::size_type StartOfMacroName = strlen("#define ");
423 std::string::size_type EndOfMacroName
424 = Missing.find_first_of("( \n\r", StartOfMacroName);
425 assert(EndOfMacroName != std::string::npos &&
426 "Couldn't find the end of the macro name");
427 std::string MacroName = Missing.substr(StartOfMacroName,
428 EndOfMacroName - StartOfMacroName);
429
430 // Determine whether this macro was given a different definition
431 // on the command line.
432 std::string MacroDefStart = "#define " + MacroName;
433 std::string::size_type MacroDefLen = MacroDefStart.size();
434 std::vector<std::string>::iterator ConflictPos
435 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
436 MacroDefStart);
437 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
438 if (!startsWith(*ConflictPos, MacroDefStart)) {
439 // Different macro; we're done.
440 ConflictPos = CmdLineLines.end();
441 break;
442 }
443
444 assert(ConflictPos->size() > MacroDefLen &&
445 "Invalid #define in predefines buffer?");
446 if ((*ConflictPos)[MacroDefLen] != ' ' &&
447 (*ConflictPos)[MacroDefLen] != '(')
448 continue; // Longer macro name; keep trying.
449
450 // We found a conflicting macro definition.
451 break;
452 }
453
454 if (ConflictPos != CmdLineLines.end()) {
455 Diag(diag::warn_cmdline_conflicting_macro_def)
456 << MacroName;
457
458 // Show the definition of this macro within the PCH file.
459 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
460 unsigned Offset = MissingDef - PCHPredef;
461 SourceLocation PCHMissingLoc
462 = SourceMgr.getLocForStartOfFile(PCHBufferID)
463 .getFileLocWithOffset(Offset);
464 Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
465 << MacroName;
466
467 ConflictingDefines = true;
468 continue;
469 }
470
471 // If the macro doesn't conflict, then we'll just pick up the
472 // macro definition from the PCH file. Warn the user that they
473 // made a mistake.
474 if (ConflictingDefines)
475 continue; // Don't complain if there are already conflicting defs
476
477 if (!MissingDefines) {
478 Diag(diag::warn_cmdline_missing_macro_defs);
479 MissingDefines = true;
480 }
481
482 // Show the definition of this macro within the PCH file.
483 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
484 unsigned Offset = MissingDef - PCHPredef;
485 SourceLocation PCHMissingLoc
486 = SourceMgr.getLocForStartOfFile(PCHBufferID)
487 .getFileLocWithOffset(Offset);
488 Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000489 }
490
Douglas Gregor9ea9b162009-04-28 22:01:16 +0000491 if (ConflictingDefines)
Douglas Gregor32de6312009-04-28 18:58:38 +0000492 return true;
Douglas Gregor32de6312009-04-28 18:58:38 +0000493
494 // Determine what predefines were introduced based on command-line
495 // parameters that were not present when building the PCH
496 // file. Extra #defines are okay, so long as the identifiers being
497 // defined were not used within the precompiled header.
498 std::vector<std::string> ExtraPredefines;
499 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
500 PCHLines.begin(), PCHLines.end(),
501 std::back_inserter(ExtraPredefines));
502 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
503 const std::string &Extra = ExtraPredefines[I];
504 if (!startsWith(Extra, "#define ") != 0) {
Douglas Gregor1c6d8cc2009-04-28 20:36:16 +0000505 Diag(diag::warn_pch_compiler_options_mismatch);
Douglas Gregor32de6312009-04-28 18:58:38 +0000506 return true;
507 }
508
509 // This is an extra macro definition. Determine the name of the
510 // macro we're defining.
511 std::string::size_type StartOfMacroName = strlen("#define ");
512 std::string::size_type EndOfMacroName
513 = Extra.find_first_of("( \n\r", StartOfMacroName);
514 assert(EndOfMacroName != std::string::npos &&
515 "Couldn't find the end of the macro name");
516 std::string MacroName = Extra.substr(StartOfMacroName,
517 EndOfMacroName - StartOfMacroName);
518
Douglas Gregor91137812009-04-28 20:33:11 +0000519 // Check whether this name was used somewhere in the PCH file. If
520 // so, defining it as a macro could change behavior, so we reject
521 // the PCH file.
522 if (IdentifierInfo *II = get(MacroName.c_str(),
523 MacroName.c_str() + MacroName.size())) {
524 Diag(diag::warn_macro_name_used_in_pch)
525 << II;
Douglas Gregor91137812009-04-28 20:33:11 +0000526 return true;
527 }
Douglas Gregor32de6312009-04-28 18:58:38 +0000528
529 // Add this definition to the suggested predefines buffer.
530 SuggestedPredefines += Extra;
531 SuggestedPredefines += '\n';
532 }
533
534 // If we get here, it's because the predefines buffer had compatible
535 // contents. Accept the PCH file.
536 return false;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000537}
538
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000539//===----------------------------------------------------------------------===//
540// Source Manager Deserialization
541//===----------------------------------------------------------------------===//
542
Douglas Gregor635f97f2009-04-13 16:31:14 +0000543/// \brief Read the line table in the source manager block.
544/// \returns true if ther was an error.
545static bool ParseLineTable(SourceManager &SourceMgr,
546 llvm::SmallVectorImpl<uint64_t> &Record) {
547 unsigned Idx = 0;
548 LineTableInfo &LineTable = SourceMgr.getLineTable();
549
550 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000551 std::map<int, int> FileIDs;
552 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000553 // Extract the file name
554 unsigned FilenameLen = Record[Idx++];
555 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
556 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000557 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
558 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000559 }
560
561 // Parse the line entries
562 std::vector<LineEntry> Entries;
563 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000564 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000565
566 // Extract the line entries
567 unsigned NumEntries = Record[Idx++];
568 Entries.clear();
569 Entries.reserve(NumEntries);
570 for (unsigned I = 0; I != NumEntries; ++I) {
571 unsigned FileOffset = Record[Idx++];
572 unsigned LineNo = Record[Idx++];
573 int FilenameID = Record[Idx++];
574 SrcMgr::CharacteristicKind FileKind
575 = (SrcMgr::CharacteristicKind)Record[Idx++];
576 unsigned IncludeOffset = Record[Idx++];
577 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
578 FileKind, IncludeOffset));
579 }
580 LineTable.AddEntry(FID, Entries);
581 }
582
583 return false;
584}
585
Douglas Gregor6cc5d192009-04-27 18:38:38 +0000586namespace {
587
588class VISIBILITY_HIDDEN PCHStatData {
589public:
590 const bool hasStat;
591 const ino_t ino;
592 const dev_t dev;
593 const mode_t mode;
594 const time_t mtime;
595 const off_t size;
596
597 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
598 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
599
600 PCHStatData()
601 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
602};
603
604class VISIBILITY_HIDDEN PCHStatLookupTrait {
605 public:
606 typedef const char *external_key_type;
607 typedef const char *internal_key_type;
608
609 typedef PCHStatData data_type;
610
611 static unsigned ComputeHash(const char *path) {
612 return BernsteinHash(path);
613 }
614
615 static internal_key_type GetInternalKey(const char *path) { return path; }
616
617 static bool EqualKey(internal_key_type a, internal_key_type b) {
618 return strcmp(a, b) == 0;
619 }
620
621 static std::pair<unsigned, unsigned>
622 ReadKeyDataLength(const unsigned char*& d) {
623 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
624 unsigned DataLen = (unsigned) *d++;
625 return std::make_pair(KeyLen + 1, DataLen);
626 }
627
628 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
629 return (const char *)d;
630 }
631
632 static data_type ReadData(const internal_key_type, const unsigned char *d,
633 unsigned /*DataLen*/) {
634 using namespace clang::io;
635
636 if (*d++ == 1)
637 return data_type();
638
639 ino_t ino = (ino_t) ReadUnalignedLE32(d);
640 dev_t dev = (dev_t) ReadUnalignedLE32(d);
641 mode_t mode = (mode_t) ReadUnalignedLE16(d);
642 time_t mtime = (time_t) ReadUnalignedLE64(d);
643 off_t size = (off_t) ReadUnalignedLE64(d);
644 return data_type(ino, dev, mode, mtime, size);
645 }
646};
647
648/// \brief stat() cache for precompiled headers.
649///
650/// This cache is very similar to the stat cache used by pretokenized
651/// headers.
652class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
653 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
654 CacheTy *Cache;
655
656 unsigned &NumStatHits, &NumStatMisses;
657public:
658 PCHStatCache(const unsigned char *Buckets,
659 const unsigned char *Base,
660 unsigned &NumStatHits,
661 unsigned &NumStatMisses)
662 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
663 Cache = CacheTy::Create(Buckets, Base);
664 }
665
666 ~PCHStatCache() { delete Cache; }
667
668 int stat(const char *path, struct stat *buf) {
669 // Do the lookup for the file's data in the PCH file.
670 CacheTy::iterator I = Cache->find(path);
671
672 // If we don't get a hit in the PCH file just forward to 'stat'.
673 if (I == Cache->end()) {
674 ++NumStatMisses;
675 return ::stat(path, buf);
676 }
677
678 ++NumStatHits;
679 PCHStatData Data = *I;
680
681 if (!Data.hasStat)
682 return 1;
683
684 buf->st_ino = Data.ino;
685 buf->st_dev = Data.dev;
686 buf->st_mtime = Data.mtime;
687 buf->st_mode = Data.mode;
688 buf->st_size = Data.size;
689 return 0;
690 }
691};
692} // end anonymous namespace
693
694
Douglas Gregorab1cef72009-04-10 03:52:48 +0000695/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000696PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000697 using namespace SrcMgr;
Douglas Gregor32e231c2009-04-27 06:38:32 +0000698
699 // Set the source-location entry cursor to the current position in
700 // the stream. This cursor will be used to read the contents of the
701 // source manager block initially, and then lazily read
702 // source-location entries as needed.
703 SLocEntryCursor = Stream;
704
705 // The stream itself is going to skip over the source manager block.
706 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000707 Error("malformed block record in PCH file");
Douglas Gregor32e231c2009-04-27 06:38:32 +0000708 return Failure;
709 }
710
711 // Enter the source manager block.
712 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000713 Error("malformed source manager block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000714 return Failure;
715 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000716
Chris Lattner270d29a2009-04-27 21:45:14 +0000717 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000718 RecordData Record;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000719 unsigned NumHeaderInfos = 0;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000720 while (true) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000721 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000722 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000723 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000724 Error("error at end of Source Manager block in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000725 return Failure;
726 }
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000727 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000728 }
729
730 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
731 // No known subblocks, always skip them.
Douglas Gregor32e231c2009-04-27 06:38:32 +0000732 SLocEntryCursor.ReadSubBlockID();
733 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000734 Error("malformed block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000735 return Failure;
736 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000737 continue;
738 }
739
740 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor32e231c2009-04-27 06:38:32 +0000741 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000742 continue;
743 }
744
745 // Read a record.
746 const char *BlobStart;
747 unsigned BlobLen;
748 Record.clear();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000749 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000750 default: // Default behavior: ignore.
751 break;
752
Chris Lattnere1be6022009-04-14 23:22:57 +0000753 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000754 if (ParseLineTable(SourceMgr, Record))
755 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000756 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000757
758 case pch::SM_HEADER_FILE_INFO: {
759 HeaderFileInfo HFI;
760 HFI.isImport = Record[0];
761 HFI.DirInfo = Record[1];
762 HFI.NumIncludes = Record[2];
763 HFI.ControllingMacroID = Record[3];
764 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
765 break;
766 }
Douglas Gregor32e231c2009-04-27 06:38:32 +0000767
768 case pch::SM_SLOC_FILE_ENTRY:
769 case pch::SM_SLOC_BUFFER_ENTRY:
770 case pch::SM_SLOC_INSTANTIATION_ENTRY:
771 // Once we hit one of the source location entries, we're done.
772 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000773 }
774 }
775}
776
Douglas Gregor32e231c2009-04-27 06:38:32 +0000777/// \brief Read in the source location entry with the given ID.
778PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
779 if (ID == 0)
780 return Success;
781
782 if (ID > TotalNumSLocEntries) {
783 Error("source location entry ID out-of-range for PCH file");
784 return Failure;
785 }
786
787 ++NumSLocEntriesRead;
788 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
789 unsigned Code = SLocEntryCursor.ReadCode();
790 if (Code == llvm::bitc::END_BLOCK ||
791 Code == llvm::bitc::ENTER_SUBBLOCK ||
792 Code == llvm::bitc::DEFINE_ABBREV) {
793 Error("incorrectly-formatted source location entry in PCH file");
794 return Failure;
795 }
796
Chris Lattner270d29a2009-04-27 21:45:14 +0000797 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor32e231c2009-04-27 06:38:32 +0000798 RecordData Record;
799 const char *BlobStart;
800 unsigned BlobLen;
801 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
802 default:
803 Error("incorrectly-formatted source location entry in PCH file");
804 return Failure;
805
806 case pch::SM_SLOC_FILE_ENTRY: {
Chris Lattner8c5a4772009-06-15 04:35:16 +0000807 const FileEntry *File = PP.getFileManager().getFile(BlobStart,
808 BlobStart + BlobLen);
809 if (File == 0) {
810 std::string ErrorStr = "could not find file '";
811 ErrorStr.append(BlobStart, BlobLen);
812 ErrorStr += "' referenced by PCH file";
813 Error(ErrorStr.c_str());
814 return Failure;
815 }
816
Douglas Gregor32e231c2009-04-27 06:38:32 +0000817 FileID FID = SourceMgr.createFileID(File,
818 SourceLocation::getFromRawEncoding(Record[1]),
819 (SrcMgr::CharacteristicKind)Record[2],
820 ID, Record[0]);
821 if (Record[3])
822 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
823 .setHasLineDirectives();
824
825 break;
826 }
827
828 case pch::SM_SLOC_BUFFER_ENTRY: {
829 const char *Name = BlobStart;
830 unsigned Offset = Record[0];
831 unsigned Code = SLocEntryCursor.ReadCode();
832 Record.clear();
833 unsigned RecCode
834 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
835 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
836 (void)RecCode;
837 llvm::MemoryBuffer *Buffer
838 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
839 BlobStart + BlobLen - 1,
840 Name);
841 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
842
Douglas Gregor91137812009-04-28 20:33:11 +0000843 if (strcmp(Name, "<built-in>") == 0) {
844 PCHPredefinesBufferID = BufferID;
845 PCHPredefines = BlobStart;
846 PCHPredefinesLen = BlobLen - 1;
847 }
Douglas Gregor32e231c2009-04-27 06:38:32 +0000848
849 break;
850 }
851
852 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
853 SourceLocation SpellingLoc
854 = SourceLocation::getFromRawEncoding(Record[1]);
855 SourceMgr.createInstantiationLoc(SpellingLoc,
856 SourceLocation::getFromRawEncoding(Record[2]),
857 SourceLocation::getFromRawEncoding(Record[3]),
858 Record[4],
859 ID,
860 Record[0]);
861 break;
862 }
863 }
864
865 return Success;
866}
867
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000868/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
869/// specified cursor. Read the abbreviations that are at the top of the block
870/// and then leave the cursor pointing into the block.
871bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
872 unsigned BlockID) {
873 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000874 Error("malformed block record in PCH file");
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000875 return Failure;
876 }
877
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000878 while (true) {
879 unsigned Code = Cursor.ReadCode();
880
881 // We expect all abbrevs to be at the start of the block.
882 if (Code != llvm::bitc::DEFINE_ABBREV)
883 return false;
884 Cursor.ReadAbbrevRecord();
885 }
886}
887
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000888void PCHReader::ReadMacroRecord(uint64_t Offset) {
889 // Keep track of where we are in the stream, then jump back there
890 // after reading this macro.
891 SavedStreamPosition SavedPosition(Stream);
892
893 Stream.JumpToBit(Offset);
894 RecordData Record;
895 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
896 MacroInfo *Macro = 0;
Steve Naroffcda68f22009-04-24 20:03:17 +0000897
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000898 while (true) {
899 unsigned Code = Stream.ReadCode();
900 switch (Code) {
901 case llvm::bitc::END_BLOCK:
902 return;
903
904 case llvm::bitc::ENTER_SUBBLOCK:
905 // No known subblocks, always skip them.
906 Stream.ReadSubBlockID();
907 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000908 Error("malformed block record in PCH file");
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000909 return;
910 }
911 continue;
912
913 case llvm::bitc::DEFINE_ABBREV:
914 Stream.ReadAbbrevRecord();
915 continue;
916 default: break;
917 }
918
919 // Read a record.
920 Record.clear();
921 pch::PreprocessorRecordTypes RecType =
922 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
923 switch (RecType) {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000924 case pch::PP_MACRO_OBJECT_LIKE:
925 case pch::PP_MACRO_FUNCTION_LIKE: {
926 // If we already have a macro, that means that we've hit the end
927 // of the definition of the macro we were looking for. We're
928 // done.
929 if (Macro)
930 return;
931
932 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
933 if (II == 0) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000934 Error("macro must have a name in PCH file");
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000935 return;
936 }
937 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
938 bool isUsed = Record[2];
939
940 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
941 MI->setIsUsed(isUsed);
942
943 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
944 // Decode function-like macro info.
945 bool isC99VarArgs = Record[3];
946 bool isGNUVarArgs = Record[4];
947 MacroArgs.clear();
948 unsigned NumArgs = Record[5];
949 for (unsigned i = 0; i != NumArgs; ++i)
950 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
951
952 // Install function-like macro info.
953 MI->setIsFunctionLike();
954 if (isC99VarArgs) MI->setIsC99Varargs();
955 if (isGNUVarArgs) MI->setIsGNUVarargs();
Douglas Gregor4e284192009-05-22 22:45:36 +0000956 MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000957 PP.getPreprocessorAllocator());
958 }
959
960 // Finally, install the macro.
961 PP.setMacroInfo(II, MI);
962
963 // Remember that we saw this macro last so that we add the tokens that
964 // form its body to it.
965 Macro = MI;
966 ++NumMacrosRead;
967 break;
968 }
969
970 case pch::PP_TOKEN: {
971 // If we see a TOKEN before a PP_MACRO_*, then the file is
972 // erroneous, just pretend we didn't see this.
973 if (Macro == 0) break;
974
975 Token Tok;
976 Tok.startToken();
977 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
978 Tok.setLength(Record[1]);
979 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
980 Tok.setIdentifierInfo(II);
981 Tok.setKind((tok::TokenKind)Record[3]);
982 Tok.setFlag((Token::TokenFlags)Record[4]);
983 Macro->AddTokenToBody(Tok);
984 break;
985 }
Steve Naroffcda68f22009-04-24 20:03:17 +0000986 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000987 }
988}
989
Douglas Gregorc713da92009-04-21 22:25:48 +0000990PCHReader::PCHReadResult
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000991PCHReader::ReadPCHBlock() {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000992 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +0000993 Error("malformed block record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +0000994 return Failure;
995 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000996
997 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000998 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000999 while (!Stream.AtEndOfStream()) {
1000 unsigned Code = Stream.ReadCode();
1001 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001002 if (Stream.ReadBlockEnd()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001003 Error("error at end of module block in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001004 return Failure;
1005 }
Chris Lattner29241862009-04-11 21:15:38 +00001006
Douglas Gregor179cfb12009-04-10 20:39:37 +00001007 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001008 }
1009
1010 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1011 switch (Stream.ReadSubBlockID()) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001012 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1013 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +00001014 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001015 Error("malformed block record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001016 return Failure;
1017 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001018 break;
1019
Chris Lattner4fc71eb2009-04-27 01:05:14 +00001020 case pch::DECLS_BLOCK_ID:
1021 // We lazily load the decls block, but we want to set up the
1022 // DeclsCursor cursor to point into it. Clone our current bitcode
1023 // cursor to it, enter the block and read the abbrevs in that block.
1024 // With the main cursor, we just skip over it.
1025 DeclsCursor = Stream;
1026 if (Stream.SkipBlock() || // Skip with the main cursor.
1027 // Read the abbrevs.
1028 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001029 Error("malformed block record in PCH file");
Chris Lattner4fc71eb2009-04-27 01:05:14 +00001030 return Failure;
1031 }
1032 break;
1033
Chris Lattner29241862009-04-11 21:15:38 +00001034 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner29241862009-04-11 21:15:38 +00001035 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001036 Error("malformed block record in PCH file");
Chris Lattner29241862009-04-11 21:15:38 +00001037 return Failure;
1038 }
1039 break;
Steve Naroff9e84d782009-04-23 10:39:46 +00001040
Douglas Gregorab1cef72009-04-10 03:52:48 +00001041 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001042 switch (ReadSourceManagerBlock()) {
1043 case Success:
1044 break;
1045
1046 case Failure:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001047 Error("malformed source manager block in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001048 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001049
1050 case IgnorePCH:
1051 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001052 }
Douglas Gregorab1cef72009-04-10 03:52:48 +00001053 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001054 }
Douglas Gregorac8f2802009-04-10 17:25:41 +00001055 continue;
1056 }
1057
1058 if (Code == llvm::bitc::DEFINE_ABBREV) {
1059 Stream.ReadAbbrevRecord();
1060 continue;
1061 }
1062
1063 // Read and process a record.
1064 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +00001065 const char *BlobStart = 0;
1066 unsigned BlobLen = 0;
1067 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1068 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +00001069 default: // Default behavior: ignore.
1070 break;
1071
1072 case pch::TYPE_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +00001073 if (!TypesLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001074 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001075 return Failure;
1076 }
Chris Lattnerea332f32009-04-27 18:24:17 +00001077 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001078 TypesLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +00001079 break;
1080
1081 case pch::DECL_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +00001082 if (!DeclsLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001083 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001084 return Failure;
1085 }
Chris Lattnerea332f32009-04-27 18:24:17 +00001086 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor24a224c2009-04-25 18:35:21 +00001087 DeclsLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +00001088 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001089
1090 case pch::LANGUAGE_OPTIONS:
1091 if (ParseLanguageOptions(Record))
1092 return IgnorePCH;
1093 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +00001094
Douglas Gregorb7064742009-04-27 22:23:34 +00001095 case pch::METADATA: {
1096 if (Record[0] != pch::VERSION_MAJOR) {
1097 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1098 : diag::warn_pch_version_too_new);
1099 return IgnorePCH;
1100 }
1101
Douglas Gregorb5887f32009-04-10 21:16:55 +00001102 std::string TargetTriple(BlobStart, BlobLen);
Chris Lattner270d29a2009-04-27 21:45:14 +00001103 if (TargetTriple != PP.getTargetInfo().getTargetTriple()) {
Douglas Gregorb5887f32009-04-10 21:16:55 +00001104 Diag(diag::warn_pch_target_triple)
Chris Lattner270d29a2009-04-27 21:45:14 +00001105 << TargetTriple << PP.getTargetInfo().getTargetTriple();
Douglas Gregorb5887f32009-04-10 21:16:55 +00001106 return IgnorePCH;
1107 }
1108 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001109 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001110
1111 case pch::IDENTIFIER_TABLE:
Douglas Gregorc713da92009-04-21 22:25:48 +00001112 IdentifierTableData = BlobStart;
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001113 if (Record[0]) {
1114 IdentifierLookupTable
1115 = PCHIdentifierLookupTable::Create(
Douglas Gregorc713da92009-04-21 22:25:48 +00001116 (const unsigned char *)IdentifierTableData + Record[0],
1117 (const unsigned char *)IdentifierTableData,
1118 PCHIdentifierLookupTrait(*this));
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001119 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1120 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001121 break;
1122
1123 case pch::IDENTIFIER_OFFSET:
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001124 if (!IdentifiersLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001125 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001126 return Failure;
1127 }
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001128 IdentifierOffsets = (const uint32_t *)BlobStart;
1129 IdentifiersLoaded.resize(Record[0]);
Douglas Gregoreccb51d2009-04-25 23:30:02 +00001130 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001131 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +00001132
1133 case pch::EXTERNAL_DEFINITIONS:
1134 if (!ExternalDefinitions.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001135 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregor631f6c62009-04-14 00:24:19 +00001136 return Failure;
1137 }
1138 ExternalDefinitions.swap(Record);
1139 break;
Douglas Gregor456e0952009-04-17 22:13:46 +00001140
Douglas Gregore01ad442009-04-18 05:55:16 +00001141 case pch::SPECIAL_TYPES:
1142 SpecialTypes.swap(Record);
1143 break;
1144
Douglas Gregor456e0952009-04-17 22:13:46 +00001145 case pch::STATISTICS:
1146 TotalNumStatements = Record[0];
Douglas Gregore0ad2dd2009-04-21 23:56:24 +00001147 TotalNumMacros = Record[1];
Douglas Gregoraf136d92009-04-22 22:34:57 +00001148 TotalLexicalDeclContexts = Record[2];
1149 TotalVisibleDeclContexts = Record[3];
Douglas Gregor456e0952009-04-17 22:13:46 +00001150 break;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001151
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001152 case pch::TENTATIVE_DEFINITIONS:
1153 if (!TentativeDefinitions.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001154 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001155 return Failure;
1156 }
1157 TentativeDefinitions.swap(Record);
1158 break;
Douglas Gregor062d9482009-04-22 22:18:58 +00001159
1160 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1161 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001162 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor062d9482009-04-22 22:18:58 +00001163 return Failure;
1164 }
1165 LocallyScopedExternalDecls.swap(Record);
1166 break;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001167
Douglas Gregor2d711832009-04-25 17:48:32 +00001168 case pch::SELECTOR_OFFSETS:
1169 SelectorOffsets = (const uint32_t *)BlobStart;
1170 TotalNumSelectors = Record[0];
1171 SelectorsLoaded.resize(TotalNumSelectors);
1172 break;
1173
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001174 case pch::METHOD_POOL:
Douglas Gregor2d711832009-04-25 17:48:32 +00001175 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1176 if (Record[0])
1177 MethodPoolLookupTable
1178 = PCHMethodPoolLookupTable::Create(
1179 MethodPoolLookupTableData + Record[0],
1180 MethodPoolLookupTableData,
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001181 PCHMethodPoolLookupTrait(*this));
Douglas Gregor2d711832009-04-25 17:48:32 +00001182 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001183 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001184
1185 case pch::PP_COUNTER_VALUE:
1186 if (!Record.empty())
1187 PP.setCounterValue(Record[0]);
1188 break;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001189
1190 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner93307da2009-04-27 19:01:47 +00001191 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor32e231c2009-04-27 06:38:32 +00001192 TotalNumSLocEntries = Record[0];
1193 PP.getSourceManager().PreallocateSLocEntries(this,
1194 TotalNumSLocEntries,
1195 Record[1]);
1196 break;
1197
1198 case pch::SOURCE_LOCATION_PRELOADS:
1199 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1200 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1201 if (Result != Success)
1202 return Result;
1203 }
1204 break;
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001205
1206 case pch::STAT_CACHE:
1207 PP.getFileManager().setStatCache(
1208 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1209 (const unsigned char *)BlobStart,
1210 NumStatHits, NumStatMisses));
1211 break;
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001212
1213 case pch::EXT_VECTOR_DECLS:
1214 if (!ExtVectorDecls.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001215 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001216 return Failure;
1217 }
1218 ExtVectorDecls.swap(Record);
1219 break;
1220
1221 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1222 if (!ObjCCategoryImpls.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001223 Error("duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
Douglas Gregorb36b20d2009-04-27 20:06:05 +00001224 return Failure;
1225 }
1226 ObjCCategoryImpls.swap(Record);
1227 break;
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001228
1229 case pch::ORIGINAL_FILE_NAME:
1230 OriginalFileName.assign(BlobStart, BlobLen);
1231 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001232 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001233 }
Douglas Gregoreae710d2009-04-28 21:53:25 +00001234 Error("premature end of bitstream in PCH file");
Douglas Gregor179cfb12009-04-10 20:39:37 +00001235 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001236}
1237
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001238PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001239 // Set the PCH file name.
1240 this->FileName = FileName;
1241
Douglas Gregorc34897d2009-04-09 22:27:44 +00001242 // Open the PCH file.
1243 std::string ErrStr;
1244 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001245 if (!Buffer) {
1246 Error(ErrStr.c_str());
1247 return IgnorePCH;
1248 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001249
1250 // Initialize the stream
Chris Lattner587788a2009-04-26 20:59:20 +00001251 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1252 (const unsigned char *)Buffer->getBufferEnd());
1253 Stream.init(StreamFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001254
1255 // Sniff for the signature.
1256 if (Stream.Read(8) != 'C' ||
1257 Stream.Read(8) != 'P' ||
1258 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001259 Stream.Read(8) != 'H') {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001260 Diag(diag::err_not_a_pch_file) << FileName;
1261 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001262 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001263
Douglas Gregorc34897d2009-04-09 22:27:44 +00001264 while (!Stream.AtEndOfStream()) {
1265 unsigned Code = Stream.ReadCode();
1266
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001267 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001268 Error("invalid record at top-level of PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001269 return Failure;
1270 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001271
1272 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregorc713da92009-04-21 22:25:48 +00001273
Douglas Gregorc34897d2009-04-09 22:27:44 +00001274 // We only know the PCH subblock ID.
1275 switch (BlockID) {
1276 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001277 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001278 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001279 return Failure;
1280 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001281 break;
1282 case pch::PCH_BLOCK_ID:
Douglas Gregorf6e1fb22009-04-26 00:07:37 +00001283 switch (ReadPCHBlock()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +00001284 case Success:
1285 break;
1286
1287 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001288 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001289
1290 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +00001291 // FIXME: We could consider reading through to the end of this
1292 // PCH block, skipping subblocks, to see if there are other
1293 // PCH blocks elsewhere.
Douglas Gregor57885192009-04-27 21:28:04 +00001294
1295 // Clear out any preallocated source location entries, so that
1296 // the source manager does not try to resolve them later.
1297 PP.getSourceManager().ClearPreallocatedSLocEntries();
1298
1299 // Remove the stat cache.
1300 PP.getFileManager().setStatCache(0);
1301
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001302 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001303 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001304 break;
1305 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001306 if (Stream.SkipBlock()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001307 Error("malformed block record in PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001308 return Failure;
1309 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001310 break;
1311 }
1312 }
1313
1314 // Load the translation unit declaration
Chris Lattner270d29a2009-04-27 21:45:14 +00001315 if (Context)
1316 ReadDeclRecord(DeclOffsets[0], 0);
Douglas Gregor91137812009-04-28 20:33:11 +00001317
1318 // Check the predefines buffer.
1319 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1320 PCHPredefinesBufferID))
1321 return IgnorePCH;
1322
Douglas Gregorc713da92009-04-21 22:25:48 +00001323 // Initialization of builtins and library builtins occurs before the
1324 // PCH file is read, so there may be some identifiers that were
1325 // loaded into the IdentifierTable before we intercepted the
1326 // creation of identifiers. Iterate through the list of known
1327 // identifiers and determine whether we have to establish
1328 // preprocessor definitions or top-level identifier declaration
1329 // chains for those identifiers.
1330 //
1331 // We copy the IdentifierInfo pointers to a small vector first,
1332 // since de-serializing declarations or macro definitions can add
1333 // new entries into the identifier table, invalidating the
1334 // iterators.
1335 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1336 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
1337 IdEnd = PP.getIdentifierTable().end();
1338 Id != IdEnd; ++Id)
1339 Identifiers.push_back(Id->second);
1340 PCHIdentifierLookupTable *IdTable
1341 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1342 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1343 IdentifierInfo *II = Identifiers[I];
1344 // Look in the on-disk hash table for an entry for
1345 PCHIdentifierLookupTrait Info(*this, II);
1346 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1347 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1348 if (Pos == IdTable->end())
1349 continue;
1350
1351 // Dereferencing the iterator has the effect of populating the
1352 // IdentifierInfo node with the various declarations it needs.
1353 (void)*Pos;
1354 }
1355
Douglas Gregore01ad442009-04-18 05:55:16 +00001356 // Load the special types.
Chris Lattner270d29a2009-04-27 21:45:14 +00001357 if (Context) {
1358 Context->setBuiltinVaListType(
1359 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1360 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1361 Context->setObjCIdType(GetType(Id));
1362 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1363 Context->setObjCSelType(GetType(Sel));
1364 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1365 Context->setObjCProtoType(GetType(Proto));
1366 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1367 Context->setObjCClassType(GetType(Class));
1368 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1369 Context->setCFConstantStringType(GetType(String));
1370 if (unsigned FastEnum
1371 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1372 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1373 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001374
Douglas Gregorc713da92009-04-21 22:25:48 +00001375 return Success;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001376}
1377
Douglas Gregoreccf0d12009-05-12 01:31:05 +00001378/// \brief Retrieve the name of the original source file name
1379/// directly from the PCH file, without actually loading the PCH
1380/// file.
1381std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1382 // Open the PCH file.
1383 std::string ErrStr;
1384 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1385 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1386 if (!Buffer) {
1387 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1388 return std::string();
1389 }
1390
1391 // Initialize the stream
1392 llvm::BitstreamReader StreamFile;
1393 llvm::BitstreamCursor Stream;
1394 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1395 (const unsigned char *)Buffer->getBufferEnd());
1396 Stream.init(StreamFile);
1397
1398 // Sniff for the signature.
1399 if (Stream.Read(8) != 'C' ||
1400 Stream.Read(8) != 'P' ||
1401 Stream.Read(8) != 'C' ||
1402 Stream.Read(8) != 'H') {
1403 fprintf(stderr,
1404 "error: '%s' does not appear to be a precompiled header file\n",
1405 PCHFileName.c_str());
1406 return std::string();
1407 }
1408
1409 RecordData Record;
1410 while (!Stream.AtEndOfStream()) {
1411 unsigned Code = Stream.ReadCode();
1412
1413 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1414 unsigned BlockID = Stream.ReadSubBlockID();
1415
1416 // We only know the PCH subblock ID.
1417 switch (BlockID) {
1418 case pch::PCH_BLOCK_ID:
1419 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1420 fprintf(stderr, "error: malformed block record in PCH file\n");
1421 return std::string();
1422 }
1423 break;
1424
1425 default:
1426 if (Stream.SkipBlock()) {
1427 fprintf(stderr, "error: malformed block record in PCH file\n");
1428 return std::string();
1429 }
1430 break;
1431 }
1432 continue;
1433 }
1434
1435 if (Code == llvm::bitc::END_BLOCK) {
1436 if (Stream.ReadBlockEnd()) {
1437 fprintf(stderr, "error: error at end of module block in PCH file\n");
1438 return std::string();
1439 }
1440 continue;
1441 }
1442
1443 if (Code == llvm::bitc::DEFINE_ABBREV) {
1444 Stream.ReadAbbrevRecord();
1445 continue;
1446 }
1447
1448 Record.clear();
1449 const char *BlobStart = 0;
1450 unsigned BlobLen = 0;
1451 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1452 == pch::ORIGINAL_FILE_NAME)
1453 return std::string(BlobStart, BlobLen);
1454 }
1455
1456 return std::string();
1457}
1458
Douglas Gregor179cfb12009-04-10 20:39:37 +00001459/// \brief Parse the record that corresponds to a LangOptions data
1460/// structure.
1461///
1462/// This routine compares the language options used to generate the
1463/// PCH file against the language options set for the current
1464/// compilation. For each option, we classify differences between the
1465/// two compiler states as either "benign" or "important". Benign
1466/// differences don't matter, and we accept them without complaint
1467/// (and without modifying the language options). Differences between
1468/// the states for important options cause the PCH file to be
1469/// unusable, so we emit a warning and return true to indicate that
1470/// there was an error.
1471///
1472/// \returns true if the PCH file is unacceptable, false otherwise.
1473bool PCHReader::ParseLanguageOptions(
1474 const llvm::SmallVectorImpl<uint64_t> &Record) {
Chris Lattner270d29a2009-04-27 21:45:14 +00001475 const LangOptions &LangOpts = PP.getLangOptions();
Douglas Gregor179cfb12009-04-10 20:39:37 +00001476#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1477#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1478 if (Record[Idx] != LangOpts.Option) { \
1479 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
Douglas Gregor179cfb12009-04-10 20:39:37 +00001480 return true; \
1481 } \
1482 ++Idx
1483
1484 unsigned Idx = 0;
1485 PARSE_LANGOPT_BENIGN(Trigraphs);
1486 PARSE_LANGOPT_BENIGN(BCPLComment);
1487 PARSE_LANGOPT_BENIGN(DollarIdents);
1488 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1489 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1490 PARSE_LANGOPT_BENIGN(ImplicitInt);
1491 PARSE_LANGOPT_BENIGN(Digraphs);
1492 PARSE_LANGOPT_BENIGN(HexFloats);
1493 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1494 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1495 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1496 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001497 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1498 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1499 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1500 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1501 PARSE_LANGOPT_BENIGN(PascalStrings);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001502 PARSE_LANGOPT_BENIGN(WritableStrings);
1503 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1504 diag::warn_pch_lax_vector_conversions);
1505 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1506 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1507 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1508 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1509 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1510 diag::warn_pch_thread_safe_statics);
1511 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1512 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1513 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1514 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1515 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1516 diag::warn_pch_heinous_extensions);
1517 // FIXME: Most of the options below are benign if the macro wasn't
1518 // used. Unfortunately, this means that a PCH compiled without
1519 // optimization can't be used with optimization turned on, even
1520 // though the only thing that changes is whether __OPTIMIZE__ was
1521 // defined... but if __OPTIMIZE__ never showed up in the header, it
1522 // doesn't matter. We could consider making this some special kind
1523 // of check.
1524 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1525 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1526 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1527 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1528 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1529 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
Anders Carlssonf2310142009-05-13 19:49:53 +00001530 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
Eli Friedmand9389be2009-06-05 07:05:05 +00001531 PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
Douglas Gregor179cfb12009-04-10 20:39:37 +00001532 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1533 Diag(diag::warn_pch_gc_mode)
1534 << (unsigned)Record[Idx] << LangOpts.getGCMode();
Douglas Gregor179cfb12009-04-10 20:39:37 +00001535 return true;
1536 }
1537 ++Idx;
1538 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1539 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1540#undef PARSE_LANGOPT_IRRELEVANT
1541#undef PARSE_LANGOPT_BENIGN
1542
1543 return false;
1544}
1545
Douglas Gregorc34897d2009-04-09 22:27:44 +00001546/// \brief Read and return the type at the given offset.
1547///
1548/// This routine actually reads the record corresponding to the type
1549/// at the given offset in the bitstream. It is a helper routine for
1550/// GetType, which deals with reading type IDs.
1551QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001552 // Keep track of where we are in the stream, then jump back there
1553 // after reading this type.
1554 SavedStreamPosition SavedPosition(Stream);
1555
Douglas Gregorc34897d2009-04-09 22:27:44 +00001556 Stream.JumpToBit(Offset);
1557 RecordData Record;
1558 unsigned Code = Stream.ReadCode();
1559 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001560 case pch::TYPE_EXT_QUAL: {
1561 assert(Record.size() == 3 &&
1562 "Incorrect encoding of extended qualifier type");
1563 QualType Base = GetType(Record[0]);
1564 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1565 unsigned AddressSpace = Record[2];
1566
1567 QualType T = Base;
1568 if (GCAttr != QualType::GCNone)
Chris Lattner270d29a2009-04-27 21:45:14 +00001569 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001570 if (AddressSpace)
Chris Lattner270d29a2009-04-27 21:45:14 +00001571 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001572 return T;
1573 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001574
Douglas Gregorc34897d2009-04-09 22:27:44 +00001575 case pch::TYPE_FIXED_WIDTH_INT: {
1576 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001577 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001578 }
1579
1580 case pch::TYPE_COMPLEX: {
1581 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1582 QualType ElemType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001583 return Context->getComplexType(ElemType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001584 }
1585
1586 case pch::TYPE_POINTER: {
1587 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1588 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001589 return Context->getPointerType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001590 }
1591
1592 case pch::TYPE_BLOCK_POINTER: {
1593 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1594 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001595 return Context->getBlockPointerType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001596 }
1597
1598 case pch::TYPE_LVALUE_REFERENCE: {
1599 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1600 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001601 return Context->getLValueReferenceType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001602 }
1603
1604 case pch::TYPE_RVALUE_REFERENCE: {
1605 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1606 QualType PointeeType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001607 return Context->getRValueReferenceType(PointeeType);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001608 }
1609
1610 case pch::TYPE_MEMBER_POINTER: {
1611 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1612 QualType PointeeType = GetType(Record[0]);
1613 QualType ClassType = GetType(Record[1]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001614 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregorc34897d2009-04-09 22:27:44 +00001615 }
1616
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001617 case pch::TYPE_CONSTANT_ARRAY: {
1618 QualType ElementType = GetType(Record[0]);
1619 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1620 unsigned IndexTypeQuals = Record[2];
1621 unsigned Idx = 3;
1622 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattner270d29a2009-04-27 21:45:14 +00001623 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001624 }
1625
1626 case pch::TYPE_INCOMPLETE_ARRAY: {
1627 QualType ElementType = GetType(Record[0]);
1628 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1629 unsigned IndexTypeQuals = Record[2];
Chris Lattner270d29a2009-04-27 21:45:14 +00001630 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001631 }
1632
1633 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001634 QualType ElementType = GetType(Record[0]);
1635 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1636 unsigned IndexTypeQuals = Record[2];
Chris Lattner270d29a2009-04-27 21:45:14 +00001637 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1638 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001639 }
1640
1641 case pch::TYPE_VECTOR: {
1642 if (Record.size() != 2) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001643 Error("incorrect encoding of vector type in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001644 return QualType();
1645 }
1646
1647 QualType ElementType = GetType(Record[0]);
1648 unsigned NumElements = Record[1];
Chris Lattner270d29a2009-04-27 21:45:14 +00001649 return Context->getVectorType(ElementType, NumElements);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001650 }
1651
1652 case pch::TYPE_EXT_VECTOR: {
1653 if (Record.size() != 2) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001654 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001655 return QualType();
1656 }
1657
1658 QualType ElementType = GetType(Record[0]);
1659 unsigned NumElements = Record[1];
Chris Lattner270d29a2009-04-27 21:45:14 +00001660 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001661 }
1662
1663 case pch::TYPE_FUNCTION_NO_PROTO: {
1664 if (Record.size() != 1) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001665 Error("incorrect encoding of no-proto function type");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001666 return QualType();
1667 }
1668 QualType ResultType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001669 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001670 }
1671
1672 case pch::TYPE_FUNCTION_PROTO: {
1673 QualType ResultType = GetType(Record[0]);
1674 unsigned Idx = 1;
1675 unsigned NumParams = Record[Idx++];
1676 llvm::SmallVector<QualType, 16> ParamTypes;
1677 for (unsigned I = 0; I != NumParams; ++I)
1678 ParamTypes.push_back(GetType(Record[Idx++]));
1679 bool isVariadic = Record[Idx++];
1680 unsigned Quals = Record[Idx++];
Sebastian Redl2767d882009-05-27 22:11:52 +00001681 bool hasExceptionSpec = Record[Idx++];
1682 bool hasAnyExceptionSpec = Record[Idx++];
1683 unsigned NumExceptions = Record[Idx++];
1684 llvm::SmallVector<QualType, 2> Exceptions;
1685 for (unsigned I = 0; I != NumExceptions; ++I)
1686 Exceptions.push_back(GetType(Record[Idx++]));
Jay Foad9e6bef42009-05-21 09:52:38 +00001687 return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
Sebastian Redl2767d882009-05-27 22:11:52 +00001688 isVariadic, Quals, hasExceptionSpec,
1689 hasAnyExceptionSpec, NumExceptions,
1690 Exceptions.data());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001691 }
1692
1693 case pch::TYPE_TYPEDEF:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001694 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001695 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001696
1697 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner270d29a2009-04-27 21:45:14 +00001698 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001699
1700 case pch::TYPE_TYPEOF: {
1701 if (Record.size() != 1) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001702 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001703 return QualType();
1704 }
1705 QualType UnderlyingType = GetType(Record[0]);
Chris Lattner270d29a2009-04-27 21:45:14 +00001706 return Context->getTypeOfType(UnderlyingType);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001707 }
1708
1709 case pch::TYPE_RECORD:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001710 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001711 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001712
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001713 case pch::TYPE_ENUM:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001714 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001715 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001716
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001717 case pch::TYPE_OBJC_INTERFACE:
Douglas Gregoreae710d2009-04-28 21:53:25 +00001718 assert(Record.size() == 1 && "incorrect encoding of objc interface type");
Chris Lattner270d29a2009-04-27 21:45:14 +00001719 return Context->getObjCInterfaceType(
Chris Lattner80f83c62009-04-22 05:57:30 +00001720 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001721
Chris Lattnerbab2c0f2009-04-22 06:45:28 +00001722 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1723 unsigned Idx = 0;
1724 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1725 unsigned NumProtos = Record[Idx++];
1726 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1727 for (unsigned I = 0; I != NumProtos; ++I)
1728 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Douglas Gregor4e284192009-05-22 22:45:36 +00001729 return Context->getObjCQualifiedInterfaceType(ItfD, Protos.data(), NumProtos);
Chris Lattnerbab2c0f2009-04-22 06:45:28 +00001730 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001731
Steve Naroffc75c1a82009-06-17 22:40:22 +00001732 case pch::TYPE_OBJC_OBJECT_POINTER: {
Chris Lattner9b9f2352009-04-22 06:40:03 +00001733 unsigned Idx = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00001734 ObjCInterfaceDecl *ItfD =
1735 cast_or_null<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
Chris Lattner9b9f2352009-04-22 06:40:03 +00001736 unsigned NumProtos = Record[Idx++];
1737 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1738 for (unsigned I = 0; I != NumProtos; ++I)
1739 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Steve Naroffc75c1a82009-06-17 22:40:22 +00001740 return Context->getObjCObjectPointerType(ItfD, Protos.data(), NumProtos);
Chris Lattner9b9f2352009-04-22 06:40:03 +00001741 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001742 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001743 // Suppress a GCC warning
1744 return QualType();
1745}
1746
Douglas Gregorc34897d2009-04-09 22:27:44 +00001747
Douglas Gregorac8f2802009-04-10 17:25:41 +00001748QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001749 unsigned Quals = ID & 0x07;
1750 unsigned Index = ID >> 3;
1751
1752 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1753 QualType T;
1754 switch ((pch::PredefinedTypeIDs)Index) {
1755 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattner270d29a2009-04-27 21:45:14 +00001756 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1757 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001758
1759 case pch::PREDEF_TYPE_CHAR_U_ID:
1760 case pch::PREDEF_TYPE_CHAR_S_ID:
1761 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattner270d29a2009-04-27 21:45:14 +00001762 T = Context->CharTy;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001763 break;
1764
Chris Lattner270d29a2009-04-27 21:45:14 +00001765 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1766 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1767 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1768 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1769 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001770 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattner270d29a2009-04-27 21:45:14 +00001771 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1772 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1773 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1774 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1775 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1776 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner6cc7e412009-04-30 02:43:43 +00001777 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattner270d29a2009-04-27 21:45:14 +00001778 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1779 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1780 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1781 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1782 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl5d0ead72009-05-10 18:38:11 +00001783 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001784 }
1785
1786 assert(!T.isNull() && "Unknown predefined type");
1787 return T.getQualifiedType(Quals);
1788 }
1789
1790 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregore43f0972009-04-26 03:49:13 +00001791 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor24a224c2009-04-25 18:35:21 +00001792 if (!TypesLoaded[Index])
1793 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001794
Douglas Gregor24a224c2009-04-25 18:35:21 +00001795 return QualType(TypesLoaded[Index], Quals);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001796}
1797
Douglas Gregorac8f2802009-04-10 17:25:41 +00001798Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001799 if (ID == 0)
1800 return 0;
1801
Douglas Gregor24a224c2009-04-25 18:35:21 +00001802 if (ID > DeclsLoaded.size()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00001803 Error("declaration ID out-of-range for PCH file");
Douglas Gregor24a224c2009-04-25 18:35:21 +00001804 return 0;
1805 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001806
Douglas Gregor24a224c2009-04-25 18:35:21 +00001807 unsigned Index = ID - 1;
1808 if (!DeclsLoaded[Index])
1809 ReadDeclRecord(DeclOffsets[Index], Index);
1810
1811 return DeclsLoaded[Index];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001812}
1813
Chris Lattner77055f62009-04-27 05:46:25 +00001814/// \brief Resolve the offset of a statement into a statement.
1815///
1816/// This operation will read a new statement from the external
1817/// source each time it is called, and is meant to be used via a
1818/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1819Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner3ef21962009-04-27 05:58:23 +00001820 // Since we know tha this statement is part of a decl, make sure to use the
1821 // decl cursor to read it.
1822 DeclsCursor.JumpToBit(Offset);
1823 return ReadStmt(DeclsCursor);
Douglas Gregor3b9a7c82009-04-18 00:07:54 +00001824}
1825
Douglas Gregorc34897d2009-04-09 22:27:44 +00001826bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001827 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001828 assert(DC->hasExternalLexicalStorage() &&
1829 "DeclContext has no lexical decls in storage");
1830 uint64_t Offset = DeclContextOffsets[DC].first;
1831 assert(Offset && "DeclContext has no lexical decls in storage");
1832
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001833 // Keep track of where we are in the stream, then jump back there
1834 // after reading this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001835 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001836
Douglas Gregorc34897d2009-04-09 22:27:44 +00001837 // Load the record containing all of the declarations lexically in
1838 // this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001839 DeclsCursor.JumpToBit(Offset);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001840 RecordData Record;
Chris Lattner85e3f642009-04-27 07:35:40 +00001841 unsigned Code = DeclsCursor.ReadCode();
1842 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001843 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001844 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1845
1846 // Load all of the declaration IDs
1847 Decls.clear();
1848 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregoraf136d92009-04-22 22:34:57 +00001849 ++NumLexicalDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001850 return false;
1851}
1852
1853bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattner85e3f642009-04-27 07:35:40 +00001854 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001855 assert(DC->hasExternalVisibleStorage() &&
1856 "DeclContext has no visible decls in storage");
1857 uint64_t Offset = DeclContextOffsets[DC].second;
1858 assert(Offset && "DeclContext has no visible decls in storage");
1859
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001860 // Keep track of where we are in the stream, then jump back there
1861 // after reading this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001862 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001863
Douglas Gregorc34897d2009-04-09 22:27:44 +00001864 // Load the record containing all of the declarations visible in
1865 // this context.
Chris Lattner85e3f642009-04-27 07:35:40 +00001866 DeclsCursor.JumpToBit(Offset);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001867 RecordData Record;
Chris Lattner85e3f642009-04-27 07:35:40 +00001868 unsigned Code = DeclsCursor.ReadCode();
1869 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001870 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001871 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1872 if (Record.size() == 0)
1873 return false;
1874
1875 Decls.clear();
1876
1877 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001878 while (Idx < Record.size()) {
1879 Decls.push_back(VisibleDeclaration());
1880 Decls.back().Name = ReadDeclarationName(Record, Idx);
1881
Douglas Gregorc34897d2009-04-09 22:27:44 +00001882 unsigned Size = Record[Idx++];
Chris Lattner85e3f642009-04-27 07:35:40 +00001883 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001884 LoadedDecls.reserve(Size);
1885 for (unsigned I = 0; I < Size; ++I)
1886 LoadedDecls.push_back(Record[Idx++]);
1887 }
1888
Douglas Gregoraf136d92009-04-22 22:34:57 +00001889 ++NumVisibleDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001890 return false;
1891}
1892
Douglas Gregor631f6c62009-04-14 00:24:19 +00001893void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor405b6432009-04-22 19:09:20 +00001894 this->Consumer = Consumer;
1895
Douglas Gregor631f6c62009-04-14 00:24:19 +00001896 if (!Consumer)
1897 return;
1898
1899 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1900 Decl *D = GetDecl(ExternalDefinitions[I]);
1901 DeclGroupRef DG(D);
1902 Consumer->HandleTopLevelDecl(DG);
1903 }
Douglas Gregorf93cfee2009-04-25 00:41:30 +00001904
1905 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
1906 DeclGroupRef DG(InterestingDecls[I]);
1907 Consumer->HandleTopLevelDecl(DG);
1908 }
Douglas Gregor631f6c62009-04-14 00:24:19 +00001909}
1910
Douglas Gregorc34897d2009-04-09 22:27:44 +00001911void PCHReader::PrintStats() {
1912 std::fprintf(stderr, "*** PCH Statistics:\n");
1913
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001914 unsigned NumTypesLoaded
1915 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
1916 (Type *)0);
1917 unsigned NumDeclsLoaded
1918 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
1919 (Decl *)0);
1920 unsigned NumIdentifiersLoaded
1921 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
1922 IdentifiersLoaded.end(),
1923 (IdentifierInfo *)0);
1924 unsigned NumSelectorsLoaded
1925 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
1926 SelectorsLoaded.end(),
1927 Selector());
Douglas Gregor9cf47422009-04-13 20:50:16 +00001928
Douglas Gregor6cc5d192009-04-27 18:38:38 +00001929 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
1930 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor32e231c2009-04-27 06:38:32 +00001931 if (TotalNumSLocEntries)
1932 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
1933 NumSLocEntriesRead, TotalNumSLocEntries,
1934 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor24a224c2009-04-25 18:35:21 +00001935 if (!TypesLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00001936 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00001937 NumTypesLoaded, (unsigned)TypesLoaded.size(),
1938 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
1939 if (!DeclsLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00001940 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00001941 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
1942 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001943 if (!IdentifiersLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00001944 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001945 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
1946 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor2d711832009-04-25 17:48:32 +00001947 if (TotalNumSelectors)
1948 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
1949 NumSelectorsLoaded, TotalNumSelectors,
1950 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
1951 if (TotalNumStatements)
1952 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
1953 NumStatementsRead, TotalNumStatements,
1954 ((float)NumStatementsRead/TotalNumStatements * 100));
1955 if (TotalNumMacros)
1956 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
1957 NumMacrosRead, TotalNumMacros,
1958 ((float)NumMacrosRead/TotalNumMacros * 100));
1959 if (TotalLexicalDeclContexts)
1960 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
1961 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
1962 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
1963 * 100));
1964 if (TotalVisibleDeclContexts)
1965 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
1966 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
1967 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
1968 * 100));
1969 if (TotalSelectorsInMethodPool) {
1970 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
1971 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
1972 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
1973 * 100));
1974 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
1975 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001976 std::fprintf(stderr, "\n");
1977}
1978
Douglas Gregorc713da92009-04-21 22:25:48 +00001979void PCHReader::InitializeSema(Sema &S) {
1980 SemaObj = &S;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001981 S.ExternalSource = this;
1982
Douglas Gregor2554cf22009-04-22 21:15:06 +00001983 // Makes sure any declarations that were deserialized "too early"
1984 // still get added to the identifier's declaration chains.
1985 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
1986 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
1987 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregorc713da92009-04-21 22:25:48 +00001988 }
Douglas Gregor2554cf22009-04-22 21:15:06 +00001989 PreloadedDecls.clear();
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001990
1991 // If there were any tentative definitions, deserialize them and add
1992 // them to Sema's table of tentative definitions.
1993 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
1994 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
1995 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
1996 }
Douglas Gregor062d9482009-04-22 22:18:58 +00001997
1998 // If there were any locally-scoped external declarations,
1999 // deserialize them and add them to Sema's table of locally-scoped
2000 // external declarations.
2001 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
2002 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
2003 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
2004 }
Douglas Gregorb36b20d2009-04-27 20:06:05 +00002005
2006 // If there were any ext_vector type declarations, deserialize them
2007 // and add them to Sema's vector of such declarations.
2008 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
2009 SemaObj->ExtVectorDecls.push_back(
2010 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
2011
2012 // If there were any Objective-C category implementations,
2013 // deserialize them and add them to Sema's vector of such
2014 // definitions.
2015 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
2016 SemaObj->ObjCCategoryImpls.push_back(
2017 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregorc713da92009-04-21 22:25:48 +00002018}
2019
2020IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2021 // Try to find this name within our on-disk hash table
2022 PCHIdentifierLookupTable *IdTable
2023 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2024 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2025 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2026 if (Pos == IdTable->end())
2027 return 0;
2028
2029 // Dereferencing the iterator has the effect of building the
2030 // IdentifierInfo node and populating it with the various
2031 // declarations it needs.
2032 return *Pos;
2033}
2034
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002035std::pair<ObjCMethodList, ObjCMethodList>
2036PCHReader::ReadMethodPool(Selector Sel) {
2037 if (!MethodPoolLookupTable)
2038 return std::pair<ObjCMethodList, ObjCMethodList>();
2039
2040 // Try to find this selector within our on-disk hash table.
2041 PCHMethodPoolLookupTable *PoolTable
2042 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2043 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor2d711832009-04-25 17:48:32 +00002044 if (Pos == PoolTable->end()) {
2045 ++NumMethodPoolMisses;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002046 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor2d711832009-04-25 17:48:32 +00002047 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002048
Douglas Gregor2d711832009-04-25 17:48:32 +00002049 ++NumMethodPoolSelectorsRead;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00002050 return *Pos;
2051}
2052
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002053void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregorc713da92009-04-21 22:25:48 +00002054 assert(ID && "Non-zero identifier ID required");
Douglas Gregoreae710d2009-04-28 21:53:25 +00002055 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002056 IdentifiersLoaded[ID - 1] = II;
Douglas Gregorc713da92009-04-21 22:25:48 +00002057}
2058
Chris Lattner29241862009-04-11 21:15:38 +00002059IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002060 if (ID == 0)
2061 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00002062
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002063 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00002064 Error("no identifier table in PCH file");
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002065 return 0;
2066 }
Chris Lattner29241862009-04-11 21:15:38 +00002067
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002068 if (!IdentifiersLoaded[ID - 1]) {
2069 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00002070 const char *Str = IdentifierTableData + Offset;
Douglas Gregor85c4a872009-04-25 21:04:17 +00002071
Douglas Gregor68619772009-04-28 20:01:51 +00002072 // All of the strings in the PCH file are preceded by a 16-bit
2073 // length. Extract that 16-bit length to avoid having to execute
2074 // strlen().
2075 const char *StrLenPtr = Str - 2;
2076 unsigned StrLen = (((unsigned) StrLenPtr[0])
2077 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2078 IdentifiersLoaded[ID - 1]
2079 = &PP.getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregor7a224cf2009-04-11 00:14:32 +00002080 }
Chris Lattner29241862009-04-11 21:15:38 +00002081
Douglas Gregorde44c9f2009-04-25 19:10:14 +00002082 return IdentifiersLoaded[ID - 1];
Douglas Gregorc34897d2009-04-09 22:27:44 +00002083}
2084
Douglas Gregor32e231c2009-04-27 06:38:32 +00002085void PCHReader::ReadSLocEntry(unsigned ID) {
2086 ReadSLocEntryRecord(ID);
2087}
2088
Steve Naroff9e84d782009-04-23 10:39:46 +00002089Selector PCHReader::DecodeSelector(unsigned ID) {
2090 if (ID == 0)
2091 return Selector();
2092
Douglas Gregoreae710d2009-04-28 21:53:25 +00002093 if (!MethodPoolLookupTableData)
Steve Naroff9e84d782009-04-23 10:39:46 +00002094 return Selector();
Douglas Gregor2d711832009-04-25 17:48:32 +00002095
2096 if (ID > TotalNumSelectors) {
Douglas Gregoreae710d2009-04-28 21:53:25 +00002097 Error("selector ID out of range in PCH file");
Steve Naroff9e84d782009-04-23 10:39:46 +00002098 return Selector();
2099 }
Douglas Gregor2d711832009-04-25 17:48:32 +00002100
2101 unsigned Index = ID - 1;
2102 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2103 // Load this selector from the selector table.
2104 // FIXME: endianness portability issues with SelectorOffsets table
2105 PCHMethodPoolLookupTrait Trait(*this);
2106 SelectorsLoaded[Index]
2107 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2108 }
2109
2110 return SelectorsLoaded[Index];
Steve Naroff9e84d782009-04-23 10:39:46 +00002111}
2112
Douglas Gregorc34897d2009-04-09 22:27:44 +00002113DeclarationName
2114PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2115 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2116 switch (Kind) {
2117 case DeclarationName::Identifier:
2118 return DeclarationName(GetIdentifierInfo(Record, Idx));
2119
2120 case DeclarationName::ObjCZeroArgSelector:
2121 case DeclarationName::ObjCOneArgSelector:
2122 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff104956f2009-04-23 15:15:40 +00002123 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregorc34897d2009-04-09 22:27:44 +00002124
2125 case DeclarationName::CXXConstructorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002126 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002127 GetType(Record[Idx++]));
2128
2129 case DeclarationName::CXXDestructorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002130 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002131 GetType(Record[Idx++]));
2132
2133 case DeclarationName::CXXConversionFunctionName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002134 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002135 GetType(Record[Idx++]));
2136
2137 case DeclarationName::CXXOperatorName:
Chris Lattner270d29a2009-04-27 21:45:14 +00002138 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregorc34897d2009-04-09 22:27:44 +00002139 (OverloadedOperatorKind)Record[Idx++]);
2140
2141 case DeclarationName::CXXUsingDirective:
2142 return DeclarationName::getUsingDirectiveName();
2143 }
2144
2145 // Required to silence GCC warning
2146 return DeclarationName();
2147}
Douglas Gregor179cfb12009-04-10 20:39:37 +00002148
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00002149/// \brief Read an integral value
2150llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2151 unsigned BitWidth = Record[Idx++];
2152 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2153 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2154 Idx += NumWords;
2155 return Result;
2156}
2157
2158/// \brief Read a signed integral value
2159llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2160 bool isUnsigned = Record[Idx++];
2161 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2162}
2163
Douglas Gregore2f37202009-04-14 21:55:33 +00002164/// \brief Read a floating-point value
2165llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00002166 return llvm::APFloat(ReadAPInt(Record, Idx));
2167}
2168
Douglas Gregor1c507882009-04-15 21:30:51 +00002169// \brief Read a string
2170std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2171 unsigned Len = Record[Idx++];
Jay Foad9e6bef42009-05-21 09:52:38 +00002172 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
Douglas Gregor1c507882009-04-15 21:30:51 +00002173 Idx += Len;
2174 return Result;
2175}
2176
Douglas Gregor179cfb12009-04-10 20:39:37 +00002177DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002178 return Diag(SourceLocation(), DiagID);
2179}
2180
2181DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2182 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Chris Lattner270d29a2009-04-27 21:45:14 +00002183 PP.getSourceManager()),
Douglas Gregor179cfb12009-04-10 20:39:37 +00002184 DiagID);
2185}
Douglas Gregor9c4782a2009-04-17 00:04:06 +00002186
Douglas Gregorc713da92009-04-21 22:25:48 +00002187/// \brief Retrieve the identifier table associated with the
2188/// preprocessor.
2189IdentifierTable &PCHReader::getIdentifierTable() {
2190 return PP.getIdentifierTable();
2191}
2192
Douglas Gregor9c4782a2009-04-17 00:04:06 +00002193/// \brief Record that the given ID maps to the given switch-case
2194/// statement.
2195void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2196 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2197 SwitchCaseStmts[ID] = SC;
2198}
2199
2200/// \brief Retrieve the switch-case statement with the given ID.
2201SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2202 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2203 return SwitchCaseStmts[ID];
2204}
Douglas Gregor6e411bf2009-04-17 18:18:49 +00002205
2206/// \brief Record that the given label statement has been
2207/// deserialized and has the given ID.
2208void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2209 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2210 "Deserialized label twice");
2211 LabelStmts[ID] = S;
2212
2213 // If we've already seen any goto statements that point to this
2214 // label, resolve them now.
2215 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2216 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2217 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2218 Goto->second->setLabel(S);
2219 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor95a8fe32009-04-17 18:58:21 +00002220
2221 // If we've already seen any address-label statements that point to
2222 // this label, resolve them now.
2223 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2224 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2225 = UnresolvedAddrLabelExprs.equal_range(ID);
2226 for (AddrLabelIter AddrLabel = AddrLabels.first;
2227 AddrLabel != AddrLabels.second; ++AddrLabel)
2228 AddrLabel->second->setLabel(S);
2229 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6e411bf2009-04-17 18:18:49 +00002230}
2231
2232/// \brief Set the label of the given statement to the label
2233/// identified by ID.
2234///
2235/// Depending on the order in which the label and other statements
2236/// referencing that label occur, this operation may complete
2237/// immediately (updating the statement) or it may queue the
2238/// statement to be back-patched later.
2239void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2240 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2241 if (Label != LabelStmts.end()) {
2242 // We've already seen this label, so set the label of the goto and
2243 // we're done.
2244 S->setLabel(Label->second);
2245 } else {
2246 // We haven't seen this label yet, so add this goto to the set of
2247 // unresolved goto statements.
2248 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2249 }
2250}
Douglas Gregor95a8fe32009-04-17 18:58:21 +00002251
2252/// \brief Set the label of the given expression to the label
2253/// identified by ID.
2254///
2255/// Depending on the order in which the label and other statements
2256/// referencing that label occur, this operation may complete
2257/// immediately (updating the statement) or it may queue the
2258/// statement to be back-patched later.
2259void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2260 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2261 if (Label != LabelStmts.end()) {
2262 // We've already seen this label, so set the label of the
2263 // label-address expression and we're done.
2264 S->setLabel(Label->second);
2265 } else {
2266 // We haven't seen this label yet, so add this label-address
2267 // expression to the set of unresolved label-address expressions.
2268 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2269 }
2270}