blob: 99b5fb96858b22be0e9c12301a998fea52df8d49 [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);
417 Diag(diag::note_ignoring_pch) << FileName;
Douglas Gregore721f952009-04-28 18:58:38 +0000418 return true;
419 }
420
421 // This is a macro definition. Determine the name of the macro
422 // we're defining.
423 std::string::size_type StartOfMacroName = strlen("#define ");
424 std::string::size_type EndOfMacroName
425 = Missing.find_first_of("( \n\r", StartOfMacroName);
426 assert(EndOfMacroName != std::string::npos &&
427 "Couldn't find the end of the macro name");
428 std::string MacroName = Missing.substr(StartOfMacroName,
429 EndOfMacroName - StartOfMacroName);
430
431 // Determine whether this macro was given a different definition
432 // on the command line.
433 std::string MacroDefStart = "#define " + MacroName;
434 std::string::size_type MacroDefLen = MacroDefStart.size();
435 std::vector<std::string>::iterator ConflictPos
436 = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
437 MacroDefStart);
438 for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
439 if (!startsWith(*ConflictPos, MacroDefStart)) {
440 // Different macro; we're done.
441 ConflictPos = CmdLineLines.end();
442 break;
443 }
444
445 assert(ConflictPos->size() > MacroDefLen &&
446 "Invalid #define in predefines buffer?");
447 if ((*ConflictPos)[MacroDefLen] != ' ' &&
448 (*ConflictPos)[MacroDefLen] != '(')
449 continue; // Longer macro name; keep trying.
450
451 // We found a conflicting macro definition.
452 break;
453 }
454
455 if (ConflictPos != CmdLineLines.end()) {
456 Diag(diag::warn_cmdline_conflicting_macro_def)
457 << MacroName;
458
459 // Show the definition of this macro within the PCH file.
460 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
461 unsigned Offset = MissingDef - PCHPredef;
462 SourceLocation PCHMissingLoc
463 = SourceMgr.getLocForStartOfFile(PCHBufferID)
464 .getFileLocWithOffset(Offset);
465 Diag(PCHMissingLoc, diag::note_pch_macro_defined_as)
466 << MacroName;
467
468 ConflictingDefines = true;
469 continue;
470 }
471
472 // If the macro doesn't conflict, then we'll just pick up the
473 // macro definition from the PCH file. Warn the user that they
474 // made a mistake.
475 if (ConflictingDefines)
476 continue; // Don't complain if there are already conflicting defs
477
478 if (!MissingDefines) {
479 Diag(diag::warn_cmdline_missing_macro_defs);
480 MissingDefines = true;
481 }
482
483 // Show the definition of this macro within the PCH file.
484 const char *MissingDef = strstr(PCHPredef, Missing.c_str());
485 unsigned Offset = MissingDef - PCHPredef;
486 SourceLocation PCHMissingLoc
487 = SourceMgr.getLocForStartOfFile(PCHBufferID)
488 .getFileLocWithOffset(Offset);
489 Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
Douglas Gregore1d918e2009-04-10 23:10:45 +0000490 }
491
Douglas Gregore721f952009-04-28 18:58:38 +0000492 if (ConflictingDefines) {
493 Diag(diag::note_ignoring_pch) << FileName;
494 return true;
495 }
496
497 // Determine what predefines were introduced based on command-line
498 // parameters that were not present when building the PCH
499 // file. Extra #defines are okay, so long as the identifiers being
500 // defined were not used within the precompiled header.
501 std::vector<std::string> ExtraPredefines;
502 std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
503 PCHLines.begin(), PCHLines.end(),
504 std::back_inserter(ExtraPredefines));
505 for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
506 const std::string &Extra = ExtraPredefines[I];
507 if (!startsWith(Extra, "#define ") != 0) {
Douglas Gregoraf1795b2009-04-28 20:36:16 +0000508 Diag(diag::warn_pch_compiler_options_mismatch);
509 Diag(diag::note_ignoring_pch) << FileName;
Douglas Gregore721f952009-04-28 18:58:38 +0000510 return true;
511 }
512
513 // This is an extra macro definition. Determine the name of the
514 // macro we're defining.
515 std::string::size_type StartOfMacroName = strlen("#define ");
516 std::string::size_type EndOfMacroName
517 = Extra.find_first_of("( \n\r", StartOfMacroName);
518 assert(EndOfMacroName != std::string::npos &&
519 "Couldn't find the end of the macro name");
520 std::string MacroName = Extra.substr(StartOfMacroName,
521 EndOfMacroName - StartOfMacroName);
522
Douglas Gregor92b059e2009-04-28 20:33:11 +0000523 // Check whether this name was used somewhere in the PCH file. If
524 // so, defining it as a macro could change behavior, so we reject
525 // the PCH file.
526 if (IdentifierInfo *II = get(MacroName.c_str(),
527 MacroName.c_str() + MacroName.size())) {
528 Diag(diag::warn_macro_name_used_in_pch)
529 << II;
530 Diag(diag::note_ignoring_pch)
531 << FileName;
532 return true;
533 }
Douglas Gregore721f952009-04-28 18:58:38 +0000534
535 // Add this definition to the suggested predefines buffer.
536 SuggestedPredefines += Extra;
537 SuggestedPredefines += '\n';
538 }
539
540 // If we get here, it's because the predefines buffer had compatible
541 // contents. Accept the PCH file.
542 return false;
Douglas Gregore1d918e2009-04-10 23:10:45 +0000543}
544
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000545//===----------------------------------------------------------------------===//
546// Source Manager Deserialization
547//===----------------------------------------------------------------------===//
548
Douglas Gregorbd945002009-04-13 16:31:14 +0000549/// \brief Read the line table in the source manager block.
550/// \returns true if ther was an error.
551static bool ParseLineTable(SourceManager &SourceMgr,
552 llvm::SmallVectorImpl<uint64_t> &Record) {
553 unsigned Idx = 0;
554 LineTableInfo &LineTable = SourceMgr.getLineTable();
555
556 // Parse the file names
Douglas Gregorff0a9872009-04-13 17:12:42 +0000557 std::map<int, int> FileIDs;
558 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregorbd945002009-04-13 16:31:14 +0000559 // Extract the file name
560 unsigned FilenameLen = Record[Idx++];
561 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
562 Idx += FilenameLen;
Douglas Gregorff0a9872009-04-13 17:12:42 +0000563 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
564 Filename.size());
Douglas Gregorbd945002009-04-13 16:31:14 +0000565 }
566
567 // Parse the line entries
568 std::vector<LineEntry> Entries;
569 while (Idx < Record.size()) {
Douglas Gregorff0a9872009-04-13 17:12:42 +0000570 int FID = FileIDs[Record[Idx++]];
Douglas Gregorbd945002009-04-13 16:31:14 +0000571
572 // Extract the line entries
573 unsigned NumEntries = Record[Idx++];
574 Entries.clear();
575 Entries.reserve(NumEntries);
576 for (unsigned I = 0; I != NumEntries; ++I) {
577 unsigned FileOffset = Record[Idx++];
578 unsigned LineNo = Record[Idx++];
579 int FilenameID = Record[Idx++];
580 SrcMgr::CharacteristicKind FileKind
581 = (SrcMgr::CharacteristicKind)Record[Idx++];
582 unsigned IncludeOffset = Record[Idx++];
583 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
584 FileKind, IncludeOffset));
585 }
586 LineTable.AddEntry(FID, Entries);
587 }
588
589 return false;
590}
591
Douglas Gregor4fed3f42009-04-27 18:38:38 +0000592namespace {
593
594class VISIBILITY_HIDDEN PCHStatData {
595public:
596 const bool hasStat;
597 const ino_t ino;
598 const dev_t dev;
599 const mode_t mode;
600 const time_t mtime;
601 const off_t size;
602
603 PCHStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
604 : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
605
606 PCHStatData()
607 : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
608};
609
610class VISIBILITY_HIDDEN PCHStatLookupTrait {
611 public:
612 typedef const char *external_key_type;
613 typedef const char *internal_key_type;
614
615 typedef PCHStatData data_type;
616
617 static unsigned ComputeHash(const char *path) {
618 return BernsteinHash(path);
619 }
620
621 static internal_key_type GetInternalKey(const char *path) { return path; }
622
623 static bool EqualKey(internal_key_type a, internal_key_type b) {
624 return strcmp(a, b) == 0;
625 }
626
627 static std::pair<unsigned, unsigned>
628 ReadKeyDataLength(const unsigned char*& d) {
629 unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
630 unsigned DataLen = (unsigned) *d++;
631 return std::make_pair(KeyLen + 1, DataLen);
632 }
633
634 static internal_key_type ReadKey(const unsigned char *d, unsigned) {
635 return (const char *)d;
636 }
637
638 static data_type ReadData(const internal_key_type, const unsigned char *d,
639 unsigned /*DataLen*/) {
640 using namespace clang::io;
641
642 if (*d++ == 1)
643 return data_type();
644
645 ino_t ino = (ino_t) ReadUnalignedLE32(d);
646 dev_t dev = (dev_t) ReadUnalignedLE32(d);
647 mode_t mode = (mode_t) ReadUnalignedLE16(d);
648 time_t mtime = (time_t) ReadUnalignedLE64(d);
649 off_t size = (off_t) ReadUnalignedLE64(d);
650 return data_type(ino, dev, mode, mtime, size);
651 }
652};
653
654/// \brief stat() cache for precompiled headers.
655///
656/// This cache is very similar to the stat cache used by pretokenized
657/// headers.
658class VISIBILITY_HIDDEN PCHStatCache : public StatSysCallCache {
659 typedef OnDiskChainedHashTable<PCHStatLookupTrait> CacheTy;
660 CacheTy *Cache;
661
662 unsigned &NumStatHits, &NumStatMisses;
663public:
664 PCHStatCache(const unsigned char *Buckets,
665 const unsigned char *Base,
666 unsigned &NumStatHits,
667 unsigned &NumStatMisses)
668 : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
669 Cache = CacheTy::Create(Buckets, Base);
670 }
671
672 ~PCHStatCache() { delete Cache; }
673
674 int stat(const char *path, struct stat *buf) {
675 // Do the lookup for the file's data in the PCH file.
676 CacheTy::iterator I = Cache->find(path);
677
678 // If we don't get a hit in the PCH file just forward to 'stat'.
679 if (I == Cache->end()) {
680 ++NumStatMisses;
681 return ::stat(path, buf);
682 }
683
684 ++NumStatHits;
685 PCHStatData Data = *I;
686
687 if (!Data.hasStat)
688 return 1;
689
690 buf->st_ino = Data.ino;
691 buf->st_dev = Data.dev;
692 buf->st_mtime = Data.mtime;
693 buf->st_mode = Data.mode;
694 buf->st_size = Data.size;
695 return 0;
696 }
697};
698} // end anonymous namespace
699
700
Douglas Gregor14f79002009-04-10 03:52:48 +0000701/// \brief Read the source manager block
Douglas Gregore1d918e2009-04-10 23:10:45 +0000702PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregor14f79002009-04-10 03:52:48 +0000703 using namespace SrcMgr;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000704
705 // Set the source-location entry cursor to the current position in
706 // the stream. This cursor will be used to read the contents of the
707 // source manager block initially, and then lazily read
708 // source-location entries as needed.
709 SLocEntryCursor = Stream;
710
711 // The stream itself is going to skip over the source manager block.
712 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000713 Error("malformed block record in PCH file");
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000714 return Failure;
715 }
716
717 // Enter the source manager block.
718 if (SLocEntryCursor.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000719 Error("malformed source manager block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000720 return Failure;
721 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000722
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000723 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor14f79002009-04-10 03:52:48 +0000724 RecordData Record;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000725 unsigned NumHeaderInfos = 0;
Douglas Gregor14f79002009-04-10 03:52:48 +0000726 while (true) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000727 unsigned Code = SLocEntryCursor.ReadCode();
Douglas Gregor14f79002009-04-10 03:52:48 +0000728 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000729 if (SLocEntryCursor.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000730 Error("error at end of Source Manager block in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000731 return Failure;
732 }
Douglas Gregore1d918e2009-04-10 23:10:45 +0000733 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000734 }
735
736 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
737 // No known subblocks, always skip them.
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000738 SLocEntryCursor.ReadSubBlockID();
739 if (SLocEntryCursor.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000740 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +0000741 return Failure;
742 }
Douglas Gregor14f79002009-04-10 03:52:48 +0000743 continue;
744 }
745
746 if (Code == llvm::bitc::DEFINE_ABBREV) {
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000747 SLocEntryCursor.ReadAbbrevRecord();
Douglas Gregor14f79002009-04-10 03:52:48 +0000748 continue;
749 }
750
751 // Read a record.
752 const char *BlobStart;
753 unsigned BlobLen;
754 Record.clear();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000755 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
Douglas Gregor14f79002009-04-10 03:52:48 +0000756 default: // Default behavior: ignore.
757 break;
758
Chris Lattner2c78b872009-04-14 23:22:57 +0000759 case pch::SM_LINE_TABLE:
Douglas Gregorbd945002009-04-13 16:31:14 +0000760 if (ParseLineTable(SourceMgr, Record))
761 return Failure;
Chris Lattner2c78b872009-04-14 23:22:57 +0000762 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000763
764 case pch::SM_HEADER_FILE_INFO: {
765 HeaderFileInfo HFI;
766 HFI.isImport = Record[0];
767 HFI.DirInfo = Record[1];
768 HFI.NumIncludes = Record[2];
769 HFI.ControllingMacroID = Record[3];
770 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
771 break;
772 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000773
774 case pch::SM_SLOC_FILE_ENTRY:
775 case pch::SM_SLOC_BUFFER_ENTRY:
776 case pch::SM_SLOC_INSTANTIATION_ENTRY:
777 // Once we hit one of the source location entries, we're done.
778 return Success;
Douglas Gregor14f79002009-04-10 03:52:48 +0000779 }
780 }
781}
782
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000783/// \brief Read in the source location entry with the given ID.
784PCHReader::PCHReadResult PCHReader::ReadSLocEntryRecord(unsigned ID) {
785 if (ID == 0)
786 return Success;
787
788 if (ID > TotalNumSLocEntries) {
789 Error("source location entry ID out-of-range for PCH file");
790 return Failure;
791 }
792
793 ++NumSLocEntriesRead;
794 SLocEntryCursor.JumpToBit(SLocOffsets[ID - 1]);
795 unsigned Code = SLocEntryCursor.ReadCode();
796 if (Code == llvm::bitc::END_BLOCK ||
797 Code == llvm::bitc::ENTER_SUBBLOCK ||
798 Code == llvm::bitc::DEFINE_ABBREV) {
799 Error("incorrectly-formatted source location entry in PCH file");
800 return Failure;
801 }
802
Chris Lattnerd1d64a02009-04-27 21:45:14 +0000803 SourceManager &SourceMgr = PP.getSourceManager();
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000804 RecordData Record;
805 const char *BlobStart;
806 unsigned BlobLen;
807 switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
808 default:
809 Error("incorrectly-formatted source location entry in PCH file");
810 return Failure;
811
812 case pch::SM_SLOC_FILE_ENTRY: {
813 const FileEntry *File
814 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
815 // FIXME: Error recovery if file cannot be found.
816 FileID FID = SourceMgr.createFileID(File,
817 SourceLocation::getFromRawEncoding(Record[1]),
818 (SrcMgr::CharacteristicKind)Record[2],
819 ID, Record[0]);
820 if (Record[3])
821 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
822 .setHasLineDirectives();
823
824 break;
825 }
826
827 case pch::SM_SLOC_BUFFER_ENTRY: {
828 const char *Name = BlobStart;
829 unsigned Offset = Record[0];
830 unsigned Code = SLocEntryCursor.ReadCode();
831 Record.clear();
832 unsigned RecCode
833 = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
834 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
835 (void)RecCode;
836 llvm::MemoryBuffer *Buffer
837 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
838 BlobStart + BlobLen - 1,
839 Name);
840 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
841
Douglas Gregor92b059e2009-04-28 20:33:11 +0000842 if (strcmp(Name, "<built-in>") == 0) {
843 PCHPredefinesBufferID = BufferID;
844 PCHPredefines = BlobStart;
845 PCHPredefinesLen = BlobLen - 1;
846 }
Douglas Gregor7f94b0b2009-04-27 06:38:32 +0000847
848 break;
849 }
850
851 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
852 SourceLocation SpellingLoc
853 = SourceLocation::getFromRawEncoding(Record[1]);
854 SourceMgr.createInstantiationLoc(SpellingLoc,
855 SourceLocation::getFromRawEncoding(Record[2]),
856 SourceLocation::getFromRawEncoding(Record[3]),
857 Record[4],
858 ID,
859 Record[0]);
860 break;
861 }
862 }
863
864 return Success;
865}
866
Chris Lattner6367f6d2009-04-27 01:05:14 +0000867/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
868/// specified cursor. Read the abbreviations that are at the top of the block
869/// and then leave the cursor pointing into the block.
870bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
871 unsigned BlockID) {
872 if (Cursor.EnterSubBlock(BlockID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000873 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +0000874 return Failure;
875 }
876
Chris Lattner6367f6d2009-04-27 01:05:14 +0000877 while (true) {
878 unsigned Code = Cursor.ReadCode();
879
880 // We expect all abbrevs to be at the start of the block.
881 if (Code != llvm::bitc::DEFINE_ABBREV)
882 return false;
883 Cursor.ReadAbbrevRecord();
884 }
885}
886
Douglas Gregor37e26842009-04-21 23:56:24 +0000887void PCHReader::ReadMacroRecord(uint64_t Offset) {
888 // Keep track of where we are in the stream, then jump back there
889 // after reading this macro.
890 SavedStreamPosition SavedPosition(Stream);
891
892 Stream.JumpToBit(Offset);
893 RecordData Record;
894 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
895 MacroInfo *Macro = 0;
Steve Naroff83d63c72009-04-24 20:03:17 +0000896
Douglas Gregor37e26842009-04-21 23:56:24 +0000897 while (true) {
898 unsigned Code = Stream.ReadCode();
899 switch (Code) {
900 case llvm::bitc::END_BLOCK:
901 return;
902
903 case llvm::bitc::ENTER_SUBBLOCK:
904 // No known subblocks, always skip them.
905 Stream.ReadSubBlockID();
906 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000907 Error("malformed block record in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +0000908 return;
909 }
910 continue;
911
912 case llvm::bitc::DEFINE_ABBREV:
913 Stream.ReadAbbrevRecord();
914 continue;
915 default: break;
916 }
917
918 // Read a record.
919 Record.clear();
920 pch::PreprocessorRecordTypes RecType =
921 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
922 switch (RecType) {
Douglas Gregor37e26842009-04-21 23:56:24 +0000923 case pch::PP_MACRO_OBJECT_LIKE:
924 case pch::PP_MACRO_FUNCTION_LIKE: {
925 // If we already have a macro, that means that we've hit the end
926 // of the definition of the macro we were looking for. We're
927 // done.
928 if (Macro)
929 return;
930
931 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
932 if (II == 0) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000933 Error("macro must have a name in PCH file");
Douglas Gregor37e26842009-04-21 23:56:24 +0000934 return;
935 }
936 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
937 bool isUsed = Record[2];
938
939 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
940 MI->setIsUsed(isUsed);
941
942 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
943 // Decode function-like macro info.
944 bool isC99VarArgs = Record[3];
945 bool isGNUVarArgs = Record[4];
946 MacroArgs.clear();
947 unsigned NumArgs = Record[5];
948 for (unsigned i = 0; i != NumArgs; ++i)
949 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
950
951 // Install function-like macro info.
952 MI->setIsFunctionLike();
953 if (isC99VarArgs) MI->setIsC99Varargs();
954 if (isGNUVarArgs) MI->setIsGNUVarargs();
955 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
956 PP.getPreprocessorAllocator());
957 }
958
959 // Finally, install the macro.
960 PP.setMacroInfo(II, MI);
961
962 // Remember that we saw this macro last so that we add the tokens that
963 // form its body to it.
964 Macro = MI;
965 ++NumMacrosRead;
966 break;
967 }
968
969 case pch::PP_TOKEN: {
970 // If we see a TOKEN before a PP_MACRO_*, then the file is
971 // erroneous, just pretend we didn't see this.
972 if (Macro == 0) break;
973
974 Token Tok;
975 Tok.startToken();
976 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
977 Tok.setLength(Record[1]);
978 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
979 Tok.setIdentifierInfo(II);
980 Tok.setKind((tok::TokenKind)Record[3]);
981 Tok.setFlag((Token::TokenFlags)Record[4]);
982 Macro->AddTokenToBody(Tok);
983 break;
984 }
Steve Naroff83d63c72009-04-24 20:03:17 +0000985 }
Douglas Gregor37e26842009-04-21 23:56:24 +0000986 }
987}
988
Douglas Gregor668c1a42009-04-21 22:25:48 +0000989PCHReader::PCHReadResult
Douglas Gregor2eafc1b2009-04-26 00:07:37 +0000990PCHReader::ReadPCHBlock() {
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000991 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +0000992 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +0000993 return Failure;
994 }
Douglas Gregor2cf26342009-04-09 22:27:44 +0000995
996 // Read all of the records and blocks for the PCH file.
Douglas Gregor8038d512009-04-10 17:25:41 +0000997 RecordData Record;
Douglas Gregor2cf26342009-04-09 22:27:44 +0000998 while (!Stream.AtEndOfStream()) {
999 unsigned Code = Stream.ReadCode();
1000 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001001 if (Stream.ReadBlockEnd()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001002 Error("error at end of module block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001003 return Failure;
1004 }
Chris Lattner7356a312009-04-11 21:15:38 +00001005
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001006 return Success;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001007 }
1008
1009 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1010 switch (Stream.ReadSubBlockID()) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001011 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
1012 default: // Skip unknown content.
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001013 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001014 Error("malformed block record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001015 return Failure;
1016 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001017 break;
1018
Chris Lattner6367f6d2009-04-27 01:05:14 +00001019 case pch::DECLS_BLOCK_ID:
1020 // We lazily load the decls block, but we want to set up the
1021 // DeclsCursor cursor to point into it. Clone our current bitcode
1022 // cursor to it, enter the block and read the abbrevs in that block.
1023 // With the main cursor, we just skip over it.
1024 DeclsCursor = Stream;
1025 if (Stream.SkipBlock() || // Skip with the main cursor.
1026 // Read the abbrevs.
1027 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001028 Error("malformed block record in PCH file");
Chris Lattner6367f6d2009-04-27 01:05:14 +00001029 return Failure;
1030 }
1031 break;
1032
Chris Lattner7356a312009-04-11 21:15:38 +00001033 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner7356a312009-04-11 21:15:38 +00001034 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001035 Error("malformed block record in PCH file");
Chris Lattner7356a312009-04-11 21:15:38 +00001036 return Failure;
1037 }
1038 break;
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001039
Douglas Gregor14f79002009-04-10 03:52:48 +00001040 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001041 switch (ReadSourceManagerBlock()) {
1042 case Success:
1043 break;
1044
1045 case Failure:
Douglas Gregora02b1472009-04-28 21:53:25 +00001046 Error("malformed source manager block in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001047 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001048
1049 case IgnorePCH:
1050 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001051 }
Douglas Gregor14f79002009-04-10 03:52:48 +00001052 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001053 }
Douglas Gregor8038d512009-04-10 17:25:41 +00001054 continue;
1055 }
1056
1057 if (Code == llvm::bitc::DEFINE_ABBREV) {
1058 Stream.ReadAbbrevRecord();
1059 continue;
1060 }
1061
1062 // Read and process a record.
1063 Record.clear();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001064 const char *BlobStart = 0;
1065 unsigned BlobLen = 0;
1066 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
1067 &BlobStart, &BlobLen)) {
Douglas Gregor8038d512009-04-10 17:25:41 +00001068 default: // Default behavior: ignore.
1069 break;
1070
1071 case pch::TYPE_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001072 if (!TypesLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001073 Error("duplicate TYPE_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001074 return Failure;
1075 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001076 TypeOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001077 TypesLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001078 break;
1079
1080 case pch::DECL_OFFSET:
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001081 if (!DeclsLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001082 Error("duplicate DECL_OFFSET record in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001083 return Failure;
1084 }
Chris Lattnerc732f5a2009-04-27 18:24:17 +00001085 DeclOffsets = (const uint32_t *)BlobStart;
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001086 DeclsLoaded.resize(Record[0]);
Douglas Gregor8038d512009-04-10 17:25:41 +00001087 break;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001088
1089 case pch::LANGUAGE_OPTIONS:
1090 if (ParseLanguageOptions(Record))
1091 return IgnorePCH;
1092 break;
Douglas Gregor2bec0412009-04-10 21:16:55 +00001093
Douglas Gregorab41e632009-04-27 22:23:34 +00001094 case pch::METADATA: {
1095 if (Record[0] != pch::VERSION_MAJOR) {
1096 Diag(Record[0] < pch::VERSION_MAJOR? diag::warn_pch_version_too_old
1097 : diag::warn_pch_version_too_new);
1098 return IgnorePCH;
1099 }
1100
Douglas Gregor2bec0412009-04-10 21:16:55 +00001101 std::string TargetTriple(BlobStart, BlobLen);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001102 if (TargetTriple != PP.getTargetInfo().getTargetTriple()) {
Douglas Gregor2bec0412009-04-10 21:16:55 +00001103 Diag(diag::warn_pch_target_triple)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001104 << TargetTriple << PP.getTargetInfo().getTargetTriple();
Douglas Gregor2bec0412009-04-10 21:16:55 +00001105 Diag(diag::note_ignoring_pch) << FileName;
1106 return IgnorePCH;
1107 }
1108 break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001109 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001110
1111 case pch::IDENTIFIER_TABLE:
Douglas Gregor668c1a42009-04-21 22:25:48 +00001112 IdentifierTableData = BlobStart;
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001113 if (Record[0]) {
1114 IdentifierLookupTable
1115 = PCHIdentifierLookupTable::Create(
Douglas Gregor668c1a42009-04-21 22:25:48 +00001116 (const unsigned char *)IdentifierTableData + Record[0],
1117 (const unsigned char *)IdentifierTableData,
1118 PCHIdentifierLookupTrait(*this));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001119 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1120 }
Douglas Gregorafaf3082009-04-11 00:14:32 +00001121 break;
1122
1123 case pch::IDENTIFIER_OFFSET:
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001124 if (!IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001125 Error("duplicate IDENTIFIER_OFFSET record in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001126 return Failure;
1127 }
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001128 IdentifierOffsets = (const uint32_t *)BlobStart;
1129 IdentifiersLoaded.resize(Record[0]);
Douglas Gregor8c5a7602009-04-25 23:30:02 +00001130 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001131 break;
Douglas Gregorfdd01722009-04-14 00:24:19 +00001132
1133 case pch::EXTERNAL_DEFINITIONS:
1134 if (!ExternalDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001135 Error("duplicate EXTERNAL_DEFINITIONS record in PCH file");
Douglas Gregorfdd01722009-04-14 00:24:19 +00001136 return Failure;
1137 }
1138 ExternalDefinitions.swap(Record);
1139 break;
Douglas Gregor3e1af842009-04-17 22:13:46 +00001140
Douglas Gregorad1de002009-04-18 05:55:16 +00001141 case pch::SPECIAL_TYPES:
1142 SpecialTypes.swap(Record);
1143 break;
1144
Douglas Gregor3e1af842009-04-17 22:13:46 +00001145 case pch::STATISTICS:
1146 TotalNumStatements = Record[0];
Douglas Gregor37e26842009-04-21 23:56:24 +00001147 TotalNumMacros = Record[1];
Douglas Gregor25123082009-04-22 22:34:57 +00001148 TotalLexicalDeclContexts = Record[2];
1149 TotalVisibleDeclContexts = Record[3];
Douglas Gregor3e1af842009-04-17 22:13:46 +00001150 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001151
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001152 case pch::TENTATIVE_DEFINITIONS:
1153 if (!TentativeDefinitions.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001154 Error("duplicate TENTATIVE_DEFINITIONS record in PCH file");
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001155 return Failure;
1156 }
1157 TentativeDefinitions.swap(Record);
1158 break;
Douglas Gregor14c22f22009-04-22 22:18:58 +00001159
1160 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
1161 if (!LocallyScopedExternalDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001162 Error("duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
Douglas Gregor14c22f22009-04-22 22:18:58 +00001163 return Failure;
1164 }
1165 LocallyScopedExternalDecls.swap(Record);
1166 break;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001167
Douglas Gregor83941df2009-04-25 17:48:32 +00001168 case pch::SELECTOR_OFFSETS:
1169 SelectorOffsets = (const uint32_t *)BlobStart;
1170 TotalNumSelectors = Record[0];
1171 SelectorsLoaded.resize(TotalNumSelectors);
1172 break;
1173
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001174 case pch::METHOD_POOL:
Douglas Gregor83941df2009-04-25 17:48:32 +00001175 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
1176 if (Record[0])
1177 MethodPoolLookupTable
1178 = PCHMethodPoolLookupTable::Create(
1179 MethodPoolLookupTableData + Record[0],
1180 MethodPoolLookupTableData,
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001181 PCHMethodPoolLookupTrait(*this));
Douglas Gregor83941df2009-04-25 17:48:32 +00001182 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001183 break;
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001184
1185 case pch::PP_COUNTER_VALUE:
1186 if (!Record.empty())
1187 PP.setCounterValue(Record[0]);
1188 break;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001189
1190 case pch::SOURCE_LOCATION_OFFSETS:
Chris Lattner090d9b52009-04-27 19:01:47 +00001191 SLocOffsets = (const uint32_t *)BlobStart;
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001192 TotalNumSLocEntries = Record[0];
1193 PP.getSourceManager().PreallocateSLocEntries(this,
1194 TotalNumSLocEntries,
1195 Record[1]);
1196 break;
1197
1198 case pch::SOURCE_LOCATION_PRELOADS:
1199 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
1200 PCHReadResult Result = ReadSLocEntryRecord(Record[I]);
1201 if (Result != Success)
1202 return Result;
1203 }
1204 break;
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001205
1206 case pch::STAT_CACHE:
1207 PP.getFileManager().setStatCache(
1208 new PCHStatCache((const unsigned char *)BlobStart + Record[0],
1209 (const unsigned char *)BlobStart,
1210 NumStatHits, NumStatMisses));
1211 break;
Douglas Gregorb81c1702009-04-27 20:06:05 +00001212
1213 case pch::EXT_VECTOR_DECLS:
1214 if (!ExtVectorDecls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001215 Error("duplicate EXT_VECTOR_DECLS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001216 return Failure;
1217 }
1218 ExtVectorDecls.swap(Record);
1219 break;
1220
1221 case pch::OBJC_CATEGORY_IMPLEMENTATIONS:
1222 if (!ObjCCategoryImpls.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001223 Error("duplicate OBJC_CATEGORY_IMPLEMENTATIONS record in PCH file");
Douglas Gregorb81c1702009-04-27 20:06:05 +00001224 return Failure;
1225 }
1226 ObjCCategoryImpls.swap(Record);
1227 break;
Douglas Gregorafaf3082009-04-11 00:14:32 +00001228 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001229 }
Douglas Gregora02b1472009-04-28 21:53:25 +00001230 Error("premature end of bitstream in PCH file");
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001231 return Failure;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001232}
1233
Douglas Gregore1d918e2009-04-10 23:10:45 +00001234PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001235 // Set the PCH file name.
1236 this->FileName = FileName;
1237
Douglas Gregor2cf26342009-04-09 22:27:44 +00001238 // Open the PCH file.
1239 std::string ErrStr;
1240 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregore1d918e2009-04-10 23:10:45 +00001241 if (!Buffer) {
1242 Error(ErrStr.c_str());
1243 return IgnorePCH;
1244 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001245
1246 // Initialize the stream
Chris Lattnerb9fa9172009-04-26 20:59:20 +00001247 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
1248 (const unsigned char *)Buffer->getBufferEnd());
1249 Stream.init(StreamFile);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001250
1251 // Sniff for the signature.
1252 if (Stream.Read(8) != 'C' ||
1253 Stream.Read(8) != 'P' ||
1254 Stream.Read(8) != 'C' ||
Douglas Gregore1d918e2009-04-10 23:10:45 +00001255 Stream.Read(8) != 'H') {
Douglas Gregora02b1472009-04-28 21:53:25 +00001256 Diag(diag::err_not_a_pch_file) << FileName;
1257 return Failure;
Douglas Gregore1d918e2009-04-10 23:10:45 +00001258 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001259
Douglas Gregor2cf26342009-04-09 22:27:44 +00001260 while (!Stream.AtEndOfStream()) {
1261 unsigned Code = Stream.ReadCode();
1262
Douglas Gregore1d918e2009-04-10 23:10:45 +00001263 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001264 Error("invalid record at top-level of PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001265 return Failure;
1266 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001267
1268 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregor668c1a42009-04-21 22:25:48 +00001269
Douglas Gregor2cf26342009-04-09 22:27:44 +00001270 // We only know the PCH subblock ID.
1271 switch (BlockID) {
1272 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001273 if (Stream.ReadBlockInfoBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001274 Error("malformed BlockInfoBlock in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001275 return Failure;
1276 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001277 break;
1278 case pch::PCH_BLOCK_ID:
Douglas Gregor2eafc1b2009-04-26 00:07:37 +00001279 switch (ReadPCHBlock()) {
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001280 case Success:
1281 break;
1282
1283 case Failure:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001284 return Failure;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001285
1286 case IgnorePCH:
Douglas Gregor2bec0412009-04-10 21:16:55 +00001287 // FIXME: We could consider reading through to the end of this
1288 // PCH block, skipping subblocks, to see if there are other
1289 // PCH blocks elsewhere.
Douglas Gregor2bf1eb02009-04-27 21:28:04 +00001290
1291 // Clear out any preallocated source location entries, so that
1292 // the source manager does not try to resolve them later.
1293 PP.getSourceManager().ClearPreallocatedSLocEntries();
1294
1295 // Remove the stat cache.
1296 PP.getFileManager().setStatCache(0);
1297
Douglas Gregore1d918e2009-04-10 23:10:45 +00001298 return IgnorePCH;
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001299 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001300 break;
1301 default:
Douglas Gregore1d918e2009-04-10 23:10:45 +00001302 if (Stream.SkipBlock()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001303 Error("malformed block record in PCH file");
Douglas Gregore1d918e2009-04-10 23:10:45 +00001304 return Failure;
1305 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001306 break;
1307 }
1308 }
1309
1310 // Load the translation unit declaration
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001311 if (Context)
1312 ReadDeclRecord(DeclOffsets[0], 0);
Douglas Gregor92b059e2009-04-28 20:33:11 +00001313
1314 // Check the predefines buffer.
1315 if (CheckPredefinesBuffer(PCHPredefines, PCHPredefinesLen,
1316 PCHPredefinesBufferID))
1317 return IgnorePCH;
1318
Douglas Gregor668c1a42009-04-21 22:25:48 +00001319 // Initialization of builtins and library builtins occurs before the
1320 // PCH file is read, so there may be some identifiers that were
1321 // loaded into the IdentifierTable before we intercepted the
1322 // creation of identifiers. Iterate through the list of known
1323 // identifiers and determine whether we have to establish
1324 // preprocessor definitions or top-level identifier declaration
1325 // chains for those identifiers.
1326 //
1327 // We copy the IdentifierInfo pointers to a small vector first,
1328 // since de-serializing declarations or macro definitions can add
1329 // new entries into the identifier table, invalidating the
1330 // iterators.
1331 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
1332 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
1333 IdEnd = PP.getIdentifierTable().end();
1334 Id != IdEnd; ++Id)
1335 Identifiers.push_back(Id->second);
1336 PCHIdentifierLookupTable *IdTable
1337 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1338 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
1339 IdentifierInfo *II = Identifiers[I];
1340 // Look in the on-disk hash table for an entry for
1341 PCHIdentifierLookupTrait Info(*this, II);
1342 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
1343 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
1344 if (Pos == IdTable->end())
1345 continue;
1346
1347 // Dereferencing the iterator has the effect of populating the
1348 // IdentifierInfo node with the various declarations it needs.
1349 (void)*Pos;
1350 }
1351
Douglas Gregorad1de002009-04-18 05:55:16 +00001352 // Load the special types.
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001353 if (Context) {
1354 Context->setBuiltinVaListType(
1355 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
1356 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
1357 Context->setObjCIdType(GetType(Id));
1358 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
1359 Context->setObjCSelType(GetType(Sel));
1360 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
1361 Context->setObjCProtoType(GetType(Proto));
1362 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
1363 Context->setObjCClassType(GetType(Class));
1364 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
1365 Context->setCFConstantStringType(GetType(String));
1366 if (unsigned FastEnum
1367 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
1368 Context->setObjCFastEnumerationStateType(GetType(FastEnum));
1369 }
Douglas Gregor0b748912009-04-14 21:18:50 +00001370
Douglas Gregor668c1a42009-04-21 22:25:48 +00001371 return Success;
Douglas Gregor0b748912009-04-14 21:18:50 +00001372}
1373
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001374/// \brief Parse the record that corresponds to a LangOptions data
1375/// structure.
1376///
1377/// This routine compares the language options used to generate the
1378/// PCH file against the language options set for the current
1379/// compilation. For each option, we classify differences between the
1380/// two compiler states as either "benign" or "important". Benign
1381/// differences don't matter, and we accept them without complaint
1382/// (and without modifying the language options). Differences between
1383/// the states for important options cause the PCH file to be
1384/// unusable, so we emit a warning and return true to indicate that
1385/// there was an error.
1386///
1387/// \returns true if the PCH file is unacceptable, false otherwise.
1388bool PCHReader::ParseLanguageOptions(
1389 const llvm::SmallVectorImpl<uint64_t> &Record) {
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001390 const LangOptions &LangOpts = PP.getLangOptions();
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001391#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1392#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1393 if (Record[Idx] != LangOpts.Option) { \
1394 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1395 Diag(diag::note_ignoring_pch) << FileName; \
1396 return true; \
1397 } \
1398 ++Idx
1399
1400 unsigned Idx = 0;
1401 PARSE_LANGOPT_BENIGN(Trigraphs);
1402 PARSE_LANGOPT_BENIGN(BCPLComment);
1403 PARSE_LANGOPT_BENIGN(DollarIdents);
1404 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1405 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1406 PARSE_LANGOPT_BENIGN(ImplicitInt);
1407 PARSE_LANGOPT_BENIGN(Digraphs);
1408 PARSE_LANGOPT_BENIGN(HexFloats);
1409 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1410 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1411 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1412 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001413 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1414 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1415 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1416 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1417 PARSE_LANGOPT_BENIGN(PascalStrings);
Douglas Gregor0a0428e2009-04-10 20:39:37 +00001418 PARSE_LANGOPT_BENIGN(WritableStrings);
1419 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1420 diag::warn_pch_lax_vector_conversions);
1421 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1422 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1423 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1424 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1425 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1426 diag::warn_pch_thread_safe_statics);
1427 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1428 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1429 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1430 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1431 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1432 diag::warn_pch_heinous_extensions);
1433 // FIXME: Most of the options below are benign if the macro wasn't
1434 // used. Unfortunately, this means that a PCH compiled without
1435 // optimization can't be used with optimization turned on, even
1436 // though the only thing that changes is whether __OPTIMIZE__ was
1437 // defined... but if __OPTIMIZE__ never showed up in the header, it
1438 // doesn't matter. We could consider making this some special kind
1439 // of check.
1440 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1441 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1442 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1443 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1444 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1445 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1446 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1447 Diag(diag::warn_pch_gc_mode)
1448 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1449 Diag(diag::note_ignoring_pch) << FileName;
1450 return true;
1451 }
1452 ++Idx;
1453 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1454 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1455#undef PARSE_LANGOPT_IRRELEVANT
1456#undef PARSE_LANGOPT_BENIGN
1457
1458 return false;
1459}
1460
Douglas Gregor2cf26342009-04-09 22:27:44 +00001461/// \brief Read and return the type at the given offset.
1462///
1463/// This routine actually reads the record corresponding to the type
1464/// at the given offset in the bitstream. It is a helper routine for
1465/// GetType, which deals with reading type IDs.
1466QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregor0b748912009-04-14 21:18:50 +00001467 // Keep track of where we are in the stream, then jump back there
1468 // after reading this type.
1469 SavedStreamPosition SavedPosition(Stream);
1470
Douglas Gregor2cf26342009-04-09 22:27:44 +00001471 Stream.JumpToBit(Offset);
1472 RecordData Record;
1473 unsigned Code = Stream.ReadCode();
1474 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor6d473962009-04-15 22:00:08 +00001475 case pch::TYPE_EXT_QUAL: {
1476 assert(Record.size() == 3 &&
1477 "Incorrect encoding of extended qualifier type");
1478 QualType Base = GetType(Record[0]);
1479 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1480 unsigned AddressSpace = Record[2];
1481
1482 QualType T = Base;
1483 if (GCAttr != QualType::GCNone)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001484 T = Context->getObjCGCQualType(T, GCAttr);
Douglas Gregor6d473962009-04-15 22:00:08 +00001485 if (AddressSpace)
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001486 T = Context->getAddrSpaceQualType(T, AddressSpace);
Douglas Gregor6d473962009-04-15 22:00:08 +00001487 return T;
1488 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001489
Douglas Gregor2cf26342009-04-09 22:27:44 +00001490 case pch::TYPE_FIXED_WIDTH_INT: {
1491 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001492 return Context->getFixedWidthIntType(Record[0], Record[1]);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001493 }
1494
1495 case pch::TYPE_COMPLEX: {
1496 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1497 QualType ElemType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001498 return Context->getComplexType(ElemType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001499 }
1500
1501 case pch::TYPE_POINTER: {
1502 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1503 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001504 return Context->getPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001505 }
1506
1507 case pch::TYPE_BLOCK_POINTER: {
1508 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1509 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001510 return Context->getBlockPointerType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001511 }
1512
1513 case pch::TYPE_LVALUE_REFERENCE: {
1514 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1515 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001516 return Context->getLValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001517 }
1518
1519 case pch::TYPE_RVALUE_REFERENCE: {
1520 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1521 QualType PointeeType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001522 return Context->getRValueReferenceType(PointeeType);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001523 }
1524
1525 case pch::TYPE_MEMBER_POINTER: {
1526 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1527 QualType PointeeType = GetType(Record[0]);
1528 QualType ClassType = GetType(Record[1]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001529 return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
Douglas Gregor2cf26342009-04-09 22:27:44 +00001530 }
1531
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001532 case pch::TYPE_CONSTANT_ARRAY: {
1533 QualType ElementType = GetType(Record[0]);
1534 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1535 unsigned IndexTypeQuals = Record[2];
1536 unsigned Idx = 3;
1537 llvm::APInt Size = ReadAPInt(Record, Idx);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001538 return Context->getConstantArrayType(ElementType, Size, ASM,IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001539 }
1540
1541 case pch::TYPE_INCOMPLETE_ARRAY: {
1542 QualType ElementType = GetType(Record[0]);
1543 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1544 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001545 return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001546 }
1547
1548 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregor0b748912009-04-14 21:18:50 +00001549 QualType ElementType = GetType(Record[0]);
1550 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1551 unsigned IndexTypeQuals = Record[2];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001552 return Context->getVariableArrayType(ElementType, ReadTypeExpr(),
1553 ASM, IndexTypeQuals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001554 }
1555
1556 case pch::TYPE_VECTOR: {
1557 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001558 Error("incorrect encoding of vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001559 return QualType();
1560 }
1561
1562 QualType ElementType = GetType(Record[0]);
1563 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001564 return Context->getVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001565 }
1566
1567 case pch::TYPE_EXT_VECTOR: {
1568 if (Record.size() != 2) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001569 Error("incorrect encoding of extended vector type in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001570 return QualType();
1571 }
1572
1573 QualType ElementType = GetType(Record[0]);
1574 unsigned NumElements = Record[1];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001575 return Context->getExtVectorType(ElementType, NumElements);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001576 }
1577
1578 case pch::TYPE_FUNCTION_NO_PROTO: {
1579 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001580 Error("incorrect encoding of no-proto function type");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001581 return QualType();
1582 }
1583 QualType ResultType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001584 return Context->getFunctionNoProtoType(ResultType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001585 }
1586
1587 case pch::TYPE_FUNCTION_PROTO: {
1588 QualType ResultType = GetType(Record[0]);
1589 unsigned Idx = 1;
1590 unsigned NumParams = Record[Idx++];
1591 llvm::SmallVector<QualType, 16> ParamTypes;
1592 for (unsigned I = 0; I != NumParams; ++I)
1593 ParamTypes.push_back(GetType(Record[Idx++]));
1594 bool isVariadic = Record[Idx++];
1595 unsigned Quals = Record[Idx++];
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001596 return Context->getFunctionType(ResultType, &ParamTypes[0], NumParams,
1597 isVariadic, Quals);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001598 }
1599
1600 case pch::TYPE_TYPEDEF:
Douglas Gregora02b1472009-04-28 21:53:25 +00001601 assert(Record.size() == 1 && "incorrect encoding of typedef type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001602 return Context->getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001603
1604 case pch::TYPE_TYPEOF_EXPR:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001605 return Context->getTypeOfExprType(ReadTypeExpr());
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001606
1607 case pch::TYPE_TYPEOF: {
1608 if (Record.size() != 1) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001609 Error("incorrect encoding of typeof(type) in PCH file");
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001610 return QualType();
1611 }
1612 QualType UnderlyingType = GetType(Record[0]);
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001613 return Context->getTypeOfType(UnderlyingType);
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001614 }
1615
1616 case pch::TYPE_RECORD:
Douglas Gregora02b1472009-04-28 21:53:25 +00001617 assert(Record.size() == 1 && "incorrect encoding of record type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001618 return Context->getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001619
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001620 case pch::TYPE_ENUM:
Douglas Gregora02b1472009-04-28 21:53:25 +00001621 assert(Record.size() == 1 && "incorrect encoding of enum type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001622 return Context->getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00001623
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001624 case pch::TYPE_OBJC_INTERFACE:
Douglas Gregora02b1472009-04-28 21:53:25 +00001625 assert(Record.size() == 1 && "incorrect encoding of objc interface type");
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001626 return Context->getObjCInterfaceType(
Chris Lattner4dcf151a2009-04-22 05:57:30 +00001627 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001628
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001629 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1630 unsigned Idx = 0;
1631 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
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->getObjCQualifiedInterfaceType(ItfD, &Protos[0], NumProtos);
Chris Lattnerc6fa4452009-04-22 06:45:28 +00001637 }
Douglas Gregorb4e715b2009-04-13 20:46:52 +00001638
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001639 case pch::TYPE_OBJC_QUALIFIED_ID: {
1640 unsigned Idx = 0;
1641 unsigned NumProtos = Record[Idx++];
1642 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1643 for (unsigned I = 0; I != NumProtos; ++I)
1644 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001645 return Context->getObjCQualifiedIdType(&Protos[0], NumProtos);
Chris Lattnerd7a3fcd2009-04-22 06:40:03 +00001646 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001647 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001648 // Suppress a GCC warning
1649 return QualType();
1650}
1651
Douglas Gregor2cf26342009-04-09 22:27:44 +00001652
Douglas Gregor8038d512009-04-10 17:25:41 +00001653QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001654 unsigned Quals = ID & 0x07;
1655 unsigned Index = ID >> 3;
1656
1657 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1658 QualType T;
1659 switch ((pch::PredefinedTypeIDs)Index) {
1660 case pch::PREDEF_TYPE_NULL_ID: return QualType();
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001661 case pch::PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
1662 case pch::PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001663
1664 case pch::PREDEF_TYPE_CHAR_U_ID:
1665 case pch::PREDEF_TYPE_CHAR_S_ID:
1666 // FIXME: Check that the signedness of CharTy is correct!
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001667 T = Context->CharTy;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001668 break;
1669
Chris Lattnerd1d64a02009-04-27 21:45:14 +00001670 case pch::PREDEF_TYPE_UCHAR_ID: T = Context->UnsignedCharTy; break;
1671 case pch::PREDEF_TYPE_USHORT_ID: T = Context->UnsignedShortTy; break;
1672 case pch::PREDEF_TYPE_UINT_ID: T = Context->UnsignedIntTy; break;
1673 case pch::PREDEF_TYPE_ULONG_ID: T = Context->UnsignedLongTy; break;
1674 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context->UnsignedLongLongTy; break;
1675 case pch::PREDEF_TYPE_SCHAR_ID: T = Context->SignedCharTy; break;
1676 case pch::PREDEF_TYPE_WCHAR_ID: T = Context->WCharTy; break;
1677 case pch::PREDEF_TYPE_SHORT_ID: T = Context->ShortTy; break;
1678 case pch::PREDEF_TYPE_INT_ID: T = Context->IntTy; break;
1679 case pch::PREDEF_TYPE_LONG_ID: T = Context->LongTy; break;
1680 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context->LongLongTy; break;
1681 case pch::PREDEF_TYPE_FLOAT_ID: T = Context->FloatTy; break;
1682 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context->DoubleTy; break;
1683 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy; break;
1684 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context->OverloadTy; break;
1685 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context->DependentTy; break;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001686 }
1687
1688 assert(!T.isNull() && "Unknown predefined type");
1689 return T.getQualifiedType(Quals);
1690 }
1691
1692 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregor366809a2009-04-26 03:49:13 +00001693 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001694 if (!TypesLoaded[Index])
1695 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregor2cf26342009-04-09 22:27:44 +00001696
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001697 return QualType(TypesLoaded[Index], Quals);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001698}
1699
Douglas Gregor8038d512009-04-10 17:25:41 +00001700Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001701 if (ID == 0)
1702 return 0;
1703
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001704 if (ID > DeclsLoaded.size()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001705 Error("declaration ID out-of-range for PCH file");
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001706 return 0;
1707 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001708
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001709 unsigned Index = ID - 1;
1710 if (!DeclsLoaded[Index])
1711 ReadDeclRecord(DeclOffsets[Index], Index);
1712
1713 return DeclsLoaded[Index];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001714}
1715
Chris Lattner887e2b32009-04-27 05:46:25 +00001716/// \brief Resolve the offset of a statement into a statement.
1717///
1718/// This operation will read a new statement from the external
1719/// source each time it is called, and is meant to be used via a
1720/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1721Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattnerda930612009-04-27 05:58:23 +00001722 // Since we know tha this statement is part of a decl, make sure to use the
1723 // decl cursor to read it.
1724 DeclsCursor.JumpToBit(Offset);
1725 return ReadStmt(DeclsCursor);
Douglas Gregor250fc9c2009-04-18 00:07:54 +00001726}
1727
Douglas Gregor2cf26342009-04-09 22:27:44 +00001728bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregor8038d512009-04-10 17:25:41 +00001729 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001730 assert(DC->hasExternalLexicalStorage() &&
1731 "DeclContext has no lexical decls in storage");
1732 uint64_t Offset = DeclContextOffsets[DC].first;
1733 assert(Offset && "DeclContext has no lexical decls in storage");
1734
Douglas Gregor0b748912009-04-14 21:18:50 +00001735 // Keep track of where we are in the stream, then jump back there
1736 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001737 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001738
Douglas Gregor2cf26342009-04-09 22:27:44 +00001739 // Load the record containing all of the declarations lexically in
1740 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001741 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001742 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001743 unsigned Code = DeclsCursor.ReadCode();
1744 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001745 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001746 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1747
1748 // Load all of the declaration IDs
1749 Decls.clear();
1750 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregor25123082009-04-22 22:34:57 +00001751 ++NumLexicalDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001752 return false;
1753}
1754
1755bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001756 llvm::SmallVectorImpl<VisibleDeclaration> &Decls) {
Douglas Gregor2cf26342009-04-09 22:27:44 +00001757 assert(DC->hasExternalVisibleStorage() &&
1758 "DeclContext has no visible decls in storage");
1759 uint64_t Offset = DeclContextOffsets[DC].second;
1760 assert(Offset && "DeclContext has no visible decls in storage");
1761
Douglas Gregor0b748912009-04-14 21:18:50 +00001762 // Keep track of where we are in the stream, then jump back there
1763 // after reading this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001764 SavedStreamPosition SavedPosition(DeclsCursor);
Douglas Gregor0b748912009-04-14 21:18:50 +00001765
Douglas Gregor2cf26342009-04-09 22:27:44 +00001766 // Load the record containing all of the declarations visible in
1767 // this context.
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001768 DeclsCursor.JumpToBit(Offset);
Douglas Gregor2cf26342009-04-09 22:27:44 +00001769 RecordData Record;
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001770 unsigned Code = DeclsCursor.ReadCode();
1771 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor6a2bfb22009-04-15 18:43:11 +00001772 (void)RecCode;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001773 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1774 if (Record.size() == 0)
1775 return false;
1776
1777 Decls.clear();
1778
1779 unsigned Idx = 0;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001780 while (Idx < Record.size()) {
1781 Decls.push_back(VisibleDeclaration());
1782 Decls.back().Name = ReadDeclarationName(Record, Idx);
1783
Douglas Gregor2cf26342009-04-09 22:27:44 +00001784 unsigned Size = Record[Idx++];
Chris Lattnerc47be9e2009-04-27 07:35:40 +00001785 llvm::SmallVector<unsigned, 4> &LoadedDecls = Decls.back().Declarations;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001786 LoadedDecls.reserve(Size);
1787 for (unsigned I = 0; I < Size; ++I)
1788 LoadedDecls.push_back(Record[Idx++]);
1789 }
1790
Douglas Gregor25123082009-04-22 22:34:57 +00001791 ++NumVisibleDeclContextsRead;
Douglas Gregor2cf26342009-04-09 22:27:44 +00001792 return false;
1793}
1794
Douglas Gregorfdd01722009-04-14 00:24:19 +00001795void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor0af2ca42009-04-22 19:09:20 +00001796 this->Consumer = Consumer;
1797
Douglas Gregorfdd01722009-04-14 00:24:19 +00001798 if (!Consumer)
1799 return;
1800
1801 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1802 Decl *D = GetDecl(ExternalDefinitions[I]);
1803 DeclGroupRef DG(D);
1804 Consumer->HandleTopLevelDecl(DG);
1805 }
Douglas Gregorc62a2fe2009-04-25 00:41:30 +00001806
1807 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
1808 DeclGroupRef DG(InterestingDecls[I]);
1809 Consumer->HandleTopLevelDecl(DG);
1810 }
Douglas Gregorfdd01722009-04-14 00:24:19 +00001811}
1812
Douglas Gregor2cf26342009-04-09 22:27:44 +00001813void PCHReader::PrintStats() {
1814 std::fprintf(stderr, "*** PCH Statistics:\n");
1815
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001816 unsigned NumTypesLoaded
1817 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
1818 (Type *)0);
1819 unsigned NumDeclsLoaded
1820 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
1821 (Decl *)0);
1822 unsigned NumIdentifiersLoaded
1823 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
1824 IdentifiersLoaded.end(),
1825 (IdentifierInfo *)0);
1826 unsigned NumSelectorsLoaded
1827 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
1828 SelectorsLoaded.end(),
1829 Selector());
Douglas Gregor2d41cc12009-04-13 20:50:16 +00001830
Douglas Gregor4fed3f42009-04-27 18:38:38 +00001831 std::fprintf(stderr, " %u stat cache hits\n", NumStatHits);
1832 std::fprintf(stderr, " %u stat cache misses\n", NumStatMisses);
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001833 if (TotalNumSLocEntries)
1834 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
1835 NumSLocEntriesRead, TotalNumSLocEntries,
1836 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001837 if (!TypesLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001838 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001839 NumTypesLoaded, (unsigned)TypesLoaded.size(),
1840 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
1841 if (!DeclsLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001842 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor8f5dc7f2009-04-25 18:35:21 +00001843 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
1844 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001845 if (!IdentifiersLoaded.empty())
Douglas Gregor83941df2009-04-25 17:48:32 +00001846 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001847 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
1848 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor83941df2009-04-25 17:48:32 +00001849 if (TotalNumSelectors)
1850 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
1851 NumSelectorsLoaded, TotalNumSelectors,
1852 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
1853 if (TotalNumStatements)
1854 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
1855 NumStatementsRead, TotalNumStatements,
1856 ((float)NumStatementsRead/TotalNumStatements * 100));
1857 if (TotalNumMacros)
1858 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
1859 NumMacrosRead, TotalNumMacros,
1860 ((float)NumMacrosRead/TotalNumMacros * 100));
1861 if (TotalLexicalDeclContexts)
1862 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
1863 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
1864 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
1865 * 100));
1866 if (TotalVisibleDeclContexts)
1867 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
1868 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
1869 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
1870 * 100));
1871 if (TotalSelectorsInMethodPool) {
1872 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
1873 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
1874 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
1875 * 100));
1876 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
1877 }
Douglas Gregor2cf26342009-04-09 22:27:44 +00001878 std::fprintf(stderr, "\n");
1879}
1880
Douglas Gregor668c1a42009-04-21 22:25:48 +00001881void PCHReader::InitializeSema(Sema &S) {
1882 SemaObj = &S;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001883 S.ExternalSource = this;
1884
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001885 // Makes sure any declarations that were deserialized "too early"
1886 // still get added to the identifier's declaration chains.
1887 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
1888 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
1889 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregor668c1a42009-04-21 22:25:48 +00001890 }
Douglas Gregor6cfc1a82009-04-22 21:15:06 +00001891 PreloadedDecls.clear();
Douglas Gregor4c0e86b2009-04-22 22:02:47 +00001892
1893 // If there were any tentative definitions, deserialize them and add
1894 // them to Sema's table of tentative definitions.
1895 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
1896 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
1897 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
1898 }
Douglas Gregor14c22f22009-04-22 22:18:58 +00001899
1900 // If there were any locally-scoped external declarations,
1901 // deserialize them and add them to Sema's table of locally-scoped
1902 // external declarations.
1903 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
1904 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
1905 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
1906 }
Douglas Gregorb81c1702009-04-27 20:06:05 +00001907
1908 // If there were any ext_vector type declarations, deserialize them
1909 // and add them to Sema's vector of such declarations.
1910 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
1911 SemaObj->ExtVectorDecls.push_back(
1912 cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
1913
1914 // If there were any Objective-C category implementations,
1915 // deserialize them and add them to Sema's vector of such
1916 // definitions.
1917 for (unsigned I = 0, N = ObjCCategoryImpls.size(); I != N; ++I)
1918 SemaObj->ObjCCategoryImpls.push_back(
1919 cast<ObjCCategoryImplDecl>(GetDecl(ObjCCategoryImpls[I])));
Douglas Gregor668c1a42009-04-21 22:25:48 +00001920}
1921
1922IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
1923 // Try to find this name within our on-disk hash table
1924 PCHIdentifierLookupTable *IdTable
1925 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1926 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
1927 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
1928 if (Pos == IdTable->end())
1929 return 0;
1930
1931 // Dereferencing the iterator has the effect of building the
1932 // IdentifierInfo node and populating it with the various
1933 // declarations it needs.
1934 return *Pos;
1935}
1936
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001937std::pair<ObjCMethodList, ObjCMethodList>
1938PCHReader::ReadMethodPool(Selector Sel) {
1939 if (!MethodPoolLookupTable)
1940 return std::pair<ObjCMethodList, ObjCMethodList>();
1941
1942 // Try to find this selector within our on-disk hash table.
1943 PCHMethodPoolLookupTable *PoolTable
1944 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
1945 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor83941df2009-04-25 17:48:32 +00001946 if (Pos == PoolTable->end()) {
1947 ++NumMethodPoolMisses;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001948 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor83941df2009-04-25 17:48:32 +00001949 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001950
Douglas Gregor83941df2009-04-25 17:48:32 +00001951 ++NumMethodPoolSelectorsRead;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00001952 return *Pos;
1953}
1954
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001955void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregor668c1a42009-04-21 22:25:48 +00001956 assert(ID && "Non-zero identifier ID required");
Douglas Gregora02b1472009-04-28 21:53:25 +00001957 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001958 IdentifiersLoaded[ID - 1] = II;
Douglas Gregor668c1a42009-04-21 22:25:48 +00001959}
1960
Chris Lattner7356a312009-04-11 21:15:38 +00001961IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregorafaf3082009-04-11 00:14:32 +00001962 if (ID == 0)
1963 return 0;
Chris Lattner7356a312009-04-11 21:15:38 +00001964
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001965 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001966 Error("no identifier table in PCH file");
Douglas Gregorafaf3082009-04-11 00:14:32 +00001967 return 0;
1968 }
Chris Lattner7356a312009-04-11 21:15:38 +00001969
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001970 if (!IdentifiersLoaded[ID - 1]) {
1971 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor17e1c5e2009-04-25 21:21:38 +00001972 const char *Str = IdentifierTableData + Offset;
Douglas Gregord6595a42009-04-25 21:04:17 +00001973
Douglas Gregor02fc7512009-04-28 20:01:51 +00001974 // All of the strings in the PCH file are preceded by a 16-bit
1975 // length. Extract that 16-bit length to avoid having to execute
1976 // strlen().
1977 const char *StrLenPtr = Str - 2;
1978 unsigned StrLen = (((unsigned) StrLenPtr[0])
1979 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
1980 IdentifiersLoaded[ID - 1]
1981 = &PP.getIdentifierTable().get(Str, Str + StrLen);
Douglas Gregorafaf3082009-04-11 00:14:32 +00001982 }
Chris Lattner7356a312009-04-11 21:15:38 +00001983
Douglas Gregor2b3a5a82009-04-25 19:10:14 +00001984 return IdentifiersLoaded[ID - 1];
Douglas Gregor2cf26342009-04-09 22:27:44 +00001985}
1986
Douglas Gregor7f94b0b2009-04-27 06:38:32 +00001987void PCHReader::ReadSLocEntry(unsigned ID) {
1988 ReadSLocEntryRecord(ID);
1989}
1990
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001991Selector PCHReader::DecodeSelector(unsigned ID) {
1992 if (ID == 0)
1993 return Selector();
1994
Douglas Gregora02b1472009-04-28 21:53:25 +00001995 if (!MethodPoolLookupTableData)
Steve Naroff90cd1bb2009-04-23 10:39:46 +00001996 return Selector();
Douglas Gregor83941df2009-04-25 17:48:32 +00001997
1998 if (ID > TotalNumSelectors) {
Douglas Gregora02b1472009-04-28 21:53:25 +00001999 Error("selector ID out of range in PCH file");
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002000 return Selector();
2001 }
Douglas Gregor83941df2009-04-25 17:48:32 +00002002
2003 unsigned Index = ID - 1;
2004 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
2005 // Load this selector from the selector table.
2006 // FIXME: endianness portability issues with SelectorOffsets table
2007 PCHMethodPoolLookupTrait Trait(*this);
2008 SelectorsLoaded[Index]
2009 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
2010 }
2011
2012 return SelectorsLoaded[Index];
Steve Naroff90cd1bb2009-04-23 10:39:46 +00002013}
2014
Douglas Gregor2cf26342009-04-09 22:27:44 +00002015DeclarationName
2016PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
2017 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
2018 switch (Kind) {
2019 case DeclarationName::Identifier:
2020 return DeclarationName(GetIdentifierInfo(Record, Idx));
2021
2022 case DeclarationName::ObjCZeroArgSelector:
2023 case DeclarationName::ObjCOneArgSelector:
2024 case DeclarationName::ObjCMultiArgSelector:
Steve Naroffa7503a72009-04-23 15:15:40 +00002025 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregor2cf26342009-04-09 22:27:44 +00002026
2027 case DeclarationName::CXXConstructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002028 return Context->DeclarationNames.getCXXConstructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002029 GetType(Record[Idx++]));
2030
2031 case DeclarationName::CXXDestructorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002032 return Context->DeclarationNames.getCXXDestructorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002033 GetType(Record[Idx++]));
2034
2035 case DeclarationName::CXXConversionFunctionName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002036 return Context->DeclarationNames.getCXXConversionFunctionName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002037 GetType(Record[Idx++]));
2038
2039 case DeclarationName::CXXOperatorName:
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002040 return Context->DeclarationNames.getCXXOperatorName(
Douglas Gregor2cf26342009-04-09 22:27:44 +00002041 (OverloadedOperatorKind)Record[Idx++]);
2042
2043 case DeclarationName::CXXUsingDirective:
2044 return DeclarationName::getUsingDirectiveName();
2045 }
2046
2047 // Required to silence GCC warning
2048 return DeclarationName();
2049}
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002050
Douglas Gregor0a2b45e2009-04-13 18:14:40 +00002051/// \brief Read an integral value
2052llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
2053 unsigned BitWidth = Record[Idx++];
2054 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
2055 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
2056 Idx += NumWords;
2057 return Result;
2058}
2059
2060/// \brief Read a signed integral value
2061llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
2062 bool isUnsigned = Record[Idx++];
2063 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
2064}
2065
Douglas Gregor17fc2232009-04-14 21:55:33 +00002066/// \brief Read a floating-point value
2067llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregor17fc2232009-04-14 21:55:33 +00002068 return llvm::APFloat(ReadAPInt(Record, Idx));
2069}
2070
Douglas Gregor68a2eb02009-04-15 21:30:51 +00002071// \brief Read a string
2072std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
2073 unsigned Len = Record[Idx++];
2074 std::string Result(&Record[Idx], &Record[Idx] + Len);
2075 Idx += Len;
2076 return Result;
2077}
2078
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002079DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregore1d918e2009-04-10 23:10:45 +00002080 return Diag(SourceLocation(), DiagID);
2081}
2082
2083DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2084 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Chris Lattnerd1d64a02009-04-27 21:45:14 +00002085 PP.getSourceManager()),
Douglas Gregor0a0428e2009-04-10 20:39:37 +00002086 DiagID);
2087}
Douglas Gregor025452f2009-04-17 00:04:06 +00002088
Douglas Gregor668c1a42009-04-21 22:25:48 +00002089/// \brief Retrieve the identifier table associated with the
2090/// preprocessor.
2091IdentifierTable &PCHReader::getIdentifierTable() {
2092 return PP.getIdentifierTable();
2093}
2094
Douglas Gregor025452f2009-04-17 00:04:06 +00002095/// \brief Record that the given ID maps to the given switch-case
2096/// statement.
2097void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
2098 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
2099 SwitchCaseStmts[ID] = SC;
2100}
2101
2102/// \brief Retrieve the switch-case statement with the given ID.
2103SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
2104 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
2105 return SwitchCaseStmts[ID];
2106}
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002107
2108/// \brief Record that the given label statement has been
2109/// deserialized and has the given ID.
2110void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
2111 assert(LabelStmts.find(ID) == LabelStmts.end() &&
2112 "Deserialized label twice");
2113 LabelStmts[ID] = S;
2114
2115 // If we've already seen any goto statements that point to this
2116 // label, resolve them now.
2117 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
2118 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
2119 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
2120 Goto->second->setLabel(S);
2121 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002122
2123 // If we've already seen any address-label statements that point to
2124 // this label, resolve them now.
2125 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
2126 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
2127 = UnresolvedAddrLabelExprs.equal_range(ID);
2128 for (AddrLabelIter AddrLabel = AddrLabels.first;
2129 AddrLabel != AddrLabels.second; ++AddrLabel)
2130 AddrLabel->second->setLabel(S);
2131 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor1de05fe2009-04-17 18:18:49 +00002132}
2133
2134/// \brief Set the label of the given statement to the label
2135/// identified by ID.
2136///
2137/// Depending on the order in which the label and other statements
2138/// referencing that label occur, this operation may complete
2139/// immediately (updating the statement) or it may queue the
2140/// statement to be back-patched later.
2141void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
2142 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2143 if (Label != LabelStmts.end()) {
2144 // We've already seen this label, so set the label of the goto and
2145 // we're done.
2146 S->setLabel(Label->second);
2147 } else {
2148 // We haven't seen this label yet, so add this goto to the set of
2149 // unresolved goto statements.
2150 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
2151 }
2152}
Douglas Gregor7d5c2f22009-04-17 18:58:21 +00002153
2154/// \brief Set the label of the given expression to the label
2155/// identified by ID.
2156///
2157/// Depending on the order in which the label and other statements
2158/// referencing that label occur, this operation may complete
2159/// immediately (updating the statement) or it may queue the
2160/// statement to be back-patched later.
2161void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
2162 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
2163 if (Label != LabelStmts.end()) {
2164 // We've already seen this label, so set the label of the
2165 // label-address expression and we're done.
2166 S->setLabel(Label->second);
2167 } else {
2168 // We haven't seen this label yet, so add this label-address
2169 // expression to the set of unresolved label-address expressions.
2170 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
2171 }
2172}