blob: 25415bb368eaa7b7876a2e645f87b757dc901fd3 [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000029#include "llvm/Bitcode/BitstreamReader.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +000039// PCH reader implementation
40//===----------------------------------------------------------------------===//
41
Chris Lattnerd1d64a02009-04-27 21:45:14 +000042PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context)
Chris Lattner4c6f9522009-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 Gregor4fed3f42009-04-27 18:38:38 +000048 TotalNumSelectors(0), NumStatHits(0), NumStatMisses(0),
49 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +000050 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +000051 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
52
53PCHReader::~PCHReader() {}
54
Chris Lattnerda930612009-04-27 05:58:23 +000055Expr *PCHReader::ReadDeclExpr() {
56 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
57}
58
59Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +000060 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +000061}
62
63
Douglas Gregor668c1a42009-04-21 22:25:48 +000064namespace {
Douglas Gregorf0aaf7a2009-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 Gregor83941df2009-04-25 17:48:32 +0000104 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000105 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000106 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-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
120 return SelTable.getSelector(N, &Args[0]);
121 }
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 Gregor668c1a42009-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 Gregor5f8e3302009-04-25 20:26:24 +0000208 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000209 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-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 Gregora92193e2009-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 Gregor5998da52009-04-28 21:32:13 +0000240 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-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 Gregora92193e2009-04-28 21:18:29 +0000251
Douglas Gregor2deaea32009-04-22 18:49:13 +0000252 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000253 DataLen -= 6;
Douglas Gregor668c1a42009-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 Gregor5f8e3302009-04-25 20:26:24 +0000259 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
260 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000261 Reader.SetIdentifierInfo(ID, II);
262
Douglas Gregor2deaea32009-04-22 18:49:13 +0000263 // Set or check the various bits in the IdentifierInfo structure.
264 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-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 Gregor37e26842009-04-21 23:56:24 +0000274 // If this identifier is a macro, deserialize the macro
275 // definition.
276 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000277 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000278 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000279 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000280 }
Douglas Gregor668c1a42009-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 Lattner6bf690f2009-04-27 22:17:41 +0000285 if (Reader.getContext() == 0) return II;
Chris Lattnercc7dea82009-04-27 22:02:30 +0000286
Douglas Gregor668c1a42009-04-21 22:25:48 +0000287 while (DataLen > 0) {
288 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregor668c1a42009-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 Gregor6cfc1a82009-04-22 21:15:06 +0000299 Reader.PreloadedDecls.push_back(D);
Douglas Gregor668c1a42009-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 Gregor2cf26342009-04-09 22:27:44 +0000315// FIXME: use the diagnostics machinery
Douglas Gregora02b1472009-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 Gregor2cf26342009-04-09 22:27:44 +0000320 return true;
321}
322
Douglas Gregore721f952009-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 Gregore1d918e2009-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 Gregore721f952009-04-28 18:58:38 +0000387 // If the two predefines buffers compare equal, we're done!
Douglas Gregore1d918e2009-04-10 23:10:45 +0000388 if (PredefLen == PCHPredefLen &&
389 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
390 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000391
Douglas Gregore1d918e2009-04-10 23:10:45 +0000392 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregore721f952009-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 Gregore1d918e2009-04-10 23:10:45 +0000399
Douglas Gregore721f952009-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 Gregore1d918e2009-04-10 23:10:45 +0000403
Douglas Gregore721f952009-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 Gregoraf1795b2009-04-28 20:36:16 +0000416 Diag(diag::warn_pch_compiler_options_mismatch);
Douglas Gregore721f952009-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 Gregore1d918e2009-04-10 23:10:45 +0000489 }
490
Douglas Gregor1ab86ac2009-04-28 22:01:16 +0000491 if (ConflictingDefines)
Douglas Gregore721f952009-04-28 18:58:38 +0000492 return true;
Douglas Gregore721f952009-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 Gregoraf1795b2009-04-28 20:36:16 +0000505 Diag(diag::warn_pch_compiler_options_mismatch);
Douglas Gregore721f952009-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 Gregor92b059e2009-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 Gregor92b059e2009-04-28 20:33:11 +0000526 return true;
527 }
Douglas Gregore721f952009-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 Gregore1d918e2009-04-10 23:10:45 +0000537}
538
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000539//===----------------------------------------------------------------------===//
540// Source Manager Deserialization
541//===----------------------------------------------------------------------===//
542
Douglas Gregorbd945002009-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 Gregorff0a9872009-04-13 17:12:42 +0000551 std::map<int, int> FileIDs;
552 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-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 Gregorff0a9872009-04-13 17:12:42 +0000557 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
558 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000559 }
560
561 // Parse the line entries
562 std::vector<LineEntry> Entries;
563 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000564 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-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 Gregor4fed3f42009-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 Gregor14f79002009-04-10 03:52:48 +0000695/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000696PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000697 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-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 Gregora02b1472009-04-28 21:53:25 +0000707 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-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 Gregora02b1472009-04-28 21:53:25 +0000713 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000714 return Failure;
715 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000716
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000717 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor14f79002009-04-10 03:52:48 +0000718 RecordData Record;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000719 unsigned NumHeaderInfos = 0;
Douglas Gregor14f79002009-04-10 03:52:48 +0000720 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000721 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000722 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000723 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000724 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000725 return Failure;
726 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000727 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000728 }
729
730 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
731 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000732 SLocEntryCursor.ReadSubBlockID();
733 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000734 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000735 return Failure;
736 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000737 continue;
738 }
739
740 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000741 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000742 continue;
743 }
744
745 // Read a record.
746 const char *BlobStart;
747 unsigned BlobLen;
748 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000749 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000750 default: // Default behavior: ignore.
751 break;
752
Chris Lattner2c78b872009-04-14 23:22:57 +0000753 case pch::SM_LINE_TABLE:
Douglas Gregorbd945002009-04-13 16:31:14 +0000754 if (ParseLineTable(SourceMgr, Record))
755 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000756 break;
Douglas Gregor2eafc1b2009-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 Gregor7f94b0b2009-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 Gregor14f79002009-04-10 03:52:48 +0000773 }
774 }
775}
776
Douglas Gregor7f94b0b2009-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 Lattnerd1d64a02009-04-27 21:45:14 +0000797 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor7f94b0b2009-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: {
807 const FileEntry *File
808 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
809 // FIXME: Error recovery if file cannot be found.
810 FileID FID = SourceMgr.createFileID(File,
811 SourceLocation::getFromRawEncoding(Record[1]),
812 (SrcMgr::CharacteristicKind)Record[2],
813 ID, Record[0]);
814 if (Record[3])
815 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
816 .setHasLineDirectives();
817
818 break;
819 }
820
821 case pch::SM_SLOC_BUFFER_ENTRY: {
822 const char *Name = BlobStart;
823 unsigned Offset = Record[0];
824 unsigned Code = SLocEntryCursor.ReadCode();
825 Record.clear();
826 unsigned RecCode
827 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
828 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
829 (void)RecCode;
830 llvm::MemoryBuffer *Buffer
831 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
832 BlobStart + BlobLen - 1,
833 Name);
834 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
835
Douglas Gregor92b059e2009-04-28 20:33:11 +0000836 if (strcmp(Name, "<built-in>") == 0) {
837 PCHPredefinesBufferID = BufferID;
838 PCHPredefines = BlobStart;
839 PCHPredefinesLen = BlobLen - 1;
840 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000841
842 break;
843 }
844
845 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
846 SourceLocation SpellingLoc
847 = SourceLocation::getFromRawEncoding(Record[1]);
848 SourceMgr.createInstantiationLoc(SpellingLoc,
849 SourceLocation::getFromRawEncoding(Record[2]),
850 SourceLocation::getFromRawEncoding(Record[3]),
851 Record[4],
852 ID,
853 Record[0]);
854 break;
855 }
856 }
857
858 return Success;
859}
860
Chris Lattner6367f6d2009-04-27 01:05:14 +0000861/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
862/// specified cursor. Read the abbreviations that are at the top of the block
863/// and then leave the cursor pointing into the block.
864bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
865 unsigned BlockID) {
866 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000867 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000868 return Failure;
869 }
870
Chris Lattner6367f6d2009-04-27 01:05:14 +0000871 while (true) {
872 unsigned Code = Cursor.ReadCode();
873
874 // We expect all abbrevs to be at the start of the block.
875 if (Code != llvm::bitc::DEFINE_ABBREV)
876 return false;
877 Cursor.ReadAbbrevRecord();
878 }
879}
880
Douglas Gregor37e26842009-04-21 23:56:24 +0000881void PCHReader::ReadMacroRecord(uint64_t Offset) {
882 // Keep track of where we are in the stream, then jump back there
883 // after reading this macro.
884 SavedStreamPosition SavedPosition(Stream);
885
886 Stream.JumpToBit(Offset);
887 RecordData Record;
888 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
889 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +0000890
Douglas Gregor37e26842009-04-21 23:56:24 +0000891 while (true) {
892 unsigned Code = Stream.ReadCode();
893 switch (Code) {
894 case llvm::bitc::END_BLOCK:
895 return;
896
897 case llvm::bitc::ENTER_SUBBLOCK:
898 // No known subblocks, always skip them.
899 Stream.ReadSubBlockID();
900 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000901 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +0000902 return;
903 }
904 continue;
905
906 case llvm::bitc::DEFINE_ABBREV:
907 Stream.ReadAbbrevRecord();
908 continue;
909 default: break;
910 }
911
912 // Read a record.
913 Record.clear();
914 pch::PreprocessorRecordTypes RecType =
915 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
916 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +0000917 case pch::PP_MACRO_OBJECT_LIKE:
918 case pch::PP_MACRO_FUNCTION_LIKE: {
919 // If we already have a macro, that means that we've hit the end
920 // of the definition of the macro we were looking for. We're
921 // done.
922 if (Macro)
923 return;
924
925 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
926 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000927 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +0000928 return;
929 }
930 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
931 bool isUsed = Record[2];
932
933 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
934 MI->setIsUsed(isUsed);
935
936 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
937 // Decode function-like macro info.
938 bool isC99VarArgs = Record[3];
939 bool isGNUVarArgs = Record[4];
940 MacroArgs.clear();
941 unsigned NumArgs = Record[5];
942 for (unsigned i = 0; i != NumArgs; ++i)
943 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
944
945 // Install function-like macro info.
946 MI->setIsFunctionLike();
947 if (isC99VarArgs) MI->setIsC99Varargs();
948 if (isGNUVarArgs) MI->setIsGNUVarargs();
949 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
950 PP.getPreprocessorAllocator());
951 }
952
953 // Finally, install the macro.
954 PP.setMacroInfo(II, MI);
955
956 // Remember that we saw this macro last so that we add the tokens that
957 // form its body to it.
958 Macro = MI;
959 ++NumMacrosRead;
960 break;
961 }
962
963 case pch::PP_TOKEN: {
964 // If we see a TOKEN before a PP_MACRO_*, then the file is
965 // erroneous, just pretend we didn't see this.
966 if (Macro == 0) break;
967
968 Token Tok;
969 Tok.startToken();
970 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
971 Tok.setLength(Record[1]);
972 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
973 Tok.setIdentifierInfo(II);
974 Tok.setKind((tok::TokenKind)Record[3]);
975 Tok.setFlag((Token::TokenFlags)Record[4]);
976 Macro->AddTokenToBody(Tok);
977 break;
978 }
Steve Naroff83d63c72009-04-24 20:03:17 +0000979 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000980 }
981}
982
Douglas Gregor668c1a42009-04-21 22:25:48 +0000983PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000984PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000985 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000986 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000987 return Failure;
988 }
Douglas Gregor2cf26342009-04-09 22:27:44 +0000989
990 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +0000991 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000992 while (!Stream.AtEndOfStream()) {
993 unsigned Code = Stream.ReadCode();
994 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000995 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000996 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000997 return Failure;
998 }
Chris Lattner7356a312009-04-11 21:15:38 +0000999
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001000 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001001 }
1002
1003 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1004 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001005 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1006 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001007 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001008 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001009 return Failure;
1010 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001011 break;
1012
Chris Lattner6367f6d2009-04-27 01:05:14 +00001013 case pch::DECLS_BLOCK_ID:
1014 // We lazily load the decls block, but we want to set up the
1015 // DeclsCursor cursor to point into it. Clone our current bitcode
1016 // cursor to it, enter the block and read the abbrevs in that block.
1017 // With the main cursor, we just skip over it.
1018 DeclsCursor = Stream;
1019 if (Stream.SkipBlock() || // Skip with the main cursor.
1020 // Read the abbrevs.
1021 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001022 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001023 return Failure;
1024 }
1025 break;
1026
Chris Lattner7356a312009-04-11 21:15:38 +00001027 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001028 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001029 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001030 return Failure;
1031 }
1032 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001033
Douglas Gregor14f79002009-04-10 03:52:48 +00001034 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001035 switch (ReadSourceManagerBlock()) {
1036 case Success:
1037 break;
1038
1039 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001040 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001041 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001042
1043 case IgnorePCH:
1044 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001045 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001046 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001047 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001048 continue;
1049 }
1050
1051 if (Code == llvm::bitc::DEFINE_ABBREV) {
1052 Stream.ReadAbbrevRecord();
1053 continue;
1054 }
1055
1056 // Read and process a record.
1057 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001058 const char *BlobStart = 0;
1059 unsigned BlobLen = 0;
1060 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1061 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001062 default: // Default behavior: ignore.
1063 break;
1064
1065 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001066 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001067 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001068 return Failure;
1069 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001070 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001071 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001072 break;
1073
1074 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001075 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001076 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001077 return Failure;
1078 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001079 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001080 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001081 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001082
1083 case pch::LANGUAGE_OPTIONS:
1084 if (ParseLanguageOptions(Record))
1085 return IgnorePCH;
1086 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001087
Douglas Gregorab41e632009-04-27 22:23:34 +00001088 case pch::METADATA: {
1089 if (Record[0] != pch::VERSION_MAJOR) {
1090 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1091 : diag::warn_pch_version_too_new);
1092 return IgnorePCH;
1093 }
1094
Douglas Gregor2bec0412009-04-10 21:16:55 +00001095 std::string TargetTriple(BlobStart, BlobLen);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001096 if (TargetTriple != PP.getTargetInfo().getTargetTriple()) {
Douglas Gregor2bec0412009-04-10 21:16:55 +00001097 Diag(diag::warn_pch_target_triple)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001098 << TargetTriple << PP.getTargetInfo().getTargetTriple();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001099 return IgnorePCH;
1100 }
1101 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001102 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001103
1104 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001105 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001106 if (Record[0]) {
1107 IdentifierLookupTable
1108 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001109 (const unsigned char *)IdentifierTableData + Record[0],
1110 (const unsigned char *)IdentifierTableData,
1111 PCHIdentifierLookupTrait(*this));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001112 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1113 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001114 break;
1115
1116 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001117 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001118 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001119 return Failure;
1120 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001121 IdentifierOffsets = (const uint32_t *)BlobStart;
1122 IdentifiersLoaded.resize(Record[0]);
Douglas Gregor8c5a7602009-04-25 23:30:02 +00001123 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001124 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001125
1126 case pch::EXTERNAL_DEFINITIONS:
1127 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001128 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001129 return Failure;
1130 }
1131 ExternalDefinitions.swap(Record);
1132 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001133
Douglas Gregorad1de002009-04-18 05:55:16 +00001134 case pch::SPECIAL_TYPES:
1135 SpecialTypes.swap(Record);
1136 break;
1137
Douglas Gregor3e1af842009-04-17 22:13:46 +00001138 case pch::STATISTICS:
1139 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001140 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001141 TotalLexicalDeclContexts = Record[2];
1142 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001143 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001144
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001145 case pch::TENTATIVE_DEFINITIONS:
1146 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001147 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001148 return Failure;
1149 }
1150 TentativeDefinitions.swap(Record);
1151 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001152
1153 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1154 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001155 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001156 return Failure;
1157 }
1158 LocallyScopedExternalDecls.swap(Record);
1159 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001160
Douglas Gregor83941df2009-04-25 17:48:32 +00001161 case pch::SELECTOR_OFFSETS:
1162 SelectorOffsets = (const uint32_t *)BlobStart;
1163 TotalNumSelectors = Record[0];
1164 SelectorsLoaded.resize(TotalNumSelectors);
1165 break;
1166
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001167 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001168 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1169 if (Record[0])
1170 MethodPoolLookupTable
1171 = PCHMethodPoolLookupTable::Create(
1172 MethodPoolLookupTableData + Record[0],
1173 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001174 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001175 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001176 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001177
1178 case pch::PP_COUNTER_VALUE:
1179 if (!Record.empty())
1180 PP.setCounterValue(Record[0]);
1181 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001182
1183 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001184 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001185 TotalNumSLocEntries = Record[0];
1186 PP.getSourceManager().PreallocateSLocEntries(this,
1187 TotalNumSLocEntries,
1188 Record[1]);
1189 break;
1190
1191 case pch::SOURCE_LOCATION_PRELOADS:
1192 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1193 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1194 if (Result != Success)
1195 return Result;
1196 }
1197 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001198
1199 case pch::STAT_CACHE:
1200 PP.getFileManager().setStatCache(
1201 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1202 (const unsigned char *)BlobStart,
1203 NumStatHits, NumStatMisses));
1204 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001205
1206 case pch::EXT_VECTOR_DECLS:
1207 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001208 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001209 return Failure;
1210 }
1211 ExtVectorDecls.swap(Record);
1212 break;
1213
1214 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1215 if (!ObjCCategoryImpls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001216 Error("duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001217 return Failure;
1218 }
1219 ObjCCategoryImpls.swap(Record);
1220 break;
Douglas Gregorb64c1932009-05-12 01:31:05 +00001221
1222 case pch::ORIGINAL_FILE_NAME:
1223 OriginalFileName.assign(BlobStart, BlobLen);
1224 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001225 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001226 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001227 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001228 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001229}
1230
Douglas Gregore1d918e2009-04-10 23:10:45 +00001231PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001232 // Set the PCH file name.
1233 this->FileName = FileName;
1234
Douglas Gregor2cf26342009-04-09 22:27:44 +00001235 // Open the PCH file.
1236 std::string ErrStr;
1237 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001238 if (!Buffer) {
1239 Error(ErrStr.c_str());
1240 return IgnorePCH;
1241 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001242
1243 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001244 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1245 (const unsigned char *)Buffer->getBufferEnd());
1246 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001247
1248 // Sniff for the signature.
1249 if (Stream.Read(8) != 'C' ||
1250 Stream.Read(8) != 'P' ||
1251 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001252 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001253 Diag(diag::err_not_a_pch_file) << FileName;
1254 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001255 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001256
Douglas Gregor2cf26342009-04-09 22:27:44 +00001257 while (!Stream.AtEndOfStream()) {
1258 unsigned Code = Stream.ReadCode();
1259
Douglas Gregore1d918e2009-04-10 23:10:45 +00001260 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001261 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001262 return Failure;
1263 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001264
1265 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001266
Douglas Gregor2cf26342009-04-09 22:27:44 +00001267 // We only know the PCH subblock ID.
1268 switch (BlockID) {
1269 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001270 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001271 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001272 return Failure;
1273 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001274 break;
1275 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001276 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001277 case Success:
1278 break;
1279
1280 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001281 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001282
1283 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001284 // FIXME: We could consider reading through to the end of this
1285 // PCH block, skipping subblocks, to see if there are other
1286 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001287
1288 // Clear out any preallocated source location entries, so that
1289 // the source manager does not try to resolve them later.
1290 PP.getSourceManager().ClearPreallocatedSLocEntries();
1291
1292 // Remove the stat cache.
1293 PP.getFileManager().setStatCache(0);
1294
Douglas Gregore1d918e2009-04-10 23:10:45 +00001295 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001296 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001297 break;
1298 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001299 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001300 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001301 return Failure;
1302 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001303 break;
1304 }
1305 }
1306
1307 // Load the translation unit declaration
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001308 if (Context)
1309 ReadDeclRecord(DeclOffsets[0], 0);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001310
1311 // Check the predefines buffer.
1312 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1313 PCHPredefinesBufferID))
1314 return IgnorePCH;
1315
Douglas Gregor668c1a42009-04-21 22:25:48 +00001316 // Initialization of builtins and library builtins occurs before the
1317 // PCH file is read, so there may be some identifiers that were
1318 // loaded into the IdentifierTable before we intercepted the
1319 // creation of identifiers. Iterate through the list of known
1320 // identifiers and determine whether we have to establish
1321 // preprocessor definitions or top-level identifier declaration
1322 // chains for those identifiers.
1323 //
1324 // We copy the IdentifierInfo pointers to a small vector first,
1325 // since de-serializing declarations or macro definitions can add
1326 // new entries into the identifier table, invalidating the
1327 // iterators.
1328 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1329 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
1330 IdEnd = PP.getIdentifierTable().end();
1331 Id != IdEnd; ++Id)
1332 Identifiers.push_back(Id->second);
1333 PCHIdentifierLookupTable *IdTable
1334 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1335 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1336 IdentifierInfo *II = Identifiers[I];
1337 // Look in the on-disk hash table for an entry for
1338 PCHIdentifierLookupTrait Info(*this, II);
1339 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1340 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1341 if (Pos == IdTable->end())
1342 continue;
1343
1344 // Dereferencing the iterator has the effect of populating the
1345 // IdentifierInfo node with the various declarations it needs.
1346 (void)*Pos;
1347 }
1348
Douglas Gregorad1de002009-04-18 05:55:16 +00001349 // Load the special types.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001350 if (Context) {
1351 Context->setBuiltinVaListType(
1352 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1353 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1354 Context->setObjCIdType(GetType(Id));
1355 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1356 Context->setObjCSelType(GetType(Sel));
1357 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1358 Context->setObjCProtoType(GetType(Proto));
1359 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1360 Context->setObjCClassType(GetType(Class));
1361 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1362 Context->setCFConstantStringType(GetType(String));
1363 if (unsigned FastEnum
1364 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1365 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1366 }
Douglas Gregor0b748912009-04-14 21:18:50 +00001367
Douglas Gregor668c1a42009-04-21 22:25:48 +00001368 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001369}
1370
Douglas Gregorb64c1932009-05-12 01:31:05 +00001371/// \brief Retrieve the name of the original source file name
1372/// directly from the PCH file, without actually loading the PCH
1373/// file.
1374std::string PCHReader::getOriginalSourceFile(const std::string &PCHFileName) {
1375 // Open the PCH file.
1376 std::string ErrStr;
1377 llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
1378 Buffer.reset(llvm::MemoryBuffer::getFile(PCHFileName.c_str(), &ErrStr));
1379 if (!Buffer) {
1380 fprintf(stderr, "error: %s\n", ErrStr.c_str());
1381 return std::string();
1382 }
1383
1384 // Initialize the stream
1385 llvm::BitstreamReader StreamFile;
1386 llvm::BitstreamCursor Stream;
1387 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1388 (const unsigned char *)Buffer->getBufferEnd());
1389 Stream.init(StreamFile);
1390
1391 // Sniff for the signature.
1392 if (Stream.Read(8) != 'C' ||
1393 Stream.Read(8) != 'P' ||
1394 Stream.Read(8) != 'C' ||
1395 Stream.Read(8) != 'H') {
1396 fprintf(stderr,
1397 "error: '%s' does not appear to be a precompiled header file\n",
1398 PCHFileName.c_str());
1399 return std::string();
1400 }
1401
1402 RecordData Record;
1403 while (!Stream.AtEndOfStream()) {
1404 unsigned Code = Stream.ReadCode();
1405
1406 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1407 unsigned BlockID = Stream.ReadSubBlockID();
1408
1409 // We only know the PCH subblock ID.
1410 switch (BlockID) {
1411 case pch::PCH_BLOCK_ID:
1412 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
1413 fprintf(stderr, "error: malformed block record in PCH file\n");
1414 return std::string();
1415 }
1416 break;
1417
1418 default:
1419 if (Stream.SkipBlock()) {
1420 fprintf(stderr, "error: malformed block record in PCH file\n");
1421 return std::string();
1422 }
1423 break;
1424 }
1425 continue;
1426 }
1427
1428 if (Code == llvm::bitc::END_BLOCK) {
1429 if (Stream.ReadBlockEnd()) {
1430 fprintf(stderr, "error: error at end of module block in PCH file\n");
1431 return std::string();
1432 }
1433 continue;
1434 }
1435
1436 if (Code == llvm::bitc::DEFINE_ABBREV) {
1437 Stream.ReadAbbrevRecord();
1438 continue;
1439 }
1440
1441 Record.clear();
1442 const char *BlobStart = 0;
1443 unsigned BlobLen = 0;
1444 if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
1445 == pch::ORIGINAL_FILE_NAME)
1446 return std::string(BlobStart, BlobLen);
1447 }
1448
1449 return std::string();
1450}
1451
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001452/// \brief Parse the record that corresponds to a LangOptions data
1453/// structure.
1454///
1455/// This routine compares the language options used to generate the
1456/// PCH file against the language options set for the current
1457/// compilation. For each option, we classify differences between the
1458/// two compiler states as either "benign" or "important". Benign
1459/// differences don't matter, and we accept them without complaint
1460/// (and without modifying the language options). Differences between
1461/// the states for important options cause the PCH file to be
1462/// unusable, so we emit a warning and return true to indicate that
1463/// there was an error.
1464///
1465/// \returns true if the PCH file is unacceptable, false otherwise.
1466bool PCHReader::ParseLanguageOptions(
1467 const llvm::SmallVectorImpl<uint64_t> &Record) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001468 const LangOptions &LangOpts = PP.getLangOptions();
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001469#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1470#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1471 if (Record[Idx] != LangOpts.Option) { \
1472 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001473 return true; \
1474 } \
1475 ++Idx
1476
1477 unsigned Idx = 0;
1478 PARSE_LANGOPT_BENIGN(Trigraphs);
1479 PARSE_LANGOPT_BENIGN(BCPLComment);
1480 PARSE_LANGOPT_BENIGN(DollarIdents);
1481 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1482 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1483 PARSE_LANGOPT_BENIGN(ImplicitInt);
1484 PARSE_LANGOPT_BENIGN(Digraphs);
1485 PARSE_LANGOPT_BENIGN(HexFloats);
1486 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1487 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1488 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1489 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001490 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1491 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1492 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1493 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1494 PARSE_LANGOPT_BENIGN(PascalStrings);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001495 PARSE_LANGOPT_BENIGN(WritableStrings);
1496 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1497 diag::warn_pch_lax_vector_conversions);
1498 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1499 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1500 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1501 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1502 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1503 diag::warn_pch_thread_safe_statics);
1504 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1505 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1506 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1507 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1508 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1509 diag::warn_pch_heinous_extensions);
1510 // FIXME: Most of the options below are benign if the macro wasn't
1511 // used. Unfortunately, this means that a PCH compiled without
1512 // optimization can't be used with optimization turned on, even
1513 // though the only thing that changes is whether __OPTIMIZE__ was
1514 // defined... but if __OPTIMIZE__ never showed up in the header, it
1515 // doesn't matter. We could consider making this some special kind
1516 // of check.
1517 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1518 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1519 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1520 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1521 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1522 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
Anders Carlssona33d9b42009-05-13 19:49:53 +00001523 PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001524 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1525 Diag(diag::warn_pch_gc_mode)
1526 << (unsigned)Record[Idx] << LangOpts.getGCMode();
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001527 return true;
1528 }
1529 ++Idx;
1530 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1531 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1532#undef PARSE_LANGOPT_IRRELEVANT
1533#undef PARSE_LANGOPT_BENIGN
1534
1535 return false;
1536}
1537
Douglas Gregor2cf26342009-04-09 22:27:44 +00001538/// \brief Read and return the type at the given offset.
1539///
1540/// This routine actually reads the record corresponding to the type
1541/// at the given offset in the bitstream. It is a helper routine for
1542/// GetType, which deals with reading type IDs.
1543QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001544 // Keep track of where we are in the stream, then jump back there
1545 // after reading this type.
1546 SavedStreamPosition SavedPosition(Stream);
1547
Douglas Gregor2cf26342009-04-09 22:27:44 +00001548 Stream.JumpToBit(Offset);
1549 RecordData Record;
1550 unsigned Code = Stream.ReadCode();
1551 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001552 case pch::TYPE_EXT_QUAL: {
1553 assert(Record.size() == 3 &&
1554 "Incorrect encoding of extended qualifier type");
1555 QualType Base = GetType(Record[0]);
1556 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1557 unsigned AddressSpace = Record[2];
1558
1559 QualType T = Base;
1560 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001561 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001562 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001563 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001564 return T;
1565 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001566
Douglas Gregor2cf26342009-04-09 22:27:44 +00001567 case pch::TYPE_FIXED_WIDTH_INT: {
1568 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001569 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001570 }
1571
1572 case pch::TYPE_COMPLEX: {
1573 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1574 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001575 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001576 }
1577
1578 case pch::TYPE_POINTER: {
1579 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1580 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001581 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001582 }
1583
1584 case pch::TYPE_BLOCK_POINTER: {
1585 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1586 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001587 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001588 }
1589
1590 case pch::TYPE_LVALUE_REFERENCE: {
1591 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1592 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001593 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001594 }
1595
1596 case pch::TYPE_RVALUE_REFERENCE: {
1597 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1598 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001599 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001600 }
1601
1602 case pch::TYPE_MEMBER_POINTER: {
1603 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1604 QualType PointeeType = GetType(Record[0]);
1605 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001606 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001607 }
1608
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001609 case pch::TYPE_CONSTANT_ARRAY: {
1610 QualType ElementType = GetType(Record[0]);
1611 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1612 unsigned IndexTypeQuals = Record[2];
1613 unsigned Idx = 3;
1614 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001615 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001616 }
1617
1618 case pch::TYPE_INCOMPLETE_ARRAY: {
1619 QualType ElementType = GetType(Record[0]);
1620 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1621 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001622 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001623 }
1624
1625 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001626 QualType ElementType = GetType(Record[0]);
1627 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1628 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001629 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1630 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001631 }
1632
1633 case pch::TYPE_VECTOR: {
1634 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001635 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001636 return QualType();
1637 }
1638
1639 QualType ElementType = GetType(Record[0]);
1640 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001641 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001642 }
1643
1644 case pch::TYPE_EXT_VECTOR: {
1645 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001646 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001647 return QualType();
1648 }
1649
1650 QualType ElementType = GetType(Record[0]);
1651 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001652 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001653 }
1654
1655 case pch::TYPE_FUNCTION_NO_PROTO: {
1656 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001657 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001658 return QualType();
1659 }
1660 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001661 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001662 }
1663
1664 case pch::TYPE_FUNCTION_PROTO: {
1665 QualType ResultType = GetType(Record[0]);
1666 unsigned Idx = 1;
1667 unsigned NumParams = Record[Idx++];
1668 llvm::SmallVector<QualType, 16> ParamTypes;
1669 for (unsigned I = 0; I != NumParams; ++I)
1670 ParamTypes.push_back(GetType(Record[Idx++]));
1671 bool isVariadic = Record[Idx++];
1672 unsigned Quals = Record[Idx++];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001673 return Context->getFunctionType(ResultType, &ParamTypes[0], NumParams,
Sebastian Redlbfa2fcb2009-05-06 23:27:55 +00001674 isVariadic, Quals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001675 }
1676
1677 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001678 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001679 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001680
1681 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001682 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001683
1684 case pch::TYPE_TYPEOF: {
1685 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001686 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001687 return QualType();
1688 }
1689 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001690 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001691 }
1692
1693 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001694 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001695 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001696
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001697 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001698 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001699 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001700
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001701 case pch::TYPE_OBJC_INTERFACE:
Douglas Gregora02b1472009-04-28 21:53:25 +00001702 assert(Record.size() == 1 && "incorrect encoding of objc interface type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001703 return Context->getObjCInterfaceType(
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001704 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001705
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001706 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1707 unsigned Idx = 0;
1708 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1709 unsigned NumProtos = Record[Idx++];
1710 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1711 for (unsigned I = 0; I != NumProtos; ++I)
1712 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001713 return Context->getObjCQualifiedInterfaceType(ItfD, &Protos[0], NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001714 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001715
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001716 case pch::TYPE_OBJC_QUALIFIED_ID: {
1717 unsigned Idx = 0;
1718 unsigned NumProtos = Record[Idx++];
1719 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1720 for (unsigned I = 0; I != NumProtos; ++I)
1721 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001722 return Context->getObjCQualifiedIdType(&Protos[0], NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001723 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001724 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001725 // Suppress a GCC warning
1726 return QualType();
1727}
1728
Douglas Gregor2cf26342009-04-09 22:27:44 +00001729
Douglas Gregor8038d512009-04-10 17:25:41 +00001730QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001731 unsigned Quals = ID & 0x07;
1732 unsigned Index = ID >> 3;
1733
1734 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1735 QualType T;
1736 switch ((pch::PredefinedTypeIDs)Index) {
1737 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001738 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1739 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001740
1741 case pch::PREDEF_TYPE_CHAR_U_ID:
1742 case pch::PREDEF_TYPE_CHAR_S_ID:
1743 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001744 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001745 break;
1746
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001747 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1748 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1749 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1750 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1751 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001752 case pch::PREDEF_TYPE_UINT128_ID: T = Context->UnsignedInt128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001753 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1754 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1755 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1756 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1757 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1758 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
Chris Lattner2df9ced2009-04-30 02:43:43 +00001759 case pch::PREDEF_TYPE_INT128_ID: T = Context->Int128Ty; break;
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001760 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1761 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1762 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1763 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1764 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001765 case pch::PREDEF_TYPE_NULLPTR_ID: T = Context->NullPtrTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001766 }
1767
1768 assert(!T.isNull() && "Unknown predefined type");
1769 return T.getQualifiedType(Quals);
1770 }
1771
1772 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregor366809a2009-04-26 03:49:13 +00001773 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001774 if (!TypesLoaded[Index])
1775 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001776
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001777 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001778}
1779
Douglas Gregor8038d512009-04-10 17:25:41 +00001780Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001781 if (ID == 0)
1782 return 0;
1783
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001784 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001785 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001786 return 0;
1787 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001788
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001789 unsigned Index = ID - 1;
1790 if (!DeclsLoaded[Index])
1791 ReadDeclRecord(DeclOffsets[Index], Index);
1792
1793 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001794}
1795
Chris Lattner887e2b32009-04-27 05:46:25 +00001796/// \brief Resolve the offset of a statement into a statement.
1797///
1798/// This operation will read a new statement from the external
1799/// source each time it is called, and is meant to be used via a
1800/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1801Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00001802 // Since we know tha this statement is part of a decl, make sure to use the
1803 // decl cursor to read it.
1804 DeclsCursor.JumpToBit(Offset);
1805 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00001806}
1807
Douglas Gregor2cf26342009-04-09 22:27:44 +00001808bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00001809 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001810 assert(DC->hasExternalLexicalStorage() &&
1811 "DeclContext has no lexical decls in storage");
1812 uint64_t Offset = DeclContextOffsets[DC].first;
1813 assert(Offset && "DeclContext has no lexical decls in storage");
1814
Douglas Gregor0b748912009-04-14 21:18:50 +00001815 // Keep track of where we are in the stream, then jump back there
1816 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001817 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001818
Douglas Gregor2cf26342009-04-09 22:27:44 +00001819 // Load the record containing all of the declarations lexically in
1820 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001821 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001822 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001823 unsigned Code = DeclsCursor.ReadCode();
1824 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001825 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001826 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1827
1828 // Load all of the declaration IDs
1829 Decls.clear();
1830 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00001831 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001832 return false;
1833}
1834
1835bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001836 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001837 assert(DC->hasExternalVisibleStorage() &&
1838 "DeclContext has no visible decls in storage");
1839 uint64_t Offset = DeclContextOffsets[DC].second;
1840 assert(Offset && "DeclContext has no visible decls in storage");
1841
Douglas Gregor0b748912009-04-14 21:18:50 +00001842 // Keep track of where we are in the stream, then jump back there
1843 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001844 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001845
Douglas Gregor2cf26342009-04-09 22:27:44 +00001846 // Load the record containing all of the declarations visible in
1847 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001848 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001849 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001850 unsigned Code = DeclsCursor.ReadCode();
1851 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001852 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001853 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1854 if (Record.size() == 0)
1855 return false;
1856
1857 Decls.clear();
1858
1859 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001860 while (Idx < Record.size()) {
1861 Decls.push_back(VisibleDeclaration());
1862 Decls.back().Name = ReadDeclarationName(Record, Idx);
1863
Douglas Gregor2cf26342009-04-09 22:27:44 +00001864 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001865 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001866 LoadedDecls.reserve(Size);
1867 for (unsigned I = 0; I < Size; ++I)
1868 LoadedDecls.push_back(Record[Idx++]);
1869 }
1870
Douglas Gregor25123082009-04-22 22:34:57 +00001871 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001872 return false;
1873}
1874
Douglas Gregorfdd01722009-04-14 00:24:19 +00001875void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00001876 this->Consumer = Consumer;
1877
Douglas Gregorfdd01722009-04-14 00:24:19 +00001878 if (!Consumer)
1879 return;
1880
1881 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1882 Decl *D = GetDecl(ExternalDefinitions[I]);
1883 DeclGroupRef DG(D);
1884 Consumer->HandleTopLevelDecl(DG);
1885 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00001886
1887 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
1888 DeclGroupRef DG(InterestingDecls[I]);
1889 Consumer->HandleTopLevelDecl(DG);
1890 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00001891}
1892
Douglas Gregor2cf26342009-04-09 22:27:44 +00001893void PCHReader::PrintStats() {
1894 std::fprintf(stderr, "*** PCH Statistics:\n");
1895
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001896 unsigned NumTypesLoaded
1897 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
1898 (Type *)0);
1899 unsigned NumDeclsLoaded
1900 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
1901 (Decl *)0);
1902 unsigned NumIdentifiersLoaded
1903 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
1904 IdentifiersLoaded.end(),
1905 (IdentifierInfo *)0);
1906 unsigned NumSelectorsLoaded
1907 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
1908 SelectorsLoaded.end(),
1909 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00001910
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001911 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
1912 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001913 if (TotalNumSLocEntries)
1914 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
1915 NumSLocEntriesRead, TotalNumSLocEntries,
1916 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001917 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001918 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001919 NumTypesLoaded, (unsigned)TypesLoaded.size(),
1920 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
1921 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001922 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001923 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
1924 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001925 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001926 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001927 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
1928 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00001929 if (TotalNumSelectors)
1930 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
1931 NumSelectorsLoaded, TotalNumSelectors,
1932 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
1933 if (TotalNumStatements)
1934 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
1935 NumStatementsRead, TotalNumStatements,
1936 ((float)NumStatementsRead/TotalNumStatements * 100));
1937 if (TotalNumMacros)
1938 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
1939 NumMacrosRead, TotalNumMacros,
1940 ((float)NumMacrosRead/TotalNumMacros * 100));
1941 if (TotalLexicalDeclContexts)
1942 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
1943 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
1944 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
1945 * 100));
1946 if (TotalVisibleDeclContexts)
1947 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
1948 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
1949 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
1950 * 100));
1951 if (TotalSelectorsInMethodPool) {
1952 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
1953 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
1954 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
1955 * 100));
1956 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
1957 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001958 std::fprintf(stderr, "\n");
1959}
1960
Douglas Gregor668c1a42009-04-21 22:25:48 +00001961void PCHReader::InitializeSema(Sema &S) {
1962 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001963 S.ExternalSource = this;
1964
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001965 // Makes sure any declarations that were deserialized "too early"
1966 // still get added to the identifier's declaration chains.
1967 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
1968 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
1969 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001970 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001971 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001972
1973 // If there were any tentative definitions, deserialize them and add
1974 // them to Sema's table of tentative definitions.
1975 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
1976 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
1977 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
1978 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00001979
1980 // If there were any locally-scoped external declarations,
1981 // deserialize them and add them to Sema's table of locally-scoped
1982 // external declarations.
1983 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
1984 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
1985 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
1986 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00001987
1988 // If there were any ext_vector type declarations, deserialize them
1989 // and add them to Sema's vector of such declarations.
1990 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
1991 SemaObj->ExtVectorDecls.push_back(
1992 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
1993
1994 // If there were any Objective-C category implementations,
1995 // deserialize them and add them to Sema's vector of such
1996 // definitions.
1997 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
1998 SemaObj->ObjCCategoryImpls.push_back(
1999 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00002000}
2001
2002IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
2003 // Try to find this name within our on-disk hash table
2004 PCHIdentifierLookupTable *IdTable
2005 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
2006 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
2007 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2008 if (Pos == IdTable->end())
2009 return 0;
2010
2011 // Dereferencing the iterator has the effect of building the
2012 // IdentifierInfo node and populating it with the various
2013 // declarations it needs.
2014 return *Pos;
2015}
2016
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002017std::pair<ObjCMethodList, ObjCMethodList>
2018PCHReader::ReadMethodPool(Selector Sel) {
2019 if (!MethodPoolLookupTable)
2020 return std::pair<ObjCMethodList, ObjCMethodList>();
2021
2022 // Try to find this selector within our on-disk hash table.
2023 PCHMethodPoolLookupTable *PoolTable
2024 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
2025 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00002026 if (Pos == PoolTable->end()) {
2027 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002028 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00002029 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002030
Douglas Gregor83941df2009-04-25 17:48:32 +00002031 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002032 return *Pos;
2033}
2034
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002035void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00002036 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00002037 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002038 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00002039}
2040
Chris Lattner7356a312009-04-11 21:15:38 +00002041IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00002042 if (ID == 0)
2043 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00002044
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002045 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002046 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00002047 return 0;
2048 }
Chris Lattner7356a312009-04-11 21:15:38 +00002049
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002050 if (!IdentifiersLoaded[ID - 1]) {
2051 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00002052 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00002053
Douglas Gregor02fc7512009-04-28 20:01:51 +00002054 // All of the strings in the PCH file are preceded by a 16-bit
2055 // length. Extract that 16-bit length to avoid having to execute
2056 // strlen().
2057 const char *StrLenPtr = Str - 2;
2058 unsigned StrLen = (((unsigned) StrLenPtr[0])
2059 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
2060 IdentifiersLoaded[ID - 1]
2061 = &PP.getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00002062 }
Chris Lattner7356a312009-04-11 21:15:38 +00002063
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00002064 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00002065}
2066
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00002067void PCHReader::ReadSLocEntry(unsigned ID) {
2068 ReadSLocEntryRecord(ID);
2069}
2070
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002071Selector PCHReader::DecodeSelector(unsigned ID) {
2072 if (ID == 0)
2073 return Selector();
2074
Douglas Gregora02b1472009-04-28 21:53:25 +00002075 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002076 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00002077
2078 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00002079 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002080 return Selector();
2081 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002082
2083 unsigned Index = ID - 1;
2084 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2085 // Load this selector from the selector table.
2086 // FIXME: endianness portability issues with SelectorOffsets table
2087 PCHMethodPoolLookupTrait Trait(*this);
2088 SelectorsLoaded[Index]
2089 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2090 }
2091
2092 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002093}
2094
Douglas Gregor2cf26342009-04-09 22:27:44 +00002095DeclarationName
2096PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2097 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2098 switch (Kind) {
2099 case DeclarationName::Identifier:
2100 return DeclarationName(GetIdentifierInfo(Record, Idx));
2101
2102 case DeclarationName::ObjCZeroArgSelector:
2103 case DeclarationName::ObjCOneArgSelector:
2104 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002105 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002106
2107 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002108 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002109 GetType(Record[Idx++]));
2110
2111 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002112 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002113 GetType(Record[Idx++]));
2114
2115 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002116 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002117 GetType(Record[Idx++]));
2118
2119 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002120 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002121 (OverloadedOperatorKind)Record[Idx++]);
2122
2123 case DeclarationName::CXXUsingDirective:
2124 return DeclarationName::getUsingDirectiveName();
2125 }
2126
2127 // Required to silence GCC warning
2128 return DeclarationName();
2129}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002130
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002131/// \brief Read an integral value
2132llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2133 unsigned BitWidth = Record[Idx++];
2134 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2135 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2136 Idx += NumWords;
2137 return Result;
2138}
2139
2140/// \brief Read a signed integral value
2141llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2142 bool isUnsigned = Record[Idx++];
2143 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2144}
2145
Douglas Gregor17fc2232009-04-14 21:55:33 +00002146/// \brief Read a floating-point value
2147llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002148 return llvm::APFloat(ReadAPInt(Record, Idx));
2149}
2150
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002151// \brief Read a string
2152std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2153 unsigned Len = Record[Idx++];
2154 std::string Result(&Record[Idx], &Record[Idx] + Len);
2155 Idx += Len;
2156 return Result;
2157}
2158
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002159DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002160 return Diag(SourceLocation(), DiagID);
2161}
2162
2163DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2164 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002165 PP.getSourceManager()),
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002166 DiagID);
2167}
Douglas Gregor025452f2009-04-17 00:04:06 +00002168
Douglas Gregor668c1a42009-04-21 22:25:48 +00002169/// \brief Retrieve the identifier table associated with the
2170/// preprocessor.
2171IdentifierTable &PCHReader::getIdentifierTable() {
2172 return PP.getIdentifierTable();
2173}
2174
Douglas Gregor025452f2009-04-17 00:04:06 +00002175/// \brief Record that the given ID maps to the given switch-case
2176/// statement.
2177void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2178 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2179 SwitchCaseStmts[ID] = SC;
2180}
2181
2182/// \brief Retrieve the switch-case statement with the given ID.
2183SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2184 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2185 return SwitchCaseStmts[ID];
2186}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002187
2188/// \brief Record that the given label statement has been
2189/// deserialized and has the given ID.
2190void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2191 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2192 "Deserialized label twice");
2193 LabelStmts[ID] = S;
2194
2195 // If we've already seen any goto statements that point to this
2196 // label, resolve them now.
2197 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2198 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2199 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2200 Goto->second->setLabel(S);
2201 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002202
2203 // If we've already seen any address-label statements that point to
2204 // this label, resolve them now.
2205 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2206 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2207 = UnresolvedAddrLabelExprs.equal_range(ID);
2208 for (AddrLabelIter AddrLabel = AddrLabels.first;
2209 AddrLabel != AddrLabels.second; ++AddrLabel)
2210 AddrLabel->second->setLabel(S);
2211 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002212}
2213
2214/// \brief Set the label of the given statement to the label
2215/// identified by ID.
2216///
2217/// Depending on the order in which the label and other statements
2218/// referencing that label occur, this operation may complete
2219/// immediately (updating the statement) or it may queue the
2220/// statement to be back-patched later.
2221void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2222 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2223 if (Label != LabelStmts.end()) {
2224 // We've already seen this label, so set the label of the goto and
2225 // we're done.
2226 S->setLabel(Label->second);
2227 } else {
2228 // We haven't seen this label yet, so add this goto to the set of
2229 // unresolved goto statements.
2230 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2231 }
2232}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002233
2234/// \brief Set the label of the given expression to the label
2235/// identified by ID.
2236///
2237/// Depending on the order in which the label and other statements
2238/// referencing that label occur, this operation may complete
2239/// immediately (updating the statement) or it may queue the
2240/// statement to be back-patched later.
2241void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2242 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2243 if (Label != LabelStmts.end()) {
2244 // We've already seen this label, so set the label of the
2245 // label-address expression and we're done.
2246 S->setLabel(Label->second);
2247 } else {
2248 // We haven't seen this label yet, so add this label-address
2249 // expression to the set of unresolved label-address expressions.
2250 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2251 }
2252}