blob: 4e3f50db2e67de8d9e604ed52f877a3169b77556 [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
316static bool Error(const char *Str) {
317 std::fprintf(stderr, "%s\n", Str);
318 return true;
319}
320
Douglas Gregore721f952009-04-28 18:58:38 +0000321/// \brief Split the given string into a vector of lines, eliminating
322/// any empty lines in the process.
323///
324/// \param Str the string to split.
325/// \param Len the length of Str.
326/// \param KeepEmptyLines true if empty lines should be included
327/// \returns a vector of lines, with the line endings removed
328std::vector<std::string> splitLines(const char *Str, unsigned Len,
329 bool KeepEmptyLines = false) {
330 std::vector<std::string> Lines;
331 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
332 unsigned LineEnd = LineStart;
333 while (LineEnd < Len && Str[LineEnd] != '\n')
334 ++LineEnd;
335 if (LineStart != LineEnd || KeepEmptyLines)
336 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
337 LineStart = LineEnd;
338 }
339 return Lines;
340}
341
342/// \brief Determine whether the string Haystack starts with the
343/// substring Needle.
344static bool startsWith(const std::string &Haystack, const char *Needle) {
345 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
346 if (I == N)
347 return false;
348 if (Haystack[I] != Needle[I])
349 return false;
350 }
351
352 return true;
353}
354
355/// \brief Determine whether the string Haystack starts with the
356/// substring Needle.
357static inline bool startsWith(const std::string &Haystack,
358 const std::string &Needle) {
359 return startsWith(Haystack, Needle.c_str());
360}
361
Douglas Gregore1d918e2009-04-10 23:10:45 +0000362/// \brief Check the contents of the predefines buffer against the
363/// contents of the predefines buffer used to build the PCH file.
364///
365/// The contents of the two predefines buffers should be the same. If
366/// not, then some command-line option changed the preprocessor state
367/// and we must reject the PCH file.
368///
369/// \param PCHPredef The start of the predefines buffer in the PCH
370/// file.
371///
372/// \param PCHPredefLen The length of the predefines buffer in the PCH
373/// file.
374///
375/// \param PCHBufferID The FileID for the PCH predefines buffer.
376///
377/// \returns true if there was a mismatch (in which case the PCH file
378/// should be ignored), or false otherwise.
379bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
380 unsigned PCHPredefLen,
381 FileID PCHBufferID) {
382 const char *Predef = PP.getPredefines().c_str();
383 unsigned PredefLen = PP.getPredefines().size();
384
Douglas Gregore721f952009-04-28 18:58:38 +0000385 // If the two predefines buffers compare equal, we're done!
Douglas Gregore1d918e2009-04-10 23:10:45 +0000386 if (PredefLen == PCHPredefLen &&
387 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
388 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000389
Douglas Gregore1d918e2009-04-10 23:10:45 +0000390 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregore721f952009-04-28 18:58:38 +0000391
392 // The predefines buffers are different. Determine what the
393 // differences are, and whether they require us to reject the PCH
394 // file.
395 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
396 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000397
Douglas Gregore721f952009-04-28 18:58:38 +0000398 // Sort both sets of predefined buffer lines, since
399 std::sort(CmdLineLines.begin(), CmdLineLines.end());
400 std::sort(PCHLines.begin(), PCHLines.end());
Douglas Gregore1d918e2009-04-10 23:10:45 +0000401
Douglas Gregore721f952009-04-28 18:58:38 +0000402 // Determine which predefines that where used to build the PCH file
403 // are missing from the command line.
404 std::vector<std::string> MissingPredefines;
405 std::set_difference(PCHLines.begin(), PCHLines.end(),
406 CmdLineLines.begin(), CmdLineLines.end(),
407 std::back_inserter(MissingPredefines));
408
409 bool MissingDefines = false;
410 bool ConflictingDefines = false;
411 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
412 const std::string &Missing = MissingPredefines[I];
413 if (!startsWith(Missing, "#define ") != 0) {
Douglas Gregoraf1795b2009-04-28 20:36:16 +0000414 Diag(diag::warn_pch_compiler_options_mismatch);
415 Diag(diag::note_ignoring_pch) << FileName;
Douglas Gregore721f952009-04-28 18:58:38 +0000416 return true;
417 }
418
419 // This is a macro definition. Determine the name of the macro
420 // we're defining.
421 std::string::size_type StartOfMacroName = strlen("#define ");
422 std::string::size_type EndOfMacroName
423 = Missing.find_first_of("( \n\r", StartOfMacroName);
424 assert(EndOfMacroName != std::string::npos &&
425 "Couldn't find the end of the macro name");
426 std::string MacroName = Missing.substr(StartOfMacroName,
427 EndOfMacroName - StartOfMacroName);
428
429 // Determine whether this macro was given a different definition
430 // on the command line.
431 std::string MacroDefStart = "#define " + MacroName;
432 std::string::size_type MacroDefLen = MacroDefStart.size();
433 std::vector<std::string>::iterator ConflictPos
434 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
435 MacroDefStart);
436 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
437 if (!startsWith(*ConflictPos, MacroDefStart)) {
438 // Different macro; we're done.
439 ConflictPos = CmdLineLines.end();
440 break;
441 }
442
443 assert(ConflictPos->size() > MacroDefLen &&
444 "Invalid #define in predefines buffer?");
445 if ((*ConflictPos)[MacroDefLen] != ' ' &&
446 (*ConflictPos)[MacroDefLen] != '(')
447 continue; // Longer macro name; keep trying.
448
449 // We found a conflicting macro definition.
450 break;
451 }
452
453 if (ConflictPos != CmdLineLines.end()) {
454 Diag(diag::warn_cmdline_conflicting_macro_def)
455 << MacroName;
456
457 // Show the definition of this macro within the PCH file.
458 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
459 unsigned Offset = MissingDef - PCHPredef;
460 SourceLocation PCHMissingLoc
461 = SourceMgr.getLocForStartOfFile(PCHBufferID)
462 .getFileLocWithOffset(Offset);
463 Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
464 << MacroName;
465
466 ConflictingDefines = true;
467 continue;
468 }
469
470 // If the macro doesn't conflict, then we'll just pick up the
471 // macro definition from the PCH file. Warn the user that they
472 // made a mistake.
473 if (ConflictingDefines)
474 continue; // Don't complain if there are already conflicting defs
475
476 if (!MissingDefines) {
477 Diag(diag::warn_cmdline_missing_macro_defs);
478 MissingDefines = true;
479 }
480
481 // Show the definition of this macro within the PCH file.
482 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
483 unsigned Offset = MissingDef - PCHPredef;
484 SourceLocation PCHMissingLoc
485 = SourceMgr.getLocForStartOfFile(PCHBufferID)
486 .getFileLocWithOffset(Offset);
487 Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000488 }
489
Douglas Gregore721f952009-04-28 18:58:38 +0000490 if (ConflictingDefines) {
491 Diag(diag::note_ignoring_pch) << FileName;
492 return true;
493 }
494
495 // Determine what predefines were introduced based on command-line
496 // parameters that were not present when building the PCH
497 // file. Extra #defines are okay, so long as the identifiers being
498 // defined were not used within the precompiled header.
499 std::vector<std::string> ExtraPredefines;
500 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
501 PCHLines.begin(), PCHLines.end(),
502 std::back_inserter(ExtraPredefines));
503 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
504 const std::string &Extra = ExtraPredefines[I];
505 if (!startsWith(Extra, "#define ") != 0) {
Douglas Gregoraf1795b2009-04-28 20:36:16 +0000506 Diag(diag::warn_pch_compiler_options_mismatch);
507 Diag(diag::note_ignoring_pch) << FileName;
Douglas Gregore721f952009-04-28 18:58:38 +0000508 return true;
509 }
510
511 // This is an extra macro definition. Determine the name of the
512 // macro we're defining.
513 std::string::size_type StartOfMacroName = strlen("#define ");
514 std::string::size_type EndOfMacroName
515 = Extra.find_first_of("( \n\r", StartOfMacroName);
516 assert(EndOfMacroName != std::string::npos &&
517 "Couldn't find the end of the macro name");
518 std::string MacroName = Extra.substr(StartOfMacroName,
519 EndOfMacroName - StartOfMacroName);
520
Douglas Gregor92b059e2009-04-28 20:33:11 +0000521 // Check whether this name was used somewhere in the PCH file. If
522 // so, defining it as a macro could change behavior, so we reject
523 // the PCH file.
524 if (IdentifierInfo *II = get(MacroName.c_str(),
525 MacroName.c_str() + MacroName.size())) {
526 Diag(diag::warn_macro_name_used_in_pch)
527 << II;
528 Diag(diag::note_ignoring_pch)
529 << FileName;
530 return true;
531 }
Douglas Gregore721f952009-04-28 18:58:38 +0000532
533 // Add this definition to the suggested predefines buffer.
534 SuggestedPredefines += Extra;
535 SuggestedPredefines += '\n';
536 }
537
538 // If we get here, it's because the predefines buffer had compatible
539 // contents. Accept the PCH file.
540 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000541}
542
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000543//===----------------------------------------------------------------------===//
544// Source Manager Deserialization
545//===----------------------------------------------------------------------===//
546
Douglas Gregorbd945002009-04-13 16:31:14 +0000547/// \brief Read the line table in the source manager block.
548/// \returns true if ther was an error.
549static bool ParseLineTable(SourceManager &SourceMgr,
550 llvm::SmallVectorImpl<uint64_t> &Record) {
551 unsigned Idx = 0;
552 LineTableInfo &LineTable = SourceMgr.getLineTable();
553
554 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000555 std::map<int, int> FileIDs;
556 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000557 // Extract the file name
558 unsigned FilenameLen = Record[Idx++];
559 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
560 Idx += FilenameLen;
Douglas Gregorff0a9872009-04-13 17:12:42 +0000561 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
562 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000563 }
564
565 // Parse the line entries
566 std::vector<LineEntry> Entries;
567 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000568 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000569
570 // Extract the line entries
571 unsigned NumEntries = Record[Idx++];
572 Entries.clear();
573 Entries.reserve(NumEntries);
574 for (unsigned I = 0; I != NumEntries; ++I) {
575 unsigned FileOffset = Record[Idx++];
576 unsigned LineNo = Record[Idx++];
577 int FilenameID = Record[Idx++];
578 SrcMgr::CharacteristicKind FileKind
579 = (SrcMgr::CharacteristicKind)Record[Idx++];
580 unsigned IncludeOffset = Record[Idx++];
581 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
582 FileKind, IncludeOffset));
583 }
584 LineTable.AddEntry(FID, Entries);
585 }
586
587 return false;
588}
589
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000590namespace {
591
592class VISIBILITY_HIDDEN PCHStatData {
593public:
594 const bool hasStat;
595 const ino_t ino;
596 const dev_t dev;
597 const mode_t mode;
598 const time_t mtime;
599 const off_t size;
600
601 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
602 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
603
604 PCHStatData()
605 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
606};
607
608class VISIBILITY_HIDDEN PCHStatLookupTrait {
609 public:
610 typedef const char *external_key_type;
611 typedef const char *internal_key_type;
612
613 typedef PCHStatData data_type;
614
615 static unsigned ComputeHash(const char *path) {
616 return BernsteinHash(path);
617 }
618
619 static internal_key_type GetInternalKey(const char *path) { return path; }
620
621 static bool EqualKey(internal_key_type a, internal_key_type b) {
622 return strcmp(a, b) == 0;
623 }
624
625 static std::pair<unsigned, unsigned>
626 ReadKeyDataLength(const unsigned char*& d) {
627 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
628 unsigned DataLen = (unsigned) *d++;
629 return std::make_pair(KeyLen + 1, DataLen);
630 }
631
632 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
633 return (const char *)d;
634 }
635
636 static data_type ReadData(const internal_key_type, const unsigned char *d,
637 unsigned /*DataLen*/) {
638 using namespace clang::io;
639
640 if (*d++ == 1)
641 return data_type();
642
643 ino_t ino = (ino_t) ReadUnalignedLE32(d);
644 dev_t dev = (dev_t) ReadUnalignedLE32(d);
645 mode_t mode = (mode_t) ReadUnalignedLE16(d);
646 time_t mtime = (time_t) ReadUnalignedLE64(d);
647 off_t size = (off_t) ReadUnalignedLE64(d);
648 return data_type(ino, dev, mode, mtime, size);
649 }
650};
651
652/// \brief stat() cache for precompiled headers.
653///
654/// This cache is very similar to the stat cache used by pretokenized
655/// headers.
656class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
657 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
658 CacheTy *Cache;
659
660 unsigned &NumStatHits, &NumStatMisses;
661public:
662 PCHStatCache(const unsigned char *Buckets,
663 const unsigned char *Base,
664 unsigned &NumStatHits,
665 unsigned &NumStatMisses)
666 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
667 Cache = CacheTy::Create(Buckets, Base);
668 }
669
670 ~PCHStatCache() { delete Cache; }
671
672 int stat(const char *path, struct stat *buf) {
673 // Do the lookup for the file's data in the PCH file.
674 CacheTy::iterator I = Cache->find(path);
675
676 // If we don't get a hit in the PCH file just forward to 'stat'.
677 if (I == Cache->end()) {
678 ++NumStatMisses;
679 return ::stat(path, buf);
680 }
681
682 ++NumStatHits;
683 PCHStatData Data = *I;
684
685 if (!Data.hasStat)
686 return 1;
687
688 buf->st_ino = Data.ino;
689 buf->st_dev = Data.dev;
690 buf->st_mtime = Data.mtime;
691 buf->st_mode = Data.mode;
692 buf->st_size = Data.size;
693 return 0;
694 }
695};
696} // end anonymous namespace
697
698
Douglas Gregor14f79002009-04-10 03:52:48 +0000699/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000700PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000701 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000702
703 // Set the source-location entry cursor to the current position in
704 // the stream. This cursor will be used to read the contents of the
705 // source manager block initially, and then lazily read
706 // source-location entries as needed.
707 SLocEntryCursor = Stream;
708
709 // The stream itself is going to skip over the source manager block.
710 if (Stream.SkipBlock()) {
711 Error("Malformed block record");
712 return Failure;
713 }
714
715 // Enter the source manager block.
716 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000717 Error("Malformed source manager block record");
718 return Failure;
719 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000720
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000721 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor14f79002009-04-10 03:52:48 +0000722 RecordData Record;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000723 unsigned NumHeaderInfos = 0;
Douglas Gregor14f79002009-04-10 03:52:48 +0000724 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000725 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000726 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000727 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000728 Error("Error at end of Source Manager block");
729 return Failure;
730 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000731 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000732 }
733
734 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
735 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000736 SLocEntryCursor.ReadSubBlockID();
737 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000738 Error("Malformed block record");
739 return Failure;
740 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000741 continue;
742 }
743
744 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000745 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000746 continue;
747 }
748
749 // Read a record.
750 const char *BlobStart;
751 unsigned BlobLen;
752 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000753 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000754 default: // Default behavior: ignore.
755 break;
756
Chris Lattner2c78b872009-04-14 23:22:57 +0000757 case pch::SM_LINE_TABLE:
Douglas Gregorbd945002009-04-13 16:31:14 +0000758 if (ParseLineTable(SourceMgr, Record))
759 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000760 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000761
762 case pch::SM_HEADER_FILE_INFO: {
763 HeaderFileInfo HFI;
764 HFI.isImport = Record[0];
765 HFI.DirInfo = Record[1];
766 HFI.NumIncludes = Record[2];
767 HFI.ControllingMacroID = Record[3];
768 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
769 break;
770 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000771
772 case pch::SM_SLOC_FILE_ENTRY:
773 case pch::SM_SLOC_BUFFER_ENTRY:
774 case pch::SM_SLOC_INSTANTIATION_ENTRY:
775 // Once we hit one of the source location entries, we're done.
776 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000777 }
778 }
779}
780
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000781/// \brief Read in the source location entry with the given ID.
782PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
783 if (ID == 0)
784 return Success;
785
786 if (ID > TotalNumSLocEntries) {
787 Error("source location entry ID out-of-range for PCH file");
788 return Failure;
789 }
790
791 ++NumSLocEntriesRead;
792 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
793 unsigned Code = SLocEntryCursor.ReadCode();
794 if (Code == llvm::bitc::END_BLOCK ||
795 Code == llvm::bitc::ENTER_SUBBLOCK ||
796 Code == llvm::bitc::DEFINE_ABBREV) {
797 Error("incorrectly-formatted source location entry in PCH file");
798 return Failure;
799 }
800
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000801 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000802 RecordData Record;
803 const char *BlobStart;
804 unsigned BlobLen;
805 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
806 default:
807 Error("incorrectly-formatted source location entry in PCH file");
808 return Failure;
809
810 case pch::SM_SLOC_FILE_ENTRY: {
811 const FileEntry *File
812 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
813 // FIXME: Error recovery if file cannot be found.
814 FileID FID = SourceMgr.createFileID(File,
815 SourceLocation::getFromRawEncoding(Record[1]),
816 (SrcMgr::CharacteristicKind)Record[2],
817 ID, Record[0]);
818 if (Record[3])
819 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
820 .setHasLineDirectives();
821
822 break;
823 }
824
825 case pch::SM_SLOC_BUFFER_ENTRY: {
826 const char *Name = BlobStart;
827 unsigned Offset = Record[0];
828 unsigned Code = SLocEntryCursor.ReadCode();
829 Record.clear();
830 unsigned RecCode
831 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
832 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
833 (void)RecCode;
834 llvm::MemoryBuffer *Buffer
835 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
836 BlobStart + BlobLen - 1,
837 Name);
838 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
839
Douglas Gregor92b059e2009-04-28 20:33:11 +0000840 if (strcmp(Name, "<built-in>") == 0) {
841 PCHPredefinesBufferID = BufferID;
842 PCHPredefines = BlobStart;
843 PCHPredefinesLen = BlobLen - 1;
844 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000845
846 break;
847 }
848
849 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
850 SourceLocation SpellingLoc
851 = SourceLocation::getFromRawEncoding(Record[1]);
852 SourceMgr.createInstantiationLoc(SpellingLoc,
853 SourceLocation::getFromRawEncoding(Record[2]),
854 SourceLocation::getFromRawEncoding(Record[3]),
855 Record[4],
856 ID,
857 Record[0]);
858 break;
859 }
860 }
861
862 return Success;
863}
864
Chris Lattner6367f6d2009-04-27 01:05:14 +0000865/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
866/// specified cursor. Read the abbreviations that are at the top of the block
867/// and then leave the cursor pointing into the block.
868bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
869 unsigned BlockID) {
870 if (Cursor.EnterSubBlock(BlockID)) {
871 Error("Malformed block record");
872 return Failure;
873 }
874
Chris Lattner6367f6d2009-04-27 01:05:14 +0000875 while (true) {
876 unsigned Code = Cursor.ReadCode();
877
878 // We expect all abbrevs to be at the start of the block.
879 if (Code != llvm::bitc::DEFINE_ABBREV)
880 return false;
881 Cursor.ReadAbbrevRecord();
882 }
883}
884
Douglas Gregor37e26842009-04-21 23:56:24 +0000885void PCHReader::ReadMacroRecord(uint64_t Offset) {
886 // Keep track of where we are in the stream, then jump back there
887 // after reading this macro.
888 SavedStreamPosition SavedPosition(Stream);
889
890 Stream.JumpToBit(Offset);
891 RecordData Record;
892 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
893 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +0000894
Douglas Gregor37e26842009-04-21 23:56:24 +0000895 while (true) {
896 unsigned Code = Stream.ReadCode();
897 switch (Code) {
898 case llvm::bitc::END_BLOCK:
899 return;
900
901 case llvm::bitc::ENTER_SUBBLOCK:
902 // No known subblocks, always skip them.
903 Stream.ReadSubBlockID();
904 if (Stream.SkipBlock()) {
905 Error("Malformed block record");
906 return;
907 }
908 continue;
909
910 case llvm::bitc::DEFINE_ABBREV:
911 Stream.ReadAbbrevRecord();
912 continue;
913 default: break;
914 }
915
916 // Read a record.
917 Record.clear();
918 pch::PreprocessorRecordTypes RecType =
919 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
920 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +0000921 case pch::PP_MACRO_OBJECT_LIKE:
922 case pch::PP_MACRO_FUNCTION_LIKE: {
923 // If we already have a macro, that means that we've hit the end
924 // of the definition of the macro we were looking for. We're
925 // done.
926 if (Macro)
927 return;
928
929 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
930 if (II == 0) {
931 Error("Macro must have a name");
932 return;
933 }
934 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
935 bool isUsed = Record[2];
936
937 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
938 MI->setIsUsed(isUsed);
939
940 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
941 // Decode function-like macro info.
942 bool isC99VarArgs = Record[3];
943 bool isGNUVarArgs = Record[4];
944 MacroArgs.clear();
945 unsigned NumArgs = Record[5];
946 for (unsigned i = 0; i != NumArgs; ++i)
947 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
948
949 // Install function-like macro info.
950 MI->setIsFunctionLike();
951 if (isC99VarArgs) MI->setIsC99Varargs();
952 if (isGNUVarArgs) MI->setIsGNUVarargs();
953 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
954 PP.getPreprocessorAllocator());
955 }
956
957 // Finally, install the macro.
958 PP.setMacroInfo(II, MI);
959
960 // Remember that we saw this macro last so that we add the tokens that
961 // form its body to it.
962 Macro = MI;
963 ++NumMacrosRead;
964 break;
965 }
966
967 case pch::PP_TOKEN: {
968 // If we see a TOKEN before a PP_MACRO_*, then the file is
969 // erroneous, just pretend we didn't see this.
970 if (Macro == 0) break;
971
972 Token Tok;
973 Tok.startToken();
974 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
975 Tok.setLength(Record[1]);
976 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
977 Tok.setIdentifierInfo(II);
978 Tok.setKind((tok::TokenKind)Record[3]);
979 Tok.setFlag((Token::TokenFlags)Record[4]);
980 Macro->AddTokenToBody(Tok);
981 break;
982 }
Steve Naroff83d63c72009-04-24 20:03:17 +0000983 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000984 }
985}
986
Douglas Gregor668c1a42009-04-21 22:25:48 +0000987PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000988PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000989 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
990 Error("Malformed block record");
991 return Failure;
992 }
Douglas Gregor2cf26342009-04-09 22:27:44 +0000993
994 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +0000995 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000996 while (!Stream.AtEndOfStream()) {
997 unsigned Code = Stream.ReadCode();
998 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000999 if (Stream.ReadBlockEnd()) {
1000 Error("Error at end of module block");
1001 return Failure;
1002 }
Chris Lattner7356a312009-04-11 21:15:38 +00001003
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001004 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001005 }
1006
1007 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1008 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001009 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1010 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001011 if (Stream.SkipBlock()) {
1012 Error("Malformed block record");
1013 return Failure;
1014 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001015 break;
1016
Chris Lattner6367f6d2009-04-27 01:05:14 +00001017 case pch::DECLS_BLOCK_ID:
1018 // We lazily load the decls block, but we want to set up the
1019 // DeclsCursor cursor to point into it. Clone our current bitcode
1020 // cursor to it, enter the block and read the abbrevs in that block.
1021 // With the main cursor, we just skip over it.
1022 DeclsCursor = Stream;
1023 if (Stream.SkipBlock() || // Skip with the main cursor.
1024 // Read the abbrevs.
1025 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
1026 Error("Malformed block record");
1027 return Failure;
1028 }
1029 break;
1030
Chris Lattner7356a312009-04-11 21:15:38 +00001031 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001032 if (Stream.SkipBlock()) {
1033 Error("Malformed block record");
1034 return Failure;
1035 }
1036 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001037
Douglas Gregor14f79002009-04-10 03:52:48 +00001038 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001039 switch (ReadSourceManagerBlock()) {
1040 case Success:
1041 break;
1042
1043 case Failure:
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001044 Error("Malformed source manager block");
1045 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001046
1047 case IgnorePCH:
1048 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001049 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001050 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001051 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001052 continue;
1053 }
1054
1055 if (Code == llvm::bitc::DEFINE_ABBREV) {
1056 Stream.ReadAbbrevRecord();
1057 continue;
1058 }
1059
1060 // Read and process a record.
1061 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001062 const char *BlobStart = 0;
1063 unsigned BlobLen = 0;
1064 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1065 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001066 default: // Default behavior: ignore.
1067 break;
1068
1069 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001070 if (!TypesLoaded.empty()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001071 Error("Duplicate TYPE_OFFSET record in PCH file");
1072 return Failure;
1073 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001074 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001075 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001076 break;
1077
1078 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001079 if (!DeclsLoaded.empty()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001080 Error("Duplicate DECL_OFFSET record in PCH file");
1081 return Failure;
1082 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001083 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001084 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001085 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001086
1087 case pch::LANGUAGE_OPTIONS:
1088 if (ParseLanguageOptions(Record))
1089 return IgnorePCH;
1090 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001091
Douglas Gregorab41e632009-04-27 22:23:34 +00001092 case pch::METADATA: {
1093 if (Record[0] != pch::VERSION_MAJOR) {
1094 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1095 : diag::warn_pch_version_too_new);
1096 return IgnorePCH;
1097 }
1098
Douglas Gregor2bec0412009-04-10 21:16:55 +00001099 std::string TargetTriple(BlobStart, BlobLen);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001100 if (TargetTriple != PP.getTargetInfo().getTargetTriple()) {
Douglas Gregor2bec0412009-04-10 21:16:55 +00001101 Diag(diag::warn_pch_target_triple)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001102 << TargetTriple << PP.getTargetInfo().getTargetTriple();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001103 Diag(diag::note_ignoring_pch) << FileName;
1104 return IgnorePCH;
1105 }
1106 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001107 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001108
1109 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001110 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001111 if (Record[0]) {
1112 IdentifierLookupTable
1113 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001114 (const unsigned char *)IdentifierTableData + Record[0],
1115 (const unsigned char *)IdentifierTableData,
1116 PCHIdentifierLookupTrait(*this));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001117 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1118 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001119 break;
1120
1121 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001122 if (!IdentifiersLoaded.empty()) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001123 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
1124 return Failure;
1125 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001126 IdentifierOffsets = (const uint32_t *)BlobStart;
1127 IdentifiersLoaded.resize(Record[0]);
Douglas Gregor8c5a7602009-04-25 23:30:02 +00001128 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001129 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001130
1131 case pch::EXTERNAL_DEFINITIONS:
1132 if (!ExternalDefinitions.empty()) {
1133 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
1134 return Failure;
1135 }
1136 ExternalDefinitions.swap(Record);
1137 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001138
Douglas Gregorad1de002009-04-18 05:55:16 +00001139 case pch::SPECIAL_TYPES:
1140 SpecialTypes.swap(Record);
1141 break;
1142
Douglas Gregor3e1af842009-04-17 22:13:46 +00001143 case pch::STATISTICS:
1144 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001145 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001146 TotalLexicalDeclContexts = Record[2];
1147 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001148 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001149
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001150 case pch::TENTATIVE_DEFINITIONS:
1151 if (!TentativeDefinitions.empty()) {
1152 Error("Duplicate TENTATIVE_DEFINITIONS record in PCH file");
1153 return Failure;
1154 }
1155 TentativeDefinitions.swap(Record);
1156 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001157
1158 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1159 if (!LocallyScopedExternalDecls.empty()) {
1160 Error("Duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
1161 return Failure;
1162 }
1163 LocallyScopedExternalDecls.swap(Record);
1164 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001165
Douglas Gregor83941df2009-04-25 17:48:32 +00001166 case pch::SELECTOR_OFFSETS:
1167 SelectorOffsets = (const uint32_t *)BlobStart;
1168 TotalNumSelectors = Record[0];
1169 SelectorsLoaded.resize(TotalNumSelectors);
1170 break;
1171
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001172 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001173 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1174 if (Record[0])
1175 MethodPoolLookupTable
1176 = PCHMethodPoolLookupTable::Create(
1177 MethodPoolLookupTableData + Record[0],
1178 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001179 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001180 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001181 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001182
1183 case pch::PP_COUNTER_VALUE:
1184 if (!Record.empty())
1185 PP.setCounterValue(Record[0]);
1186 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001187
1188 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001189 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001190 TotalNumSLocEntries = Record[0];
1191 PP.getSourceManager().PreallocateSLocEntries(this,
1192 TotalNumSLocEntries,
1193 Record[1]);
1194 break;
1195
1196 case pch::SOURCE_LOCATION_PRELOADS:
1197 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1198 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1199 if (Result != Success)
1200 return Result;
1201 }
1202 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001203
1204 case pch::STAT_CACHE:
1205 PP.getFileManager().setStatCache(
1206 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1207 (const unsigned char *)BlobStart,
1208 NumStatHits, NumStatMisses));
1209 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001210
1211 case pch::EXT_VECTOR_DECLS:
1212 if (!ExtVectorDecls.empty()) {
1213 Error("Duplicate EXT_VECTOR_DECLS record in PCH file");
1214 return Failure;
1215 }
1216 ExtVectorDecls.swap(Record);
1217 break;
1218
1219 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1220 if (!ObjCCategoryImpls.empty()) {
1221 Error("Duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
1222 return Failure;
1223 }
1224 ObjCCategoryImpls.swap(Record);
1225 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001226 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001227 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001228 Error("Premature end of bitstream");
1229 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001230}
1231
Douglas Gregore1d918e2009-04-10 23:10:45 +00001232PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001233 // Set the PCH file name.
1234 this->FileName = FileName;
1235
Douglas Gregor2cf26342009-04-09 22:27:44 +00001236 // Open the PCH file.
1237 std::string ErrStr;
1238 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001239 if (!Buffer) {
1240 Error(ErrStr.c_str());
1241 return IgnorePCH;
1242 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001243
1244 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001245 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1246 (const unsigned char *)Buffer->getBufferEnd());
1247 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001248
1249 // Sniff for the signature.
1250 if (Stream.Read(8) != 'C' ||
1251 Stream.Read(8) != 'P' ||
1252 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001253 Stream.Read(8) != 'H') {
1254 Error("Not a PCH file");
1255 return IgnorePCH;
1256 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001257
Douglas Gregor2cf26342009-04-09 22:27:44 +00001258 while (!Stream.AtEndOfStream()) {
1259 unsigned Code = Stream.ReadCode();
1260
Douglas Gregore1d918e2009-04-10 23:10:45 +00001261 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1262 Error("Invalid record at top-level");
1263 return Failure;
1264 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001265
1266 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001267
Douglas Gregor2cf26342009-04-09 22:27:44 +00001268 // We only know the PCH subblock ID.
1269 switch (BlockID) {
1270 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001271 if (Stream.ReadBlockInfoBlock()) {
1272 Error("Malformed BlockInfoBlock");
1273 return Failure;
1274 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001275 break;
1276 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001277 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001278 case Success:
1279 break;
1280
1281 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001282 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001283
1284 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001285 // FIXME: We could consider reading through to the end of this
1286 // PCH block, skipping subblocks, to see if there are other
1287 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001288
1289 // Clear out any preallocated source location entries, so that
1290 // the source manager does not try to resolve them later.
1291 PP.getSourceManager().ClearPreallocatedSLocEntries();
1292
1293 // Remove the stat cache.
1294 PP.getFileManager().setStatCache(0);
1295
Douglas Gregore1d918e2009-04-10 23:10:45 +00001296 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001297 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001298 break;
1299 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001300 if (Stream.SkipBlock()) {
1301 Error("Malformed block record");
1302 return Failure;
1303 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001304 break;
1305 }
1306 }
1307
1308 // Load the translation unit declaration
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001309 if (Context)
1310 ReadDeclRecord(DeclOffsets[0], 0);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001311
1312 // Check the predefines buffer.
1313 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1314 PCHPredefinesBufferID))
1315 return IgnorePCH;
1316
Douglas Gregor668c1a42009-04-21 22:25:48 +00001317 // Initialization of builtins and library builtins occurs before the
1318 // PCH file is read, so there may be some identifiers that were
1319 // loaded into the IdentifierTable before we intercepted the
1320 // creation of identifiers. Iterate through the list of known
1321 // identifiers and determine whether we have to establish
1322 // preprocessor definitions or top-level identifier declaration
1323 // chains for those identifiers.
1324 //
1325 // We copy the IdentifierInfo pointers to a small vector first,
1326 // since de-serializing declarations or macro definitions can add
1327 // new entries into the identifier table, invalidating the
1328 // iterators.
1329 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1330 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
1331 IdEnd = PP.getIdentifierTable().end();
1332 Id != IdEnd; ++Id)
1333 Identifiers.push_back(Id->second);
1334 PCHIdentifierLookupTable *IdTable
1335 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1336 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1337 IdentifierInfo *II = Identifiers[I];
1338 // Look in the on-disk hash table for an entry for
1339 PCHIdentifierLookupTrait Info(*this, II);
1340 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1341 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1342 if (Pos == IdTable->end())
1343 continue;
1344
1345 // Dereferencing the iterator has the effect of populating the
1346 // IdentifierInfo node with the various declarations it needs.
1347 (void)*Pos;
1348 }
1349
Douglas Gregorad1de002009-04-18 05:55:16 +00001350 // Load the special types.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001351 if (Context) {
1352 Context->setBuiltinVaListType(
1353 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1354 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1355 Context->setObjCIdType(GetType(Id));
1356 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1357 Context->setObjCSelType(GetType(Sel));
1358 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1359 Context->setObjCProtoType(GetType(Proto));
1360 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1361 Context->setObjCClassType(GetType(Class));
1362 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1363 Context->setCFConstantStringType(GetType(String));
1364 if (unsigned FastEnum
1365 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1366 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1367 }
Douglas Gregor0b748912009-04-14 21:18:50 +00001368
Douglas Gregor668c1a42009-04-21 22:25:48 +00001369 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001370}
1371
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001372/// \brief Parse the record that corresponds to a LangOptions data
1373/// structure.
1374///
1375/// This routine compares the language options used to generate the
1376/// PCH file against the language options set for the current
1377/// compilation. For each option, we classify differences between the
1378/// two compiler states as either "benign" or "important". Benign
1379/// differences don't matter, and we accept them without complaint
1380/// (and without modifying the language options). Differences between
1381/// the states for important options cause the PCH file to be
1382/// unusable, so we emit a warning and return true to indicate that
1383/// there was an error.
1384///
1385/// \returns true if the PCH file is unacceptable, false otherwise.
1386bool PCHReader::ParseLanguageOptions(
1387 const llvm::SmallVectorImpl<uint64_t> &Record) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001388 const LangOptions &LangOpts = PP.getLangOptions();
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001389#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1390#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1391 if (Record[Idx] != LangOpts.Option) { \
1392 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1393 Diag(diag::note_ignoring_pch) << FileName; \
1394 return true; \
1395 } \
1396 ++Idx
1397
1398 unsigned Idx = 0;
1399 PARSE_LANGOPT_BENIGN(Trigraphs);
1400 PARSE_LANGOPT_BENIGN(BCPLComment);
1401 PARSE_LANGOPT_BENIGN(DollarIdents);
1402 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1403 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1404 PARSE_LANGOPT_BENIGN(ImplicitInt);
1405 PARSE_LANGOPT_BENIGN(Digraphs);
1406 PARSE_LANGOPT_BENIGN(HexFloats);
1407 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1408 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1409 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1410 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001411 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1412 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1413 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1414 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1415 PARSE_LANGOPT_BENIGN(PascalStrings);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001416 PARSE_LANGOPT_BENIGN(WritableStrings);
1417 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1418 diag::warn_pch_lax_vector_conversions);
1419 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1420 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1421 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1422 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1423 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1424 diag::warn_pch_thread_safe_statics);
1425 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1426 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1427 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1428 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1429 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1430 diag::warn_pch_heinous_extensions);
1431 // FIXME: Most of the options below are benign if the macro wasn't
1432 // used. Unfortunately, this means that a PCH compiled without
1433 // optimization can't be used with optimization turned on, even
1434 // though the only thing that changes is whether __OPTIMIZE__ was
1435 // defined... but if __OPTIMIZE__ never showed up in the header, it
1436 // doesn't matter. We could consider making this some special kind
1437 // of check.
1438 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1439 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1440 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1441 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1442 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1443 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1444 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1445 Diag(diag::warn_pch_gc_mode)
1446 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1447 Diag(diag::note_ignoring_pch) << FileName;
1448 return true;
1449 }
1450 ++Idx;
1451 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1452 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1453#undef PARSE_LANGOPT_IRRELEVANT
1454#undef PARSE_LANGOPT_BENIGN
1455
1456 return false;
1457}
1458
Douglas Gregor2cf26342009-04-09 22:27:44 +00001459/// \brief Read and return the type at the given offset.
1460///
1461/// This routine actually reads the record corresponding to the type
1462/// at the given offset in the bitstream. It is a helper routine for
1463/// GetType, which deals with reading type IDs.
1464QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001465 // Keep track of where we are in the stream, then jump back there
1466 // after reading this type.
1467 SavedStreamPosition SavedPosition(Stream);
1468
Douglas Gregor2cf26342009-04-09 22:27:44 +00001469 Stream.JumpToBit(Offset);
1470 RecordData Record;
1471 unsigned Code = Stream.ReadCode();
1472 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001473 case pch::TYPE_EXT_QUAL: {
1474 assert(Record.size() == 3 &&
1475 "Incorrect encoding of extended qualifier type");
1476 QualType Base = GetType(Record[0]);
1477 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1478 unsigned AddressSpace = Record[2];
1479
1480 QualType T = Base;
1481 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001482 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001483 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001484 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001485 return T;
1486 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001487
Douglas Gregor2cf26342009-04-09 22:27:44 +00001488 case pch::TYPE_FIXED_WIDTH_INT: {
1489 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001490 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001491 }
1492
1493 case pch::TYPE_COMPLEX: {
1494 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1495 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001496 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001497 }
1498
1499 case pch::TYPE_POINTER: {
1500 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1501 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001502 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001503 }
1504
1505 case pch::TYPE_BLOCK_POINTER: {
1506 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1507 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001508 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001509 }
1510
1511 case pch::TYPE_LVALUE_REFERENCE: {
1512 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1513 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001514 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001515 }
1516
1517 case pch::TYPE_RVALUE_REFERENCE: {
1518 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1519 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001520 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001521 }
1522
1523 case pch::TYPE_MEMBER_POINTER: {
1524 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1525 QualType PointeeType = GetType(Record[0]);
1526 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001527 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001528 }
1529
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001530 case pch::TYPE_CONSTANT_ARRAY: {
1531 QualType ElementType = GetType(Record[0]);
1532 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1533 unsigned IndexTypeQuals = Record[2];
1534 unsigned Idx = 3;
1535 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001536 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001537 }
1538
1539 case pch::TYPE_INCOMPLETE_ARRAY: {
1540 QualType ElementType = GetType(Record[0]);
1541 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1542 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001543 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001544 }
1545
1546 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001547 QualType ElementType = GetType(Record[0]);
1548 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1549 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001550 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1551 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001552 }
1553
1554 case pch::TYPE_VECTOR: {
1555 if (Record.size() != 2) {
1556 Error("Incorrect encoding of vector type in PCH file");
1557 return QualType();
1558 }
1559
1560 QualType ElementType = GetType(Record[0]);
1561 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001562 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001563 }
1564
1565 case pch::TYPE_EXT_VECTOR: {
1566 if (Record.size() != 2) {
1567 Error("Incorrect encoding of extended vector type in PCH file");
1568 return QualType();
1569 }
1570
1571 QualType ElementType = GetType(Record[0]);
1572 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001573 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001574 }
1575
1576 case pch::TYPE_FUNCTION_NO_PROTO: {
1577 if (Record.size() != 1) {
1578 Error("Incorrect encoding of no-proto function type");
1579 return QualType();
1580 }
1581 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001582 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001583 }
1584
1585 case pch::TYPE_FUNCTION_PROTO: {
1586 QualType ResultType = GetType(Record[0]);
1587 unsigned Idx = 1;
1588 unsigned NumParams = Record[Idx++];
1589 llvm::SmallVector<QualType, 16> ParamTypes;
1590 for (unsigned I = 0; I != NumParams; ++I)
1591 ParamTypes.push_back(GetType(Record[Idx++]));
1592 bool isVariadic = Record[Idx++];
1593 unsigned Quals = Record[Idx++];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001594 return Context->getFunctionType(ResultType, &ParamTypes[0], NumParams,
1595 isVariadic, Quals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001596 }
1597
1598 case pch::TYPE_TYPEDEF:
1599 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001600 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001601
1602 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001603 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001604
1605 case pch::TYPE_TYPEOF: {
1606 if (Record.size() != 1) {
1607 Error("Incorrect encoding of typeof(type) in PCH file");
1608 return QualType();
1609 }
1610 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001611 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001612 }
1613
1614 case pch::TYPE_RECORD:
Douglas Gregor8c700062009-04-13 21:20:57 +00001615 assert(Record.size() == 1 && "Incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001616 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001617
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001618 case pch::TYPE_ENUM:
1619 assert(Record.size() == 1 && "Incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001620 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001621
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001622 case pch::TYPE_OBJC_INTERFACE:
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001623 assert(Record.size() == 1 && "Incorrect encoding of objc interface type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001624 return Context->getObjCInterfaceType(
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001625 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001626
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001627 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1628 unsigned Idx = 0;
1629 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1630 unsigned NumProtos = Record[Idx++];
1631 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1632 for (unsigned I = 0; I != NumProtos; ++I)
1633 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001634 return Context->getObjCQualifiedInterfaceType(ItfD, &Protos[0], NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001635 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001636
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001637 case pch::TYPE_OBJC_QUALIFIED_ID: {
1638 unsigned Idx = 0;
1639 unsigned NumProtos = Record[Idx++];
1640 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1641 for (unsigned I = 0; I != NumProtos; ++I)
1642 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001643 return Context->getObjCQualifiedIdType(&Protos[0], NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001644 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001645 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001646 // Suppress a GCC warning
1647 return QualType();
1648}
1649
Douglas Gregor2cf26342009-04-09 22:27:44 +00001650
Douglas Gregor8038d512009-04-10 17:25:41 +00001651QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001652 unsigned Quals = ID & 0x07;
1653 unsigned Index = ID >> 3;
1654
1655 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1656 QualType T;
1657 switch ((pch::PredefinedTypeIDs)Index) {
1658 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001659 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1660 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001661
1662 case pch::PREDEF_TYPE_CHAR_U_ID:
1663 case pch::PREDEF_TYPE_CHAR_S_ID:
1664 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001665 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001666 break;
1667
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001668 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1669 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1670 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1671 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1672 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
1673 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1674 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1675 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1676 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1677 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1678 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
1679 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1680 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1681 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1682 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1683 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001684 }
1685
1686 assert(!T.isNull() && "Unknown predefined type");
1687 return T.getQualifiedType(Quals);
1688 }
1689
1690 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregor366809a2009-04-26 03:49:13 +00001691 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001692 if (!TypesLoaded[Index])
1693 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001694
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001695 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001696}
1697
Douglas Gregor8038d512009-04-10 17:25:41 +00001698Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001699 if (ID == 0)
1700 return 0;
1701
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001702 if (ID > DeclsLoaded.size()) {
1703 Error("Declaration ID out-of-range for PCH file");
1704 return 0;
1705 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001706
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001707 unsigned Index = ID - 1;
1708 if (!DeclsLoaded[Index])
1709 ReadDeclRecord(DeclOffsets[Index], Index);
1710
1711 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001712}
1713
Chris Lattner887e2b32009-04-27 05:46:25 +00001714/// \brief Resolve the offset of a statement into a statement.
1715///
1716/// This operation will read a new statement from the external
1717/// source each time it is called, and is meant to be used via a
1718/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1719Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00001720 // Since we know tha this statement is part of a decl, make sure to use the
1721 // decl cursor to read it.
1722 DeclsCursor.JumpToBit(Offset);
1723 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00001724}
1725
Douglas Gregor2cf26342009-04-09 22:27:44 +00001726bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00001727 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001728 assert(DC->hasExternalLexicalStorage() &&
1729 "DeclContext has no lexical decls in storage");
1730 uint64_t Offset = DeclContextOffsets[DC].first;
1731 assert(Offset && "DeclContext has no lexical decls in storage");
1732
Douglas Gregor0b748912009-04-14 21:18:50 +00001733 // Keep track of where we are in the stream, then jump back there
1734 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001735 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001736
Douglas Gregor2cf26342009-04-09 22:27:44 +00001737 // Load the record containing all of the declarations lexically in
1738 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001739 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001740 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001741 unsigned Code = DeclsCursor.ReadCode();
1742 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001743 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001744 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1745
1746 // Load all of the declaration IDs
1747 Decls.clear();
1748 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00001749 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001750 return false;
1751}
1752
1753bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001754 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001755 assert(DC->hasExternalVisibleStorage() &&
1756 "DeclContext has no visible decls in storage");
1757 uint64_t Offset = DeclContextOffsets[DC].second;
1758 assert(Offset && "DeclContext has no visible decls in storage");
1759
Douglas Gregor0b748912009-04-14 21:18:50 +00001760 // Keep track of where we are in the stream, then jump back there
1761 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001762 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001763
Douglas Gregor2cf26342009-04-09 22:27:44 +00001764 // Load the record containing all of the declarations visible in
1765 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001766 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001767 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001768 unsigned Code = DeclsCursor.ReadCode();
1769 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001770 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001771 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1772 if (Record.size() == 0)
1773 return false;
1774
1775 Decls.clear();
1776
1777 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001778 while (Idx < Record.size()) {
1779 Decls.push_back(VisibleDeclaration());
1780 Decls.back().Name = ReadDeclarationName(Record, Idx);
1781
Douglas Gregor2cf26342009-04-09 22:27:44 +00001782 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001783 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001784 LoadedDecls.reserve(Size);
1785 for (unsigned I = 0; I < Size; ++I)
1786 LoadedDecls.push_back(Record[Idx++]);
1787 }
1788
Douglas Gregor25123082009-04-22 22:34:57 +00001789 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001790 return false;
1791}
1792
Douglas Gregorfdd01722009-04-14 00:24:19 +00001793void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00001794 this->Consumer = Consumer;
1795
Douglas Gregorfdd01722009-04-14 00:24:19 +00001796 if (!Consumer)
1797 return;
1798
1799 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1800 Decl *D = GetDecl(ExternalDefinitions[I]);
1801 DeclGroupRef DG(D);
1802 Consumer->HandleTopLevelDecl(DG);
1803 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00001804
1805 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
1806 DeclGroupRef DG(InterestingDecls[I]);
1807 Consumer->HandleTopLevelDecl(DG);
1808 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00001809}
1810
Douglas Gregor2cf26342009-04-09 22:27:44 +00001811void PCHReader::PrintStats() {
1812 std::fprintf(stderr, "*** PCH Statistics:\n");
1813
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001814 unsigned NumTypesLoaded
1815 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
1816 (Type *)0);
1817 unsigned NumDeclsLoaded
1818 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
1819 (Decl *)0);
1820 unsigned NumIdentifiersLoaded
1821 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
1822 IdentifiersLoaded.end(),
1823 (IdentifierInfo *)0);
1824 unsigned NumSelectorsLoaded
1825 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
1826 SelectorsLoaded.end(),
1827 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00001828
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001829 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
1830 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001831 if (TotalNumSLocEntries)
1832 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
1833 NumSLocEntriesRead, TotalNumSLocEntries,
1834 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001835 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001836 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001837 NumTypesLoaded, (unsigned)TypesLoaded.size(),
1838 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
1839 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001840 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001841 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
1842 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001843 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001844 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001845 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
1846 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00001847 if (TotalNumSelectors)
1848 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
1849 NumSelectorsLoaded, TotalNumSelectors,
1850 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
1851 if (TotalNumStatements)
1852 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
1853 NumStatementsRead, TotalNumStatements,
1854 ((float)NumStatementsRead/TotalNumStatements * 100));
1855 if (TotalNumMacros)
1856 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
1857 NumMacrosRead, TotalNumMacros,
1858 ((float)NumMacrosRead/TotalNumMacros * 100));
1859 if (TotalLexicalDeclContexts)
1860 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
1861 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
1862 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
1863 * 100));
1864 if (TotalVisibleDeclContexts)
1865 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
1866 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
1867 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
1868 * 100));
1869 if (TotalSelectorsInMethodPool) {
1870 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
1871 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
1872 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
1873 * 100));
1874 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
1875 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001876 std::fprintf(stderr, "\n");
1877}
1878
Douglas Gregor668c1a42009-04-21 22:25:48 +00001879void PCHReader::InitializeSema(Sema &S) {
1880 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001881 S.ExternalSource = this;
1882
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001883 // Makes sure any declarations that were deserialized "too early"
1884 // still get added to the identifier's declaration chains.
1885 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
1886 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
1887 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001888 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001889 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001890
1891 // If there were any tentative definitions, deserialize them and add
1892 // them to Sema's table of tentative definitions.
1893 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
1894 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
1895 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
1896 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00001897
1898 // If there were any locally-scoped external declarations,
1899 // deserialize them and add them to Sema's table of locally-scoped
1900 // external declarations.
1901 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
1902 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
1903 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
1904 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00001905
1906 // If there were any ext_vector type declarations, deserialize them
1907 // and add them to Sema's vector of such declarations.
1908 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
1909 SemaObj->ExtVectorDecls.push_back(
1910 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
1911
1912 // If there were any Objective-C category implementations,
1913 // deserialize them and add them to Sema's vector of such
1914 // definitions.
1915 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
1916 SemaObj->ObjCCategoryImpls.push_back(
1917 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001918}
1919
1920IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
1921 // Try to find this name within our on-disk hash table
1922 PCHIdentifierLookupTable *IdTable
1923 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1924 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
1925 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
1926 if (Pos == IdTable->end())
1927 return 0;
1928
1929 // Dereferencing the iterator has the effect of building the
1930 // IdentifierInfo node and populating it with the various
1931 // declarations it needs.
1932 return *Pos;
1933}
1934
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001935std::pair<ObjCMethodList, ObjCMethodList>
1936PCHReader::ReadMethodPool(Selector Sel) {
1937 if (!MethodPoolLookupTable)
1938 return std::pair<ObjCMethodList, ObjCMethodList>();
1939
1940 // Try to find this selector within our on-disk hash table.
1941 PCHMethodPoolLookupTable *PoolTable
1942 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
1943 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00001944 if (Pos == PoolTable->end()) {
1945 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001946 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00001947 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001948
Douglas Gregor83941df2009-04-25 17:48:32 +00001949 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001950 return *Pos;
1951}
1952
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001953void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00001954 assert(ID && "Non-zero identifier ID required");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001955 assert(ID <= IdentifiersLoaded.size() && "Identifier ID out of range");
1956 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001957}
1958
Chris Lattner7356a312009-04-11 21:15:38 +00001959IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001960 if (ID == 0)
1961 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00001962
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001963 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001964 Error("No identifier table in PCH file");
1965 return 0;
1966 }
Chris Lattner7356a312009-04-11 21:15:38 +00001967
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001968 if (!IdentifiersLoaded[ID - 1]) {
1969 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00001970 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00001971
Douglas Gregor02fc7512009-04-28 20:01:51 +00001972 // All of the strings in the PCH file are preceded by a 16-bit
1973 // length. Extract that 16-bit length to avoid having to execute
1974 // strlen().
1975 const char *StrLenPtr = Str - 2;
1976 unsigned StrLen = (((unsigned) StrLenPtr[0])
1977 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
1978 IdentifiersLoaded[ID - 1]
1979 = &PP.getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001980 }
Chris Lattner7356a312009-04-11 21:15:38 +00001981
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001982 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001983}
1984
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001985void PCHReader::ReadSLocEntry(unsigned ID) {
1986 ReadSLocEntryRecord(ID);
1987}
1988
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001989Selector PCHReader::DecodeSelector(unsigned ID) {
1990 if (ID == 0)
1991 return Selector();
1992
Douglas Gregor83941df2009-04-25 17:48:32 +00001993 if (!MethodPoolLookupTableData) {
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001994 Error("No selector table in PCH file");
1995 return Selector();
1996 }
Douglas Gregor83941df2009-04-25 17:48:32 +00001997
1998 if (ID > TotalNumSelectors) {
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001999 Error("Selector ID out of range");
2000 return Selector();
2001 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002002
2003 unsigned Index = ID - 1;
2004 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2005 // Load this selector from the selector table.
2006 // FIXME: endianness portability issues with SelectorOffsets table
2007 PCHMethodPoolLookupTrait Trait(*this);
2008 SelectorsLoaded[Index]
2009 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2010 }
2011
2012 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002013}
2014
Douglas Gregor2cf26342009-04-09 22:27:44 +00002015DeclarationName
2016PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2017 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2018 switch (Kind) {
2019 case DeclarationName::Identifier:
2020 return DeclarationName(GetIdentifierInfo(Record, Idx));
2021
2022 case DeclarationName::ObjCZeroArgSelector:
2023 case DeclarationName::ObjCOneArgSelector:
2024 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002025 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002026
2027 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002028 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002029 GetType(Record[Idx++]));
2030
2031 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002032 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002033 GetType(Record[Idx++]));
2034
2035 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002036 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002037 GetType(Record[Idx++]));
2038
2039 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002040 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002041 (OverloadedOperatorKind)Record[Idx++]);
2042
2043 case DeclarationName::CXXUsingDirective:
2044 return DeclarationName::getUsingDirectiveName();
2045 }
2046
2047 // Required to silence GCC warning
2048 return DeclarationName();
2049}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002050
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002051/// \brief Read an integral value
2052llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2053 unsigned BitWidth = Record[Idx++];
2054 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2055 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2056 Idx += NumWords;
2057 return Result;
2058}
2059
2060/// \brief Read a signed integral value
2061llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2062 bool isUnsigned = Record[Idx++];
2063 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2064}
2065
Douglas Gregor17fc2232009-04-14 21:55:33 +00002066/// \brief Read a floating-point value
2067llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002068 return llvm::APFloat(ReadAPInt(Record, Idx));
2069}
2070
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002071// \brief Read a string
2072std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2073 unsigned Len = Record[Idx++];
2074 std::string Result(&Record[Idx], &Record[Idx] + Len);
2075 Idx += Len;
2076 return Result;
2077}
2078
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002079DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002080 return Diag(SourceLocation(), DiagID);
2081}
2082
2083DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2084 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002085 PP.getSourceManager()),
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002086 DiagID);
2087}
Douglas Gregor025452f2009-04-17 00:04:06 +00002088
Douglas Gregor668c1a42009-04-21 22:25:48 +00002089/// \brief Retrieve the identifier table associated with the
2090/// preprocessor.
2091IdentifierTable &PCHReader::getIdentifierTable() {
2092 return PP.getIdentifierTable();
2093}
2094
Douglas Gregor025452f2009-04-17 00:04:06 +00002095/// \brief Record that the given ID maps to the given switch-case
2096/// statement.
2097void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2098 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2099 SwitchCaseStmts[ID] = SC;
2100}
2101
2102/// \brief Retrieve the switch-case statement with the given ID.
2103SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2104 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2105 return SwitchCaseStmts[ID];
2106}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002107
2108/// \brief Record that the given label statement has been
2109/// deserialized and has the given ID.
2110void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2111 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2112 "Deserialized label twice");
2113 LabelStmts[ID] = S;
2114
2115 // If we've already seen any goto statements that point to this
2116 // label, resolve them now.
2117 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2118 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2119 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2120 Goto->second->setLabel(S);
2121 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002122
2123 // If we've already seen any address-label statements that point to
2124 // this label, resolve them now.
2125 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2126 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2127 = UnresolvedAddrLabelExprs.equal_range(ID);
2128 for (AddrLabelIter AddrLabel = AddrLabels.first;
2129 AddrLabel != AddrLabels.second; ++AddrLabel)
2130 AddrLabel->second->setLabel(S);
2131 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002132}
2133
2134/// \brief Set the label of the given statement to the label
2135/// identified by ID.
2136///
2137/// Depending on the order in which the label and other statements
2138/// referencing that label occur, this operation may complete
2139/// immediately (updating the statement) or it may queue the
2140/// statement to be back-patched later.
2141void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2142 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2143 if (Label != LabelStmts.end()) {
2144 // We've already seen this label, so set the label of the goto and
2145 // we're done.
2146 S->setLabel(Label->second);
2147 } else {
2148 // We haven't seen this label yet, so add this goto to the set of
2149 // unresolved goto statements.
2150 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2151 }
2152}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002153
2154/// \brief Set the label of the given expression to the label
2155/// identified by ID.
2156///
2157/// Depending on the order in which the label and other statements
2158/// referencing that label occur, this operation may complete
2159/// immediately (updating the statement) or it may queue the
2160/// statement to be back-patched later.
2161void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2162 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2163 if (Label != LabelStmts.end()) {
2164 // We've already seen this label, so set the label of the
2165 // label-address expression and we're done.
2166 S->setLabel(Label->second);
2167 } else {
2168 // We haven't seen this label yet, so add this label-address
2169 // expression to the set of unresolved label-address expressions.
2170 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2171 }
2172}