blob: ead6dcc1016ca1a933ccd23438927278a15a8feb [file] [log] [blame]
Douglas Gregor2cf26342009-04-09 22:27:44 +00001//===--- PCHReader.cpp - Precompiled Headers Reader -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the PCHReader class, which reads a precompiled header.
11//
12//===----------------------------------------------------------------------===//
Chris Lattner4c6f9522009-04-27 05:14:47 +000013
Douglas Gregor2cf26342009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor0a0428e2009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregorfdd01722009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor0b748912009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattner42d42b52009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroff83d63c72009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregor668c1a42009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregorbd945002009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregor14f79002009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregor2bec0412009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000029#include "llvm/Bitcode/BitstreamReader.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include <algorithm>
Douglas Gregore721f952009-04-28 18:58:38 +000033#include <iterator>
Douglas Gregor2cf26342009-04-09 22:27:44 +000034#include <cstdio>
Douglas Gregor4fed3f42009-04-27 18:38:38 +000035#include <sys/stat.h>
Douglas Gregor2cf26342009-04-09 22:27:44 +000036using namespace clang;
37
38//===----------------------------------------------------------------------===//
Douglas Gregor668c1a42009-04-21 22:25:48 +000039// PCH reader implementation
40//===----------------------------------------------------------------------===//
41
Chris Lattnerd1d64a02009-04-27 21:45:14 +000042PCHReader::PCHReader(Preprocessor &PP, ASTContext *Context)
Chris Lattner4c6f9522009-04-27 05:14:47 +000043 : SemaObj(0), PP(PP), Context(Context), Consumer(0),
44 IdentifierTableData(0), IdentifierLookupTable(0),
45 IdentifierOffsets(0),
46 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
47 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
Douglas Gregor4fed3f42009-04-27 18:38:38 +000048 TotalNumSelectors(0), NumStatHits(0), NumStatMisses(0),
49 NumSLocEntriesRead(0), NumStatementsRead(0),
Douglas Gregor7f94b0b2009-04-27 06:38:32 +000050 NumMacrosRead(0), NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
Chris Lattner4c6f9522009-04-27 05:14:47 +000051 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
52
53PCHReader::~PCHReader() {}
54
Chris Lattnerda930612009-04-27 05:58:23 +000055Expr *PCHReader::ReadDeclExpr() {
56 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
57}
58
59Expr *PCHReader::ReadTypeExpr() {
Chris Lattner52e97d12009-04-27 05:41:06 +000060 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner4c6f9522009-04-27 05:14:47 +000061}
62
63
Douglas Gregor668c1a42009-04-21 22:25:48 +000064namespace {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +000065class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
66 PCHReader &Reader;
67
68public:
69 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
70
71 typedef Selector external_key_type;
72 typedef external_key_type internal_key_type;
73
74 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
75
76 static bool EqualKey(const internal_key_type& a,
77 const internal_key_type& b) {
78 return a == b;
79 }
80
81 static unsigned ComputeHash(Selector Sel) {
82 unsigned N = Sel.getNumArgs();
83 if (N == 0)
84 ++N;
85 unsigned R = 5381;
86 for (unsigned I = 0; I != N; ++I)
87 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
88 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
89 return R;
90 }
91
92 // This hopefully will just get inlined and removed by the optimizer.
93 static const internal_key_type&
94 GetInternalKey(const external_key_type& x) { return x; }
95
96 static std::pair<unsigned, unsigned>
97 ReadKeyDataLength(const unsigned char*& d) {
98 using namespace clang::io;
99 unsigned KeyLen = ReadUnalignedLE16(d);
100 unsigned DataLen = ReadUnalignedLE16(d);
101 return std::make_pair(KeyLen, DataLen);
102 }
103
Douglas Gregor83941df2009-04-25 17:48:32 +0000104 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000105 using namespace clang::io;
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000106 SelectorTable &SelTable = Reader.getContext()->Selectors;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000107 unsigned N = ReadUnalignedLE16(d);
108 IdentifierInfo *FirstII
109 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
110 if (N == 0)
111 return SelTable.getNullarySelector(FirstII);
112 else if (N == 1)
113 return SelTable.getUnarySelector(FirstII);
114
115 llvm::SmallVector<IdentifierInfo *, 16> Args;
116 Args.push_back(FirstII);
117 for (unsigned I = 1; I != N; ++I)
118 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
119
120 return SelTable.getSelector(N, &Args[0]);
121 }
122
123 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
124 using namespace clang::io;
125 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
126 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
127
128 data_type Result;
129
130 // Load instance methods
131 ObjCMethodList *Prev = 0;
132 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
133 ObjCMethodDecl *Method
134 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
135 if (!Result.first.Method) {
136 // This is the first method, which is the easy case.
137 Result.first.Method = Method;
138 Prev = &Result.first;
139 continue;
140 }
141
142 Prev->Next = new ObjCMethodList(Method, 0);
143 Prev = Prev->Next;
144 }
145
146 // Load factory methods
147 Prev = 0;
148 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
149 ObjCMethodDecl *Method
150 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
151 if (!Result.second.Method) {
152 // This is the first method, which is the easy case.
153 Result.second.Method = Method;
154 Prev = &Result.second;
155 continue;
156 }
157
158 Prev->Next = new ObjCMethodList(Method, 0);
159 Prev = Prev->Next;
160 }
161
162 return Result;
163 }
164};
165
166} // end anonymous namespace
167
168/// \brief The on-disk hash table used for the global method pool.
169typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
170 PCHMethodPoolLookupTable;
171
172namespace {
Douglas Gregor668c1a42009-04-21 22:25:48 +0000173class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
174 PCHReader &Reader;
175
176 // If we know the IdentifierInfo in advance, it is here and we will
177 // not build a new one. Used when deserializing information about an
178 // identifier that was constructed before the PCH file was read.
179 IdentifierInfo *KnownII;
180
181public:
182 typedef IdentifierInfo * data_type;
183
184 typedef const std::pair<const char*, unsigned> external_key_type;
185
186 typedef external_key_type internal_key_type;
187
188 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
189 : Reader(Reader), KnownII(II) { }
190
191 static bool EqualKey(const internal_key_type& a,
192 const internal_key_type& b) {
193 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
194 : false;
195 }
196
197 static unsigned ComputeHash(const internal_key_type& a) {
198 return BernsteinHash(a.first, a.second);
199 }
200
201 // This hopefully will just get inlined and removed by the optimizer.
202 static const internal_key_type&
203 GetInternalKey(const external_key_type& x) { return x; }
204
205 static std::pair<unsigned, unsigned>
206 ReadKeyDataLength(const unsigned char*& d) {
207 using namespace clang::io;
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000208 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregord6595a42009-04-25 21:04:17 +0000209 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000210 return std::make_pair(KeyLen, DataLen);
211 }
212
213 static std::pair<const char*, unsigned>
214 ReadKey(const unsigned char* d, unsigned n) {
215 assert(n >= 2 && d[n-1] == '\0');
216 return std::make_pair((const char*) d, n-1);
217 }
218
219 IdentifierInfo *ReadData(const internal_key_type& k,
220 const unsigned char* d,
221 unsigned DataLen) {
222 using namespace clang::io;
Douglas Gregora92193e2009-04-28 21:18:29 +0000223 pch::IdentID ID = ReadUnalignedLE32(d);
224 bool IsInteresting = ID & 0x01;
225
226 // Wipe out the "is interesting" bit.
227 ID = ID >> 1;
228
229 if (!IsInteresting) {
230 // For unintersting identifiers, just build the IdentifierInfo
231 // and associate it with the persistent ID.
232 IdentifierInfo *II = KnownII;
233 if (!II)
234 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
235 k.first, k.first + k.second);
236 Reader.SetIdentifierInfo(ID, II);
237 return II;
238 }
239
Douglas Gregor5998da52009-04-28 21:32:13 +0000240 unsigned Bits = ReadUnalignedLE16(d);
Douglas Gregor2deaea32009-04-22 18:49:13 +0000241 bool CPlusPlusOperatorKeyword = Bits & 0x01;
242 Bits >>= 1;
243 bool Poisoned = Bits & 0x01;
244 Bits >>= 1;
245 bool ExtensionToken = Bits & 0x01;
246 Bits >>= 1;
247 bool hasMacroDefinition = Bits & 0x01;
248 Bits >>= 1;
249 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
250 Bits >>= 10;
Douglas Gregora92193e2009-04-28 21:18:29 +0000251
Douglas Gregor2deaea32009-04-22 18:49:13 +0000252 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregor5998da52009-04-28 21:32:13 +0000253 DataLen -= 6;
Douglas Gregor668c1a42009-04-21 22:25:48 +0000254
255 // Build the IdentifierInfo itself and link the identifier ID with
256 // the new IdentifierInfo.
257 IdentifierInfo *II = KnownII;
258 if (!II)
Douglas Gregor5f8e3302009-04-25 20:26:24 +0000259 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
260 k.first, k.first + k.second);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000261 Reader.SetIdentifierInfo(ID, II);
262
Douglas Gregor2deaea32009-04-22 18:49:13 +0000263 // Set or check the various bits in the IdentifierInfo structure.
264 // FIXME: Load token IDs lazily, too?
Douglas Gregor2deaea32009-04-22 18:49:13 +0000265 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
266 assert(II->isExtensionToken() == ExtensionToken &&
267 "Incorrect extension token flag");
268 (void)ExtensionToken;
269 II->setIsPoisoned(Poisoned);
270 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
271 "Incorrect C++ operator keyword flag");
272 (void)CPlusPlusOperatorKeyword;
273
Douglas Gregor37e26842009-04-21 23:56:24 +0000274 // If this identifier is a macro, deserialize the macro
275 // definition.
276 if (hasMacroDefinition) {
Douglas Gregor5998da52009-04-28 21:32:13 +0000277 uint32_t Offset = ReadUnalignedLE32(d);
Douglas Gregor37e26842009-04-21 23:56:24 +0000278 Reader.ReadMacroRecord(Offset);
Douglas Gregor5998da52009-04-28 21:32:13 +0000279 DataLen -= 4;
Douglas Gregor37e26842009-04-21 23:56:24 +0000280 }
Douglas Gregor668c1a42009-04-21 22:25:48 +0000281
282 // Read all of the declarations visible at global scope with this
283 // name.
284 Sema *SemaObj = Reader.getSema();
Chris Lattner6bf690f2009-04-27 22:17:41 +0000285 if (Reader.getContext() == 0) return II;
Chris Lattnercc7dea82009-04-27 22:02:30 +0000286
Douglas Gregor668c1a42009-04-21 22:25:48 +0000287 while (DataLen > 0) {
288 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregor668c1a42009-04-21 22:25:48 +0000289 if (SemaObj) {
290 // Introduce this declaration into the translation-unit scope
291 // and add it to the declaration chain for this identifier, so
292 // that (unqualified) name lookup will find it.
293 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
294 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
295 } else {
296 // Queue this declaration so that it will be added to the
297 // translation unit scope and identifier's declaration chain
298 // once a Sema object is known.
Douglas Gregor6cfc1a82009-04-22 21:15:06 +0000299 Reader.PreloadedDecls.push_back(D);
Douglas Gregor668c1a42009-04-21 22:25:48 +0000300 }
301
302 DataLen -= 4;
303 }
304 return II;
305 }
306};
307
308} // end anonymous namespace
309
310/// \brief The on-disk hash table used to contain information about
311/// all of the identifiers in the program.
312typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
313 PCHIdentifierLookupTable;
314
Douglas Gregor2cf26342009-04-09 22:27:44 +0000315// FIXME: use the diagnostics machinery
Douglas Gregora02b1472009-04-28 21:53:25 +0000316bool PCHReader::Error(const char *Msg) {
317 Diagnostic &Diags = PP.getDiagnostics();
318 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Fatal, Msg);
319 Diag(DiagID);
Douglas Gregor2cf26342009-04-09 22:27:44 +0000320 return true;
321}
322
Douglas Gregore721f952009-04-28 18:58:38 +0000323/// \brief Split the given string into a vector of lines, eliminating
324/// any empty lines in the process.
325///
326/// \param Str the string to split.
327/// \param Len the length of Str.
328/// \param KeepEmptyLines true if empty lines should be included
329/// \returns a vector of lines, with the line endings removed
330std::vector<std::string> splitLines(const char *Str, unsigned Len,
331 bool KeepEmptyLines = false) {
332 std::vector<std::string> Lines;
333 for (unsigned LineStart = 0; LineStart < Len; ++LineStart) {
334 unsigned LineEnd = LineStart;
335 while (LineEnd < Len && Str[LineEnd] != '\n')
336 ++LineEnd;
337 if (LineStart != LineEnd || KeepEmptyLines)
338 Lines.push_back(std::string(&Str[LineStart], &Str[LineEnd]));
339 LineStart = LineEnd;
340 }
341 return Lines;
342}
343
344/// \brief Determine whether the string Haystack starts with the
345/// substring Needle.
346static bool startsWith(const std::string &Haystack, const char *Needle) {
347 for (unsigned I = 0, N = Haystack.size(); Needle[I] != 0; ++I) {
348 if (I == N)
349 return false;
350 if (Haystack[I] != Needle[I])
351 return false;
352 }
353
354 return true;
355}
356
357/// \brief Determine whether the string Haystack starts with the
358/// substring Needle.
359static inline bool startsWith(const std::string &Haystack,
360 const std::string &Needle) {
361 return startsWith(Haystack, Needle.c_str());
362}
363
Douglas Gregore1d918e2009-04-10 23:10:45 +0000364/// \brief Check the contents of the predefines buffer against the
365/// contents of the predefines buffer used to build the PCH file.
366///
367/// The contents of the two predefines buffers should be the same. If
368/// not, then some command-line option changed the preprocessor state
369/// and we must reject the PCH file.
370///
371/// \param PCHPredef The start of the predefines buffer in the PCH
372/// file.
373///
374/// \param PCHPredefLen The length of the predefines buffer in the PCH
375/// file.
376///
377/// \param PCHBufferID The FileID for the PCH predefines buffer.
378///
379/// \returns true if there was a mismatch (in which case the PCH file
380/// should be ignored), or false otherwise.
381bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
382 unsigned PCHPredefLen,
383 FileID PCHBufferID) {
384 const char *Predef = PP.getPredefines().c_str();
385 unsigned PredefLen = PP.getPredefines().size();
386
Douglas Gregore721f952009-04-28 18:58:38 +0000387 // If the two predefines buffers compare equal, we're done!
Douglas Gregore1d918e2009-04-10 23:10:45 +0000388 if (PredefLen == PCHPredefLen &&
389 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
390 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000391
Douglas Gregore1d918e2009-04-10 23:10:45 +0000392 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregore721f952009-04-28 18:58:38 +0000393
394 // The predefines buffers are different. Determine what the
395 // differences are, and whether they require us to reject the PCH
396 // file.
397 std::vector<std::string> CmdLineLines = splitLines(Predef, PredefLen);
398 std::vector<std::string> PCHLines = splitLines(PCHPredef, PCHPredefLen);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000399
Douglas Gregore721f952009-04-28 18:58:38 +0000400 // Sort both sets of predefined buffer lines, since
401 std::sort(CmdLineLines.begin(), CmdLineLines.end());
402 std::sort(PCHLines.begin(), PCHLines.end());
Douglas Gregore1d918e2009-04-10 23:10:45 +0000403
Douglas Gregore721f952009-04-28 18:58:38 +0000404 // Determine which predefines that where used to build the PCH file
405 // are missing from the command line.
406 std::vector<std::string> MissingPredefines;
407 std::set_difference(PCHLines.begin(), PCHLines.end(),
408 CmdLineLines.begin(), CmdLineLines.end(),
409 std::back_inserter(MissingPredefines));
410
411 bool MissingDefines = false;
412 bool ConflictingDefines = false;
413 for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
414 const std::string &Missing = MissingPredefines[I];
415 if (!startsWith(Missing, "#define ") != 0) {
Douglas Gregoraf1795b2009-04-28 20:36:16 +0000416 Diag(diag::warn_pch_compiler_options_mismatch);
Douglas Gregore721f952009-04-28 18:58:38 +0000417 return true;
418 }
419
420 // This is a macro definition. Determine the name of the macro
421 // we're defining.
422 std::string::size_type StartOfMacroName = strlen("#define ");
423 std::string::size_type EndOfMacroName
424 = Missing.find_first_of("( \n\r", StartOfMacroName);
425 assert(EndOfMacroName != std::string::npos &&
426 "Couldn't find the end of the macro name");
427 std::string MacroName = Missing.substr(StartOfMacroName,
428 EndOfMacroName - StartOfMacroName);
429
430 // Determine whether this macro was given a different definition
431 // on the command line.
432 std::string MacroDefStart = "#define " + MacroName;
433 std::string::size_type MacroDefLen = MacroDefStart.size();
434 std::vector<std::string>::iterator ConflictPos
435 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
436 MacroDefStart);
437 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
438 if (!startsWith(*ConflictPos, MacroDefStart)) {
439 // Different macro; we're done.
440 ConflictPos = CmdLineLines.end();
441 break;
442 }
443
444 assert(ConflictPos->size() > MacroDefLen &&
445 "Invalid #define in predefines buffer?");
446 if ((*ConflictPos)[MacroDefLen] != ' ' &&
447 (*ConflictPos)[MacroDefLen] != '(')
448 continue; // Longer macro name; keep trying.
449
450 // We found a conflicting macro definition.
451 break;
452 }
453
454 if (ConflictPos != CmdLineLines.end()) {
455 Diag(diag::warn_cmdline_conflicting_macro_def)
456 << MacroName;
457
458 // Show the definition of this macro within the PCH file.
459 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
460 unsigned Offset = MissingDef - PCHPredef;
461 SourceLocation PCHMissingLoc
462 = SourceMgr.getLocForStartOfFile(PCHBufferID)
463 .getFileLocWithOffset(Offset);
464 Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
465 << MacroName;
466
467 ConflictingDefines = true;
468 continue;
469 }
470
471 // If the macro doesn't conflict, then we'll just pick up the
472 // macro definition from the PCH file. Warn the user that they
473 // made a mistake.
474 if (ConflictingDefines)
475 continue; // Don't complain if there are already conflicting defs
476
477 if (!MissingDefines) {
478 Diag(diag::warn_cmdline_missing_macro_defs);
479 MissingDefines = true;
480 }
481
482 // Show the definition of this macro within the PCH file.
483 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
484 unsigned Offset = MissingDef - PCHPredef;
485 SourceLocation PCHMissingLoc
486 = SourceMgr.getLocForStartOfFile(PCHBufferID)
487 .getFileLocWithOffset(Offset);
488 Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000489 }
490
Douglas Gregor1ab86ac2009-04-28 22:01:16 +0000491 if (ConflictingDefines)
Douglas Gregore721f952009-04-28 18:58:38 +0000492 return true;
Douglas Gregore721f952009-04-28 18:58:38 +0000493
494 // Determine what predefines were introduced based on command-line
495 // parameters that were not present when building the PCH
496 // file. Extra #defines are okay, so long as the identifiers being
497 // defined were not used within the precompiled header.
498 std::vector<std::string> ExtraPredefines;
499 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
500 PCHLines.begin(), PCHLines.end(),
501 std::back_inserter(ExtraPredefines));
502 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
503 const std::string &Extra = ExtraPredefines[I];
504 if (!startsWith(Extra, "#define ") != 0) {
Douglas Gregoraf1795b2009-04-28 20:36:16 +0000505 Diag(diag::warn_pch_compiler_options_mismatch);
Douglas Gregore721f952009-04-28 18:58:38 +0000506 return true;
507 }
508
509 // This is an extra macro definition. Determine the name of the
510 // macro we're defining.
511 std::string::size_type StartOfMacroName = strlen("#define ");
512 std::string::size_type EndOfMacroName
513 = Extra.find_first_of("( \n\r", StartOfMacroName);
514 assert(EndOfMacroName != std::string::npos &&
515 "Couldn't find the end of the macro name");
516 std::string MacroName = Extra.substr(StartOfMacroName,
517 EndOfMacroName - StartOfMacroName);
518
Douglas Gregor92b059e2009-04-28 20:33:11 +0000519 // Check whether this name was used somewhere in the PCH file. If
520 // so, defining it as a macro could change behavior, so we reject
521 // the PCH file.
522 if (IdentifierInfo *II = get(MacroName.c_str(),
523 MacroName.c_str() + MacroName.size())) {
524 Diag(diag::warn_macro_name_used_in_pch)
525 << II;
Douglas Gregor92b059e2009-04-28 20:33:11 +0000526 return true;
527 }
Douglas Gregore721f952009-04-28 18:58:38 +0000528
529 // Add this definition to the suggested predefines buffer.
530 SuggestedPredefines += Extra;
531 SuggestedPredefines += '\n';
532 }
533
534 // If we get here, it's because the predefines buffer had compatible
535 // contents. Accept the PCH file.
536 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000537}
538
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000539//===----------------------------------------------------------------------===//
540// Source Manager Deserialization
541//===----------------------------------------------------------------------===//
542
Douglas Gregorbd945002009-04-13 16:31:14 +0000543/// \brief Read the line table in the source manager block.
544/// \returns true if ther was an error.
545static bool ParseLineTable(SourceManager &SourceMgr,
546 llvm::SmallVectorImpl<uint64_t> &Record) {
547 unsigned Idx = 0;
548 LineTableInfo &LineTable = SourceMgr.getLineTable();
549
550 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000551 std::map<int, int> FileIDs;
552 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000553 // Extract the file name
554 unsigned FilenameLen = Record[Idx++];
555 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
556 Idx += FilenameLen;
Douglas Gregorff0a9872009-04-13 17:12:42 +0000557 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
558 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000559 }
560
561 // Parse the line entries
562 std::vector<LineEntry> Entries;
563 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000564 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000565
566 // Extract the line entries
567 unsigned NumEntries = Record[Idx++];
568 Entries.clear();
569 Entries.reserve(NumEntries);
570 for (unsigned I = 0; I != NumEntries; ++I) {
571 unsigned FileOffset = Record[Idx++];
572 unsigned LineNo = Record[Idx++];
573 int FilenameID = Record[Idx++];
574 SrcMgr::CharacteristicKind FileKind
575 = (SrcMgr::CharacteristicKind)Record[Idx++];
576 unsigned IncludeOffset = Record[Idx++];
577 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
578 FileKind, IncludeOffset));
579 }
580 LineTable.AddEntry(FID, Entries);
581 }
582
583 return false;
584}
585
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000586namespace {
587
588class VISIBILITY_HIDDEN PCHStatData {
589public:
590 const bool hasStat;
591 const ino_t ino;
592 const dev_t dev;
593 const mode_t mode;
594 const time_t mtime;
595 const off_t size;
596
597 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
598 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
599
600 PCHStatData()
601 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
602};
603
604class VISIBILITY_HIDDEN PCHStatLookupTrait {
605 public:
606 typedef const char *external_key_type;
607 typedef const char *internal_key_type;
608
609 typedef PCHStatData data_type;
610
611 static unsigned ComputeHash(const char *path) {
612 return BernsteinHash(path);
613 }
614
615 static internal_key_type GetInternalKey(const char *path) { return path; }
616
617 static bool EqualKey(internal_key_type a, internal_key_type b) {
618 return strcmp(a, b) == 0;
619 }
620
621 static std::pair<unsigned, unsigned>
622 ReadKeyDataLength(const unsigned char*& d) {
623 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
624 unsigned DataLen = (unsigned) *d++;
625 return std::make_pair(KeyLen + 1, DataLen);
626 }
627
628 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
629 return (const char *)d;
630 }
631
632 static data_type ReadData(const internal_key_type, const unsigned char *d,
633 unsigned /*DataLen*/) {
634 using namespace clang::io;
635
636 if (*d++ == 1)
637 return data_type();
638
639 ino_t ino = (ino_t) ReadUnalignedLE32(d);
640 dev_t dev = (dev_t) ReadUnalignedLE32(d);
641 mode_t mode = (mode_t) ReadUnalignedLE16(d);
642 time_t mtime = (time_t) ReadUnalignedLE64(d);
643 off_t size = (off_t) ReadUnalignedLE64(d);
644 return data_type(ino, dev, mode, mtime, size);
645 }
646};
647
648/// \brief stat() cache for precompiled headers.
649///
650/// This cache is very similar to the stat cache used by pretokenized
651/// headers.
652class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
653 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
654 CacheTy *Cache;
655
656 unsigned &NumStatHits, &NumStatMisses;
657public:
658 PCHStatCache(const unsigned char *Buckets,
659 const unsigned char *Base,
660 unsigned &NumStatHits,
661 unsigned &NumStatMisses)
662 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
663 Cache = CacheTy::Create(Buckets, Base);
664 }
665
666 ~PCHStatCache() { delete Cache; }
667
668 int stat(const char *path, struct stat *buf) {
669 // Do the lookup for the file's data in the PCH file.
670 CacheTy::iterator I = Cache->find(path);
671
672 // If we don't get a hit in the PCH file just forward to 'stat'.
673 if (I == Cache->end()) {
674 ++NumStatMisses;
675 return ::stat(path, buf);
676 }
677
678 ++NumStatHits;
679 PCHStatData Data = *I;
680
681 if (!Data.hasStat)
682 return 1;
683
684 buf->st_ino = Data.ino;
685 buf->st_dev = Data.dev;
686 buf->st_mtime = Data.mtime;
687 buf->st_mode = Data.mode;
688 buf->st_size = Data.size;
689 return 0;
690 }
691};
692} // end anonymous namespace
693
694
Douglas Gregor14f79002009-04-10 03:52:48 +0000695/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000696PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000697 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000698
699 // Set the source-location entry cursor to the current position in
700 // the stream. This cursor will be used to read the contents of the
701 // source manager block initially, and then lazily read
702 // source-location entries as needed.
703 SLocEntryCursor = Stream;
704
705 // The stream itself is going to skip over the source manager block.
706 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000707 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000708 return Failure;
709 }
710
711 // Enter the source manager block.
712 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000713 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000714 return Failure;
715 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000716
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000717 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor14f79002009-04-10 03:52:48 +0000718 RecordData Record;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000719 unsigned NumHeaderInfos = 0;
Douglas Gregor14f79002009-04-10 03:52:48 +0000720 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000721 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000722 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000723 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000724 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000725 return Failure;
726 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000727 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000728 }
729
730 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
731 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000732 SLocEntryCursor.ReadSubBlockID();
733 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000734 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000735 return Failure;
736 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000737 continue;
738 }
739
740 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000741 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000742 continue;
743 }
744
745 // Read a record.
746 const char *BlobStart;
747 unsigned BlobLen;
748 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000749 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000750 default: // Default behavior: ignore.
751 break;
752
Chris Lattner2c78b872009-04-14 23:22:57 +0000753 case pch::SM_LINE_TABLE:
Douglas Gregorbd945002009-04-13 16:31:14 +0000754 if (ParseLineTable(SourceMgr, Record))
755 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000756 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000757
758 case pch::SM_HEADER_FILE_INFO: {
759 HeaderFileInfo HFI;
760 HFI.isImport = Record[0];
761 HFI.DirInfo = Record[1];
762 HFI.NumIncludes = Record[2];
763 HFI.ControllingMacroID = Record[3];
764 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
765 break;
766 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000767
768 case pch::SM_SLOC_FILE_ENTRY:
769 case pch::SM_SLOC_BUFFER_ENTRY:
770 case pch::SM_SLOC_INSTANTIATION_ENTRY:
771 // Once we hit one of the source location entries, we're done.
772 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000773 }
774 }
775}
776
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000777/// \brief Read in the source location entry with the given ID.
778PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
779 if (ID == 0)
780 return Success;
781
782 if (ID > TotalNumSLocEntries) {
783 Error("source location entry ID out-of-range for PCH file");
784 return Failure;
785 }
786
787 ++NumSLocEntriesRead;
788 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
789 unsigned Code = SLocEntryCursor.ReadCode();
790 if (Code == llvm::bitc::END_BLOCK ||
791 Code == llvm::bitc::ENTER_SUBBLOCK ||
792 Code == llvm::bitc::DEFINE_ABBREV) {
793 Error("incorrectly-formatted source location entry in PCH file");
794 return Failure;
795 }
796
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000797 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000798 RecordData Record;
799 const char *BlobStart;
800 unsigned BlobLen;
801 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
802 default:
803 Error("incorrectly-formatted source location entry in PCH file");
804 return Failure;
805
806 case pch::SM_SLOC_FILE_ENTRY: {
807 const FileEntry *File
808 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
809 // FIXME: Error recovery if file cannot be found.
810 FileID FID = SourceMgr.createFileID(File,
811 SourceLocation::getFromRawEncoding(Record[1]),
812 (SrcMgr::CharacteristicKind)Record[2],
813 ID, Record[0]);
814 if (Record[3])
815 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
816 .setHasLineDirectives();
817
818 break;
819 }
820
821 case pch::SM_SLOC_BUFFER_ENTRY: {
822 const char *Name = BlobStart;
823 unsigned Offset = Record[0];
824 unsigned Code = SLocEntryCursor.ReadCode();
825 Record.clear();
826 unsigned RecCode
827 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
828 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
829 (void)RecCode;
830 llvm::MemoryBuffer *Buffer
831 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
832 BlobStart + BlobLen - 1,
833 Name);
834 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
835
Douglas Gregor92b059e2009-04-28 20:33:11 +0000836 if (strcmp(Name, "<built-in>") == 0) {
837 PCHPredefinesBufferID = BufferID;
838 PCHPredefines = BlobStart;
839 PCHPredefinesLen = BlobLen - 1;
840 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000841
842 break;
843 }
844
845 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
846 SourceLocation SpellingLoc
847 = SourceLocation::getFromRawEncoding(Record[1]);
848 SourceMgr.createInstantiationLoc(SpellingLoc,
849 SourceLocation::getFromRawEncoding(Record[2]),
850 SourceLocation::getFromRawEncoding(Record[3]),
851 Record[4],
852 ID,
853 Record[0]);
854 break;
855 }
856 }
857
858 return Success;
859}
860
Chris Lattner6367f6d2009-04-27 01:05:14 +0000861/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
862/// specified cursor. Read the abbreviations that are at the top of the block
863/// and then leave the cursor pointing into the block.
864bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
865 unsigned BlockID) {
866 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000867 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000868 return Failure;
869 }
870
Chris Lattner6367f6d2009-04-27 01:05:14 +0000871 while (true) {
872 unsigned Code = Cursor.ReadCode();
873
874 // We expect all abbrevs to be at the start of the block.
875 if (Code != llvm::bitc::DEFINE_ABBREV)
876 return false;
877 Cursor.ReadAbbrevRecord();
878 }
879}
880
Douglas Gregor37e26842009-04-21 23:56:24 +0000881void PCHReader::ReadMacroRecord(uint64_t Offset) {
882 // Keep track of where we are in the stream, then jump back there
883 // after reading this macro.
884 SavedStreamPosition SavedPosition(Stream);
885
886 Stream.JumpToBit(Offset);
887 RecordData Record;
888 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
889 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +0000890
Douglas Gregor37e26842009-04-21 23:56:24 +0000891 while (true) {
892 unsigned Code = Stream.ReadCode();
893 switch (Code) {
894 case llvm::bitc::END_BLOCK:
895 return;
896
897 case llvm::bitc::ENTER_SUBBLOCK:
898 // No known subblocks, always skip them.
899 Stream.ReadSubBlockID();
900 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000901 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +0000902 return;
903 }
904 continue;
905
906 case llvm::bitc::DEFINE_ABBREV:
907 Stream.ReadAbbrevRecord();
908 continue;
909 default: break;
910 }
911
912 // Read a record.
913 Record.clear();
914 pch::PreprocessorRecordTypes RecType =
915 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
916 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +0000917 case pch::PP_MACRO_OBJECT_LIKE:
918 case pch::PP_MACRO_FUNCTION_LIKE: {
919 // If we already have a macro, that means that we've hit the end
920 // of the definition of the macro we were looking for. We're
921 // done.
922 if (Macro)
923 return;
924
925 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
926 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000927 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +0000928 return;
929 }
930 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
931 bool isUsed = Record[2];
932
933 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
934 MI->setIsUsed(isUsed);
935
936 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
937 // Decode function-like macro info.
938 bool isC99VarArgs = Record[3];
939 bool isGNUVarArgs = Record[4];
940 MacroArgs.clear();
941 unsigned NumArgs = Record[5];
942 for (unsigned i = 0; i != NumArgs; ++i)
943 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
944
945 // Install function-like macro info.
946 MI->setIsFunctionLike();
947 if (isC99VarArgs) MI->setIsC99Varargs();
948 if (isGNUVarArgs) MI->setIsGNUVarargs();
949 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
950 PP.getPreprocessorAllocator());
951 }
952
953 // Finally, install the macro.
954 PP.setMacroInfo(II, MI);
955
956 // Remember that we saw this macro last so that we add the tokens that
957 // form its body to it.
958 Macro = MI;
959 ++NumMacrosRead;
960 break;
961 }
962
963 case pch::PP_TOKEN: {
964 // If we see a TOKEN before a PP_MACRO_*, then the file is
965 // erroneous, just pretend we didn't see this.
966 if (Macro == 0) break;
967
968 Token Tok;
969 Tok.startToken();
970 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
971 Tok.setLength(Record[1]);
972 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
973 Tok.setIdentifierInfo(II);
974 Tok.setKind((tok::TokenKind)Record[3]);
975 Tok.setFlag((Token::TokenFlags)Record[4]);
976 Macro->AddTokenToBody(Tok);
977 break;
978 }
Steve Naroff83d63c72009-04-24 20:03:17 +0000979 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000980 }
981}
982
Douglas Gregor668c1a42009-04-21 22:25:48 +0000983PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000984PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000985 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000986 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000987 return Failure;
988 }
Douglas Gregor2cf26342009-04-09 22:27:44 +0000989
990 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +0000991 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000992 while (!Stream.AtEndOfStream()) {
993 unsigned Code = Stream.ReadCode();
994 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000995 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000996 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000997 return Failure;
998 }
Chris Lattner7356a312009-04-11 21:15:38 +0000999
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001000 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001001 }
1002
1003 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1004 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001005 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1006 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001007 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001008 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001009 return Failure;
1010 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001011 break;
1012
Chris Lattner6367f6d2009-04-27 01:05:14 +00001013 case pch::DECLS_BLOCK_ID:
1014 // We lazily load the decls block, but we want to set up the
1015 // DeclsCursor cursor to point into it. Clone our current bitcode
1016 // cursor to it, enter the block and read the abbrevs in that block.
1017 // With the main cursor, we just skip over it.
1018 DeclsCursor = Stream;
1019 if (Stream.SkipBlock() || // Skip with the main cursor.
1020 // Read the abbrevs.
1021 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001022 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001023 return Failure;
1024 }
1025 break;
1026
Chris Lattner7356a312009-04-11 21:15:38 +00001027 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001028 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001029 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001030 return Failure;
1031 }
1032 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001033
Douglas Gregor14f79002009-04-10 03:52:48 +00001034 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001035 switch (ReadSourceManagerBlock()) {
1036 case Success:
1037 break;
1038
1039 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001040 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001041 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001042
1043 case IgnorePCH:
1044 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001045 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001046 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001047 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001048 continue;
1049 }
1050
1051 if (Code == llvm::bitc::DEFINE_ABBREV) {
1052 Stream.ReadAbbrevRecord();
1053 continue;
1054 }
1055
1056 // Read and process a record.
1057 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001058 const char *BlobStart = 0;
1059 unsigned BlobLen = 0;
1060 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1061 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001062 default: // Default behavior: ignore.
1063 break;
1064
1065 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001066 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001067 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001068 return Failure;
1069 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001070 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001071 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001072 break;
1073
1074 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001075 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001076 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001077 return Failure;
1078 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001079 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001080 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001081 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001082
1083 case pch::LANGUAGE_OPTIONS:
1084 if (ParseLanguageOptions(Record))
1085 return IgnorePCH;
1086 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001087
Douglas Gregorab41e632009-04-27 22:23:34 +00001088 case pch::METADATA: {
1089 if (Record[0] != pch::VERSION_MAJOR) {
1090 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1091 : diag::warn_pch_version_too_new);
1092 return IgnorePCH;
1093 }
1094
Douglas Gregor2bec0412009-04-10 21:16:55 +00001095 std::string TargetTriple(BlobStart, BlobLen);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001096 if (TargetTriple != PP.getTargetInfo().getTargetTriple()) {
Douglas Gregor2bec0412009-04-10 21:16:55 +00001097 Diag(diag::warn_pch_target_triple)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001098 << TargetTriple << PP.getTargetInfo().getTargetTriple();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001099 return IgnorePCH;
1100 }
1101 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001102 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001103
1104 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001105 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001106 if (Record[0]) {
1107 IdentifierLookupTable
1108 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001109 (const unsigned char *)IdentifierTableData + Record[0],
1110 (const unsigned char *)IdentifierTableData,
1111 PCHIdentifierLookupTrait(*this));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001112 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1113 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001114 break;
1115
1116 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001117 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001118 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001119 return Failure;
1120 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001121 IdentifierOffsets = (const uint32_t *)BlobStart;
1122 IdentifiersLoaded.resize(Record[0]);
Douglas Gregor8c5a7602009-04-25 23:30:02 +00001123 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001124 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001125
1126 case pch::EXTERNAL_DEFINITIONS:
1127 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001128 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001129 return Failure;
1130 }
1131 ExternalDefinitions.swap(Record);
1132 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001133
Douglas Gregorad1de002009-04-18 05:55:16 +00001134 case pch::SPECIAL_TYPES:
1135 SpecialTypes.swap(Record);
1136 break;
1137
Douglas Gregor3e1af842009-04-17 22:13:46 +00001138 case pch::STATISTICS:
1139 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001140 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001141 TotalLexicalDeclContexts = Record[2];
1142 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001143 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001144
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001145 case pch::TENTATIVE_DEFINITIONS:
1146 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001147 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001148 return Failure;
1149 }
1150 TentativeDefinitions.swap(Record);
1151 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001152
1153 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1154 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001155 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001156 return Failure;
1157 }
1158 LocallyScopedExternalDecls.swap(Record);
1159 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001160
Douglas Gregor83941df2009-04-25 17:48:32 +00001161 case pch::SELECTOR_OFFSETS:
1162 SelectorOffsets = (const uint32_t *)BlobStart;
1163 TotalNumSelectors = Record[0];
1164 SelectorsLoaded.resize(TotalNumSelectors);
1165 break;
1166
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001167 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001168 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1169 if (Record[0])
1170 MethodPoolLookupTable
1171 = PCHMethodPoolLookupTable::Create(
1172 MethodPoolLookupTableData + Record[0],
1173 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001174 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001175 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001176 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001177
1178 case pch::PP_COUNTER_VALUE:
1179 if (!Record.empty())
1180 PP.setCounterValue(Record[0]);
1181 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001182
1183 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001184 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001185 TotalNumSLocEntries = Record[0];
1186 PP.getSourceManager().PreallocateSLocEntries(this,
1187 TotalNumSLocEntries,
1188 Record[1]);
1189 break;
1190
1191 case pch::SOURCE_LOCATION_PRELOADS:
1192 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1193 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1194 if (Result != Success)
1195 return Result;
1196 }
1197 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001198
1199 case pch::STAT_CACHE:
1200 PP.getFileManager().setStatCache(
1201 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1202 (const unsigned char *)BlobStart,
1203 NumStatHits, NumStatMisses));
1204 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001205
1206 case pch::EXT_VECTOR_DECLS:
1207 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001208 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001209 return Failure;
1210 }
1211 ExtVectorDecls.swap(Record);
1212 break;
1213
1214 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1215 if (!ObjCCategoryImpls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001216 Error("duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001217 return Failure;
1218 }
1219 ObjCCategoryImpls.swap(Record);
1220 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001221 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001222 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001223 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001224 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001225}
1226
Douglas Gregore1d918e2009-04-10 23:10:45 +00001227PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001228 // Set the PCH file name.
1229 this->FileName = FileName;
1230
Douglas Gregor2cf26342009-04-09 22:27:44 +00001231 // Open the PCH file.
1232 std::string ErrStr;
1233 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001234 if (!Buffer) {
1235 Error(ErrStr.c_str());
1236 return IgnorePCH;
1237 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001238
1239 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001240 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1241 (const unsigned char *)Buffer->getBufferEnd());
1242 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001243
1244 // Sniff for the signature.
1245 if (Stream.Read(8) != 'C' ||
1246 Stream.Read(8) != 'P' ||
1247 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001248 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001249 Diag(diag::err_not_a_pch_file) << FileName;
1250 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001251 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001252
Douglas Gregor2cf26342009-04-09 22:27:44 +00001253 while (!Stream.AtEndOfStream()) {
1254 unsigned Code = Stream.ReadCode();
1255
Douglas Gregore1d918e2009-04-10 23:10:45 +00001256 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001257 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001258 return Failure;
1259 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001260
1261 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001262
Douglas Gregor2cf26342009-04-09 22:27:44 +00001263 // We only know the PCH subblock ID.
1264 switch (BlockID) {
1265 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001266 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001267 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001268 return Failure;
1269 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001270 break;
1271 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001272 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001273 case Success:
1274 break;
1275
1276 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001277 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001278
1279 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001280 // FIXME: We could consider reading through to the end of this
1281 // PCH block, skipping subblocks, to see if there are other
1282 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001283
1284 // Clear out any preallocated source location entries, so that
1285 // the source manager does not try to resolve them later.
1286 PP.getSourceManager().ClearPreallocatedSLocEntries();
1287
1288 // Remove the stat cache.
1289 PP.getFileManager().setStatCache(0);
1290
Douglas Gregore1d918e2009-04-10 23:10:45 +00001291 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001292 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001293 break;
1294 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001295 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001296 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001297 return Failure;
1298 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001299 break;
1300 }
1301 }
1302
1303 // Load the translation unit declaration
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001304 if (Context)
1305 ReadDeclRecord(DeclOffsets[0], 0);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001306
1307 // Check the predefines buffer.
1308 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1309 PCHPredefinesBufferID))
1310 return IgnorePCH;
1311
Douglas Gregor668c1a42009-04-21 22:25:48 +00001312 // Initialization of builtins and library builtins occurs before the
1313 // PCH file is read, so there may be some identifiers that were
1314 // loaded into the IdentifierTable before we intercepted the
1315 // creation of identifiers. Iterate through the list of known
1316 // identifiers and determine whether we have to establish
1317 // preprocessor definitions or top-level identifier declaration
1318 // chains for those identifiers.
1319 //
1320 // We copy the IdentifierInfo pointers to a small vector first,
1321 // since de-serializing declarations or macro definitions can add
1322 // new entries into the identifier table, invalidating the
1323 // iterators.
1324 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1325 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
1326 IdEnd = PP.getIdentifierTable().end();
1327 Id != IdEnd; ++Id)
1328 Identifiers.push_back(Id->second);
1329 PCHIdentifierLookupTable *IdTable
1330 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1331 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1332 IdentifierInfo *II = Identifiers[I];
1333 // Look in the on-disk hash table for an entry for
1334 PCHIdentifierLookupTrait Info(*this, II);
1335 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1336 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1337 if (Pos == IdTable->end())
1338 continue;
1339
1340 // Dereferencing the iterator has the effect of populating the
1341 // IdentifierInfo node with the various declarations it needs.
1342 (void)*Pos;
1343 }
1344
Douglas Gregorad1de002009-04-18 05:55:16 +00001345 // Load the special types.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001346 if (Context) {
1347 Context->setBuiltinVaListType(
1348 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1349 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1350 Context->setObjCIdType(GetType(Id));
1351 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1352 Context->setObjCSelType(GetType(Sel));
1353 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1354 Context->setObjCProtoType(GetType(Proto));
1355 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1356 Context->setObjCClassType(GetType(Class));
1357 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1358 Context->setCFConstantStringType(GetType(String));
1359 if (unsigned FastEnum
1360 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1361 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1362 }
Douglas Gregor0b748912009-04-14 21:18:50 +00001363
Douglas Gregor668c1a42009-04-21 22:25:48 +00001364 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001365}
1366
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001367/// \brief Parse the record that corresponds to a LangOptions data
1368/// structure.
1369///
1370/// This routine compares the language options used to generate the
1371/// PCH file against the language options set for the current
1372/// compilation. For each option, we classify differences between the
1373/// two compiler states as either "benign" or "important". Benign
1374/// differences don't matter, and we accept them without complaint
1375/// (and without modifying the language options). Differences between
1376/// the states for important options cause the PCH file to be
1377/// unusable, so we emit a warning and return true to indicate that
1378/// there was an error.
1379///
1380/// \returns true if the PCH file is unacceptable, false otherwise.
1381bool PCHReader::ParseLanguageOptions(
1382 const llvm::SmallVectorImpl<uint64_t> &Record) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001383 const LangOptions &LangOpts = PP.getLangOptions();
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001384#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1385#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1386 if (Record[Idx] != LangOpts.Option) { \
1387 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001388 return true; \
1389 } \
1390 ++Idx
1391
1392 unsigned Idx = 0;
1393 PARSE_LANGOPT_BENIGN(Trigraphs);
1394 PARSE_LANGOPT_BENIGN(BCPLComment);
1395 PARSE_LANGOPT_BENIGN(DollarIdents);
1396 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1397 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1398 PARSE_LANGOPT_BENIGN(ImplicitInt);
1399 PARSE_LANGOPT_BENIGN(Digraphs);
1400 PARSE_LANGOPT_BENIGN(HexFloats);
1401 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1402 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1403 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1404 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001405 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1406 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1407 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1408 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1409 PARSE_LANGOPT_BENIGN(PascalStrings);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001410 PARSE_LANGOPT_BENIGN(WritableStrings);
1411 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1412 diag::warn_pch_lax_vector_conversions);
1413 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1414 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1415 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1416 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1417 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1418 diag::warn_pch_thread_safe_statics);
1419 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1420 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1421 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1422 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1423 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1424 diag::warn_pch_heinous_extensions);
1425 // FIXME: Most of the options below are benign if the macro wasn't
1426 // used. Unfortunately, this means that a PCH compiled without
1427 // optimization can't be used with optimization turned on, even
1428 // though the only thing that changes is whether __OPTIMIZE__ was
1429 // defined... but if __OPTIMIZE__ never showed up in the header, it
1430 // doesn't matter. We could consider making this some special kind
1431 // of check.
1432 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1433 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1434 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1435 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1436 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1437 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1438 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1439 Diag(diag::warn_pch_gc_mode)
1440 << (unsigned)Record[Idx] << LangOpts.getGCMode();
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001441 return true;
1442 }
1443 ++Idx;
1444 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1445 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1446#undef PARSE_LANGOPT_IRRELEVANT
1447#undef PARSE_LANGOPT_BENIGN
1448
1449 return false;
1450}
1451
Douglas Gregor2cf26342009-04-09 22:27:44 +00001452/// \brief Read and return the type at the given offset.
1453///
1454/// This routine actually reads the record corresponding to the type
1455/// at the given offset in the bitstream. It is a helper routine for
1456/// GetType, which deals with reading type IDs.
1457QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001458 // Keep track of where we are in the stream, then jump back there
1459 // after reading this type.
1460 SavedStreamPosition SavedPosition(Stream);
1461
Douglas Gregor2cf26342009-04-09 22:27:44 +00001462 Stream.JumpToBit(Offset);
1463 RecordData Record;
1464 unsigned Code = Stream.ReadCode();
1465 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001466 case pch::TYPE_EXT_QUAL: {
1467 assert(Record.size() == 3 &&
1468 "Incorrect encoding of extended qualifier type");
1469 QualType Base = GetType(Record[0]);
1470 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1471 unsigned AddressSpace = Record[2];
1472
1473 QualType T = Base;
1474 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001475 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001476 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001477 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001478 return T;
1479 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001480
Douglas Gregor2cf26342009-04-09 22:27:44 +00001481 case pch::TYPE_FIXED_WIDTH_INT: {
1482 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001483 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001484 }
1485
1486 case pch::TYPE_COMPLEX: {
1487 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1488 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001489 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001490 }
1491
1492 case pch::TYPE_POINTER: {
1493 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1494 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001495 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001496 }
1497
1498 case pch::TYPE_BLOCK_POINTER: {
1499 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1500 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001501 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001502 }
1503
1504 case pch::TYPE_LVALUE_REFERENCE: {
1505 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1506 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001507 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001508 }
1509
1510 case pch::TYPE_RVALUE_REFERENCE: {
1511 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1512 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001513 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001514 }
1515
1516 case pch::TYPE_MEMBER_POINTER: {
1517 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1518 QualType PointeeType = GetType(Record[0]);
1519 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001520 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001521 }
1522
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001523 case pch::TYPE_CONSTANT_ARRAY: {
1524 QualType ElementType = GetType(Record[0]);
1525 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1526 unsigned IndexTypeQuals = Record[2];
1527 unsigned Idx = 3;
1528 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001529 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001530 }
1531
1532 case pch::TYPE_INCOMPLETE_ARRAY: {
1533 QualType ElementType = GetType(Record[0]);
1534 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1535 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001536 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001537 }
1538
1539 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001540 QualType ElementType = GetType(Record[0]);
1541 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1542 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001543 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1544 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001545 }
1546
1547 case pch::TYPE_VECTOR: {
1548 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001549 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001550 return QualType();
1551 }
1552
1553 QualType ElementType = GetType(Record[0]);
1554 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001555 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001556 }
1557
1558 case pch::TYPE_EXT_VECTOR: {
1559 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001560 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001561 return QualType();
1562 }
1563
1564 QualType ElementType = GetType(Record[0]);
1565 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001566 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001567 }
1568
1569 case pch::TYPE_FUNCTION_NO_PROTO: {
1570 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001571 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001572 return QualType();
1573 }
1574 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001575 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001576 }
1577
1578 case pch::TYPE_FUNCTION_PROTO: {
1579 QualType ResultType = GetType(Record[0]);
1580 unsigned Idx = 1;
1581 unsigned NumParams = Record[Idx++];
1582 llvm::SmallVector<QualType, 16> ParamTypes;
1583 for (unsigned I = 0; I != NumParams; ++I)
1584 ParamTypes.push_back(GetType(Record[Idx++]));
1585 bool isVariadic = Record[Idx++];
1586 unsigned Quals = Record[Idx++];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001587 return Context->getFunctionType(ResultType, &ParamTypes[0], NumParams,
1588 isVariadic, Quals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001589 }
1590
1591 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001592 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001593 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001594
1595 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001596 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001597
1598 case pch::TYPE_TYPEOF: {
1599 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001600 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001601 return QualType();
1602 }
1603 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001604 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001605 }
1606
1607 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001608 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001609 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001610
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001611 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001612 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001613 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001614
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001615 case pch::TYPE_OBJC_INTERFACE:
Douglas Gregora02b1472009-04-28 21:53:25 +00001616 assert(Record.size() == 1 && "incorrect encoding of objc interface type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001617 return Context->getObjCInterfaceType(
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001618 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001619
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001620 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1621 unsigned Idx = 0;
1622 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1623 unsigned NumProtos = Record[Idx++];
1624 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1625 for (unsigned I = 0; I != NumProtos; ++I)
1626 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001627 return Context->getObjCQualifiedInterfaceType(ItfD, &Protos[0], NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001628 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001629
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001630 case pch::TYPE_OBJC_QUALIFIED_ID: {
1631 unsigned Idx = 0;
1632 unsigned NumProtos = Record[Idx++];
1633 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1634 for (unsigned I = 0; I != NumProtos; ++I)
1635 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001636 return Context->getObjCQualifiedIdType(&Protos[0], NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001637 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001638 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001639 // Suppress a GCC warning
1640 return QualType();
1641}
1642
Douglas Gregor2cf26342009-04-09 22:27:44 +00001643
Douglas Gregor8038d512009-04-10 17:25:41 +00001644QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001645 unsigned Quals = ID & 0x07;
1646 unsigned Index = ID >> 3;
1647
1648 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1649 QualType T;
1650 switch ((pch::PredefinedTypeIDs)Index) {
1651 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001652 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1653 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001654
1655 case pch::PREDEF_TYPE_CHAR_U_ID:
1656 case pch::PREDEF_TYPE_CHAR_S_ID:
1657 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001658 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001659 break;
1660
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001661 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1662 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1663 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1664 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1665 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
1666 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1667 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1668 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1669 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1670 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1671 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
1672 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1673 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1674 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1675 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1676 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001677 }
1678
1679 assert(!T.isNull() && "Unknown predefined type");
1680 return T.getQualifiedType(Quals);
1681 }
1682
1683 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregor366809a2009-04-26 03:49:13 +00001684 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001685 if (!TypesLoaded[Index])
1686 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001687
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001688 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001689}
1690
Douglas Gregor8038d512009-04-10 17:25:41 +00001691Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001692 if (ID == 0)
1693 return 0;
1694
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001695 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001696 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001697 return 0;
1698 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001699
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001700 unsigned Index = ID - 1;
1701 if (!DeclsLoaded[Index])
1702 ReadDeclRecord(DeclOffsets[Index], Index);
1703
1704 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001705}
1706
Chris Lattner887e2b32009-04-27 05:46:25 +00001707/// \brief Resolve the offset of a statement into a statement.
1708///
1709/// This operation will read a new statement from the external
1710/// source each time it is called, and is meant to be used via a
1711/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1712Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00001713 // Since we know tha this statement is part of a decl, make sure to use the
1714 // decl cursor to read it.
1715 DeclsCursor.JumpToBit(Offset);
1716 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00001717}
1718
Douglas Gregor2cf26342009-04-09 22:27:44 +00001719bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00001720 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001721 assert(DC->hasExternalLexicalStorage() &&
1722 "DeclContext has no lexical decls in storage");
1723 uint64_t Offset = DeclContextOffsets[DC].first;
1724 assert(Offset && "DeclContext has no lexical decls in storage");
1725
Douglas Gregor0b748912009-04-14 21:18:50 +00001726 // Keep track of where we are in the stream, then jump back there
1727 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001728 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001729
Douglas Gregor2cf26342009-04-09 22:27:44 +00001730 // Load the record containing all of the declarations lexically in
1731 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001732 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001733 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001734 unsigned Code = DeclsCursor.ReadCode();
1735 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001736 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001737 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1738
1739 // Load all of the declaration IDs
1740 Decls.clear();
1741 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00001742 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001743 return false;
1744}
1745
1746bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001747 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001748 assert(DC->hasExternalVisibleStorage() &&
1749 "DeclContext has no visible decls in storage");
1750 uint64_t Offset = DeclContextOffsets[DC].second;
1751 assert(Offset && "DeclContext has no visible decls in storage");
1752
Douglas Gregor0b748912009-04-14 21:18:50 +00001753 // Keep track of where we are in the stream, then jump back there
1754 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001755 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001756
Douglas Gregor2cf26342009-04-09 22:27:44 +00001757 // Load the record containing all of the declarations visible in
1758 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001759 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001760 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001761 unsigned Code = DeclsCursor.ReadCode();
1762 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001763 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001764 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1765 if (Record.size() == 0)
1766 return false;
1767
1768 Decls.clear();
1769
1770 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001771 while (Idx < Record.size()) {
1772 Decls.push_back(VisibleDeclaration());
1773 Decls.back().Name = ReadDeclarationName(Record, Idx);
1774
Douglas Gregor2cf26342009-04-09 22:27:44 +00001775 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001776 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001777 LoadedDecls.reserve(Size);
1778 for (unsigned I = 0; I < Size; ++I)
1779 LoadedDecls.push_back(Record[Idx++]);
1780 }
1781
Douglas Gregor25123082009-04-22 22:34:57 +00001782 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001783 return false;
1784}
1785
Douglas Gregorfdd01722009-04-14 00:24:19 +00001786void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00001787 this->Consumer = Consumer;
1788
Douglas Gregorfdd01722009-04-14 00:24:19 +00001789 if (!Consumer)
1790 return;
1791
1792 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1793 Decl *D = GetDecl(ExternalDefinitions[I]);
1794 DeclGroupRef DG(D);
1795 Consumer->HandleTopLevelDecl(DG);
1796 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00001797
1798 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
1799 DeclGroupRef DG(InterestingDecls[I]);
1800 Consumer->HandleTopLevelDecl(DG);
1801 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00001802}
1803
Douglas Gregor2cf26342009-04-09 22:27:44 +00001804void PCHReader::PrintStats() {
1805 std::fprintf(stderr, "*** PCH Statistics:\n");
1806
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001807 unsigned NumTypesLoaded
1808 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
1809 (Type *)0);
1810 unsigned NumDeclsLoaded
1811 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
1812 (Decl *)0);
1813 unsigned NumIdentifiersLoaded
1814 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
1815 IdentifiersLoaded.end(),
1816 (IdentifierInfo *)0);
1817 unsigned NumSelectorsLoaded
1818 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
1819 SelectorsLoaded.end(),
1820 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00001821
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001822 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
1823 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001824 if (TotalNumSLocEntries)
1825 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
1826 NumSLocEntriesRead, TotalNumSLocEntries,
1827 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001828 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001829 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001830 NumTypesLoaded, (unsigned)TypesLoaded.size(),
1831 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
1832 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001833 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001834 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
1835 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001836 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001837 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001838 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
1839 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00001840 if (TotalNumSelectors)
1841 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
1842 NumSelectorsLoaded, TotalNumSelectors,
1843 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
1844 if (TotalNumStatements)
1845 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
1846 NumStatementsRead, TotalNumStatements,
1847 ((float)NumStatementsRead/TotalNumStatements * 100));
1848 if (TotalNumMacros)
1849 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
1850 NumMacrosRead, TotalNumMacros,
1851 ((float)NumMacrosRead/TotalNumMacros * 100));
1852 if (TotalLexicalDeclContexts)
1853 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
1854 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
1855 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
1856 * 100));
1857 if (TotalVisibleDeclContexts)
1858 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
1859 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
1860 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
1861 * 100));
1862 if (TotalSelectorsInMethodPool) {
1863 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
1864 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
1865 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
1866 * 100));
1867 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
1868 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001869 std::fprintf(stderr, "\n");
1870}
1871
Douglas Gregor668c1a42009-04-21 22:25:48 +00001872void PCHReader::InitializeSema(Sema &S) {
1873 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001874 S.ExternalSource = this;
1875
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001876 // Makes sure any declarations that were deserialized "too early"
1877 // still get added to the identifier's declaration chains.
1878 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
1879 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
1880 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001881 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001882 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001883
1884 // If there were any tentative definitions, deserialize them and add
1885 // them to Sema's table of tentative definitions.
1886 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
1887 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
1888 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
1889 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00001890
1891 // If there were any locally-scoped external declarations,
1892 // deserialize them and add them to Sema's table of locally-scoped
1893 // external declarations.
1894 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
1895 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
1896 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
1897 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00001898
1899 // If there were any ext_vector type declarations, deserialize them
1900 // and add them to Sema's vector of such declarations.
1901 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
1902 SemaObj->ExtVectorDecls.push_back(
1903 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
1904
1905 // If there were any Objective-C category implementations,
1906 // deserialize them and add them to Sema's vector of such
1907 // definitions.
1908 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
1909 SemaObj->ObjCCategoryImpls.push_back(
1910 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001911}
1912
1913IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
1914 // Try to find this name within our on-disk hash table
1915 PCHIdentifierLookupTable *IdTable
1916 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1917 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
1918 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
1919 if (Pos == IdTable->end())
1920 return 0;
1921
1922 // Dereferencing the iterator has the effect of building the
1923 // IdentifierInfo node and populating it with the various
1924 // declarations it needs.
1925 return *Pos;
1926}
1927
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001928std::pair<ObjCMethodList, ObjCMethodList>
1929PCHReader::ReadMethodPool(Selector Sel) {
1930 if (!MethodPoolLookupTable)
1931 return std::pair<ObjCMethodList, ObjCMethodList>();
1932
1933 // Try to find this selector within our on-disk hash table.
1934 PCHMethodPoolLookupTable *PoolTable
1935 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
1936 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00001937 if (Pos == PoolTable->end()) {
1938 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001939 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00001940 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001941
Douglas Gregor83941df2009-04-25 17:48:32 +00001942 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001943 return *Pos;
1944}
1945
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001946void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00001947 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00001948 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001949 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001950}
1951
Chris Lattner7356a312009-04-11 21:15:38 +00001952IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001953 if (ID == 0)
1954 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00001955
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001956 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001957 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001958 return 0;
1959 }
Chris Lattner7356a312009-04-11 21:15:38 +00001960
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001961 if (!IdentifiersLoaded[ID - 1]) {
1962 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00001963 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00001964
Douglas Gregor02fc7512009-04-28 20:01:51 +00001965 // All of the strings in the PCH file are preceded by a 16-bit
1966 // length. Extract that 16-bit length to avoid having to execute
1967 // strlen().
1968 const char *StrLenPtr = Str - 2;
1969 unsigned StrLen = (((unsigned) StrLenPtr[0])
1970 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
1971 IdentifiersLoaded[ID - 1]
1972 = &PP.getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001973 }
Chris Lattner7356a312009-04-11 21:15:38 +00001974
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001975 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001976}
1977
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001978void PCHReader::ReadSLocEntry(unsigned ID) {
1979 ReadSLocEntryRecord(ID);
1980}
1981
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001982Selector PCHReader::DecodeSelector(unsigned ID) {
1983 if (ID == 0)
1984 return Selector();
1985
Douglas Gregora02b1472009-04-28 21:53:25 +00001986 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001987 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00001988
1989 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001990 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001991 return Selector();
1992 }
Douglas Gregor83941df2009-04-25 17:48:32 +00001993
1994 unsigned Index = ID - 1;
1995 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
1996 // Load this selector from the selector table.
1997 // FIXME: endianness portability issues with SelectorOffsets table
1998 PCHMethodPoolLookupTrait Trait(*this);
1999 SelectorsLoaded[Index]
2000 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2001 }
2002
2003 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002004}
2005
Douglas Gregor2cf26342009-04-09 22:27:44 +00002006DeclarationName
2007PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2008 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2009 switch (Kind) {
2010 case DeclarationName::Identifier:
2011 return DeclarationName(GetIdentifierInfo(Record, Idx));
2012
2013 case DeclarationName::ObjCZeroArgSelector:
2014 case DeclarationName::ObjCOneArgSelector:
2015 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002016 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002017
2018 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002019 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002020 GetType(Record[Idx++]));
2021
2022 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002023 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002024 GetType(Record[Idx++]));
2025
2026 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002027 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002028 GetType(Record[Idx++]));
2029
2030 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002031 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002032 (OverloadedOperatorKind)Record[Idx++]);
2033
2034 case DeclarationName::CXXUsingDirective:
2035 return DeclarationName::getUsingDirectiveName();
2036 }
2037
2038 // Required to silence GCC warning
2039 return DeclarationName();
2040}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002041
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002042/// \brief Read an integral value
2043llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2044 unsigned BitWidth = Record[Idx++];
2045 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2046 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2047 Idx += NumWords;
2048 return Result;
2049}
2050
2051/// \brief Read a signed integral value
2052llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2053 bool isUnsigned = Record[Idx++];
2054 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2055}
2056
Douglas Gregor17fc2232009-04-14 21:55:33 +00002057/// \brief Read a floating-point value
2058llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002059 return llvm::APFloat(ReadAPInt(Record, Idx));
2060}
2061
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002062// \brief Read a string
2063std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2064 unsigned Len = Record[Idx++];
2065 std::string Result(&Record[Idx], &Record[Idx] + Len);
2066 Idx += Len;
2067 return Result;
2068}
2069
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002070DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002071 return Diag(SourceLocation(), DiagID);
2072}
2073
2074DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2075 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002076 PP.getSourceManager()),
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002077 DiagID);
2078}
Douglas Gregor025452f2009-04-17 00:04:06 +00002079
Douglas Gregor668c1a42009-04-21 22:25:48 +00002080/// \brief Retrieve the identifier table associated with the
2081/// preprocessor.
2082IdentifierTable &PCHReader::getIdentifierTable() {
2083 return PP.getIdentifierTable();
2084}
2085
Douglas Gregor025452f2009-04-17 00:04:06 +00002086/// \brief Record that the given ID maps to the given switch-case
2087/// statement.
2088void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2089 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2090 SwitchCaseStmts[ID] = SC;
2091}
2092
2093/// \brief Retrieve the switch-case statement with the given ID.
2094SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2095 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2096 return SwitchCaseStmts[ID];
2097}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002098
2099/// \brief Record that the given label statement has been
2100/// deserialized and has the given ID.
2101void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2102 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2103 "Deserialized label twice");
2104 LabelStmts[ID] = S;
2105
2106 // If we've already seen any goto statements that point to this
2107 // label, resolve them now.
2108 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2109 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2110 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2111 Goto->second->setLabel(S);
2112 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002113
2114 // If we've already seen any address-label statements that point to
2115 // this label, resolve them now.
2116 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2117 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2118 = UnresolvedAddrLabelExprs.equal_range(ID);
2119 for (AddrLabelIter AddrLabel = AddrLabels.first;
2120 AddrLabel != AddrLabels.second; ++AddrLabel)
2121 AddrLabel->second->setLabel(S);
2122 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002123}
2124
2125/// \brief Set the label of the given statement to the label
2126/// identified by ID.
2127///
2128/// Depending on the order in which the label and other statements
2129/// referencing that label occur, this operation may complete
2130/// immediately (updating the statement) or it may queue the
2131/// statement to be back-patched later.
2132void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2133 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2134 if (Label != LabelStmts.end()) {
2135 // We've already seen this label, so set the label of the goto and
2136 // we're done.
2137 S->setLabel(Label->second);
2138 } else {
2139 // We haven't seen this label yet, so add this goto to the set of
2140 // unresolved goto statements.
2141 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2142 }
2143}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002144
2145/// \brief Set the label of the given expression to the label
2146/// identified by ID.
2147///
2148/// Depending on the order in which the label and other statements
2149/// referencing that label occur, this operation may complete
2150/// immediately (updating the statement) or it may queue the
2151/// statement to be back-patched later.
2152void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2153 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2154 if (Label != LabelStmts.end()) {
2155 // We've already seen this label, so set the label of the
2156 // label-address expression and we're done.
2157 S->setLabel(Label->second);
2158 } else {
2159 // We haven't seen this label yet, so add this label-address
2160 // expression to the set of unresolved label-address expressions.
2161 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2162 }
2163}