blob: f1d7e7a5586ce4b50a6f8fc2b36e9d973e2e196e [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 Gregor6cfc1a82009-04-22 21:15:06 +0000223 uint32_t Bits = ReadUnalignedLE32(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000224 bool CPlusPlusOperatorKeyword = Bits & 0x01;
225 Bits >>= 1;
226 bool Poisoned = Bits & 0x01;
227 Bits >>= 1;
228 bool ExtensionToken = Bits & 0x01;
229 Bits >>= 1;
230 bool hasMacroDefinition = Bits & 0x01;
231 Bits >>= 1;
232 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
233 Bits >>= 10;
234 unsigned TokenID = Bits & 0xFF;
235 Bits >>= 8;
236
Douglas Gregor668c1a42009-04-21 22:25:48 +0000237 pch::IdentID ID = ReadUnalignedLE32(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000238 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor668c1a42009-04-21 22:25:48 +0000239 DataLen -= 8;
240
241 // Build the IdentifierInfo itself and link the identifier ID with
242 // the new IdentifierInfo.
243 IdentifierInfo *II = KnownII;
244 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000245 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
246 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000247 Reader.SetIdentifierInfo(ID, II);
248
Douglas Gregor2deaea32009-04-22 18:49:13 +0000249 // Set or check the various bits in the IdentifierInfo structure.
250 // FIXME: Load token IDs lazily, too?
251 assert((unsigned)II->getTokenID() == TokenID &&
252 "Incorrect token ID loaded");
253 (void)TokenID;
254 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
255 assert(II->isExtensionToken() == ExtensionToken &&
256 "Incorrect extension token flag");
257 (void)ExtensionToken;
258 II->setIsPoisoned(Poisoned);
259 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
260 "Incorrect C++ operator keyword flag");
261 (void)CPlusPlusOperatorKeyword;
262
Douglas Gregor37e26842009-04-21 23:56:24 +0000263 // If this identifier is a macro, deserialize the macro
264 // definition.
265 if (hasMacroDefinition) {
266 uint32_t Offset = ReadUnalignedLE64(d);
267 Reader.ReadMacroRecord(Offset);
268 DataLen -= 8;
269 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000270
271 // Read all of the declarations visible at global scope with this
272 // name.
273 Sema *SemaObj = Reader.getSema();
Chris Lattner6bf690f2009-04-27 22:17:41 +0000274 if (Reader.getContext() == 0) return II;
Chris Lattnercc7dea82009-04-27 22:02:30 +0000275
Douglas Gregor668c1a42009-04-21 22:25:48 +0000276 while (DataLen > 0) {
277 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000278 if (SemaObj) {
279 // Introduce this declaration into the translation-unit scope
280 // and add it to the declaration chain for this identifier, so
281 // that (unqualified) name lookup will find it.
282 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
283 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
284 } else {
285 // Queue this declaration so that it will be added to the
286 // translation unit scope and identifier's declaration chain
287 // once a Sema object is known.
Douglas Gregor6cfc1a82009-04-22 21:15:06 +0000288 Reader.PreloadedDecls.push_back(D);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000289 }
290
291 DataLen -= 4;
292 }
293 return II;
294 }
295};
296
297} // end anonymous namespace
298
299/// \brief The on-disk hash table used to contain information about
300/// all of the identifiers in the program.
301typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
302 PCHIdentifierLookupTable;
303
Douglas Gregor2cf26342009-04-09 22:27:44 +0000304// FIXME: use the diagnostics machinery
305static bool Error(const char *Str) {
306 std::fprintf(stderr, "%s\n", Str);
307 return true;
308}
309
Douglas Gregore721f952009-04-28 18:58:38 +0000310/// \brief Split the given string into a vector of lines, eliminating
311/// any empty lines in the process.
312///
313/// \param Str the string to split.
314/// \param Len the length of Str.
315/// \param KeepEmptyLines true if empty lines should be included
316/// \returns a vector of lines, with the line endings removed
317std::vector<std::string> splitLines(const char *Str, unsigned Len,
318 bool KeepEmptyLines = false) {
319 std::vector<std::string> Lines;
320 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
321 unsigned LineEnd = LineStart;
322 while (LineEnd < Len && Str[LineEnd] != '\n')
323 ++LineEnd;
324 if (LineStart != LineEnd || KeepEmptyLines)
325 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
326 LineStart = LineEnd;
327 }
328 return Lines;
329}
330
331/// \brief Determine whether the string Haystack starts with the
332/// substring Needle.
333static bool startsWith(const std::string &Haystack, const char *Needle) {
334 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
335 if (I == N)
336 return false;
337 if (Haystack[I] != Needle[I])
338 return false;
339 }
340
341 return true;
342}
343
344/// \brief Determine whether the string Haystack starts with the
345/// substring Needle.
346static inline bool startsWith(const std::string &Haystack,
347 const std::string &Needle) {
348 return startsWith(Haystack, Needle.c_str());
349}
350
Douglas Gregore1d918e2009-04-10 23:10:45 +0000351/// \brief Check the contents of the predefines buffer against the
352/// contents of the predefines buffer used to build the PCH file.
353///
354/// The contents of the two predefines buffers should be the same. If
355/// not, then some command-line option changed the preprocessor state
356/// and we must reject the PCH file.
357///
358/// \param PCHPredef The start of the predefines buffer in the PCH
359/// file.
360///
361/// \param PCHPredefLen The length of the predefines buffer in the PCH
362/// file.
363///
364/// \param PCHBufferID The FileID for the PCH predefines buffer.
365///
366/// \returns true if there was a mismatch (in which case the PCH file
367/// should be ignored), or false otherwise.
368bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
369 unsigned PCHPredefLen,
370 FileID PCHBufferID) {
371 const char *Predef = PP.getPredefines().c_str();
372 unsigned PredefLen = PP.getPredefines().size();
373
Douglas Gregore721f952009-04-28 18:58:38 +0000374 // If the two predefines buffers compare equal, we're done!
Douglas Gregore1d918e2009-04-10 23:10:45 +0000375 if (PredefLen == PCHPredefLen &&
376 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
377 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000378
Douglas Gregore1d918e2009-04-10 23:10:45 +0000379 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregore721f952009-04-28 18:58:38 +0000380
381 // The predefines buffers are different. Determine what the
382 // differences are, and whether they require us to reject the PCH
383 // file.
384 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
385 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000386
Douglas Gregore721f952009-04-28 18:58:38 +0000387 // Sort both sets of predefined buffer lines, since
388 std::sort(CmdLineLines.begin(), CmdLineLines.end());
389 std::sort(PCHLines.begin(), PCHLines.end());
Douglas Gregore1d918e2009-04-10 23:10:45 +0000390
Douglas Gregore721f952009-04-28 18:58:38 +0000391 // Determine which predefines that where used to build the PCH file
392 // are missing from the command line.
393 std::vector<std::string> MissingPredefines;
394 std::set_difference(PCHLines.begin(), PCHLines.end(),
395 CmdLineLines.begin(), CmdLineLines.end(),
396 std::back_inserter(MissingPredefines));
397
398 bool MissingDefines = false;
399 bool ConflictingDefines = false;
400 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
401 const std::string &Missing = MissingPredefines[I];
402 if (!startsWith(Missing, "#define ") != 0) {
403 fprintf(stderr, "FIXME: command line is missing a non-macro entry in the predefines buffer that was used to build the PCH file\n%s\n",
404 Missing.c_str());
405 return true;
406 }
407
408 // This is a macro definition. Determine the name of the macro
409 // we're defining.
410 std::string::size_type StartOfMacroName = strlen("#define ");
411 std::string::size_type EndOfMacroName
412 = Missing.find_first_of("( \n\r", StartOfMacroName);
413 assert(EndOfMacroName != std::string::npos &&
414 "Couldn't find the end of the macro name");
415 std::string MacroName = Missing.substr(StartOfMacroName,
416 EndOfMacroName - StartOfMacroName);
417
418 // Determine whether this macro was given a different definition
419 // on the command line.
420 std::string MacroDefStart = "#define " + MacroName;
421 std::string::size_type MacroDefLen = MacroDefStart.size();
422 std::vector<std::string>::iterator ConflictPos
423 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
424 MacroDefStart);
425 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
426 if (!startsWith(*ConflictPos, MacroDefStart)) {
427 // Different macro; we're done.
428 ConflictPos = CmdLineLines.end();
429 break;
430 }
431
432 assert(ConflictPos->size() > MacroDefLen &&
433 "Invalid #define in predefines buffer?");
434 if ((*ConflictPos)[MacroDefLen] != ' ' &&
435 (*ConflictPos)[MacroDefLen] != '(')
436 continue; // Longer macro name; keep trying.
437
438 // We found a conflicting macro definition.
439 break;
440 }
441
442 if (ConflictPos != CmdLineLines.end()) {
443 Diag(diag::warn_cmdline_conflicting_macro_def)
444 << MacroName;
445
446 // Show the definition of this macro within the PCH file.
447 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
448 unsigned Offset = MissingDef - PCHPredef;
449 SourceLocation PCHMissingLoc
450 = SourceMgr.getLocForStartOfFile(PCHBufferID)
451 .getFileLocWithOffset(Offset);
452 Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
453 << MacroName;
454
455 ConflictingDefines = true;
456 continue;
457 }
458
459 // If the macro doesn't conflict, then we'll just pick up the
460 // macro definition from the PCH file. Warn the user that they
461 // made a mistake.
462 if (ConflictingDefines)
463 continue; // Don't complain if there are already conflicting defs
464
465 if (!MissingDefines) {
466 Diag(diag::warn_cmdline_missing_macro_defs);
467 MissingDefines = true;
468 }
469
470 // Show the definition of this macro within the PCH file.
471 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
472 unsigned Offset = MissingDef - PCHPredef;
473 SourceLocation PCHMissingLoc
474 = SourceMgr.getLocForStartOfFile(PCHBufferID)
475 .getFileLocWithOffset(Offset);
476 Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000477 }
478
Douglas Gregore721f952009-04-28 18:58:38 +0000479 if (ConflictingDefines) {
480 Diag(diag::note_ignoring_pch) << FileName;
481 return true;
482 }
483
484 // Determine what predefines were introduced based on command-line
485 // parameters that were not present when building the PCH
486 // file. Extra #defines are okay, so long as the identifiers being
487 // defined were not used within the precompiled header.
488 std::vector<std::string> ExtraPredefines;
489 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
490 PCHLines.begin(), PCHLines.end(),
491 std::back_inserter(ExtraPredefines));
492 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
493 const std::string &Extra = ExtraPredefines[I];
494 if (!startsWith(Extra, "#define ") != 0) {
495 fprintf(stderr, "FIXME: command line has extra predefines not used to build the PCH file.%s\n",
496 Extra.c_str());
497 return true;
498 }
499
500 // This is an extra macro definition. Determine the name of the
501 // macro we're defining.
502 std::string::size_type StartOfMacroName = strlen("#define ");
503 std::string::size_type EndOfMacroName
504 = Extra.find_first_of("( \n\r", StartOfMacroName);
505 assert(EndOfMacroName != std::string::npos &&
506 "Couldn't find the end of the macro name");
507 std::string MacroName = Extra.substr(StartOfMacroName,
508 EndOfMacroName - StartOfMacroName);
509
510 // FIXME: Perform this check!
511 fprintf(stderr, "FIXME: check whether '%s' was used in the PCH file\n",
512 MacroName.c_str());
513
514 // Add this definition to the suggested predefines buffer.
515 SuggestedPredefines += Extra;
516 SuggestedPredefines += '\n';
517 }
518
519 // If we get here, it's because the predefines buffer had compatible
520 // contents. Accept the PCH file.
521 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000522}
523
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000524//===----------------------------------------------------------------------===//
525// Source Manager Deserialization
526//===----------------------------------------------------------------------===//
527
Douglas Gregorbd945002009-04-13 16:31:14 +0000528/// \brief Read the line table in the source manager block.
529/// \returns true if ther was an error.
530static bool ParseLineTable(SourceManager &SourceMgr,
531 llvm::SmallVectorImpl<uint64_t> &Record) {
532 unsigned Idx = 0;
533 LineTableInfo &LineTable = SourceMgr.getLineTable();
534
535 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000536 std::map<int, int> FileIDs;
537 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000538 // Extract the file name
539 unsigned FilenameLen = Record[Idx++];
540 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
541 Idx += FilenameLen;
Douglas Gregorff0a9872009-04-13 17:12:42 +0000542 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
543 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000544 }
545
546 // Parse the line entries
547 std::vector<LineEntry> Entries;
548 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000549 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000550
551 // Extract the line entries
552 unsigned NumEntries = Record[Idx++];
553 Entries.clear();
554 Entries.reserve(NumEntries);
555 for (unsigned I = 0; I != NumEntries; ++I) {
556 unsigned FileOffset = Record[Idx++];
557 unsigned LineNo = Record[Idx++];
558 int FilenameID = Record[Idx++];
559 SrcMgr::CharacteristicKind FileKind
560 = (SrcMgr::CharacteristicKind)Record[Idx++];
561 unsigned IncludeOffset = Record[Idx++];
562 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
563 FileKind, IncludeOffset));
564 }
565 LineTable.AddEntry(FID, Entries);
566 }
567
568 return false;
569}
570
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000571namespace {
572
573class VISIBILITY_HIDDEN PCHStatData {
574public:
575 const bool hasStat;
576 const ino_t ino;
577 const dev_t dev;
578 const mode_t mode;
579 const time_t mtime;
580 const off_t size;
581
582 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
583 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
584
585 PCHStatData()
586 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
587};
588
589class VISIBILITY_HIDDEN PCHStatLookupTrait {
590 public:
591 typedef const char *external_key_type;
592 typedef const char *internal_key_type;
593
594 typedef PCHStatData data_type;
595
596 static unsigned ComputeHash(const char *path) {
597 return BernsteinHash(path);
598 }
599
600 static internal_key_type GetInternalKey(const char *path) { return path; }
601
602 static bool EqualKey(internal_key_type a, internal_key_type b) {
603 return strcmp(a, b) == 0;
604 }
605
606 static std::pair<unsigned, unsigned>
607 ReadKeyDataLength(const unsigned char*& d) {
608 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
609 unsigned DataLen = (unsigned) *d++;
610 return std::make_pair(KeyLen + 1, DataLen);
611 }
612
613 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
614 return (const char *)d;
615 }
616
617 static data_type ReadData(const internal_key_type, const unsigned char *d,
618 unsigned /*DataLen*/) {
619 using namespace clang::io;
620
621 if (*d++ == 1)
622 return data_type();
623
624 ino_t ino = (ino_t) ReadUnalignedLE32(d);
625 dev_t dev = (dev_t) ReadUnalignedLE32(d);
626 mode_t mode = (mode_t) ReadUnalignedLE16(d);
627 time_t mtime = (time_t) ReadUnalignedLE64(d);
628 off_t size = (off_t) ReadUnalignedLE64(d);
629 return data_type(ino, dev, mode, mtime, size);
630 }
631};
632
633/// \brief stat() cache for precompiled headers.
634///
635/// This cache is very similar to the stat cache used by pretokenized
636/// headers.
637class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
638 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
639 CacheTy *Cache;
640
641 unsigned &NumStatHits, &NumStatMisses;
642public:
643 PCHStatCache(const unsigned char *Buckets,
644 const unsigned char *Base,
645 unsigned &NumStatHits,
646 unsigned &NumStatMisses)
647 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
648 Cache = CacheTy::Create(Buckets, Base);
649 }
650
651 ~PCHStatCache() { delete Cache; }
652
653 int stat(const char *path, struct stat *buf) {
654 // Do the lookup for the file's data in the PCH file.
655 CacheTy::iterator I = Cache->find(path);
656
657 // If we don't get a hit in the PCH file just forward to 'stat'.
658 if (I == Cache->end()) {
659 ++NumStatMisses;
660 return ::stat(path, buf);
661 }
662
663 ++NumStatHits;
664 PCHStatData Data = *I;
665
666 if (!Data.hasStat)
667 return 1;
668
669 buf->st_ino = Data.ino;
670 buf->st_dev = Data.dev;
671 buf->st_mtime = Data.mtime;
672 buf->st_mode = Data.mode;
673 buf->st_size = Data.size;
674 return 0;
675 }
676};
677} // end anonymous namespace
678
679
Douglas Gregor14f79002009-04-10 03:52:48 +0000680/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000681PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000682 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000683
684 // Set the source-location entry cursor to the current position in
685 // the stream. This cursor will be used to read the contents of the
686 // source manager block initially, and then lazily read
687 // source-location entries as needed.
688 SLocEntryCursor = Stream;
689
690 // The stream itself is going to skip over the source manager block.
691 if (Stream.SkipBlock()) {
692 Error("Malformed block record");
693 return Failure;
694 }
695
696 // Enter the source manager block.
697 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000698 Error("Malformed source manager block record");
699 return Failure;
700 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000701
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000702 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor14f79002009-04-10 03:52:48 +0000703 RecordData Record;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000704 unsigned NumHeaderInfos = 0;
Douglas Gregor14f79002009-04-10 03:52:48 +0000705 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000706 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000707 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000708 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000709 Error("Error at end of Source Manager block");
710 return Failure;
711 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000712 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000713 }
714
715 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
716 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000717 SLocEntryCursor.ReadSubBlockID();
718 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000719 Error("Malformed block record");
720 return Failure;
721 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000722 continue;
723 }
724
725 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000726 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000727 continue;
728 }
729
730 // Read a record.
731 const char *BlobStart;
732 unsigned BlobLen;
733 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000734 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000735 default: // Default behavior: ignore.
736 break;
737
Chris Lattner2c78b872009-04-14 23:22:57 +0000738 case pch::SM_LINE_TABLE:
Douglas Gregorbd945002009-04-13 16:31:14 +0000739 if (ParseLineTable(SourceMgr, Record))
740 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000741 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000742
743 case pch::SM_HEADER_FILE_INFO: {
744 HeaderFileInfo HFI;
745 HFI.isImport = Record[0];
746 HFI.DirInfo = Record[1];
747 HFI.NumIncludes = Record[2];
748 HFI.ControllingMacroID = Record[3];
749 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
750 break;
751 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000752
753 case pch::SM_SLOC_FILE_ENTRY:
754 case pch::SM_SLOC_BUFFER_ENTRY:
755 case pch::SM_SLOC_INSTANTIATION_ENTRY:
756 // Once we hit one of the source location entries, we're done.
757 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000758 }
759 }
760}
761
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000762/// \brief Read in the source location entry with the given ID.
763PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
764 if (ID == 0)
765 return Success;
766
767 if (ID > TotalNumSLocEntries) {
768 Error("source location entry ID out-of-range for PCH file");
769 return Failure;
770 }
771
772 ++NumSLocEntriesRead;
773 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
774 unsigned Code = SLocEntryCursor.ReadCode();
775 if (Code == llvm::bitc::END_BLOCK ||
776 Code == llvm::bitc::ENTER_SUBBLOCK ||
777 Code == llvm::bitc::DEFINE_ABBREV) {
778 Error("incorrectly-formatted source location entry in PCH file");
779 return Failure;
780 }
781
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000782 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000783 RecordData Record;
784 const char *BlobStart;
785 unsigned BlobLen;
786 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
787 default:
788 Error("incorrectly-formatted source location entry in PCH file");
789 return Failure;
790
791 case pch::SM_SLOC_FILE_ENTRY: {
792 const FileEntry *File
793 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
794 // FIXME: Error recovery if file cannot be found.
795 FileID FID = SourceMgr.createFileID(File,
796 SourceLocation::getFromRawEncoding(Record[1]),
797 (SrcMgr::CharacteristicKind)Record[2],
798 ID, Record[0]);
799 if (Record[3])
800 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
801 .setHasLineDirectives();
802
803 break;
804 }
805
806 case pch::SM_SLOC_BUFFER_ENTRY: {
807 const char *Name = BlobStart;
808 unsigned Offset = Record[0];
809 unsigned Code = SLocEntryCursor.ReadCode();
810 Record.clear();
811 unsigned RecCode
812 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
813 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
814 (void)RecCode;
815 llvm::MemoryBuffer *Buffer
816 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
817 BlobStart + BlobLen - 1,
818 Name);
819 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
820
821 if (strcmp(Name, "<built-in>") == 0
822 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
823 return IgnorePCH;
824
825 break;
826 }
827
828 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
829 SourceLocation SpellingLoc
830 = SourceLocation::getFromRawEncoding(Record[1]);
831 SourceMgr.createInstantiationLoc(SpellingLoc,
832 SourceLocation::getFromRawEncoding(Record[2]),
833 SourceLocation::getFromRawEncoding(Record[3]),
834 Record[4],
835 ID,
836 Record[0]);
837 break;
838 }
839 }
840
841 return Success;
842}
843
Chris Lattner6367f6d2009-04-27 01:05:14 +0000844/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
845/// specified cursor. Read the abbreviations that are at the top of the block
846/// and then leave the cursor pointing into the block.
847bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
848 unsigned BlockID) {
849 if (Cursor.EnterSubBlock(BlockID)) {
850 Error("Malformed block record");
851 return Failure;
852 }
853
Chris Lattner6367f6d2009-04-27 01:05:14 +0000854 while (true) {
855 unsigned Code = Cursor.ReadCode();
856
857 // We expect all abbrevs to be at the start of the block.
858 if (Code != llvm::bitc::DEFINE_ABBREV)
859 return false;
860 Cursor.ReadAbbrevRecord();
861 }
862}
863
Douglas Gregor37e26842009-04-21 23:56:24 +0000864void PCHReader::ReadMacroRecord(uint64_t Offset) {
865 // Keep track of where we are in the stream, then jump back there
866 // after reading this macro.
867 SavedStreamPosition SavedPosition(Stream);
868
869 Stream.JumpToBit(Offset);
870 RecordData Record;
871 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
872 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +0000873
Douglas Gregor37e26842009-04-21 23:56:24 +0000874 while (true) {
875 unsigned Code = Stream.ReadCode();
876 switch (Code) {
877 case llvm::bitc::END_BLOCK:
878 return;
879
880 case llvm::bitc::ENTER_SUBBLOCK:
881 // No known subblocks, always skip them.
882 Stream.ReadSubBlockID();
883 if (Stream.SkipBlock()) {
884 Error("Malformed block record");
885 return;
886 }
887 continue;
888
889 case llvm::bitc::DEFINE_ABBREV:
890 Stream.ReadAbbrevRecord();
891 continue;
892 default: break;
893 }
894
895 // Read a record.
896 Record.clear();
897 pch::PreprocessorRecordTypes RecType =
898 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
899 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +0000900 case pch::PP_MACRO_OBJECT_LIKE:
901 case pch::PP_MACRO_FUNCTION_LIKE: {
902 // If we already have a macro, that means that we've hit the end
903 // of the definition of the macro we were looking for. We're
904 // done.
905 if (Macro)
906 return;
907
908 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
909 if (II == 0) {
910 Error("Macro must have a name");
911 return;
912 }
913 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
914 bool isUsed = Record[2];
915
916 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
917 MI->setIsUsed(isUsed);
918
919 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
920 // Decode function-like macro info.
921 bool isC99VarArgs = Record[3];
922 bool isGNUVarArgs = Record[4];
923 MacroArgs.clear();
924 unsigned NumArgs = Record[5];
925 for (unsigned i = 0; i != NumArgs; ++i)
926 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
927
928 // Install function-like macro info.
929 MI->setIsFunctionLike();
930 if (isC99VarArgs) MI->setIsC99Varargs();
931 if (isGNUVarArgs) MI->setIsGNUVarargs();
932 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
933 PP.getPreprocessorAllocator());
934 }
935
936 // Finally, install the macro.
937 PP.setMacroInfo(II, MI);
938
939 // Remember that we saw this macro last so that we add the tokens that
940 // form its body to it.
941 Macro = MI;
942 ++NumMacrosRead;
943 break;
944 }
945
946 case pch::PP_TOKEN: {
947 // If we see a TOKEN before a PP_MACRO_*, then the file is
948 // erroneous, just pretend we didn't see this.
949 if (Macro == 0) break;
950
951 Token Tok;
952 Tok.startToken();
953 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
954 Tok.setLength(Record[1]);
955 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
956 Tok.setIdentifierInfo(II);
957 Tok.setKind((tok::TokenKind)Record[3]);
958 Tok.setFlag((Token::TokenFlags)Record[4]);
959 Macro->AddTokenToBody(Tok);
960 break;
961 }
Steve Naroff83d63c72009-04-24 20:03:17 +0000962 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000963 }
964}
965
Douglas Gregor668c1a42009-04-21 22:25:48 +0000966PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000967PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000968 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
969 Error("Malformed block record");
970 return Failure;
971 }
Douglas Gregor2cf26342009-04-09 22:27:44 +0000972
973 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +0000974 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000975 while (!Stream.AtEndOfStream()) {
976 unsigned Code = Stream.ReadCode();
977 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000978 if (Stream.ReadBlockEnd()) {
979 Error("Error at end of module block");
980 return Failure;
981 }
Chris Lattner7356a312009-04-11 21:15:38 +0000982
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000983 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000984 }
985
986 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
987 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000988 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
989 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000990 if (Stream.SkipBlock()) {
991 Error("Malformed block record");
992 return Failure;
993 }
Douglas Gregor2cf26342009-04-09 22:27:44 +0000994 break;
995
Chris Lattner6367f6d2009-04-27 01:05:14 +0000996 case pch::DECLS_BLOCK_ID:
997 // We lazily load the decls block, but we want to set up the
998 // DeclsCursor cursor to point into it. Clone our current bitcode
999 // cursor to it, enter the block and read the abbrevs in that block.
1000 // With the main cursor, we just skip over it.
1001 DeclsCursor = Stream;
1002 if (Stream.SkipBlock() || // Skip with the main cursor.
1003 // Read the abbrevs.
1004 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
1005 Error("Malformed block record");
1006 return Failure;
1007 }
1008 break;
1009
Chris Lattner7356a312009-04-11 21:15:38 +00001010 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001011 if (Stream.SkipBlock()) {
1012 Error("Malformed block record");
1013 return Failure;
1014 }
1015 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001016
Douglas Gregor14f79002009-04-10 03:52:48 +00001017 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001018 switch (ReadSourceManagerBlock()) {
1019 case Success:
1020 break;
1021
1022 case Failure:
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001023 Error("Malformed source manager block");
1024 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001025
1026 case IgnorePCH:
1027 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001028 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001029 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001030 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001031 continue;
1032 }
1033
1034 if (Code == llvm::bitc::DEFINE_ABBREV) {
1035 Stream.ReadAbbrevRecord();
1036 continue;
1037 }
1038
1039 // Read and process a record.
1040 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001041 const char *BlobStart = 0;
1042 unsigned BlobLen = 0;
1043 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1044 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001045 default: // Default behavior: ignore.
1046 break;
1047
1048 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001049 if (!TypesLoaded.empty()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001050 Error("Duplicate TYPE_OFFSET record in PCH file");
1051 return Failure;
1052 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001053 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001054 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001055 break;
1056
1057 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001058 if (!DeclsLoaded.empty()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001059 Error("Duplicate DECL_OFFSET record in PCH file");
1060 return Failure;
1061 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001062 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001063 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001064 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001065
1066 case pch::LANGUAGE_OPTIONS:
1067 if (ParseLanguageOptions(Record))
1068 return IgnorePCH;
1069 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001070
Douglas Gregorab41e632009-04-27 22:23:34 +00001071 case pch::METADATA: {
1072 if (Record[0] != pch::VERSION_MAJOR) {
1073 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1074 : diag::warn_pch_version_too_new);
1075 return IgnorePCH;
1076 }
1077
Douglas Gregor2bec0412009-04-10 21:16:55 +00001078 std::string TargetTriple(BlobStart, BlobLen);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001079 if (TargetTriple != PP.getTargetInfo().getTargetTriple()) {
Douglas Gregor2bec0412009-04-10 21:16:55 +00001080 Diag(diag::warn_pch_target_triple)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001081 << TargetTriple << PP.getTargetInfo().getTargetTriple();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001082 Diag(diag::note_ignoring_pch) << FileName;
1083 return IgnorePCH;
1084 }
1085 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001086 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001087
1088 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001089 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001090 if (Record[0]) {
1091 IdentifierLookupTable
1092 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001093 (const unsigned char *)IdentifierTableData + Record[0],
1094 (const unsigned char *)IdentifierTableData,
1095 PCHIdentifierLookupTrait(*this));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001096 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1097 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001098 break;
1099
1100 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001101 if (!IdentifiersLoaded.empty()) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001102 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
1103 return Failure;
1104 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001105 IdentifierOffsets = (const uint32_t *)BlobStart;
1106 IdentifiersLoaded.resize(Record[0]);
Douglas Gregor8c5a7602009-04-25 23:30:02 +00001107 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001108 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001109
1110 case pch::EXTERNAL_DEFINITIONS:
1111 if (!ExternalDefinitions.empty()) {
1112 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
1113 return Failure;
1114 }
1115 ExternalDefinitions.swap(Record);
1116 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001117
Douglas Gregorad1de002009-04-18 05:55:16 +00001118 case pch::SPECIAL_TYPES:
1119 SpecialTypes.swap(Record);
1120 break;
1121
Douglas Gregor3e1af842009-04-17 22:13:46 +00001122 case pch::STATISTICS:
1123 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001124 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001125 TotalLexicalDeclContexts = Record[2];
1126 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001127 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001128
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001129 case pch::TENTATIVE_DEFINITIONS:
1130 if (!TentativeDefinitions.empty()) {
1131 Error("Duplicate TENTATIVE_DEFINITIONS record in PCH file");
1132 return Failure;
1133 }
1134 TentativeDefinitions.swap(Record);
1135 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001136
1137 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1138 if (!LocallyScopedExternalDecls.empty()) {
1139 Error("Duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
1140 return Failure;
1141 }
1142 LocallyScopedExternalDecls.swap(Record);
1143 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001144
Douglas Gregor83941df2009-04-25 17:48:32 +00001145 case pch::SELECTOR_OFFSETS:
1146 SelectorOffsets = (const uint32_t *)BlobStart;
1147 TotalNumSelectors = Record[0];
1148 SelectorsLoaded.resize(TotalNumSelectors);
1149 break;
1150
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001151 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001152 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1153 if (Record[0])
1154 MethodPoolLookupTable
1155 = PCHMethodPoolLookupTable::Create(
1156 MethodPoolLookupTableData + Record[0],
1157 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001158 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001159 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001160 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001161
1162 case pch::PP_COUNTER_VALUE:
1163 if (!Record.empty())
1164 PP.setCounterValue(Record[0]);
1165 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001166
1167 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001168 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001169 TotalNumSLocEntries = Record[0];
1170 PP.getSourceManager().PreallocateSLocEntries(this,
1171 TotalNumSLocEntries,
1172 Record[1]);
1173 break;
1174
1175 case pch::SOURCE_LOCATION_PRELOADS:
1176 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1177 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1178 if (Result != Success)
1179 return Result;
1180 }
1181 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001182
1183 case pch::STAT_CACHE:
1184 PP.getFileManager().setStatCache(
1185 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1186 (const unsigned char *)BlobStart,
1187 NumStatHits, NumStatMisses));
1188 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001189
1190 case pch::EXT_VECTOR_DECLS:
1191 if (!ExtVectorDecls.empty()) {
1192 Error("Duplicate EXT_VECTOR_DECLS record in PCH file");
1193 return Failure;
1194 }
1195 ExtVectorDecls.swap(Record);
1196 break;
1197
1198 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1199 if (!ObjCCategoryImpls.empty()) {
1200 Error("Duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
1201 return Failure;
1202 }
1203 ObjCCategoryImpls.swap(Record);
1204 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001205 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001206 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001207 Error("Premature end of bitstream");
1208 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001209}
1210
Douglas Gregore1d918e2009-04-10 23:10:45 +00001211PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001212 // Set the PCH file name.
1213 this->FileName = FileName;
1214
Douglas Gregor2cf26342009-04-09 22:27:44 +00001215 // Open the PCH file.
1216 std::string ErrStr;
1217 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001218 if (!Buffer) {
1219 Error(ErrStr.c_str());
1220 return IgnorePCH;
1221 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001222
1223 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001224 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1225 (const unsigned char *)Buffer->getBufferEnd());
1226 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001227
1228 // Sniff for the signature.
1229 if (Stream.Read(8) != 'C' ||
1230 Stream.Read(8) != 'P' ||
1231 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001232 Stream.Read(8) != 'H') {
1233 Error("Not a PCH file");
1234 return IgnorePCH;
1235 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001236
Douglas Gregor2cf26342009-04-09 22:27:44 +00001237 while (!Stream.AtEndOfStream()) {
1238 unsigned Code = Stream.ReadCode();
1239
Douglas Gregore1d918e2009-04-10 23:10:45 +00001240 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1241 Error("Invalid record at top-level");
1242 return Failure;
1243 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001244
1245 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001246
Douglas Gregor2cf26342009-04-09 22:27:44 +00001247 // We only know the PCH subblock ID.
1248 switch (BlockID) {
1249 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001250 if (Stream.ReadBlockInfoBlock()) {
1251 Error("Malformed BlockInfoBlock");
1252 return Failure;
1253 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001254 break;
1255 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001256 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001257 case Success:
1258 break;
1259
1260 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001261 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001262
1263 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001264 // FIXME: We could consider reading through to the end of this
1265 // PCH block, skipping subblocks, to see if there are other
1266 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001267
1268 // Clear out any preallocated source location entries, so that
1269 // the source manager does not try to resolve them later.
1270 PP.getSourceManager().ClearPreallocatedSLocEntries();
1271
1272 // Remove the stat cache.
1273 PP.getFileManager().setStatCache(0);
1274
Douglas Gregore1d918e2009-04-10 23:10:45 +00001275 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001276 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001277 break;
1278 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001279 if (Stream.SkipBlock()) {
1280 Error("Malformed block record");
1281 return Failure;
1282 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001283 break;
1284 }
1285 }
1286
1287 // Load the translation unit declaration
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001288 if (Context)
1289 ReadDeclRecord(DeclOffsets[0], 0);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001290
Douglas Gregor668c1a42009-04-21 22:25:48 +00001291 // Initialization of builtins and library builtins occurs before the
1292 // PCH file is read, so there may be some identifiers that were
1293 // loaded into the IdentifierTable before we intercepted the
1294 // creation of identifiers. Iterate through the list of known
1295 // identifiers and determine whether we have to establish
1296 // preprocessor definitions or top-level identifier declaration
1297 // chains for those identifiers.
1298 //
1299 // We copy the IdentifierInfo pointers to a small vector first,
1300 // since de-serializing declarations or macro definitions can add
1301 // new entries into the identifier table, invalidating the
1302 // iterators.
1303 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1304 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
1305 IdEnd = PP.getIdentifierTable().end();
1306 Id != IdEnd; ++Id)
1307 Identifiers.push_back(Id->second);
1308 PCHIdentifierLookupTable *IdTable
1309 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1310 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1311 IdentifierInfo *II = Identifiers[I];
1312 // Look in the on-disk hash table for an entry for
1313 PCHIdentifierLookupTrait Info(*this, II);
1314 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1315 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1316 if (Pos == IdTable->end())
1317 continue;
1318
1319 // Dereferencing the iterator has the effect of populating the
1320 // IdentifierInfo node with the various declarations it needs.
1321 (void)*Pos;
1322 }
1323
Douglas Gregorad1de002009-04-18 05:55:16 +00001324 // Load the special types.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001325 if (Context) {
1326 Context->setBuiltinVaListType(
1327 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1328 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1329 Context->setObjCIdType(GetType(Id));
1330 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1331 Context->setObjCSelType(GetType(Sel));
1332 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1333 Context->setObjCProtoType(GetType(Proto));
1334 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1335 Context->setObjCClassType(GetType(Class));
1336 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1337 Context->setCFConstantStringType(GetType(String));
1338 if (unsigned FastEnum
1339 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1340 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1341 }
Douglas Gregor0b748912009-04-14 21:18:50 +00001342
Douglas Gregor668c1a42009-04-21 22:25:48 +00001343 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001344}
1345
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001346/// \brief Parse the record that corresponds to a LangOptions data
1347/// structure.
1348///
1349/// This routine compares the language options used to generate the
1350/// PCH file against the language options set for the current
1351/// compilation. For each option, we classify differences between the
1352/// two compiler states as either "benign" or "important". Benign
1353/// differences don't matter, and we accept them without complaint
1354/// (and without modifying the language options). Differences between
1355/// the states for important options cause the PCH file to be
1356/// unusable, so we emit a warning and return true to indicate that
1357/// there was an error.
1358///
1359/// \returns true if the PCH file is unacceptable, false otherwise.
1360bool PCHReader::ParseLanguageOptions(
1361 const llvm::SmallVectorImpl<uint64_t> &Record) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001362 const LangOptions &LangOpts = PP.getLangOptions();
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001363#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1364#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1365 if (Record[Idx] != LangOpts.Option) { \
1366 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1367 Diag(diag::note_ignoring_pch) << FileName; \
1368 return true; \
1369 } \
1370 ++Idx
1371
1372 unsigned Idx = 0;
1373 PARSE_LANGOPT_BENIGN(Trigraphs);
1374 PARSE_LANGOPT_BENIGN(BCPLComment);
1375 PARSE_LANGOPT_BENIGN(DollarIdents);
1376 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1377 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1378 PARSE_LANGOPT_BENIGN(ImplicitInt);
1379 PARSE_LANGOPT_BENIGN(Digraphs);
1380 PARSE_LANGOPT_BENIGN(HexFloats);
1381 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1382 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1383 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1384 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001385 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1386 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1387 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1388 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1389 PARSE_LANGOPT_BENIGN(PascalStrings);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001390 PARSE_LANGOPT_BENIGN(WritableStrings);
1391 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1392 diag::warn_pch_lax_vector_conversions);
1393 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1394 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1395 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1396 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1397 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1398 diag::warn_pch_thread_safe_statics);
1399 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1400 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1401 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1402 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1403 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1404 diag::warn_pch_heinous_extensions);
1405 // FIXME: Most of the options below are benign if the macro wasn't
1406 // used. Unfortunately, this means that a PCH compiled without
1407 // optimization can't be used with optimization turned on, even
1408 // though the only thing that changes is whether __OPTIMIZE__ was
1409 // defined... but if __OPTIMIZE__ never showed up in the header, it
1410 // doesn't matter. We could consider making this some special kind
1411 // of check.
1412 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1413 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1414 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1415 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1416 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1417 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1418 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1419 Diag(diag::warn_pch_gc_mode)
1420 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1421 Diag(diag::note_ignoring_pch) << FileName;
1422 return true;
1423 }
1424 ++Idx;
1425 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1426 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1427#undef PARSE_LANGOPT_IRRELEVANT
1428#undef PARSE_LANGOPT_BENIGN
1429
1430 return false;
1431}
1432
Douglas Gregor2cf26342009-04-09 22:27:44 +00001433/// \brief Read and return the type at the given offset.
1434///
1435/// This routine actually reads the record corresponding to the type
1436/// at the given offset in the bitstream. It is a helper routine for
1437/// GetType, which deals with reading type IDs.
1438QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001439 // Keep track of where we are in the stream, then jump back there
1440 // after reading this type.
1441 SavedStreamPosition SavedPosition(Stream);
1442
Douglas Gregor2cf26342009-04-09 22:27:44 +00001443 Stream.JumpToBit(Offset);
1444 RecordData Record;
1445 unsigned Code = Stream.ReadCode();
1446 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001447 case pch::TYPE_EXT_QUAL: {
1448 assert(Record.size() == 3 &&
1449 "Incorrect encoding of extended qualifier type");
1450 QualType Base = GetType(Record[0]);
1451 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1452 unsigned AddressSpace = Record[2];
1453
1454 QualType T = Base;
1455 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001456 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001457 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001458 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001459 return T;
1460 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001461
Douglas Gregor2cf26342009-04-09 22:27:44 +00001462 case pch::TYPE_FIXED_WIDTH_INT: {
1463 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001464 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001465 }
1466
1467 case pch::TYPE_COMPLEX: {
1468 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1469 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001470 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001471 }
1472
1473 case pch::TYPE_POINTER: {
1474 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1475 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001476 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001477 }
1478
1479 case pch::TYPE_BLOCK_POINTER: {
1480 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1481 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001482 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001483 }
1484
1485 case pch::TYPE_LVALUE_REFERENCE: {
1486 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1487 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001488 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001489 }
1490
1491 case pch::TYPE_RVALUE_REFERENCE: {
1492 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1493 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001494 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001495 }
1496
1497 case pch::TYPE_MEMBER_POINTER: {
1498 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1499 QualType PointeeType = GetType(Record[0]);
1500 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001501 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001502 }
1503
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001504 case pch::TYPE_CONSTANT_ARRAY: {
1505 QualType ElementType = GetType(Record[0]);
1506 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1507 unsigned IndexTypeQuals = Record[2];
1508 unsigned Idx = 3;
1509 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001510 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001511 }
1512
1513 case pch::TYPE_INCOMPLETE_ARRAY: {
1514 QualType ElementType = GetType(Record[0]);
1515 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1516 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001517 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001518 }
1519
1520 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001521 QualType ElementType = GetType(Record[0]);
1522 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1523 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001524 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1525 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001526 }
1527
1528 case pch::TYPE_VECTOR: {
1529 if (Record.size() != 2) {
1530 Error("Incorrect encoding of vector type in PCH file");
1531 return QualType();
1532 }
1533
1534 QualType ElementType = GetType(Record[0]);
1535 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001536 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001537 }
1538
1539 case pch::TYPE_EXT_VECTOR: {
1540 if (Record.size() != 2) {
1541 Error("Incorrect encoding of extended vector type in PCH file");
1542 return QualType();
1543 }
1544
1545 QualType ElementType = GetType(Record[0]);
1546 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001547 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001548 }
1549
1550 case pch::TYPE_FUNCTION_NO_PROTO: {
1551 if (Record.size() != 1) {
1552 Error("Incorrect encoding of no-proto function type");
1553 return QualType();
1554 }
1555 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001556 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001557 }
1558
1559 case pch::TYPE_FUNCTION_PROTO: {
1560 QualType ResultType = GetType(Record[0]);
1561 unsigned Idx = 1;
1562 unsigned NumParams = Record[Idx++];
1563 llvm::SmallVector<QualType, 16> ParamTypes;
1564 for (unsigned I = 0; I != NumParams; ++I)
1565 ParamTypes.push_back(GetType(Record[Idx++]));
1566 bool isVariadic = Record[Idx++];
1567 unsigned Quals = Record[Idx++];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001568 return Context->getFunctionType(ResultType, &ParamTypes[0], NumParams,
1569 isVariadic, Quals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001570 }
1571
1572 case pch::TYPE_TYPEDEF:
1573 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001574 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001575
1576 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001577 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001578
1579 case pch::TYPE_TYPEOF: {
1580 if (Record.size() != 1) {
1581 Error("Incorrect encoding of typeof(type) in PCH file");
1582 return QualType();
1583 }
1584 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001585 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001586 }
1587
1588 case pch::TYPE_RECORD:
Douglas Gregor8c700062009-04-13 21:20:57 +00001589 assert(Record.size() == 1 && "Incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001590 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001591
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001592 case pch::TYPE_ENUM:
1593 assert(Record.size() == 1 && "Incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001594 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001595
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001596 case pch::TYPE_OBJC_INTERFACE:
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001597 assert(Record.size() == 1 && "Incorrect encoding of objc interface type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001598 return Context->getObjCInterfaceType(
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001599 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001600
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001601 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1602 unsigned Idx = 0;
1603 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1604 unsigned NumProtos = Record[Idx++];
1605 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1606 for (unsigned I = 0; I != NumProtos; ++I)
1607 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001608 return Context->getObjCQualifiedInterfaceType(ItfD, &Protos[0], NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001609 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001610
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001611 case pch::TYPE_OBJC_QUALIFIED_ID: {
1612 unsigned Idx = 0;
1613 unsigned NumProtos = Record[Idx++];
1614 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1615 for (unsigned I = 0; I != NumProtos; ++I)
1616 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001617 return Context->getObjCQualifiedIdType(&Protos[0], NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001618 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001619 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001620 // Suppress a GCC warning
1621 return QualType();
1622}
1623
Douglas Gregor2cf26342009-04-09 22:27:44 +00001624
Douglas Gregor8038d512009-04-10 17:25:41 +00001625QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001626 unsigned Quals = ID & 0x07;
1627 unsigned Index = ID >> 3;
1628
1629 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1630 QualType T;
1631 switch ((pch::PredefinedTypeIDs)Index) {
1632 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001633 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1634 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001635
1636 case pch::PREDEF_TYPE_CHAR_U_ID:
1637 case pch::PREDEF_TYPE_CHAR_S_ID:
1638 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001639 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001640 break;
1641
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001642 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1643 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1644 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1645 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1646 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
1647 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1648 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1649 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1650 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1651 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1652 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
1653 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1654 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1655 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1656 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1657 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001658 }
1659
1660 assert(!T.isNull() && "Unknown predefined type");
1661 return T.getQualifiedType(Quals);
1662 }
1663
1664 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregor366809a2009-04-26 03:49:13 +00001665 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001666 if (!TypesLoaded[Index])
1667 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001668
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001669 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001670}
1671
Douglas Gregor8038d512009-04-10 17:25:41 +00001672Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001673 if (ID == 0)
1674 return 0;
1675
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001676 if (ID > DeclsLoaded.size()) {
1677 Error("Declaration ID out-of-range for PCH file");
1678 return 0;
1679 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001680
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001681 unsigned Index = ID - 1;
1682 if (!DeclsLoaded[Index])
1683 ReadDeclRecord(DeclOffsets[Index], Index);
1684
1685 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001686}
1687
Chris Lattner887e2b32009-04-27 05:46:25 +00001688/// \brief Resolve the offset of a statement into a statement.
1689///
1690/// This operation will read a new statement from the external
1691/// source each time it is called, and is meant to be used via a
1692/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1693Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00001694 // Since we know tha this statement is part of a decl, make sure to use the
1695 // decl cursor to read it.
1696 DeclsCursor.JumpToBit(Offset);
1697 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00001698}
1699
Douglas Gregor2cf26342009-04-09 22:27:44 +00001700bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00001701 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001702 assert(DC->hasExternalLexicalStorage() &&
1703 "DeclContext has no lexical decls in storage");
1704 uint64_t Offset = DeclContextOffsets[DC].first;
1705 assert(Offset && "DeclContext has no lexical decls in storage");
1706
Douglas Gregor0b748912009-04-14 21:18:50 +00001707 // Keep track of where we are in the stream, then jump back there
1708 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001709 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001710
Douglas Gregor2cf26342009-04-09 22:27:44 +00001711 // Load the record containing all of the declarations lexically in
1712 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001713 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001714 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001715 unsigned Code = DeclsCursor.ReadCode();
1716 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001717 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001718 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1719
1720 // Load all of the declaration IDs
1721 Decls.clear();
1722 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00001723 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001724 return false;
1725}
1726
1727bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001728 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001729 assert(DC->hasExternalVisibleStorage() &&
1730 "DeclContext has no visible decls in storage");
1731 uint64_t Offset = DeclContextOffsets[DC].second;
1732 assert(Offset && "DeclContext has no visible decls in storage");
1733
Douglas Gregor0b748912009-04-14 21:18:50 +00001734 // Keep track of where we are in the stream, then jump back there
1735 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001736 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001737
Douglas Gregor2cf26342009-04-09 22:27:44 +00001738 // Load the record containing all of the declarations visible in
1739 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001740 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001741 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001742 unsigned Code = DeclsCursor.ReadCode();
1743 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001744 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001745 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1746 if (Record.size() == 0)
1747 return false;
1748
1749 Decls.clear();
1750
1751 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001752 while (Idx < Record.size()) {
1753 Decls.push_back(VisibleDeclaration());
1754 Decls.back().Name = ReadDeclarationName(Record, Idx);
1755
Douglas Gregor2cf26342009-04-09 22:27:44 +00001756 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001757 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001758 LoadedDecls.reserve(Size);
1759 for (unsigned I = 0; I < Size; ++I)
1760 LoadedDecls.push_back(Record[Idx++]);
1761 }
1762
Douglas Gregor25123082009-04-22 22:34:57 +00001763 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001764 return false;
1765}
1766
Douglas Gregorfdd01722009-04-14 00:24:19 +00001767void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00001768 this->Consumer = Consumer;
1769
Douglas Gregorfdd01722009-04-14 00:24:19 +00001770 if (!Consumer)
1771 return;
1772
1773 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1774 Decl *D = GetDecl(ExternalDefinitions[I]);
1775 DeclGroupRef DG(D);
1776 Consumer->HandleTopLevelDecl(DG);
1777 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00001778
1779 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
1780 DeclGroupRef DG(InterestingDecls[I]);
1781 Consumer->HandleTopLevelDecl(DG);
1782 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00001783}
1784
Douglas Gregor2cf26342009-04-09 22:27:44 +00001785void PCHReader::PrintStats() {
1786 std::fprintf(stderr, "*** PCH Statistics:\n");
1787
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001788 unsigned NumTypesLoaded
1789 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
1790 (Type *)0);
1791 unsigned NumDeclsLoaded
1792 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
1793 (Decl *)0);
1794 unsigned NumIdentifiersLoaded
1795 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
1796 IdentifiersLoaded.end(),
1797 (IdentifierInfo *)0);
1798 unsigned NumSelectorsLoaded
1799 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
1800 SelectorsLoaded.end(),
1801 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00001802
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001803 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
1804 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001805 if (TotalNumSLocEntries)
1806 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
1807 NumSLocEntriesRead, TotalNumSLocEntries,
1808 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001809 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001810 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001811 NumTypesLoaded, (unsigned)TypesLoaded.size(),
1812 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
1813 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001814 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001815 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
1816 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001817 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001818 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001819 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
1820 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00001821 if (TotalNumSelectors)
1822 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
1823 NumSelectorsLoaded, TotalNumSelectors,
1824 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
1825 if (TotalNumStatements)
1826 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
1827 NumStatementsRead, TotalNumStatements,
1828 ((float)NumStatementsRead/TotalNumStatements * 100));
1829 if (TotalNumMacros)
1830 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
1831 NumMacrosRead, TotalNumMacros,
1832 ((float)NumMacrosRead/TotalNumMacros * 100));
1833 if (TotalLexicalDeclContexts)
1834 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
1835 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
1836 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
1837 * 100));
1838 if (TotalVisibleDeclContexts)
1839 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
1840 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
1841 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
1842 * 100));
1843 if (TotalSelectorsInMethodPool) {
1844 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
1845 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
1846 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
1847 * 100));
1848 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
1849 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001850 std::fprintf(stderr, "\n");
1851}
1852
Douglas Gregor668c1a42009-04-21 22:25:48 +00001853void PCHReader::InitializeSema(Sema &S) {
1854 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001855 S.ExternalSource = this;
1856
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001857 // Makes sure any declarations that were deserialized "too early"
1858 // still get added to the identifier's declaration chains.
1859 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
1860 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
1861 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001862 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001863 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001864
1865 // If there were any tentative definitions, deserialize them and add
1866 // them to Sema's table of tentative definitions.
1867 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
1868 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
1869 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
1870 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00001871
1872 // If there were any locally-scoped external declarations,
1873 // deserialize them and add them to Sema's table of locally-scoped
1874 // external declarations.
1875 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
1876 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
1877 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
1878 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00001879
1880 // If there were any ext_vector type declarations, deserialize them
1881 // and add them to Sema's vector of such declarations.
1882 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
1883 SemaObj->ExtVectorDecls.push_back(
1884 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
1885
1886 // If there were any Objective-C category implementations,
1887 // deserialize them and add them to Sema's vector of such
1888 // definitions.
1889 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
1890 SemaObj->ObjCCategoryImpls.push_back(
1891 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001892}
1893
1894IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
1895 // Try to find this name within our on-disk hash table
1896 PCHIdentifierLookupTable *IdTable
1897 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1898 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
1899 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
1900 if (Pos == IdTable->end())
1901 return 0;
1902
1903 // Dereferencing the iterator has the effect of building the
1904 // IdentifierInfo node and populating it with the various
1905 // declarations it needs.
1906 return *Pos;
1907}
1908
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001909std::pair<ObjCMethodList, ObjCMethodList>
1910PCHReader::ReadMethodPool(Selector Sel) {
1911 if (!MethodPoolLookupTable)
1912 return std::pair<ObjCMethodList, ObjCMethodList>();
1913
1914 // Try to find this selector within our on-disk hash table.
1915 PCHMethodPoolLookupTable *PoolTable
1916 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
1917 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00001918 if (Pos == PoolTable->end()) {
1919 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001920 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00001921 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001922
Douglas Gregor83941df2009-04-25 17:48:32 +00001923 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001924 return *Pos;
1925}
1926
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001927void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00001928 assert(ID && "Non-zero identifier ID required");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001929 assert(ID <= IdentifiersLoaded.size() && "Identifier ID out of range");
1930 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001931}
1932
Chris Lattner7356a312009-04-11 21:15:38 +00001933IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001934 if (ID == 0)
1935 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00001936
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001937 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001938 Error("No identifier table in PCH file");
1939 return 0;
1940 }
Chris Lattner7356a312009-04-11 21:15:38 +00001941
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001942 if (!IdentifiersLoaded[ID - 1]) {
1943 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00001944 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00001945
Douglas Gregor02fc7512009-04-28 20:01:51 +00001946 // All of the strings in the PCH file are preceded by a 16-bit
1947 // length. Extract that 16-bit length to avoid having to execute
1948 // strlen().
1949 const char *StrLenPtr = Str - 2;
1950 unsigned StrLen = (((unsigned) StrLenPtr[0])
1951 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
1952 IdentifiersLoaded[ID - 1]
1953 = &PP.getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001954 }
Chris Lattner7356a312009-04-11 21:15:38 +00001955
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001956 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001957}
1958
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001959void PCHReader::ReadSLocEntry(unsigned ID) {
1960 ReadSLocEntryRecord(ID);
1961}
1962
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001963Selector PCHReader::DecodeSelector(unsigned ID) {
1964 if (ID == 0)
1965 return Selector();
1966
Douglas Gregor83941df2009-04-25 17:48:32 +00001967 if (!MethodPoolLookupTableData) {
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001968 Error("No selector table in PCH file");
1969 return Selector();
1970 }
Douglas Gregor83941df2009-04-25 17:48:32 +00001971
1972 if (ID > TotalNumSelectors) {
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001973 Error("Selector ID out of range");
1974 return Selector();
1975 }
Douglas Gregor83941df2009-04-25 17:48:32 +00001976
1977 unsigned Index = ID - 1;
1978 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
1979 // Load this selector from the selector table.
1980 // FIXME: endianness portability issues with SelectorOffsets table
1981 PCHMethodPoolLookupTrait Trait(*this);
1982 SelectorsLoaded[Index]
1983 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
1984 }
1985
1986 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001987}
1988
Douglas Gregor2cf26342009-04-09 22:27:44 +00001989DeclarationName
1990PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1991 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1992 switch (Kind) {
1993 case DeclarationName::Identifier:
1994 return DeclarationName(GetIdentifierInfo(Record, Idx));
1995
1996 case DeclarationName::ObjCZeroArgSelector:
1997 case DeclarationName::ObjCOneArgSelector:
1998 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00001999 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002000
2001 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002002 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002003 GetType(Record[Idx++]));
2004
2005 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002006 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002007 GetType(Record[Idx++]));
2008
2009 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002010 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002011 GetType(Record[Idx++]));
2012
2013 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002014 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002015 (OverloadedOperatorKind)Record[Idx++]);
2016
2017 case DeclarationName::CXXUsingDirective:
2018 return DeclarationName::getUsingDirectiveName();
2019 }
2020
2021 // Required to silence GCC warning
2022 return DeclarationName();
2023}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002024
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002025/// \brief Read an integral value
2026llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2027 unsigned BitWidth = Record[Idx++];
2028 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2029 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2030 Idx += NumWords;
2031 return Result;
2032}
2033
2034/// \brief Read a signed integral value
2035llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2036 bool isUnsigned = Record[Idx++];
2037 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2038}
2039
Douglas Gregor17fc2232009-04-14 21:55:33 +00002040/// \brief Read a floating-point value
2041llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002042 return llvm::APFloat(ReadAPInt(Record, Idx));
2043}
2044
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002045// \brief Read a string
2046std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2047 unsigned Len = Record[Idx++];
2048 std::string Result(&Record[Idx], &Record[Idx] + Len);
2049 Idx += Len;
2050 return Result;
2051}
2052
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002053DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002054 return Diag(SourceLocation(), DiagID);
2055}
2056
2057DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2058 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002059 PP.getSourceManager()),
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002060 DiagID);
2061}
Douglas Gregor025452f2009-04-17 00:04:06 +00002062
Douglas Gregor668c1a42009-04-21 22:25:48 +00002063/// \brief Retrieve the identifier table associated with the
2064/// preprocessor.
2065IdentifierTable &PCHReader::getIdentifierTable() {
2066 return PP.getIdentifierTable();
2067}
2068
Douglas Gregor025452f2009-04-17 00:04:06 +00002069/// \brief Record that the given ID maps to the given switch-case
2070/// statement.
2071void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2072 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2073 SwitchCaseStmts[ID] = SC;
2074}
2075
2076/// \brief Retrieve the switch-case statement with the given ID.
2077SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2078 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2079 return SwitchCaseStmts[ID];
2080}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002081
2082/// \brief Record that the given label statement has been
2083/// deserialized and has the given ID.
2084void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2085 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2086 "Deserialized label twice");
2087 LabelStmts[ID] = S;
2088
2089 // If we've already seen any goto statements that point to this
2090 // label, resolve them now.
2091 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2092 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2093 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2094 Goto->second->setLabel(S);
2095 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002096
2097 // If we've already seen any address-label statements that point to
2098 // this label, resolve them now.
2099 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2100 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2101 = UnresolvedAddrLabelExprs.equal_range(ID);
2102 for (AddrLabelIter AddrLabel = AddrLabels.first;
2103 AddrLabel != AddrLabels.second; ++AddrLabel)
2104 AddrLabel->second->setLabel(S);
2105 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002106}
2107
2108/// \brief Set the label of the given statement to the label
2109/// identified by ID.
2110///
2111/// Depending on the order in which the label and other statements
2112/// referencing that label occur, this operation may complete
2113/// immediately (updating the statement) or it may queue the
2114/// statement to be back-patched later.
2115void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2116 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2117 if (Label != LabelStmts.end()) {
2118 // We've already seen this label, so set the label of the goto and
2119 // we're done.
2120 S->setLabel(Label->second);
2121 } else {
2122 // We haven't seen this label yet, so add this goto to the set of
2123 // unresolved goto statements.
2124 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2125 }
2126}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002127
2128/// \brief Set the label of the given expression to the label
2129/// identified by ID.
2130///
2131/// Depending on the order in which the label and other statements
2132/// referencing that label occur, this operation may complete
2133/// immediately (updating the statement) or it may queue the
2134/// statement to be back-patched later.
2135void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2136 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2137 if (Label != LabelStmts.end()) {
2138 // We've already seen this label, so set the label of the
2139 // label-address expression and we're done.
2140 S->setLabel(Label->second);
2141 } else {
2142 // We haven't seen this label yet, so add this label-address
2143 // expression to the set of unresolved label-address expressions.
2144 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2145 }
2146}