blob: e7404f899bc69c9124e535ccbc545705e7f4376a [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
Douglas Gregor92b059e2009-04-28 20:33:11 +0000510 // Check whether this name was used somewhere in the PCH file. If
511 // so, defining it as a macro could change behavior, so we reject
512 // the PCH file.
513 if (IdentifierInfo *II = get(MacroName.c_str(),
514 MacroName.c_str() + MacroName.size())) {
515 Diag(diag::warn_macro_name_used_in_pch)
516 << II;
517 Diag(diag::note_ignoring_pch)
518 << FileName;
519 return true;
520 }
Douglas Gregore721f952009-04-28 18:58:38 +0000521
522 // Add this definition to the suggested predefines buffer.
523 SuggestedPredefines += Extra;
524 SuggestedPredefines += '\n';
525 }
526
527 // If we get here, it's because the predefines buffer had compatible
528 // contents. Accept the PCH file.
529 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000530}
531
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000532//===----------------------------------------------------------------------===//
533// Source Manager Deserialization
534//===----------------------------------------------------------------------===//
535
Douglas Gregorbd945002009-04-13 16:31:14 +0000536/// \brief Read the line table in the source manager block.
537/// \returns true if ther was an error.
538static bool ParseLineTable(SourceManager &SourceMgr,
539 llvm::SmallVectorImpl<uint64_t> &Record) {
540 unsigned Idx = 0;
541 LineTableInfo &LineTable = SourceMgr.getLineTable();
542
543 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000544 std::map<int, int> FileIDs;
545 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000546 // Extract the file name
547 unsigned FilenameLen = Record[Idx++];
548 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
549 Idx += FilenameLen;
Douglas Gregorff0a9872009-04-13 17:12:42 +0000550 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
551 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000552 }
553
554 // Parse the line entries
555 std::vector<LineEntry> Entries;
556 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000557 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000558
559 // Extract the line entries
560 unsigned NumEntries = Record[Idx++];
561 Entries.clear();
562 Entries.reserve(NumEntries);
563 for (unsigned I = 0; I != NumEntries; ++I) {
564 unsigned FileOffset = Record[Idx++];
565 unsigned LineNo = Record[Idx++];
566 int FilenameID = Record[Idx++];
567 SrcMgr::CharacteristicKind FileKind
568 = (SrcMgr::CharacteristicKind)Record[Idx++];
569 unsigned IncludeOffset = Record[Idx++];
570 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
571 FileKind, IncludeOffset));
572 }
573 LineTable.AddEntry(FID, Entries);
574 }
575
576 return false;
577}
578
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000579namespace {
580
581class VISIBILITY_HIDDEN PCHStatData {
582public:
583 const bool hasStat;
584 const ino_t ino;
585 const dev_t dev;
586 const mode_t mode;
587 const time_t mtime;
588 const off_t size;
589
590 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
591 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
592
593 PCHStatData()
594 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
595};
596
597class VISIBILITY_HIDDEN PCHStatLookupTrait {
598 public:
599 typedef const char *external_key_type;
600 typedef const char *internal_key_type;
601
602 typedef PCHStatData data_type;
603
604 static unsigned ComputeHash(const char *path) {
605 return BernsteinHash(path);
606 }
607
608 static internal_key_type GetInternalKey(const char *path) { return path; }
609
610 static bool EqualKey(internal_key_type a, internal_key_type b) {
611 return strcmp(a, b) == 0;
612 }
613
614 static std::pair<unsigned, unsigned>
615 ReadKeyDataLength(const unsigned char*& d) {
616 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
617 unsigned DataLen = (unsigned) *d++;
618 return std::make_pair(KeyLen + 1, DataLen);
619 }
620
621 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
622 return (const char *)d;
623 }
624
625 static data_type ReadData(const internal_key_type, const unsigned char *d,
626 unsigned /*DataLen*/) {
627 using namespace clang::io;
628
629 if (*d++ == 1)
630 return data_type();
631
632 ino_t ino = (ino_t) ReadUnalignedLE32(d);
633 dev_t dev = (dev_t) ReadUnalignedLE32(d);
634 mode_t mode = (mode_t) ReadUnalignedLE16(d);
635 time_t mtime = (time_t) ReadUnalignedLE64(d);
636 off_t size = (off_t) ReadUnalignedLE64(d);
637 return data_type(ino, dev, mode, mtime, size);
638 }
639};
640
641/// \brief stat() cache for precompiled headers.
642///
643/// This cache is very similar to the stat cache used by pretokenized
644/// headers.
645class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
646 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
647 CacheTy *Cache;
648
649 unsigned &NumStatHits, &NumStatMisses;
650public:
651 PCHStatCache(const unsigned char *Buckets,
652 const unsigned char *Base,
653 unsigned &NumStatHits,
654 unsigned &NumStatMisses)
655 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
656 Cache = CacheTy::Create(Buckets, Base);
657 }
658
659 ~PCHStatCache() { delete Cache; }
660
661 int stat(const char *path, struct stat *buf) {
662 // Do the lookup for the file's data in the PCH file.
663 CacheTy::iterator I = Cache->find(path);
664
665 // If we don't get a hit in the PCH file just forward to 'stat'.
666 if (I == Cache->end()) {
667 ++NumStatMisses;
668 return ::stat(path, buf);
669 }
670
671 ++NumStatHits;
672 PCHStatData Data = *I;
673
674 if (!Data.hasStat)
675 return 1;
676
677 buf->st_ino = Data.ino;
678 buf->st_dev = Data.dev;
679 buf->st_mtime = Data.mtime;
680 buf->st_mode = Data.mode;
681 buf->st_size = Data.size;
682 return 0;
683 }
684};
685} // end anonymous namespace
686
687
Douglas Gregor14f79002009-04-10 03:52:48 +0000688/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000689PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000690 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000691
692 // Set the source-location entry cursor to the current position in
693 // the stream. This cursor will be used to read the contents of the
694 // source manager block initially, and then lazily read
695 // source-location entries as needed.
696 SLocEntryCursor = Stream;
697
698 // The stream itself is going to skip over the source manager block.
699 if (Stream.SkipBlock()) {
700 Error("Malformed block record");
701 return Failure;
702 }
703
704 // Enter the source manager block.
705 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000706 Error("Malformed source manager block record");
707 return Failure;
708 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000709
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000710 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor14f79002009-04-10 03:52:48 +0000711 RecordData Record;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000712 unsigned NumHeaderInfos = 0;
Douglas Gregor14f79002009-04-10 03:52:48 +0000713 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000714 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000715 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000716 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000717 Error("Error at end of Source Manager block");
718 return Failure;
719 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000720 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000721 }
722
723 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
724 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000725 SLocEntryCursor.ReadSubBlockID();
726 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregore1d918e2009-04-10 23:10:45 +0000727 Error("Malformed block record");
728 return Failure;
729 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000730 continue;
731 }
732
733 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000734 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000735 continue;
736 }
737
738 // Read a record.
739 const char *BlobStart;
740 unsigned BlobLen;
741 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000742 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000743 default: // Default behavior: ignore.
744 break;
745
Chris Lattner2c78b872009-04-14 23:22:57 +0000746 case pch::SM_LINE_TABLE:
Douglas Gregorbd945002009-04-13 16:31:14 +0000747 if (ParseLineTable(SourceMgr, Record))
748 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000749 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000750
751 case pch::SM_HEADER_FILE_INFO: {
752 HeaderFileInfo HFI;
753 HFI.isImport = Record[0];
754 HFI.DirInfo = Record[1];
755 HFI.NumIncludes = Record[2];
756 HFI.ControllingMacroID = Record[3];
757 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
758 break;
759 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000760
761 case pch::SM_SLOC_FILE_ENTRY:
762 case pch::SM_SLOC_BUFFER_ENTRY:
763 case pch::SM_SLOC_INSTANTIATION_ENTRY:
764 // Once we hit one of the source location entries, we're done.
765 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000766 }
767 }
768}
769
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000770/// \brief Read in the source location entry with the given ID.
771PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
772 if (ID == 0)
773 return Success;
774
775 if (ID > TotalNumSLocEntries) {
776 Error("source location entry ID out-of-range for PCH file");
777 return Failure;
778 }
779
780 ++NumSLocEntriesRead;
781 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
782 unsigned Code = SLocEntryCursor.ReadCode();
783 if (Code == llvm::bitc::END_BLOCK ||
784 Code == llvm::bitc::ENTER_SUBBLOCK ||
785 Code == llvm::bitc::DEFINE_ABBREV) {
786 Error("incorrectly-formatted source location entry in PCH file");
787 return Failure;
788 }
789
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000790 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000791 RecordData Record;
792 const char *BlobStart;
793 unsigned BlobLen;
794 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
795 default:
796 Error("incorrectly-formatted source location entry in PCH file");
797 return Failure;
798
799 case pch::SM_SLOC_FILE_ENTRY: {
800 const FileEntry *File
801 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
802 // FIXME: Error recovery if file cannot be found.
803 FileID FID = SourceMgr.createFileID(File,
804 SourceLocation::getFromRawEncoding(Record[1]),
805 (SrcMgr::CharacteristicKind)Record[2],
806 ID, Record[0]);
807 if (Record[3])
808 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
809 .setHasLineDirectives();
810
811 break;
812 }
813
814 case pch::SM_SLOC_BUFFER_ENTRY: {
815 const char *Name = BlobStart;
816 unsigned Offset = Record[0];
817 unsigned Code = SLocEntryCursor.ReadCode();
818 Record.clear();
819 unsigned RecCode
820 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
821 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
822 (void)RecCode;
823 llvm::MemoryBuffer *Buffer
824 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
825 BlobStart + BlobLen - 1,
826 Name);
827 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
828
Douglas Gregor92b059e2009-04-28 20:33:11 +0000829 if (strcmp(Name, "<built-in>") == 0) {
830 PCHPredefinesBufferID = BufferID;
831 PCHPredefines = BlobStart;
832 PCHPredefinesLen = BlobLen - 1;
833 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000834
835 break;
836 }
837
838 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
839 SourceLocation SpellingLoc
840 = SourceLocation::getFromRawEncoding(Record[1]);
841 SourceMgr.createInstantiationLoc(SpellingLoc,
842 SourceLocation::getFromRawEncoding(Record[2]),
843 SourceLocation::getFromRawEncoding(Record[3]),
844 Record[4],
845 ID,
846 Record[0]);
847 break;
848 }
849 }
850
851 return Success;
852}
853
Chris Lattner6367f6d2009-04-27 01:05:14 +0000854/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
855/// specified cursor. Read the abbreviations that are at the top of the block
856/// and then leave the cursor pointing into the block.
857bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
858 unsigned BlockID) {
859 if (Cursor.EnterSubBlock(BlockID)) {
860 Error("Malformed block record");
861 return Failure;
862 }
863
Chris Lattner6367f6d2009-04-27 01:05:14 +0000864 while (true) {
865 unsigned Code = Cursor.ReadCode();
866
867 // We expect all abbrevs to be at the start of the block.
868 if (Code != llvm::bitc::DEFINE_ABBREV)
869 return false;
870 Cursor.ReadAbbrevRecord();
871 }
872}
873
Douglas Gregor37e26842009-04-21 23:56:24 +0000874void PCHReader::ReadMacroRecord(uint64_t Offset) {
875 // Keep track of where we are in the stream, then jump back there
876 // after reading this macro.
877 SavedStreamPosition SavedPosition(Stream);
878
879 Stream.JumpToBit(Offset);
880 RecordData Record;
881 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
882 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +0000883
Douglas Gregor37e26842009-04-21 23:56:24 +0000884 while (true) {
885 unsigned Code = Stream.ReadCode();
886 switch (Code) {
887 case llvm::bitc::END_BLOCK:
888 return;
889
890 case llvm::bitc::ENTER_SUBBLOCK:
891 // No known subblocks, always skip them.
892 Stream.ReadSubBlockID();
893 if (Stream.SkipBlock()) {
894 Error("Malformed block record");
895 return;
896 }
897 continue;
898
899 case llvm::bitc::DEFINE_ABBREV:
900 Stream.ReadAbbrevRecord();
901 continue;
902 default: break;
903 }
904
905 // Read a record.
906 Record.clear();
907 pch::PreprocessorRecordTypes RecType =
908 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
909 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +0000910 case pch::PP_MACRO_OBJECT_LIKE:
911 case pch::PP_MACRO_FUNCTION_LIKE: {
912 // If we already have a macro, that means that we've hit the end
913 // of the definition of the macro we were looking for. We're
914 // done.
915 if (Macro)
916 return;
917
918 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
919 if (II == 0) {
920 Error("Macro must have a name");
921 return;
922 }
923 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
924 bool isUsed = Record[2];
925
926 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
927 MI->setIsUsed(isUsed);
928
929 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
930 // Decode function-like macro info.
931 bool isC99VarArgs = Record[3];
932 bool isGNUVarArgs = Record[4];
933 MacroArgs.clear();
934 unsigned NumArgs = Record[5];
935 for (unsigned i = 0; i != NumArgs; ++i)
936 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
937
938 // Install function-like macro info.
939 MI->setIsFunctionLike();
940 if (isC99VarArgs) MI->setIsC99Varargs();
941 if (isGNUVarArgs) MI->setIsGNUVarargs();
942 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
943 PP.getPreprocessorAllocator());
944 }
945
946 // Finally, install the macro.
947 PP.setMacroInfo(II, MI);
948
949 // Remember that we saw this macro last so that we add the tokens that
950 // form its body to it.
951 Macro = MI;
952 ++NumMacrosRead;
953 break;
954 }
955
956 case pch::PP_TOKEN: {
957 // If we see a TOKEN before a PP_MACRO_*, then the file is
958 // erroneous, just pretend we didn't see this.
959 if (Macro == 0) break;
960
961 Token Tok;
962 Tok.startToken();
963 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
964 Tok.setLength(Record[1]);
965 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
966 Tok.setIdentifierInfo(II);
967 Tok.setKind((tok::TokenKind)Record[3]);
968 Tok.setFlag((Token::TokenFlags)Record[4]);
969 Macro->AddTokenToBody(Tok);
970 break;
971 }
Steve Naroff83d63c72009-04-24 20:03:17 +0000972 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000973 }
974}
975
Douglas Gregor668c1a42009-04-21 22:25:48 +0000976PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000977PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000978 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
979 Error("Malformed block record");
980 return Failure;
981 }
Douglas Gregor2cf26342009-04-09 22:27:44 +0000982
983 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +0000984 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000985 while (!Stream.AtEndOfStream()) {
986 unsigned Code = Stream.ReadCode();
987 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000988 if (Stream.ReadBlockEnd()) {
989 Error("Error at end of module block");
990 return Failure;
991 }
Chris Lattner7356a312009-04-11 21:15:38 +0000992
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000993 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000994 }
995
996 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
997 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +0000998 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
999 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001000 if (Stream.SkipBlock()) {
1001 Error("Malformed block record");
1002 return Failure;
1003 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001004 break;
1005
Chris Lattner6367f6d2009-04-27 01:05:14 +00001006 case pch::DECLS_BLOCK_ID:
1007 // We lazily load the decls block, but we want to set up the
1008 // DeclsCursor cursor to point into it. Clone our current bitcode
1009 // cursor to it, enter the block and read the abbrevs in that block.
1010 // With the main cursor, we just skip over it.
1011 DeclsCursor = Stream;
1012 if (Stream.SkipBlock() || // Skip with the main cursor.
1013 // Read the abbrevs.
1014 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
1015 Error("Malformed block record");
1016 return Failure;
1017 }
1018 break;
1019
Chris Lattner7356a312009-04-11 21:15:38 +00001020 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001021 if (Stream.SkipBlock()) {
1022 Error("Malformed block record");
1023 return Failure;
1024 }
1025 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001026
Douglas Gregor14f79002009-04-10 03:52:48 +00001027 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001028 switch (ReadSourceManagerBlock()) {
1029 case Success:
1030 break;
1031
1032 case Failure:
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001033 Error("Malformed source manager block");
1034 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001035
1036 case IgnorePCH:
1037 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001038 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001039 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001040 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001041 continue;
1042 }
1043
1044 if (Code == llvm::bitc::DEFINE_ABBREV) {
1045 Stream.ReadAbbrevRecord();
1046 continue;
1047 }
1048
1049 // Read and process a record.
1050 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001051 const char *BlobStart = 0;
1052 unsigned BlobLen = 0;
1053 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1054 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001055 default: // Default behavior: ignore.
1056 break;
1057
1058 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001059 if (!TypesLoaded.empty()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001060 Error("Duplicate TYPE_OFFSET record in PCH file");
1061 return Failure;
1062 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001063 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001064 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001065 break;
1066
1067 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001068 if (!DeclsLoaded.empty()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001069 Error("Duplicate DECL_OFFSET record in PCH file");
1070 return Failure;
1071 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001072 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001073 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001074 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001075
1076 case pch::LANGUAGE_OPTIONS:
1077 if (ParseLanguageOptions(Record))
1078 return IgnorePCH;
1079 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001080
Douglas Gregorab41e632009-04-27 22:23:34 +00001081 case pch::METADATA: {
1082 if (Record[0] != pch::VERSION_MAJOR) {
1083 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1084 : diag::warn_pch_version_too_new);
1085 return IgnorePCH;
1086 }
1087
Douglas Gregor2bec0412009-04-10 21:16:55 +00001088 std::string TargetTriple(BlobStart, BlobLen);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001089 if (TargetTriple != PP.getTargetInfo().getTargetTriple()) {
Douglas Gregor2bec0412009-04-10 21:16:55 +00001090 Diag(diag::warn_pch_target_triple)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001091 << TargetTriple << PP.getTargetInfo().getTargetTriple();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001092 Diag(diag::note_ignoring_pch) << FileName;
1093 return IgnorePCH;
1094 }
1095 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001096 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001097
1098 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001099 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001100 if (Record[0]) {
1101 IdentifierLookupTable
1102 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001103 (const unsigned char *)IdentifierTableData + Record[0],
1104 (const unsigned char *)IdentifierTableData,
1105 PCHIdentifierLookupTrait(*this));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001106 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1107 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001108 break;
1109
1110 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001111 if (!IdentifiersLoaded.empty()) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001112 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
1113 return Failure;
1114 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001115 IdentifierOffsets = (const uint32_t *)BlobStart;
1116 IdentifiersLoaded.resize(Record[0]);
Douglas Gregor8c5a7602009-04-25 23:30:02 +00001117 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001118 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001119
1120 case pch::EXTERNAL_DEFINITIONS:
1121 if (!ExternalDefinitions.empty()) {
1122 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
1123 return Failure;
1124 }
1125 ExternalDefinitions.swap(Record);
1126 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001127
Douglas Gregorad1de002009-04-18 05:55:16 +00001128 case pch::SPECIAL_TYPES:
1129 SpecialTypes.swap(Record);
1130 break;
1131
Douglas Gregor3e1af842009-04-17 22:13:46 +00001132 case pch::STATISTICS:
1133 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001134 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001135 TotalLexicalDeclContexts = Record[2];
1136 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001137 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001138
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001139 case pch::TENTATIVE_DEFINITIONS:
1140 if (!TentativeDefinitions.empty()) {
1141 Error("Duplicate TENTATIVE_DEFINITIONS record in PCH file");
1142 return Failure;
1143 }
1144 TentativeDefinitions.swap(Record);
1145 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001146
1147 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1148 if (!LocallyScopedExternalDecls.empty()) {
1149 Error("Duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
1150 return Failure;
1151 }
1152 LocallyScopedExternalDecls.swap(Record);
1153 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001154
Douglas Gregor83941df2009-04-25 17:48:32 +00001155 case pch::SELECTOR_OFFSETS:
1156 SelectorOffsets = (const uint32_t *)BlobStart;
1157 TotalNumSelectors = Record[0];
1158 SelectorsLoaded.resize(TotalNumSelectors);
1159 break;
1160
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001161 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001162 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1163 if (Record[0])
1164 MethodPoolLookupTable
1165 = PCHMethodPoolLookupTable::Create(
1166 MethodPoolLookupTableData + Record[0],
1167 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001168 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001169 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001170 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001171
1172 case pch::PP_COUNTER_VALUE:
1173 if (!Record.empty())
1174 PP.setCounterValue(Record[0]);
1175 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001176
1177 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001178 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001179 TotalNumSLocEntries = Record[0];
1180 PP.getSourceManager().PreallocateSLocEntries(this,
1181 TotalNumSLocEntries,
1182 Record[1]);
1183 break;
1184
1185 case pch::SOURCE_LOCATION_PRELOADS:
1186 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1187 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1188 if (Result != Success)
1189 return Result;
1190 }
1191 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001192
1193 case pch::STAT_CACHE:
1194 PP.getFileManager().setStatCache(
1195 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1196 (const unsigned char *)BlobStart,
1197 NumStatHits, NumStatMisses));
1198 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001199
1200 case pch::EXT_VECTOR_DECLS:
1201 if (!ExtVectorDecls.empty()) {
1202 Error("Duplicate EXT_VECTOR_DECLS record in PCH file");
1203 return Failure;
1204 }
1205 ExtVectorDecls.swap(Record);
1206 break;
1207
1208 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1209 if (!ObjCCategoryImpls.empty()) {
1210 Error("Duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
1211 return Failure;
1212 }
1213 ObjCCategoryImpls.swap(Record);
1214 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001215 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001216 }
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001217 Error("Premature end of bitstream");
1218 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001219}
1220
Douglas Gregore1d918e2009-04-10 23:10:45 +00001221PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001222 // Set the PCH file name.
1223 this->FileName = FileName;
1224
Douglas Gregor2cf26342009-04-09 22:27:44 +00001225 // Open the PCH file.
1226 std::string ErrStr;
1227 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001228 if (!Buffer) {
1229 Error(ErrStr.c_str());
1230 return IgnorePCH;
1231 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001232
1233 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001234 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1235 (const unsigned char *)Buffer->getBufferEnd());
1236 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001237
1238 // Sniff for the signature.
1239 if (Stream.Read(8) != 'C' ||
1240 Stream.Read(8) != 'P' ||
1241 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001242 Stream.Read(8) != 'H') {
1243 Error("Not a PCH file");
1244 return IgnorePCH;
1245 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001246
Douglas Gregor2cf26342009-04-09 22:27:44 +00001247 while (!Stream.AtEndOfStream()) {
1248 unsigned Code = Stream.ReadCode();
1249
Douglas Gregore1d918e2009-04-10 23:10:45 +00001250 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
1251 Error("Invalid record at top-level");
1252 return Failure;
1253 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001254
1255 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001256
Douglas Gregor2cf26342009-04-09 22:27:44 +00001257 // We only know the PCH subblock ID.
1258 switch (BlockID) {
1259 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001260 if (Stream.ReadBlockInfoBlock()) {
1261 Error("Malformed BlockInfoBlock");
1262 return Failure;
1263 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001264 break;
1265 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001266 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001267 case Success:
1268 break;
1269
1270 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001271 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001272
1273 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001274 // FIXME: We could consider reading through to the end of this
1275 // PCH block, skipping subblocks, to see if there are other
1276 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001277
1278 // Clear out any preallocated source location entries, so that
1279 // the source manager does not try to resolve them later.
1280 PP.getSourceManager().ClearPreallocatedSLocEntries();
1281
1282 // Remove the stat cache.
1283 PP.getFileManager().setStatCache(0);
1284
Douglas Gregore1d918e2009-04-10 23:10:45 +00001285 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001286 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001287 break;
1288 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001289 if (Stream.SkipBlock()) {
1290 Error("Malformed block record");
1291 return Failure;
1292 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001293 break;
1294 }
1295 }
1296
1297 // Load the translation unit declaration
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001298 if (Context)
1299 ReadDeclRecord(DeclOffsets[0], 0);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001300
1301 // Check the predefines buffer.
1302 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1303 PCHPredefinesBufferID))
1304 return IgnorePCH;
1305
Douglas Gregor668c1a42009-04-21 22:25:48 +00001306 // Initialization of builtins and library builtins occurs before the
1307 // PCH file is read, so there may be some identifiers that were
1308 // loaded into the IdentifierTable before we intercepted the
1309 // creation of identifiers. Iterate through the list of known
1310 // identifiers and determine whether we have to establish
1311 // preprocessor definitions or top-level identifier declaration
1312 // chains for those identifiers.
1313 //
1314 // We copy the IdentifierInfo pointers to a small vector first,
1315 // since de-serializing declarations or macro definitions can add
1316 // new entries into the identifier table, invalidating the
1317 // iterators.
1318 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1319 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
1320 IdEnd = PP.getIdentifierTable().end();
1321 Id != IdEnd; ++Id)
1322 Identifiers.push_back(Id->second);
1323 PCHIdentifierLookupTable *IdTable
1324 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1325 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1326 IdentifierInfo *II = Identifiers[I];
1327 // Look in the on-disk hash table for an entry for
1328 PCHIdentifierLookupTrait Info(*this, II);
1329 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1330 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1331 if (Pos == IdTable->end())
1332 continue;
1333
1334 // Dereferencing the iterator has the effect of populating the
1335 // IdentifierInfo node with the various declarations it needs.
1336 (void)*Pos;
1337 }
1338
Douglas Gregorad1de002009-04-18 05:55:16 +00001339 // Load the special types.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001340 if (Context) {
1341 Context->setBuiltinVaListType(
1342 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1343 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1344 Context->setObjCIdType(GetType(Id));
1345 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1346 Context->setObjCSelType(GetType(Sel));
1347 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1348 Context->setObjCProtoType(GetType(Proto));
1349 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1350 Context->setObjCClassType(GetType(Class));
1351 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1352 Context->setCFConstantStringType(GetType(String));
1353 if (unsigned FastEnum
1354 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1355 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1356 }
Douglas Gregor0b748912009-04-14 21:18:50 +00001357
Douglas Gregor668c1a42009-04-21 22:25:48 +00001358 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001359}
1360
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001361/// \brief Parse the record that corresponds to a LangOptions data
1362/// structure.
1363///
1364/// This routine compares the language options used to generate the
1365/// PCH file against the language options set for the current
1366/// compilation. For each option, we classify differences between the
1367/// two compiler states as either "benign" or "important". Benign
1368/// differences don't matter, and we accept them without complaint
1369/// (and without modifying the language options). Differences between
1370/// the states for important options cause the PCH file to be
1371/// unusable, so we emit a warning and return true to indicate that
1372/// there was an error.
1373///
1374/// \returns true if the PCH file is unacceptable, false otherwise.
1375bool PCHReader::ParseLanguageOptions(
1376 const llvm::SmallVectorImpl<uint64_t> &Record) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001377 const LangOptions &LangOpts = PP.getLangOptions();
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001378#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1379#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1380 if (Record[Idx] != LangOpts.Option) { \
1381 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1382 Diag(diag::note_ignoring_pch) << FileName; \
1383 return true; \
1384 } \
1385 ++Idx
1386
1387 unsigned Idx = 0;
1388 PARSE_LANGOPT_BENIGN(Trigraphs);
1389 PARSE_LANGOPT_BENIGN(BCPLComment);
1390 PARSE_LANGOPT_BENIGN(DollarIdents);
1391 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1392 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1393 PARSE_LANGOPT_BENIGN(ImplicitInt);
1394 PARSE_LANGOPT_BENIGN(Digraphs);
1395 PARSE_LANGOPT_BENIGN(HexFloats);
1396 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1397 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1398 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1399 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001400 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1401 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1402 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1403 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1404 PARSE_LANGOPT_BENIGN(PascalStrings);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001405 PARSE_LANGOPT_BENIGN(WritableStrings);
1406 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1407 diag::warn_pch_lax_vector_conversions);
1408 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1409 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1410 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1411 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1412 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1413 diag::warn_pch_thread_safe_statics);
1414 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1415 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1416 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1417 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1418 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1419 diag::warn_pch_heinous_extensions);
1420 // FIXME: Most of the options below are benign if the macro wasn't
1421 // used. Unfortunately, this means that a PCH compiled without
1422 // optimization can't be used with optimization turned on, even
1423 // though the only thing that changes is whether __OPTIMIZE__ was
1424 // defined... but if __OPTIMIZE__ never showed up in the header, it
1425 // doesn't matter. We could consider making this some special kind
1426 // of check.
1427 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1428 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1429 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1430 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1431 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1432 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1433 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1434 Diag(diag::warn_pch_gc_mode)
1435 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1436 Diag(diag::note_ignoring_pch) << FileName;
1437 return true;
1438 }
1439 ++Idx;
1440 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1441 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1442#undef PARSE_LANGOPT_IRRELEVANT
1443#undef PARSE_LANGOPT_BENIGN
1444
1445 return false;
1446}
1447
Douglas Gregor2cf26342009-04-09 22:27:44 +00001448/// \brief Read and return the type at the given offset.
1449///
1450/// This routine actually reads the record corresponding to the type
1451/// at the given offset in the bitstream. It is a helper routine for
1452/// GetType, which deals with reading type IDs.
1453QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001454 // Keep track of where we are in the stream, then jump back there
1455 // after reading this type.
1456 SavedStreamPosition SavedPosition(Stream);
1457
Douglas Gregor2cf26342009-04-09 22:27:44 +00001458 Stream.JumpToBit(Offset);
1459 RecordData Record;
1460 unsigned Code = Stream.ReadCode();
1461 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001462 case pch::TYPE_EXT_QUAL: {
1463 assert(Record.size() == 3 &&
1464 "Incorrect encoding of extended qualifier type");
1465 QualType Base = GetType(Record[0]);
1466 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1467 unsigned AddressSpace = Record[2];
1468
1469 QualType T = Base;
1470 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001471 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001472 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001473 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001474 return T;
1475 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001476
Douglas Gregor2cf26342009-04-09 22:27:44 +00001477 case pch::TYPE_FIXED_WIDTH_INT: {
1478 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001479 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001480 }
1481
1482 case pch::TYPE_COMPLEX: {
1483 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1484 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001485 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001486 }
1487
1488 case pch::TYPE_POINTER: {
1489 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1490 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001491 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001492 }
1493
1494 case pch::TYPE_BLOCK_POINTER: {
1495 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1496 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001497 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001498 }
1499
1500 case pch::TYPE_LVALUE_REFERENCE: {
1501 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1502 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001503 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001504 }
1505
1506 case pch::TYPE_RVALUE_REFERENCE: {
1507 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1508 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001509 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001510 }
1511
1512 case pch::TYPE_MEMBER_POINTER: {
1513 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1514 QualType PointeeType = GetType(Record[0]);
1515 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001516 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001517 }
1518
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001519 case pch::TYPE_CONSTANT_ARRAY: {
1520 QualType ElementType = GetType(Record[0]);
1521 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1522 unsigned IndexTypeQuals = Record[2];
1523 unsigned Idx = 3;
1524 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001525 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001526 }
1527
1528 case pch::TYPE_INCOMPLETE_ARRAY: {
1529 QualType ElementType = GetType(Record[0]);
1530 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1531 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001532 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001533 }
1534
1535 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001536 QualType ElementType = GetType(Record[0]);
1537 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1538 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001539 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1540 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001541 }
1542
1543 case pch::TYPE_VECTOR: {
1544 if (Record.size() != 2) {
1545 Error("Incorrect encoding of vector type in PCH file");
1546 return QualType();
1547 }
1548
1549 QualType ElementType = GetType(Record[0]);
1550 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001551 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001552 }
1553
1554 case pch::TYPE_EXT_VECTOR: {
1555 if (Record.size() != 2) {
1556 Error("Incorrect encoding of extended vector type in PCH file");
1557 return QualType();
1558 }
1559
1560 QualType ElementType = GetType(Record[0]);
1561 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001562 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001563 }
1564
1565 case pch::TYPE_FUNCTION_NO_PROTO: {
1566 if (Record.size() != 1) {
1567 Error("Incorrect encoding of no-proto function type");
1568 return QualType();
1569 }
1570 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001571 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001572 }
1573
1574 case pch::TYPE_FUNCTION_PROTO: {
1575 QualType ResultType = GetType(Record[0]);
1576 unsigned Idx = 1;
1577 unsigned NumParams = Record[Idx++];
1578 llvm::SmallVector<QualType, 16> ParamTypes;
1579 for (unsigned I = 0; I != NumParams; ++I)
1580 ParamTypes.push_back(GetType(Record[Idx++]));
1581 bool isVariadic = Record[Idx++];
1582 unsigned Quals = Record[Idx++];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001583 return Context->getFunctionType(ResultType, &ParamTypes[0], NumParams,
1584 isVariadic, Quals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001585 }
1586
1587 case pch::TYPE_TYPEDEF:
1588 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001589 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001590
1591 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001592 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001593
1594 case pch::TYPE_TYPEOF: {
1595 if (Record.size() != 1) {
1596 Error("Incorrect encoding of typeof(type) in PCH file");
1597 return QualType();
1598 }
1599 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001600 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001601 }
1602
1603 case pch::TYPE_RECORD:
Douglas Gregor8c700062009-04-13 21:20:57 +00001604 assert(Record.size() == 1 && "Incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001605 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001606
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001607 case pch::TYPE_ENUM:
1608 assert(Record.size() == 1 && "Incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001609 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001610
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001611 case pch::TYPE_OBJC_INTERFACE:
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001612 assert(Record.size() == 1 && "Incorrect encoding of objc interface type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001613 return Context->getObjCInterfaceType(
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001614 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001615
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001616 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1617 unsigned Idx = 0;
1618 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1619 unsigned NumProtos = Record[Idx++];
1620 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1621 for (unsigned I = 0; I != NumProtos; ++I)
1622 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001623 return Context->getObjCQualifiedInterfaceType(ItfD, &Protos[0], NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001624 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001625
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001626 case pch::TYPE_OBJC_QUALIFIED_ID: {
1627 unsigned Idx = 0;
1628 unsigned NumProtos = Record[Idx++];
1629 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1630 for (unsigned I = 0; I != NumProtos; ++I)
1631 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001632 return Context->getObjCQualifiedIdType(&Protos[0], NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001633 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001634 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001635 // Suppress a GCC warning
1636 return QualType();
1637}
1638
Douglas Gregor2cf26342009-04-09 22:27:44 +00001639
Douglas Gregor8038d512009-04-10 17:25:41 +00001640QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001641 unsigned Quals = ID & 0x07;
1642 unsigned Index = ID >> 3;
1643
1644 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1645 QualType T;
1646 switch ((pch::PredefinedTypeIDs)Index) {
1647 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001648 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1649 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001650
1651 case pch::PREDEF_TYPE_CHAR_U_ID:
1652 case pch::PREDEF_TYPE_CHAR_S_ID:
1653 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001654 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001655 break;
1656
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001657 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1658 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1659 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1660 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1661 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
1662 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1663 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1664 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1665 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1666 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1667 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
1668 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1669 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1670 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1671 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1672 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001673 }
1674
1675 assert(!T.isNull() && "Unknown predefined type");
1676 return T.getQualifiedType(Quals);
1677 }
1678
1679 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregor366809a2009-04-26 03:49:13 +00001680 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001681 if (!TypesLoaded[Index])
1682 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001683
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001684 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001685}
1686
Douglas Gregor8038d512009-04-10 17:25:41 +00001687Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001688 if (ID == 0)
1689 return 0;
1690
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001691 if (ID > DeclsLoaded.size()) {
1692 Error("Declaration ID out-of-range for PCH file");
1693 return 0;
1694 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001695
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001696 unsigned Index = ID - 1;
1697 if (!DeclsLoaded[Index])
1698 ReadDeclRecord(DeclOffsets[Index], Index);
1699
1700 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001701}
1702
Chris Lattner887e2b32009-04-27 05:46:25 +00001703/// \brief Resolve the offset of a statement into a statement.
1704///
1705/// This operation will read a new statement from the external
1706/// source each time it is called, and is meant to be used via a
1707/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1708Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00001709 // Since we know tha this statement is part of a decl, make sure to use the
1710 // decl cursor to read it.
1711 DeclsCursor.JumpToBit(Offset);
1712 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00001713}
1714
Douglas Gregor2cf26342009-04-09 22:27:44 +00001715bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00001716 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001717 assert(DC->hasExternalLexicalStorage() &&
1718 "DeclContext has no lexical decls in storage");
1719 uint64_t Offset = DeclContextOffsets[DC].first;
1720 assert(Offset && "DeclContext has no lexical decls in storage");
1721
Douglas Gregor0b748912009-04-14 21:18:50 +00001722 // Keep track of where we are in the stream, then jump back there
1723 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001724 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001725
Douglas Gregor2cf26342009-04-09 22:27:44 +00001726 // Load the record containing all of the declarations lexically in
1727 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001728 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001729 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001730 unsigned Code = DeclsCursor.ReadCode();
1731 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001732 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001733 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1734
1735 // Load all of the declaration IDs
1736 Decls.clear();
1737 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00001738 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001739 return false;
1740}
1741
1742bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001743 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001744 assert(DC->hasExternalVisibleStorage() &&
1745 "DeclContext has no visible decls in storage");
1746 uint64_t Offset = DeclContextOffsets[DC].second;
1747 assert(Offset && "DeclContext has no visible decls in storage");
1748
Douglas Gregor0b748912009-04-14 21:18:50 +00001749 // Keep track of where we are in the stream, then jump back there
1750 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001751 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001752
Douglas Gregor2cf26342009-04-09 22:27:44 +00001753 // Load the record containing all of the declarations visible in
1754 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001755 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001756 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001757 unsigned Code = DeclsCursor.ReadCode();
1758 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001759 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001760 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1761 if (Record.size() == 0)
1762 return false;
1763
1764 Decls.clear();
1765
1766 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001767 while (Idx < Record.size()) {
1768 Decls.push_back(VisibleDeclaration());
1769 Decls.back().Name = ReadDeclarationName(Record, Idx);
1770
Douglas Gregor2cf26342009-04-09 22:27:44 +00001771 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001772 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001773 LoadedDecls.reserve(Size);
1774 for (unsigned I = 0; I < Size; ++I)
1775 LoadedDecls.push_back(Record[Idx++]);
1776 }
1777
Douglas Gregor25123082009-04-22 22:34:57 +00001778 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001779 return false;
1780}
1781
Douglas Gregorfdd01722009-04-14 00:24:19 +00001782void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00001783 this->Consumer = Consumer;
1784
Douglas Gregorfdd01722009-04-14 00:24:19 +00001785 if (!Consumer)
1786 return;
1787
1788 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1789 Decl *D = GetDecl(ExternalDefinitions[I]);
1790 DeclGroupRef DG(D);
1791 Consumer->HandleTopLevelDecl(DG);
1792 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00001793
1794 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
1795 DeclGroupRef DG(InterestingDecls[I]);
1796 Consumer->HandleTopLevelDecl(DG);
1797 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00001798}
1799
Douglas Gregor2cf26342009-04-09 22:27:44 +00001800void PCHReader::PrintStats() {
1801 std::fprintf(stderr, "*** PCH Statistics:\n");
1802
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001803 unsigned NumTypesLoaded
1804 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
1805 (Type *)0);
1806 unsigned NumDeclsLoaded
1807 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
1808 (Decl *)0);
1809 unsigned NumIdentifiersLoaded
1810 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
1811 IdentifiersLoaded.end(),
1812 (IdentifierInfo *)0);
1813 unsigned NumSelectorsLoaded
1814 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
1815 SelectorsLoaded.end(),
1816 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00001817
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001818 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
1819 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001820 if (TotalNumSLocEntries)
1821 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
1822 NumSLocEntriesRead, TotalNumSLocEntries,
1823 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001824 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001825 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001826 NumTypesLoaded, (unsigned)TypesLoaded.size(),
1827 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
1828 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001829 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001830 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
1831 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001832 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001833 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001834 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
1835 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00001836 if (TotalNumSelectors)
1837 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
1838 NumSelectorsLoaded, TotalNumSelectors,
1839 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
1840 if (TotalNumStatements)
1841 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
1842 NumStatementsRead, TotalNumStatements,
1843 ((float)NumStatementsRead/TotalNumStatements * 100));
1844 if (TotalNumMacros)
1845 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
1846 NumMacrosRead, TotalNumMacros,
1847 ((float)NumMacrosRead/TotalNumMacros * 100));
1848 if (TotalLexicalDeclContexts)
1849 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
1850 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
1851 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
1852 * 100));
1853 if (TotalVisibleDeclContexts)
1854 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
1855 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
1856 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
1857 * 100));
1858 if (TotalSelectorsInMethodPool) {
1859 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
1860 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
1861 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
1862 * 100));
1863 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
1864 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001865 std::fprintf(stderr, "\n");
1866}
1867
Douglas Gregor668c1a42009-04-21 22:25:48 +00001868void PCHReader::InitializeSema(Sema &S) {
1869 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001870 S.ExternalSource = this;
1871
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001872 // Makes sure any declarations that were deserialized "too early"
1873 // still get added to the identifier's declaration chains.
1874 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
1875 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
1876 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001877 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001878 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001879
1880 // If there were any tentative definitions, deserialize them and add
1881 // them to Sema's table of tentative definitions.
1882 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
1883 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
1884 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
1885 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00001886
1887 // If there were any locally-scoped external declarations,
1888 // deserialize them and add them to Sema's table of locally-scoped
1889 // external declarations.
1890 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
1891 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
1892 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
1893 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00001894
1895 // If there were any ext_vector type declarations, deserialize them
1896 // and add them to Sema's vector of such declarations.
1897 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
1898 SemaObj->ExtVectorDecls.push_back(
1899 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
1900
1901 // If there were any Objective-C category implementations,
1902 // deserialize them and add them to Sema's vector of such
1903 // definitions.
1904 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
1905 SemaObj->ObjCCategoryImpls.push_back(
1906 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001907}
1908
1909IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
1910 // Try to find this name within our on-disk hash table
1911 PCHIdentifierLookupTable *IdTable
1912 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1913 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
1914 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
1915 if (Pos == IdTable->end())
1916 return 0;
1917
1918 // Dereferencing the iterator has the effect of building the
1919 // IdentifierInfo node and populating it with the various
1920 // declarations it needs.
1921 return *Pos;
1922}
1923
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001924std::pair<ObjCMethodList, ObjCMethodList>
1925PCHReader::ReadMethodPool(Selector Sel) {
1926 if (!MethodPoolLookupTable)
1927 return std::pair<ObjCMethodList, ObjCMethodList>();
1928
1929 // Try to find this selector within our on-disk hash table.
1930 PCHMethodPoolLookupTable *PoolTable
1931 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
1932 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00001933 if (Pos == PoolTable->end()) {
1934 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001935 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00001936 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001937
Douglas Gregor83941df2009-04-25 17:48:32 +00001938 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001939 return *Pos;
1940}
1941
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001942void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00001943 assert(ID && "Non-zero identifier ID required");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001944 assert(ID <= IdentifiersLoaded.size() && "Identifier ID out of range");
1945 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001946}
1947
Chris Lattner7356a312009-04-11 21:15:38 +00001948IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001949 if (ID == 0)
1950 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00001951
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001952 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001953 Error("No identifier table in PCH file");
1954 return 0;
1955 }
Chris Lattner7356a312009-04-11 21:15:38 +00001956
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001957 if (!IdentifiersLoaded[ID - 1]) {
1958 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00001959 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00001960
Douglas Gregor02fc7512009-04-28 20:01:51 +00001961 // All of the strings in the PCH file are preceded by a 16-bit
1962 // length. Extract that 16-bit length to avoid having to execute
1963 // strlen().
1964 const char *StrLenPtr = Str - 2;
1965 unsigned StrLen = (((unsigned) StrLenPtr[0])
1966 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
1967 IdentifiersLoaded[ID - 1]
1968 = &PP.getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001969 }
Chris Lattner7356a312009-04-11 21:15:38 +00001970
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001971 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001972}
1973
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001974void PCHReader::ReadSLocEntry(unsigned ID) {
1975 ReadSLocEntryRecord(ID);
1976}
1977
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001978Selector PCHReader::DecodeSelector(unsigned ID) {
1979 if (ID == 0)
1980 return Selector();
1981
Douglas Gregor83941df2009-04-25 17:48:32 +00001982 if (!MethodPoolLookupTableData) {
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001983 Error("No selector table in PCH file");
1984 return Selector();
1985 }
Douglas Gregor83941df2009-04-25 17:48:32 +00001986
1987 if (ID > TotalNumSelectors) {
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001988 Error("Selector ID out of range");
1989 return Selector();
1990 }
Douglas Gregor83941df2009-04-25 17:48:32 +00001991
1992 unsigned Index = ID - 1;
1993 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
1994 // Load this selector from the selector table.
1995 // FIXME: endianness portability issues with SelectorOffsets table
1996 PCHMethodPoolLookupTrait Trait(*this);
1997 SelectorsLoaded[Index]
1998 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
1999 }
2000
2001 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002002}
2003
Douglas Gregor2cf26342009-04-09 22:27:44 +00002004DeclarationName
2005PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2006 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2007 switch (Kind) {
2008 case DeclarationName::Identifier:
2009 return DeclarationName(GetIdentifierInfo(Record, Idx));
2010
2011 case DeclarationName::ObjCZeroArgSelector:
2012 case DeclarationName::ObjCOneArgSelector:
2013 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002014 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002015
2016 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002017 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002018 GetType(Record[Idx++]));
2019
2020 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002021 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002022 GetType(Record[Idx++]));
2023
2024 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002025 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002026 GetType(Record[Idx++]));
2027
2028 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002029 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002030 (OverloadedOperatorKind)Record[Idx++]);
2031
2032 case DeclarationName::CXXUsingDirective:
2033 return DeclarationName::getUsingDirectiveName();
2034 }
2035
2036 // Required to silence GCC warning
2037 return DeclarationName();
2038}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002039
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002040/// \brief Read an integral value
2041llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2042 unsigned BitWidth = Record[Idx++];
2043 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2044 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2045 Idx += NumWords;
2046 return Result;
2047}
2048
2049/// \brief Read a signed integral value
2050llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2051 bool isUnsigned = Record[Idx++];
2052 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2053}
2054
Douglas Gregor17fc2232009-04-14 21:55:33 +00002055/// \brief Read a floating-point value
2056llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002057 return llvm::APFloat(ReadAPInt(Record, Idx));
2058}
2059
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002060// \brief Read a string
2061std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2062 unsigned Len = Record[Idx++];
2063 std::string Result(&Record[Idx], &Record[Idx] + Len);
2064 Idx += Len;
2065 return Result;
2066}
2067
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002068DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002069 return Diag(SourceLocation(), DiagID);
2070}
2071
2072DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2073 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002074 PP.getSourceManager()),
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002075 DiagID);
2076}
Douglas Gregor025452f2009-04-17 00:04:06 +00002077
Douglas Gregor668c1a42009-04-21 22:25:48 +00002078/// \brief Retrieve the identifier table associated with the
2079/// preprocessor.
2080IdentifierTable &PCHReader::getIdentifierTable() {
2081 return PP.getIdentifierTable();
2082}
2083
Douglas Gregor025452f2009-04-17 00:04:06 +00002084/// \brief Record that the given ID maps to the given switch-case
2085/// statement.
2086void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2087 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2088 SwitchCaseStmts[ID] = SC;
2089}
2090
2091/// \brief Retrieve the switch-case statement with the given ID.
2092SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2093 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2094 return SwitchCaseStmts[ID];
2095}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002096
2097/// \brief Record that the given label statement has been
2098/// deserialized and has the given ID.
2099void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2100 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2101 "Deserialized label twice");
2102 LabelStmts[ID] = S;
2103
2104 // If we've already seen any goto statements that point to this
2105 // label, resolve them now.
2106 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2107 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2108 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2109 Goto->second->setLabel(S);
2110 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002111
2112 // If we've already seen any address-label statements that point to
2113 // this label, resolve them now.
2114 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2115 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2116 = UnresolvedAddrLabelExprs.equal_range(ID);
2117 for (AddrLabelIter AddrLabel = AddrLabels.first;
2118 AddrLabel != AddrLabels.second; ++AddrLabel)
2119 AddrLabel->second->setLabel(S);
2120 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002121}
2122
2123/// \brief Set the label of the given statement to the label
2124/// identified by ID.
2125///
2126/// Depending on the order in which the label and other statements
2127/// referencing that label occur, this operation may complete
2128/// immediately (updating the statement) or it may queue the
2129/// statement to be back-patched later.
2130void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2131 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2132 if (Label != LabelStmts.end()) {
2133 // We've already seen this label, so set the label of the goto and
2134 // we're done.
2135 S->setLabel(Label->second);
2136 } else {
2137 // We haven't seen this label yet, so add this goto to the set of
2138 // unresolved goto statements.
2139 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2140 }
2141}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002142
2143/// \brief Set the label of the given expression to the label
2144/// identified by ID.
2145///
2146/// Depending on the order in which the label and other statements
2147/// referencing that label occur, this operation may complete
2148/// immediately (updating the statement) or it may queue the
2149/// statement to be back-patched later.
2150void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2151 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2152 if (Label != LabelStmts.end()) {
2153 // We've already seen this label, so set the label of the
2154 // label-address expression and we're done.
2155 S->setLabel(Label->second);
2156 } else {
2157 // We haven't seen this label yet, so add this label-address
2158 // expression to the set of unresolved label-address expressions.
2159 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2160 }
2161}