blob: 4f60db9e685b284ba0eebf5d1ed9a17cc7debd3a [file] [log] [blame]
Douglas Gregorc34897d2009-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 Lattner09547942009-04-27 05:14:47 +000013
Douglas Gregorc34897d2009-04-09 22:27:44 +000014#include "clang/Frontend/PCHReader.h"
Douglas Gregor179cfb12009-04-10 20:39:37 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregorc713da92009-04-21 22:25:48 +000016#include "../Sema/Sema.h" // FIXME: move Sema headers elsewhere
Douglas Gregor631f6c62009-04-14 00:24:19 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000020#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000021#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000022#include "clang/Lex/Preprocessor.h"
Steve Naroffcda68f22009-04-24 20:03:17 +000023#include "clang/Lex/HeaderSearch.h"
Douglas Gregorc713da92009-04-21 22:25:48 +000024#include "clang/Basic/OnDiskHashTable.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000025#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000026#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000027#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000028#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-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>
33#include <cstdio>
Douglas Gregorc34897d2009-04-09 22:27:44 +000034using namespace clang;
35
Douglas Gregore0ad2dd2009-04-21 23:56:24 +000036namespace {
37 /// \brief Helper class that saves the current stream position and
38 /// then restores it when destroyed.
39 struct VISIBILITY_HIDDEN SavedStreamPosition {
Chris Lattner587788a2009-04-26 20:59:20 +000040 explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
41 : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +000042
43 ~SavedStreamPosition() {
Chris Lattner587788a2009-04-26 20:59:20 +000044 Cursor.JumpToBit(Offset);
Douglas Gregore0ad2dd2009-04-21 23:56:24 +000045 }
46
47 private:
Chris Lattner587788a2009-04-26 20:59:20 +000048 llvm::BitstreamCursor &Cursor;
Douglas Gregore0ad2dd2009-04-21 23:56:24 +000049 uint64_t Offset;
50 };
51}
52
Douglas Gregorc34897d2009-04-09 22:27:44 +000053//===----------------------------------------------------------------------===//
Douglas Gregorc713da92009-04-21 22:25:48 +000054// PCH reader implementation
55//===----------------------------------------------------------------------===//
56
Chris Lattner09547942009-04-27 05:14:47 +000057PCHReader::PCHReader(Preprocessor &PP, ASTContext &Context)
58 : SemaObj(0), PP(PP), Context(Context), Consumer(0),
59 IdentifierTableData(0), IdentifierLookupTable(0),
60 IdentifierOffsets(0),
61 MethodPoolLookupTable(0), MethodPoolLookupTableData(0),
62 TotalSelectorsInMethodPool(0), SelectorOffsets(0),
63 TotalNumSelectors(0), NumStatementsRead(0), NumMacrosRead(0),
64 NumMethodPoolSelectorsRead(0), NumMethodPoolMisses(0),
65 NumLexicalDeclContextsRead(0), NumVisibleDeclContextsRead(0) { }
66
67PCHReader::~PCHReader() {}
68
Chris Lattner3ef21962009-04-27 05:58:23 +000069Expr *PCHReader::ReadDeclExpr() {
70 return dyn_cast_or_null<Expr>(ReadStmt(DeclsCursor));
71}
72
73Expr *PCHReader::ReadTypeExpr() {
Chris Lattner3282c392009-04-27 05:41:06 +000074 return dyn_cast_or_null<Expr>(ReadStmt(Stream));
Chris Lattner09547942009-04-27 05:14:47 +000075}
76
77
Douglas Gregorc713da92009-04-21 22:25:48 +000078namespace {
Douglas Gregorc3221aa2009-04-24 21:10:55 +000079class VISIBILITY_HIDDEN PCHMethodPoolLookupTrait {
80 PCHReader &Reader;
81
82public:
83 typedef std::pair<ObjCMethodList, ObjCMethodList> data_type;
84
85 typedef Selector external_key_type;
86 typedef external_key_type internal_key_type;
87
88 explicit PCHMethodPoolLookupTrait(PCHReader &Reader) : Reader(Reader) { }
89
90 static bool EqualKey(const internal_key_type& a,
91 const internal_key_type& b) {
92 return a == b;
93 }
94
95 static unsigned ComputeHash(Selector Sel) {
96 unsigned N = Sel.getNumArgs();
97 if (N == 0)
98 ++N;
99 unsigned R = 5381;
100 for (unsigned I = 0; I != N; ++I)
101 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(I))
102 R = clang::BernsteinHashPartial(II->getName(), II->getLength(), R);
103 return R;
104 }
105
106 // This hopefully will just get inlined and removed by the optimizer.
107 static const internal_key_type&
108 GetInternalKey(const external_key_type& x) { return x; }
109
110 static std::pair<unsigned, unsigned>
111 ReadKeyDataLength(const unsigned char*& d) {
112 using namespace clang::io;
113 unsigned KeyLen = ReadUnalignedLE16(d);
114 unsigned DataLen = ReadUnalignedLE16(d);
115 return std::make_pair(KeyLen, DataLen);
116 }
117
Douglas Gregor2d711832009-04-25 17:48:32 +0000118 internal_key_type ReadKey(const unsigned char* d, unsigned) {
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000119 using namespace clang::io;
120 SelectorTable &SelTable = Reader.getContext().Selectors;
121 unsigned N = ReadUnalignedLE16(d);
122 IdentifierInfo *FirstII
123 = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
124 if (N == 0)
125 return SelTable.getNullarySelector(FirstII);
126 else if (N == 1)
127 return SelTable.getUnarySelector(FirstII);
128
129 llvm::SmallVector<IdentifierInfo *, 16> Args;
130 Args.push_back(FirstII);
131 for (unsigned I = 1; I != N; ++I)
132 Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
133
134 return SelTable.getSelector(N, &Args[0]);
135 }
136
137 data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
138 using namespace clang::io;
139 unsigned NumInstanceMethods = ReadUnalignedLE16(d);
140 unsigned NumFactoryMethods = ReadUnalignedLE16(d);
141
142 data_type Result;
143
144 // Load instance methods
145 ObjCMethodList *Prev = 0;
146 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
147 ObjCMethodDecl *Method
148 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
149 if (!Result.first.Method) {
150 // This is the first method, which is the easy case.
151 Result.first.Method = Method;
152 Prev = &Result.first;
153 continue;
154 }
155
156 Prev->Next = new ObjCMethodList(Method, 0);
157 Prev = Prev->Next;
158 }
159
160 // Load factory methods
161 Prev = 0;
162 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
163 ObjCMethodDecl *Method
164 = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
165 if (!Result.second.Method) {
166 // This is the first method, which is the easy case.
167 Result.second.Method = Method;
168 Prev = &Result.second;
169 continue;
170 }
171
172 Prev->Next = new ObjCMethodList(Method, 0);
173 Prev = Prev->Next;
174 }
175
176 return Result;
177 }
178};
179
180} // end anonymous namespace
181
182/// \brief The on-disk hash table used for the global method pool.
183typedef OnDiskChainedHashTable<PCHMethodPoolLookupTrait>
184 PCHMethodPoolLookupTable;
185
186namespace {
Douglas Gregorc713da92009-04-21 22:25:48 +0000187class VISIBILITY_HIDDEN PCHIdentifierLookupTrait {
188 PCHReader &Reader;
189
190 // If we know the IdentifierInfo in advance, it is here and we will
191 // not build a new one. Used when deserializing information about an
192 // identifier that was constructed before the PCH file was read.
193 IdentifierInfo *KnownII;
194
195public:
196 typedef IdentifierInfo * data_type;
197
198 typedef const std::pair<const char*, unsigned> external_key_type;
199
200 typedef external_key_type internal_key_type;
201
202 explicit PCHIdentifierLookupTrait(PCHReader &Reader, IdentifierInfo *II = 0)
203 : Reader(Reader), KnownII(II) { }
204
205 static bool EqualKey(const internal_key_type& a,
206 const internal_key_type& b) {
207 return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
208 : false;
209 }
210
211 static unsigned ComputeHash(const internal_key_type& a) {
212 return BernsteinHash(a.first, a.second);
213 }
214
215 // This hopefully will just get inlined and removed by the optimizer.
216 static const internal_key_type&
217 GetInternalKey(const external_key_type& x) { return x; }
218
219 static std::pair<unsigned, unsigned>
220 ReadKeyDataLength(const unsigned char*& d) {
221 using namespace clang::io;
Douglas Gregor4bb24882009-04-25 20:26:24 +0000222 unsigned DataLen = ReadUnalignedLE16(d);
Douglas Gregor85c4a872009-04-25 21:04:17 +0000223 unsigned KeyLen = ReadUnalignedLE16(d);
Douglas Gregorc713da92009-04-21 22:25:48 +0000224 return std::make_pair(KeyLen, DataLen);
225 }
226
227 static std::pair<const char*, unsigned>
228 ReadKey(const unsigned char* d, unsigned n) {
229 assert(n >= 2 && d[n-1] == '\0');
230 return std::make_pair((const char*) d, n-1);
231 }
232
233 IdentifierInfo *ReadData(const internal_key_type& k,
234 const unsigned char* d,
235 unsigned DataLen) {
236 using namespace clang::io;
Douglas Gregor2554cf22009-04-22 21:15:06 +0000237 uint32_t Bits = ReadUnalignedLE32(d);
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000238 bool CPlusPlusOperatorKeyword = Bits & 0x01;
239 Bits >>= 1;
240 bool Poisoned = Bits & 0x01;
241 Bits >>= 1;
242 bool ExtensionToken = Bits & 0x01;
243 Bits >>= 1;
244 bool hasMacroDefinition = Bits & 0x01;
245 Bits >>= 1;
246 unsigned ObjCOrBuiltinID = Bits & 0x3FF;
247 Bits >>= 10;
248 unsigned TokenID = Bits & 0xFF;
249 Bits >>= 8;
250
Douglas Gregorc713da92009-04-21 22:25:48 +0000251 pch::IdentID ID = ReadUnalignedLE32(d);
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000252 assert(Bits == 0 && "Extra bits in the identifier?");
Douglas Gregorc713da92009-04-21 22:25:48 +0000253 DataLen -= 8;
254
255 // Build the IdentifierInfo itself and link the identifier ID with
256 // the new IdentifierInfo.
257 IdentifierInfo *II = KnownII;
258 if (!II)
Douglas Gregor4bb24882009-04-25 20:26:24 +0000259 II = &Reader.getIdentifierTable().CreateIdentifierInfo(
260 k.first, k.first + k.second);
Douglas Gregorc713da92009-04-21 22:25:48 +0000261 Reader.SetIdentifierInfo(ID, II);
262
Douglas Gregorda38c6c2009-04-22 18:49:13 +0000263 // Set or check the various bits in the IdentifierInfo structure.
264 // FIXME: Load token IDs lazily, too?
265 assert((unsigned)II->getTokenID() == TokenID &&
266 "Incorrect token ID loaded");
267 (void)TokenID;
268 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
269 assert(II->isExtensionToken() == ExtensionToken &&
270 "Incorrect extension token flag");
271 (void)ExtensionToken;
272 II->setIsPoisoned(Poisoned);
273 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
274 "Incorrect C++ operator keyword flag");
275 (void)CPlusPlusOperatorKeyword;
276
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000277 // If this identifier is a macro, deserialize the macro
278 // definition.
279 if (hasMacroDefinition) {
280 uint32_t Offset = ReadUnalignedLE64(d);
281 Reader.ReadMacroRecord(Offset);
282 DataLen -= 8;
283 }
Douglas Gregorc713da92009-04-21 22:25:48 +0000284
285 // Read all of the declarations visible at global scope with this
286 // name.
287 Sema *SemaObj = Reader.getSema();
288 while (DataLen > 0) {
289 NamedDecl *D = cast<NamedDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
Douglas Gregorc713da92009-04-21 22:25:48 +0000290 if (SemaObj) {
291 // Introduce this declaration into the translation-unit scope
292 // and add it to the declaration chain for this identifier, so
293 // that (unqualified) name lookup will find it.
294 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(D));
295 SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
296 } else {
297 // Queue this declaration so that it will be added to the
298 // translation unit scope and identifier's declaration chain
299 // once a Sema object is known.
Douglas Gregor2554cf22009-04-22 21:15:06 +0000300 Reader.PreloadedDecls.push_back(D);
Douglas Gregorc713da92009-04-21 22:25:48 +0000301 }
302
303 DataLen -= 4;
304 }
305 return II;
306 }
307};
308
309} // end anonymous namespace
310
311/// \brief The on-disk hash table used to contain information about
312/// all of the identifiers in the program.
313typedef OnDiskChainedHashTable<PCHIdentifierLookupTrait>
314 PCHIdentifierLookupTable;
315
Douglas Gregorc34897d2009-04-09 22:27:44 +0000316// FIXME: use the diagnostics machinery
317static bool Error(const char *Str) {
318 std::fprintf(stderr, "%s\n", Str);
319 return true;
320}
321
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000322/// \brief Check the contents of the predefines buffer against the
323/// contents of the predefines buffer used to build the PCH file.
324///
325/// The contents of the two predefines buffers should be the same. If
326/// not, then some command-line option changed the preprocessor state
327/// and we must reject the PCH file.
328///
329/// \param PCHPredef The start of the predefines buffer in the PCH
330/// file.
331///
332/// \param PCHPredefLen The length of the predefines buffer in the PCH
333/// file.
334///
335/// \param PCHBufferID The FileID for the PCH predefines buffer.
336///
337/// \returns true if there was a mismatch (in which case the PCH file
338/// should be ignored), or false otherwise.
339bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
340 unsigned PCHPredefLen,
341 FileID PCHBufferID) {
342 const char *Predef = PP.getPredefines().c_str();
343 unsigned PredefLen = PP.getPredefines().size();
344
345 // If the two predefines buffers compare equal, we're done!.
346 if (PredefLen == PCHPredefLen &&
347 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
348 return false;
349
350 // The predefines buffers are different. Produce a reasonable
351 // diagnostic showing where they are different.
352
353 // The source locations (potentially in the two different predefines
354 // buffers)
355 SourceLocation Loc1, Loc2;
356 SourceManager &SourceMgr = PP.getSourceManager();
357
358 // Create a source buffer for our predefines string, so
359 // that we can build a diagnostic that points into that
360 // source buffer.
361 FileID BufferID;
362 if (Predef && Predef[0]) {
363 llvm::MemoryBuffer *Buffer
364 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
365 "<built-in>");
366 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
367 }
368
369 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
370 std::pair<const char *, const char *> Locations
371 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
372
373 if (Locations.first != Predef + MinLen) {
374 // We found the location in the two buffers where there is a
375 // difference. Form source locations to point there (in both
376 // buffers).
377 unsigned Offset = Locations.first - Predef;
378 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
379 .getFileLocWithOffset(Offset);
380 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
381 .getFileLocWithOffset(Offset);
382 } else if (PredefLen > PCHPredefLen) {
383 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
384 .getFileLocWithOffset(MinLen);
385 } else {
386 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
387 .getFileLocWithOffset(MinLen);
388 }
389
390 Diag(Loc1, diag::warn_pch_preprocessor);
391 if (Loc2.isValid())
392 Diag(Loc2, diag::note_predef_in_pch);
393 Diag(diag::note_ignoring_pch) << FileName;
394 return true;
395}
396
Douglas Gregor635f97f2009-04-13 16:31:14 +0000397/// \brief Read the line table in the source manager block.
398/// \returns true if ther was an error.
399static bool ParseLineTable(SourceManager &SourceMgr,
400 llvm::SmallVectorImpl<uint64_t> &Record) {
401 unsigned Idx = 0;
402 LineTableInfo &LineTable = SourceMgr.getLineTable();
403
404 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000405 std::map<int, int> FileIDs;
406 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000407 // Extract the file name
408 unsigned FilenameLen = Record[Idx++];
409 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
410 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000411 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
412 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000413 }
414
415 // Parse the line entries
416 std::vector<LineEntry> Entries;
417 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000418 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000419
420 // Extract the line entries
421 unsigned NumEntries = Record[Idx++];
422 Entries.clear();
423 Entries.reserve(NumEntries);
424 for (unsigned I = 0; I != NumEntries; ++I) {
425 unsigned FileOffset = Record[Idx++];
426 unsigned LineNo = Record[Idx++];
427 int FilenameID = Record[Idx++];
428 SrcMgr::CharacteristicKind FileKind
429 = (SrcMgr::CharacteristicKind)Record[Idx++];
430 unsigned IncludeOffset = Record[Idx++];
431 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
432 FileKind, IncludeOffset));
433 }
434 LineTable.AddEntry(FID, Entries);
435 }
436
437 return false;
438}
439
Douglas Gregorab1cef72009-04-10 03:52:48 +0000440/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000441PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000442 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000443 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
444 Error("Malformed source manager block record");
445 return Failure;
446 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000447
448 SourceManager &SourceMgr = Context.getSourceManager();
449 RecordData Record;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000450 unsigned NumHeaderInfos = 0;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000451 while (true) {
452 unsigned Code = Stream.ReadCode();
453 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000454 if (Stream.ReadBlockEnd()) {
455 Error("Error at end of Source Manager block");
456 return Failure;
457 }
458
459 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000460 }
461
462 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
463 // No known subblocks, always skip them.
464 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000465 if (Stream.SkipBlock()) {
466 Error("Malformed block record");
467 return Failure;
468 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000469 continue;
470 }
471
472 if (Code == llvm::bitc::DEFINE_ABBREV) {
473 Stream.ReadAbbrevRecord();
474 continue;
475 }
476
477 // Read a record.
478 const char *BlobStart;
479 unsigned BlobLen;
480 Record.clear();
481 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
482 default: // Default behavior: ignore.
483 break;
484
485 case pch::SM_SLOC_FILE_ENTRY: {
486 // FIXME: We would really like to delay the creation of this
487 // FileEntry until it is actually required, e.g., when producing
488 // a diagnostic with a source location in this file.
489 const FileEntry *File
490 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
491 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000492 FileID ID = SourceMgr.createFileID(File,
493 SourceLocation::getFromRawEncoding(Record[1]),
494 (CharacteristicKind)Record[2]);
495 if (Record[3])
496 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
497 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000498 break;
499 }
500
501 case pch::SM_SLOC_BUFFER_ENTRY: {
502 const char *Name = BlobStart;
503 unsigned Code = Stream.ReadCode();
504 Record.clear();
505 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
506 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000507 (void)RecCode;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000508 llvm::MemoryBuffer *Buffer
509 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
510 BlobStart + BlobLen - 1,
511 Name);
512 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
513
514 if (strcmp(Name, "<built-in>") == 0
515 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
516 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000517 break;
518 }
519
520 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
521 SourceLocation SpellingLoc
522 = SourceLocation::getFromRawEncoding(Record[1]);
523 SourceMgr.createInstantiationLoc(
524 SpellingLoc,
525 SourceLocation::getFromRawEncoding(Record[2]),
526 SourceLocation::getFromRawEncoding(Record[3]),
Douglas Gregor364e5802009-04-15 18:05:10 +0000527 Record[4]);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000528 break;
529 }
530
Chris Lattnere1be6022009-04-14 23:22:57 +0000531 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000532 if (ParseLineTable(SourceMgr, Record))
533 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000534 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000535
536 case pch::SM_HEADER_FILE_INFO: {
537 HeaderFileInfo HFI;
538 HFI.isImport = Record[0];
539 HFI.DirInfo = Record[1];
540 HFI.NumIncludes = Record[2];
541 HFI.ControllingMacroID = Record[3];
542 PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
543 break;
544 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000545 }
546 }
547}
548
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000549/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
550/// specified cursor. Read the abbreviations that are at the top of the block
551/// and then leave the cursor pointing into the block.
552bool PCHReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
553 unsigned BlockID) {
554 if (Cursor.EnterSubBlock(BlockID)) {
555 Error("Malformed block record");
556 return Failure;
557 }
558
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000559 while (true) {
560 unsigned Code = Cursor.ReadCode();
561
562 // We expect all abbrevs to be at the start of the block.
563 if (Code != llvm::bitc::DEFINE_ABBREV)
564 return false;
565 Cursor.ReadAbbrevRecord();
566 }
567}
568
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000569void PCHReader::ReadMacroRecord(uint64_t Offset) {
570 // Keep track of where we are in the stream, then jump back there
571 // after reading this macro.
572 SavedStreamPosition SavedPosition(Stream);
573
574 Stream.JumpToBit(Offset);
575 RecordData Record;
576 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
577 MacroInfo *Macro = 0;
Steve Naroffcda68f22009-04-24 20:03:17 +0000578
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000579 while (true) {
580 unsigned Code = Stream.ReadCode();
581 switch (Code) {
582 case llvm::bitc::END_BLOCK:
583 return;
584
585 case llvm::bitc::ENTER_SUBBLOCK:
586 // No known subblocks, always skip them.
587 Stream.ReadSubBlockID();
588 if (Stream.SkipBlock()) {
589 Error("Malformed block record");
590 return;
591 }
592 continue;
593
594 case llvm::bitc::DEFINE_ABBREV:
595 Stream.ReadAbbrevRecord();
596 continue;
597 default: break;
598 }
599
600 // Read a record.
601 Record.clear();
602 pch::PreprocessorRecordTypes RecType =
603 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
604 switch (RecType) {
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000605 case pch::PP_MACRO_OBJECT_LIKE:
606 case pch::PP_MACRO_FUNCTION_LIKE: {
607 // If we already have a macro, that means that we've hit the end
608 // of the definition of the macro we were looking for. We're
609 // done.
610 if (Macro)
611 return;
612
613 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
614 if (II == 0) {
615 Error("Macro must have a name");
616 return;
617 }
618 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
619 bool isUsed = Record[2];
620
621 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
622 MI->setIsUsed(isUsed);
623
624 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
625 // Decode function-like macro info.
626 bool isC99VarArgs = Record[3];
627 bool isGNUVarArgs = Record[4];
628 MacroArgs.clear();
629 unsigned NumArgs = Record[5];
630 for (unsigned i = 0; i != NumArgs; ++i)
631 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
632
633 // Install function-like macro info.
634 MI->setIsFunctionLike();
635 if (isC99VarArgs) MI->setIsC99Varargs();
636 if (isGNUVarArgs) MI->setIsGNUVarargs();
637 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
638 PP.getPreprocessorAllocator());
639 }
640
641 // Finally, install the macro.
642 PP.setMacroInfo(II, MI);
643
644 // Remember that we saw this macro last so that we add the tokens that
645 // form its body to it.
646 Macro = MI;
647 ++NumMacrosRead;
648 break;
649 }
650
651 case pch::PP_TOKEN: {
652 // If we see a TOKEN before a PP_MACRO_*, then the file is
653 // erroneous, just pretend we didn't see this.
654 if (Macro == 0) break;
655
656 Token Tok;
657 Tok.startToken();
658 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
659 Tok.setLength(Record[1]);
660 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
661 Tok.setIdentifierInfo(II);
662 Tok.setKind((tok::TokenKind)Record[3]);
663 Tok.setFlag((Token::TokenFlags)Record[4]);
664 Macro->AddTokenToBody(Tok);
665 break;
666 }
Steve Naroffcda68f22009-04-24 20:03:17 +0000667 }
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000668 }
669}
670
Douglas Gregorc713da92009-04-21 22:25:48 +0000671PCHReader::PCHReadResult
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000672PCHReader::ReadPCHBlock() {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000673 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
674 Error("Malformed block record");
675 return Failure;
676 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000677
678 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000679 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000680 while (!Stream.AtEndOfStream()) {
681 unsigned Code = Stream.ReadCode();
682 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000683 if (Stream.ReadBlockEnd()) {
684 Error("Error at end of module block");
685 return Failure;
686 }
Chris Lattner29241862009-04-11 21:15:38 +0000687
Douglas Gregor179cfb12009-04-10 20:39:37 +0000688 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000689 }
690
691 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
692 switch (Stream.ReadSubBlockID()) {
Douglas Gregorc34897d2009-04-09 22:27:44 +0000693 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
694 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000695 if (Stream.SkipBlock()) {
696 Error("Malformed block record");
697 return Failure;
698 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000699 break;
700
Chris Lattner4fc71eb2009-04-27 01:05:14 +0000701 case pch::DECLS_BLOCK_ID:
702 // We lazily load the decls block, but we want to set up the
703 // DeclsCursor cursor to point into it. Clone our current bitcode
704 // cursor to it, enter the block and read the abbrevs in that block.
705 // With the main cursor, we just skip over it.
706 DeclsCursor = Stream;
707 if (Stream.SkipBlock() || // Skip with the main cursor.
708 // Read the abbrevs.
709 ReadBlockAbbrevs(DeclsCursor, pch::DECLS_BLOCK_ID)) {
710 Error("Malformed block record");
711 return Failure;
712 }
713 break;
714
Chris Lattner29241862009-04-11 21:15:38 +0000715 case pch::PREPROCESSOR_BLOCK_ID:
Chris Lattner29241862009-04-11 21:15:38 +0000716 if (Stream.SkipBlock()) {
717 Error("Malformed block record");
718 return Failure;
719 }
720 break;
Steve Naroff9e84d782009-04-23 10:39:46 +0000721
Douglas Gregorab1cef72009-04-10 03:52:48 +0000722 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000723 switch (ReadSourceManagerBlock()) {
724 case Success:
725 break;
726
727 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000728 Error("Malformed source manager block");
729 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000730
731 case IgnorePCH:
732 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000733 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000734 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000735 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000736 continue;
737 }
738
739 if (Code == llvm::bitc::DEFINE_ABBREV) {
740 Stream.ReadAbbrevRecord();
741 continue;
742 }
743
744 // Read and process a record.
745 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000746 const char *BlobStart = 0;
747 unsigned BlobLen = 0;
748 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
749 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000750 default: // Default behavior: ignore.
751 break;
752
753 case pch::TYPE_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +0000754 if (!TypesLoaded.empty()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000755 Error("Duplicate TYPE_OFFSET record in PCH file");
756 return Failure;
757 }
Douglas Gregor24a224c2009-04-25 18:35:21 +0000758 TypeOffsets = (const uint64_t *)BlobStart;
759 TypesLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +0000760 break;
761
762 case pch::DECL_OFFSET:
Douglas Gregor24a224c2009-04-25 18:35:21 +0000763 if (!DeclsLoaded.empty()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000764 Error("Duplicate DECL_OFFSET record in PCH file");
765 return Failure;
766 }
Douglas Gregor24a224c2009-04-25 18:35:21 +0000767 DeclOffsets = (const uint64_t *)BlobStart;
768 DeclsLoaded.resize(Record[0]);
Douglas Gregorac8f2802009-04-10 17:25:41 +0000769 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000770
771 case pch::LANGUAGE_OPTIONS:
772 if (ParseLanguageOptions(Record))
773 return IgnorePCH;
774 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000775
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000776 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000777 std::string TargetTriple(BlobStart, BlobLen);
778 if (TargetTriple != Context.Target.getTargetTriple()) {
779 Diag(diag::warn_pch_target_triple)
780 << TargetTriple << Context.Target.getTargetTriple();
781 Diag(diag::note_ignoring_pch) << FileName;
782 return IgnorePCH;
783 }
784 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000785 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000786
787 case pch::IDENTIFIER_TABLE:
Douglas Gregorc713da92009-04-21 22:25:48 +0000788 IdentifierTableData = BlobStart;
Douglas Gregorde44c9f2009-04-25 19:10:14 +0000789 if (Record[0]) {
790 IdentifierLookupTable
791 = PCHIdentifierLookupTable::Create(
Douglas Gregorc713da92009-04-21 22:25:48 +0000792 (const unsigned char *)IdentifierTableData + Record[0],
793 (const unsigned char *)IdentifierTableData,
794 PCHIdentifierLookupTrait(*this));
Douglas Gregorde44c9f2009-04-25 19:10:14 +0000795 PP.getIdentifierTable().setExternalIdentifierLookup(this);
796 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000797 break;
798
799 case pch::IDENTIFIER_OFFSET:
Douglas Gregorde44c9f2009-04-25 19:10:14 +0000800 if (!IdentifiersLoaded.empty()) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000801 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
802 return Failure;
803 }
Douglas Gregorde44c9f2009-04-25 19:10:14 +0000804 IdentifierOffsets = (const uint32_t *)BlobStart;
805 IdentifiersLoaded.resize(Record[0]);
Douglas Gregoreccb51d2009-04-25 23:30:02 +0000806 PP.getHeaderSearchInfo().SetExternalLookup(this);
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000807 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000808
809 case pch::EXTERNAL_DEFINITIONS:
810 if (!ExternalDefinitions.empty()) {
811 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
812 return Failure;
813 }
814 ExternalDefinitions.swap(Record);
815 break;
Douglas Gregor456e0952009-04-17 22:13:46 +0000816
Douglas Gregore01ad442009-04-18 05:55:16 +0000817 case pch::SPECIAL_TYPES:
818 SpecialTypes.swap(Record);
819 break;
820
Douglas Gregor456e0952009-04-17 22:13:46 +0000821 case pch::STATISTICS:
822 TotalNumStatements = Record[0];
Douglas Gregore0ad2dd2009-04-21 23:56:24 +0000823 TotalNumMacros = Record[1];
Douglas Gregoraf136d92009-04-22 22:34:57 +0000824 TotalLexicalDeclContexts = Record[2];
825 TotalVisibleDeclContexts = Record[3];
Douglas Gregor456e0952009-04-17 22:13:46 +0000826 break;
Douglas Gregor77b2cd52009-04-22 22:02:47 +0000827 case pch::TENTATIVE_DEFINITIONS:
828 if (!TentativeDefinitions.empty()) {
829 Error("Duplicate TENTATIVE_DEFINITIONS record in PCH file");
830 return Failure;
831 }
832 TentativeDefinitions.swap(Record);
833 break;
Douglas Gregor062d9482009-04-22 22:18:58 +0000834
835 case pch::LOCALLY_SCOPED_EXTERNAL_DECLS:
836 if (!LocallyScopedExternalDecls.empty()) {
837 Error("Duplicate LOCALLY_SCOPED_EXTERNAL_DECLS record in PCH file");
838 return Failure;
839 }
840 LocallyScopedExternalDecls.swap(Record);
841 break;
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000842
Douglas Gregor2d711832009-04-25 17:48:32 +0000843 case pch::SELECTOR_OFFSETS:
844 SelectorOffsets = (const uint32_t *)BlobStart;
845 TotalNumSelectors = Record[0];
846 SelectorsLoaded.resize(TotalNumSelectors);
847 break;
848
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000849 case pch::METHOD_POOL:
Douglas Gregor2d711832009-04-25 17:48:32 +0000850 MethodPoolLookupTableData = (const unsigned char *)BlobStart;
851 if (Record[0])
852 MethodPoolLookupTable
853 = PCHMethodPoolLookupTable::Create(
854 MethodPoolLookupTableData + Record[0],
855 MethodPoolLookupTableData,
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000856 PCHMethodPoolLookupTrait(*this));
Douglas Gregor2d711832009-04-25 17:48:32 +0000857 TotalSelectorsInMethodPool = Record[1];
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000858 break;
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000859
860 case pch::PP_COUNTER_VALUE:
861 if (!Record.empty())
862 PP.setCounterValue(Record[0]);
863 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000864 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000865 }
Douglas Gregor179cfb12009-04-10 20:39:37 +0000866 Error("Premature end of bitstream");
867 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000868}
869
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000870PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000871 // Set the PCH file name.
872 this->FileName = FileName;
873
Douglas Gregorc34897d2009-04-09 22:27:44 +0000874 // Open the PCH file.
875 std::string ErrStr;
876 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000877 if (!Buffer) {
878 Error(ErrStr.c_str());
879 return IgnorePCH;
880 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000881
882 // Initialize the stream
Chris Lattner587788a2009-04-26 20:59:20 +0000883 StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
884 (const unsigned char *)Buffer->getBufferEnd());
885 Stream.init(StreamFile);
Douglas Gregorc34897d2009-04-09 22:27:44 +0000886
887 // Sniff for the signature.
888 if (Stream.Read(8) != 'C' ||
889 Stream.Read(8) != 'P' ||
890 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000891 Stream.Read(8) != 'H') {
892 Error("Not a PCH file");
893 return IgnorePCH;
894 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000895
Douglas Gregorc34897d2009-04-09 22:27:44 +0000896 while (!Stream.AtEndOfStream()) {
897 unsigned Code = Stream.ReadCode();
898
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000899 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
900 Error("Invalid record at top-level");
901 return Failure;
902 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000903
904 unsigned BlockID = Stream.ReadSubBlockID();
Douglas Gregorc713da92009-04-21 22:25:48 +0000905
Douglas Gregorc34897d2009-04-09 22:27:44 +0000906 // We only know the PCH subblock ID.
907 switch (BlockID) {
908 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000909 if (Stream.ReadBlockInfoBlock()) {
910 Error("Malformed BlockInfoBlock");
911 return Failure;
912 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000913 break;
914 case pch::PCH_BLOCK_ID:
Douglas Gregorf6e1fb22009-04-26 00:07:37 +0000915 switch (ReadPCHBlock()) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000916 case Success:
917 break;
918
919 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000920 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000921
922 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000923 // FIXME: We could consider reading through to the end of this
924 // PCH block, skipping subblocks, to see if there are other
925 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000926 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000927 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000928 break;
929 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000930 if (Stream.SkipBlock()) {
931 Error("Malformed block record");
932 return Failure;
933 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000934 break;
935 }
936 }
937
938 // Load the translation unit declaration
939 ReadDeclRecord(DeclOffsets[0], 0);
940
Douglas Gregorc713da92009-04-21 22:25:48 +0000941 // Initialization of builtins and library builtins occurs before the
942 // PCH file is read, so there may be some identifiers that were
943 // loaded into the IdentifierTable before we intercepted the
944 // creation of identifiers. Iterate through the list of known
945 // identifiers and determine whether we have to establish
946 // preprocessor definitions or top-level identifier declaration
947 // chains for those identifiers.
948 //
949 // We copy the IdentifierInfo pointers to a small vector first,
950 // since de-serializing declarations or macro definitions can add
951 // new entries into the identifier table, invalidating the
952 // iterators.
953 llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
954 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
955 IdEnd = PP.getIdentifierTable().end();
956 Id != IdEnd; ++Id)
957 Identifiers.push_back(Id->second);
958 PCHIdentifierLookupTable *IdTable
959 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
960 for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
961 IdentifierInfo *II = Identifiers[I];
962 // Look in the on-disk hash table for an entry for
963 PCHIdentifierLookupTrait Info(*this, II);
964 std::pair<const char*, unsigned> Key(II->getName(), II->getLength());
965 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
966 if (Pos == IdTable->end())
967 continue;
968
969 // Dereferencing the iterator has the effect of populating the
970 // IdentifierInfo node with the various declarations it needs.
971 (void)*Pos;
972 }
973
Douglas Gregore01ad442009-04-18 05:55:16 +0000974 // Load the special types.
975 Context.setBuiltinVaListType(
976 GetType(SpecialTypes[pch::SPECIAL_TYPE_BUILTIN_VA_LIST]));
Douglas Gregorbb21d4b2009-04-23 22:29:11 +0000977 if (unsigned Id = SpecialTypes[pch::SPECIAL_TYPE_OBJC_ID])
978 Context.setObjCIdType(GetType(Id));
979 if (unsigned Sel = SpecialTypes[pch::SPECIAL_TYPE_OBJC_SELECTOR])
980 Context.setObjCSelType(GetType(Sel));
981 if (unsigned Proto = SpecialTypes[pch::SPECIAL_TYPE_OBJC_PROTOCOL])
982 Context.setObjCProtoType(GetType(Proto));
983 if (unsigned Class = SpecialTypes[pch::SPECIAL_TYPE_OBJC_CLASS])
984 Context.setObjCClassType(GetType(Class));
985 if (unsigned String = SpecialTypes[pch::SPECIAL_TYPE_CF_CONSTANT_STRING])
986 Context.setCFConstantStringType(GetType(String));
987 if (unsigned FastEnum
988 = SpecialTypes[pch::SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
989 Context.setObjCFastEnumerationStateType(GetType(FastEnum));
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000990
Douglas Gregorc713da92009-04-21 22:25:48 +0000991 return Success;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000992}
993
Douglas Gregor179cfb12009-04-10 20:39:37 +0000994/// \brief Parse the record that corresponds to a LangOptions data
995/// structure.
996///
997/// This routine compares the language options used to generate the
998/// PCH file against the language options set for the current
999/// compilation. For each option, we classify differences between the
1000/// two compiler states as either "benign" or "important". Benign
1001/// differences don't matter, and we accept them without complaint
1002/// (and without modifying the language options). Differences between
1003/// the states for important options cause the PCH file to be
1004/// unusable, so we emit a warning and return true to indicate that
1005/// there was an error.
1006///
1007/// \returns true if the PCH file is unacceptable, false otherwise.
1008bool PCHReader::ParseLanguageOptions(
1009 const llvm::SmallVectorImpl<uint64_t> &Record) {
1010 const LangOptions &LangOpts = Context.getLangOptions();
1011#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1012#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1013 if (Record[Idx] != LangOpts.Option) { \
1014 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1015 Diag(diag::note_ignoring_pch) << FileName; \
1016 return true; \
1017 } \
1018 ++Idx
1019
1020 unsigned Idx = 0;
1021 PARSE_LANGOPT_BENIGN(Trigraphs);
1022 PARSE_LANGOPT_BENIGN(BCPLComment);
1023 PARSE_LANGOPT_BENIGN(DollarIdents);
1024 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1025 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1026 PARSE_LANGOPT_BENIGN(ImplicitInt);
1027 PARSE_LANGOPT_BENIGN(Digraphs);
1028 PARSE_LANGOPT_BENIGN(HexFloats);
1029 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1030 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1031 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1032 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1033 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1034 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1035 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1036 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1037 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1038 PARSE_LANGOPT_BENIGN(PascalStrings);
1039 PARSE_LANGOPT_BENIGN(Boolean);
1040 PARSE_LANGOPT_BENIGN(WritableStrings);
1041 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1042 diag::warn_pch_lax_vector_conversions);
1043 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1044 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1045 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1046 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1047 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1048 diag::warn_pch_thread_safe_statics);
1049 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1050 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1051 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1052 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1053 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1054 diag::warn_pch_heinous_extensions);
1055 // FIXME: Most of the options below are benign if the macro wasn't
1056 // used. Unfortunately, this means that a PCH compiled without
1057 // optimization can't be used with optimization turned on, even
1058 // though the only thing that changes is whether __OPTIMIZE__ was
1059 // defined... but if __OPTIMIZE__ never showed up in the header, it
1060 // doesn't matter. We could consider making this some special kind
1061 // of check.
1062 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1063 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1064 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1065 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1066 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1067 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1068 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1069 Diag(diag::warn_pch_gc_mode)
1070 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1071 Diag(diag::note_ignoring_pch) << FileName;
1072 return true;
1073 }
1074 ++Idx;
1075 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1076 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1077#undef PARSE_LANGOPT_IRRELEVANT
1078#undef PARSE_LANGOPT_BENIGN
1079
1080 return false;
1081}
1082
Douglas Gregorc34897d2009-04-09 22:27:44 +00001083/// \brief Read and return the type at the given offset.
1084///
1085/// This routine actually reads the record corresponding to the type
1086/// at the given offset in the bitstream. It is a helper routine for
1087/// GetType, which deals with reading type IDs.
1088QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001089 // Keep track of where we are in the stream, then jump back there
1090 // after reading this type.
1091 SavedStreamPosition SavedPosition(Stream);
1092
Douglas Gregorc34897d2009-04-09 22:27:44 +00001093 Stream.JumpToBit(Offset);
1094 RecordData Record;
1095 unsigned Code = Stream.ReadCode();
1096 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001097 case pch::TYPE_EXT_QUAL: {
1098 assert(Record.size() == 3 &&
1099 "Incorrect encoding of extended qualifier type");
1100 QualType Base = GetType(Record[0]);
1101 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1102 unsigned AddressSpace = Record[2];
1103
1104 QualType T = Base;
1105 if (GCAttr != QualType::GCNone)
1106 T = Context.getObjCGCQualType(T, GCAttr);
1107 if (AddressSpace)
1108 T = Context.getAddrSpaceQualType(T, AddressSpace);
1109 return T;
1110 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001111
Douglas Gregorc34897d2009-04-09 22:27:44 +00001112 case pch::TYPE_FIXED_WIDTH_INT: {
1113 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1114 return Context.getFixedWidthIntType(Record[0], Record[1]);
1115 }
1116
1117 case pch::TYPE_COMPLEX: {
1118 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1119 QualType ElemType = GetType(Record[0]);
1120 return Context.getComplexType(ElemType);
1121 }
1122
1123 case pch::TYPE_POINTER: {
1124 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1125 QualType PointeeType = GetType(Record[0]);
1126 return Context.getPointerType(PointeeType);
1127 }
1128
1129 case pch::TYPE_BLOCK_POINTER: {
1130 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1131 QualType PointeeType = GetType(Record[0]);
1132 return Context.getBlockPointerType(PointeeType);
1133 }
1134
1135 case pch::TYPE_LVALUE_REFERENCE: {
1136 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1137 QualType PointeeType = GetType(Record[0]);
1138 return Context.getLValueReferenceType(PointeeType);
1139 }
1140
1141 case pch::TYPE_RVALUE_REFERENCE: {
1142 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1143 QualType PointeeType = GetType(Record[0]);
1144 return Context.getRValueReferenceType(PointeeType);
1145 }
1146
1147 case pch::TYPE_MEMBER_POINTER: {
1148 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1149 QualType PointeeType = GetType(Record[0]);
1150 QualType ClassType = GetType(Record[1]);
1151 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1152 }
1153
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001154 case pch::TYPE_CONSTANT_ARRAY: {
1155 QualType ElementType = GetType(Record[0]);
1156 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1157 unsigned IndexTypeQuals = Record[2];
1158 unsigned Idx = 3;
1159 llvm::APInt Size = ReadAPInt(Record, Idx);
1160 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1161 }
1162
1163 case pch::TYPE_INCOMPLETE_ARRAY: {
1164 QualType ElementType = GetType(Record[0]);
1165 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1166 unsigned IndexTypeQuals = Record[2];
1167 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1168 }
1169
1170 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001171 QualType ElementType = GetType(Record[0]);
1172 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1173 unsigned IndexTypeQuals = Record[2];
Chris Lattner3ef21962009-04-27 05:58:23 +00001174 return Context.getVariableArrayType(ElementType, ReadTypeExpr(),
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001175 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001176 }
1177
1178 case pch::TYPE_VECTOR: {
1179 if (Record.size() != 2) {
1180 Error("Incorrect encoding of vector type in PCH file");
1181 return QualType();
1182 }
1183
1184 QualType ElementType = GetType(Record[0]);
1185 unsigned NumElements = Record[1];
1186 return Context.getVectorType(ElementType, NumElements);
1187 }
1188
1189 case pch::TYPE_EXT_VECTOR: {
1190 if (Record.size() != 2) {
1191 Error("Incorrect encoding of extended vector type in PCH file");
1192 return QualType();
1193 }
1194
1195 QualType ElementType = GetType(Record[0]);
1196 unsigned NumElements = Record[1];
1197 return Context.getExtVectorType(ElementType, NumElements);
1198 }
1199
1200 case pch::TYPE_FUNCTION_NO_PROTO: {
1201 if (Record.size() != 1) {
1202 Error("Incorrect encoding of no-proto function type");
1203 return QualType();
1204 }
1205 QualType ResultType = GetType(Record[0]);
1206 return Context.getFunctionNoProtoType(ResultType);
1207 }
1208
1209 case pch::TYPE_FUNCTION_PROTO: {
1210 QualType ResultType = GetType(Record[0]);
1211 unsigned Idx = 1;
1212 unsigned NumParams = Record[Idx++];
1213 llvm::SmallVector<QualType, 16> ParamTypes;
1214 for (unsigned I = 0; I != NumParams; ++I)
1215 ParamTypes.push_back(GetType(Record[Idx++]));
1216 bool isVariadic = Record[Idx++];
1217 unsigned Quals = Record[Idx++];
1218 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1219 isVariadic, Quals);
1220 }
1221
1222 case pch::TYPE_TYPEDEF:
1223 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1224 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1225
1226 case pch::TYPE_TYPEOF_EXPR:
Chris Lattner3ef21962009-04-27 05:58:23 +00001227 return Context.getTypeOfExprType(ReadTypeExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001228
1229 case pch::TYPE_TYPEOF: {
1230 if (Record.size() != 1) {
1231 Error("Incorrect encoding of typeof(type) in PCH file");
1232 return QualType();
1233 }
1234 QualType UnderlyingType = GetType(Record[0]);
1235 return Context.getTypeOfType(UnderlyingType);
1236 }
1237
1238 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001239 assert(Record.size() == 1 && "Incorrect encoding of record type");
1240 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001241
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001242 case pch::TYPE_ENUM:
1243 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1244 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1245
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001246 case pch::TYPE_OBJC_INTERFACE:
Chris Lattner80f83c62009-04-22 05:57:30 +00001247 assert(Record.size() == 1 && "Incorrect encoding of objc interface type");
1248 return Context.getObjCInterfaceType(
1249 cast<ObjCInterfaceDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001250
Chris Lattnerbab2c0f2009-04-22 06:45:28 +00001251 case pch::TYPE_OBJC_QUALIFIED_INTERFACE: {
1252 unsigned Idx = 0;
1253 ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
1254 unsigned NumProtos = Record[Idx++];
1255 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1256 for (unsigned I = 0; I != NumProtos; ++I)
1257 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1258 return Context.getObjCQualifiedInterfaceType(ItfD, &Protos[0], NumProtos);
1259 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001260
Chris Lattner9b9f2352009-04-22 06:40:03 +00001261 case pch::TYPE_OBJC_QUALIFIED_ID: {
1262 unsigned Idx = 0;
1263 unsigned NumProtos = Record[Idx++];
1264 llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
1265 for (unsigned I = 0; I != NumProtos; ++I)
1266 Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
1267 return Context.getObjCQualifiedIdType(&Protos[0], NumProtos);
1268 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001269 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001270 // Suppress a GCC warning
1271 return QualType();
1272}
1273
Douglas Gregorc34897d2009-04-09 22:27:44 +00001274
Douglas Gregorac8f2802009-04-10 17:25:41 +00001275QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001276 unsigned Quals = ID & 0x07;
1277 unsigned Index = ID >> 3;
1278
1279 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1280 QualType T;
1281 switch ((pch::PredefinedTypeIDs)Index) {
1282 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1283 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1284 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1285
1286 case pch::PREDEF_TYPE_CHAR_U_ID:
1287 case pch::PREDEF_TYPE_CHAR_S_ID:
1288 // FIXME: Check that the signedness of CharTy is correct!
1289 T = Context.CharTy;
1290 break;
1291
1292 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1293 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1294 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1295 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1296 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1297 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1298 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1299 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1300 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1301 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1302 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1303 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1304 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1305 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1306 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1307 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1308 }
1309
1310 assert(!T.isNull() && "Unknown predefined type");
1311 return T.getQualifiedType(Quals);
1312 }
1313
1314 Index -= pch::NUM_PREDEF_TYPE_IDS;
Douglas Gregore43f0972009-04-26 03:49:13 +00001315 assert(Index < TypesLoaded.size() && "Type index out-of-range");
Douglas Gregor24a224c2009-04-25 18:35:21 +00001316 if (!TypesLoaded[Index])
1317 TypesLoaded[Index] = ReadTypeRecord(TypeOffsets[Index]).getTypePtr();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001318
Douglas Gregor24a224c2009-04-25 18:35:21 +00001319 return QualType(TypesLoaded[Index], Quals);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001320}
1321
Douglas Gregorac8f2802009-04-10 17:25:41 +00001322Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001323 if (ID == 0)
1324 return 0;
1325
Douglas Gregor24a224c2009-04-25 18:35:21 +00001326 if (ID > DeclsLoaded.size()) {
1327 Error("Declaration ID out-of-range for PCH file");
1328 return 0;
1329 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001330
Douglas Gregor24a224c2009-04-25 18:35:21 +00001331 unsigned Index = ID - 1;
1332 if (!DeclsLoaded[Index])
1333 ReadDeclRecord(DeclOffsets[Index], Index);
1334
1335 return DeclsLoaded[Index];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001336}
1337
Chris Lattner77055f62009-04-27 05:46:25 +00001338/// \brief Resolve the offset of a statement into a statement.
1339///
1340/// This operation will read a new statement from the external
1341/// source each time it is called, and is meant to be used via a
1342/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1343Stmt *PCHReader::GetDeclStmt(uint64_t Offset) {
Chris Lattner3ef21962009-04-27 05:58:23 +00001344 // Since we know tha this statement is part of a decl, make sure to use the
1345 // decl cursor to read it.
1346 DeclsCursor.JumpToBit(Offset);
1347 return ReadStmt(DeclsCursor);
Douglas Gregor3b9a7c82009-04-18 00:07:54 +00001348}
1349
Douglas Gregorc34897d2009-04-09 22:27:44 +00001350bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001351 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001352 assert(DC->hasExternalLexicalStorage() &&
1353 "DeclContext has no lexical decls in storage");
1354 uint64_t Offset = DeclContextOffsets[DC].first;
1355 assert(Offset && "DeclContext has no lexical decls in storage");
1356
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001357 // Keep track of where we are in the stream, then jump back there
1358 // after reading this context.
1359 SavedStreamPosition SavedPosition(Stream);
1360
Douglas Gregorc34897d2009-04-09 22:27:44 +00001361 // Load the record containing all of the declarations lexically in
1362 // this context.
1363 Stream.JumpToBit(Offset);
1364 RecordData Record;
1365 unsigned Code = Stream.ReadCode();
1366 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001367 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001368 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1369
1370 // Load all of the declaration IDs
1371 Decls.clear();
1372 Decls.insert(Decls.end(), Record.begin(), Record.end());
Douglas Gregoraf136d92009-04-22 22:34:57 +00001373 ++NumLexicalDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001374 return false;
1375}
1376
1377bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1378 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1379 assert(DC->hasExternalVisibleStorage() &&
1380 "DeclContext has no visible decls in storage");
1381 uint64_t Offset = DeclContextOffsets[DC].second;
1382 assert(Offset && "DeclContext has no visible decls in storage");
1383
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001384 // Keep track of where we are in the stream, then jump back there
1385 // after reading this context.
1386 SavedStreamPosition SavedPosition(Stream);
1387
Douglas Gregorc34897d2009-04-09 22:27:44 +00001388 // Load the record containing all of the declarations visible in
1389 // this context.
1390 Stream.JumpToBit(Offset);
1391 RecordData Record;
1392 unsigned Code = Stream.ReadCode();
1393 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001394 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001395 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1396 if (Record.size() == 0)
1397 return false;
1398
1399 Decls.clear();
1400
1401 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001402 while (Idx < Record.size()) {
1403 Decls.push_back(VisibleDeclaration());
1404 Decls.back().Name = ReadDeclarationName(Record, Idx);
1405
Douglas Gregorc34897d2009-04-09 22:27:44 +00001406 unsigned Size = Record[Idx++];
1407 llvm::SmallVector<unsigned, 4> & LoadedDecls
1408 = Decls.back().Declarations;
1409 LoadedDecls.reserve(Size);
1410 for (unsigned I = 0; I < Size; ++I)
1411 LoadedDecls.push_back(Record[Idx++]);
1412 }
1413
Douglas Gregoraf136d92009-04-22 22:34:57 +00001414 ++NumVisibleDeclContextsRead;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001415 return false;
1416}
1417
Douglas Gregor631f6c62009-04-14 00:24:19 +00001418void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
Douglas Gregor405b6432009-04-22 19:09:20 +00001419 this->Consumer = Consumer;
1420
Douglas Gregor631f6c62009-04-14 00:24:19 +00001421 if (!Consumer)
1422 return;
1423
1424 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1425 Decl *D = GetDecl(ExternalDefinitions[I]);
1426 DeclGroupRef DG(D);
1427 Consumer->HandleTopLevelDecl(DG);
1428 }
Douglas Gregorf93cfee2009-04-25 00:41:30 +00001429
1430 for (unsigned I = 0, N = InterestingDecls.size(); I != N; ++I) {
1431 DeclGroupRef DG(InterestingDecls[I]);
1432 Consumer->HandleTopLevelDecl(DG);
1433 }
Douglas Gregor631f6c62009-04-14 00:24:19 +00001434}
1435
Douglas Gregorc34897d2009-04-09 22:27:44 +00001436void PCHReader::PrintStats() {
1437 std::fprintf(stderr, "*** PCH Statistics:\n");
1438
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001439 unsigned NumTypesLoaded
1440 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
1441 (Type *)0);
1442 unsigned NumDeclsLoaded
1443 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
1444 (Decl *)0);
1445 unsigned NumIdentifiersLoaded
1446 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
1447 IdentifiersLoaded.end(),
1448 (IdentifierInfo *)0);
1449 unsigned NumSelectorsLoaded
1450 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
1451 SelectorsLoaded.end(),
1452 Selector());
Douglas Gregor9cf47422009-04-13 20:50:16 +00001453
Douglas Gregor24a224c2009-04-25 18:35:21 +00001454 if (!TypesLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00001455 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00001456 NumTypesLoaded, (unsigned)TypesLoaded.size(),
1457 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
1458 if (!DeclsLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00001459 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
Douglas Gregor24a224c2009-04-25 18:35:21 +00001460 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
1461 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001462 if (!IdentifiersLoaded.empty())
Douglas Gregor2d711832009-04-25 17:48:32 +00001463 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001464 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
1465 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
Douglas Gregor2d711832009-04-25 17:48:32 +00001466 if (TotalNumSelectors)
1467 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
1468 NumSelectorsLoaded, TotalNumSelectors,
1469 ((float)NumSelectorsLoaded/TotalNumSelectors * 100));
1470 if (TotalNumStatements)
1471 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
1472 NumStatementsRead, TotalNumStatements,
1473 ((float)NumStatementsRead/TotalNumStatements * 100));
1474 if (TotalNumMacros)
1475 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
1476 NumMacrosRead, TotalNumMacros,
1477 ((float)NumMacrosRead/TotalNumMacros * 100));
1478 if (TotalLexicalDeclContexts)
1479 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
1480 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
1481 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
1482 * 100));
1483 if (TotalVisibleDeclContexts)
1484 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
1485 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
1486 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
1487 * 100));
1488 if (TotalSelectorsInMethodPool) {
1489 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
1490 NumMethodPoolSelectorsRead, TotalSelectorsInMethodPool,
1491 ((float)NumMethodPoolSelectorsRead/TotalSelectorsInMethodPool
1492 * 100));
1493 std::fprintf(stderr, " %u method pool misses\n", NumMethodPoolMisses);
1494 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001495 std::fprintf(stderr, "\n");
1496}
1497
Douglas Gregorc713da92009-04-21 22:25:48 +00001498void PCHReader::InitializeSema(Sema &S) {
1499 SemaObj = &S;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001500 S.ExternalSource = this;
1501
Douglas Gregor2554cf22009-04-22 21:15:06 +00001502 // Makes sure any declarations that were deserialized "too early"
1503 // still get added to the identifier's declaration chains.
1504 for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
1505 SemaObj->TUScope->AddDecl(Action::DeclPtrTy::make(PreloadedDecls[I]));
1506 SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
Douglas Gregorc713da92009-04-21 22:25:48 +00001507 }
Douglas Gregor2554cf22009-04-22 21:15:06 +00001508 PreloadedDecls.clear();
Douglas Gregor77b2cd52009-04-22 22:02:47 +00001509
1510 // If there were any tentative definitions, deserialize them and add
1511 // them to Sema's table of tentative definitions.
1512 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
1513 VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
1514 SemaObj->TentativeDefinitions[Var->getDeclName()] = Var;
1515 }
Douglas Gregor062d9482009-04-22 22:18:58 +00001516
1517 // If there were any locally-scoped external declarations,
1518 // deserialize them and add them to Sema's table of locally-scoped
1519 // external declarations.
1520 for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
1521 NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
1522 SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
1523 }
Douglas Gregorc713da92009-04-21 22:25:48 +00001524}
1525
1526IdentifierInfo* PCHReader::get(const char *NameStart, const char *NameEnd) {
1527 // Try to find this name within our on-disk hash table
1528 PCHIdentifierLookupTable *IdTable
1529 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
1530 std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
1531 PCHIdentifierLookupTable::iterator Pos = IdTable->find(Key);
1532 if (Pos == IdTable->end())
1533 return 0;
1534
1535 // Dereferencing the iterator has the effect of building the
1536 // IdentifierInfo node and populating it with the various
1537 // declarations it needs.
1538 return *Pos;
1539}
1540
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001541std::pair<ObjCMethodList, ObjCMethodList>
1542PCHReader::ReadMethodPool(Selector Sel) {
1543 if (!MethodPoolLookupTable)
1544 return std::pair<ObjCMethodList, ObjCMethodList>();
1545
1546 // Try to find this selector within our on-disk hash table.
1547 PCHMethodPoolLookupTable *PoolTable
1548 = (PCHMethodPoolLookupTable*)MethodPoolLookupTable;
1549 PCHMethodPoolLookupTable::iterator Pos = PoolTable->find(Sel);
Douglas Gregor2d711832009-04-25 17:48:32 +00001550 if (Pos == PoolTable->end()) {
1551 ++NumMethodPoolMisses;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001552 return std::pair<ObjCMethodList, ObjCMethodList>();;
Douglas Gregor2d711832009-04-25 17:48:32 +00001553 }
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001554
Douglas Gregor2d711832009-04-25 17:48:32 +00001555 ++NumMethodPoolSelectorsRead;
Douglas Gregorc3221aa2009-04-24 21:10:55 +00001556 return *Pos;
1557}
1558
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001559void PCHReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
Douglas Gregorc713da92009-04-21 22:25:48 +00001560 assert(ID && "Non-zero identifier ID required");
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001561 assert(ID <= IdentifiersLoaded.size() && "Identifier ID out of range");
1562 IdentifiersLoaded[ID - 1] = II;
Douglas Gregorc713da92009-04-21 22:25:48 +00001563}
1564
Chris Lattner29241862009-04-11 21:15:38 +00001565IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001566 if (ID == 0)
1567 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001568
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001569 if (!IdentifierTableData || IdentifiersLoaded.empty()) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001570 Error("No identifier table in PCH file");
1571 return 0;
1572 }
Chris Lattner29241862009-04-11 21:15:38 +00001573
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001574 if (!IdentifiersLoaded[ID - 1]) {
1575 uint32_t Offset = IdentifierOffsets[ID - 1];
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00001576 const char *Str = IdentifierTableData + Offset;
Douglas Gregor85c4a872009-04-25 21:04:17 +00001577
1578 // If there is an identifier lookup table, but the offset of this
1579 // string is after the identifier table itself, then we know that
1580 // this string is not in the on-disk hash table. Therefore,
1581 // disable lookup into the hash table when looking for this
1582 // identifier.
1583 PCHIdentifierLookupTable *IdTable
1584 = (PCHIdentifierLookupTable *)IdentifierLookupTable;
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00001585 if (!IdTable ||
1586 Offset >= uint32_t(IdTable->getBuckets() - IdTable->getBase())) {
1587 // Turn off lookup into the on-disk hash table. We know that
1588 // this identifier is not there.
1589 if (IdTable)
1590 PP.getIdentifierTable().setExternalIdentifierLookup(0);
Douglas Gregor85c4a872009-04-25 21:04:17 +00001591
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00001592 // All of the strings in the PCH file are preceded by a 16-bit
1593 // length. Extract that 16-bit length to avoid having to execute
1594 // strlen().
1595 const char *StrLenPtr = Str - 2;
1596 unsigned StrLen = (((unsigned) StrLenPtr[0])
1597 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
1598 IdentifiersLoaded[ID - 1] = &Context.Idents.get(Str, Str + StrLen);
Douglas Gregor85c4a872009-04-25 21:04:17 +00001599
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00001600 // Turn on lookup into the on-disk hash table, if we have an
1601 // on-disk hash table.
1602 if (IdTable)
1603 PP.getIdentifierTable().setExternalIdentifierLookup(this);
1604 } else {
1605 // The identifier is a key in our on-disk hash table. Since we
1606 // know where the hash table entry starts, just read in this
1607 // (key, value) pair.
1608 PCHIdentifierLookupTrait Trait(const_cast<PCHReader &>(*this));
1609 const unsigned char *Pos = (const unsigned char *)Str - 4;
1610 std::pair<unsigned, unsigned> KeyDataLengths
1611 = Trait.ReadKeyDataLength(Pos);
Douglas Gregor85c4a872009-04-25 21:04:17 +00001612
Douglas Gregor4d7a6e42009-04-25 21:21:38 +00001613 PCHIdentifierLookupTrait::internal_key_type InternalKey
1614 = Trait.ReadKey(Pos, KeyDataLengths.first);
1615 Pos = (const unsigned char *)Str + KeyDataLengths.first;
1616 IdentifiersLoaded[ID - 1] = Trait.ReadData(InternalKey, Pos,
1617 KeyDataLengths.second);
1618 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001619 }
Chris Lattner29241862009-04-11 21:15:38 +00001620
Douglas Gregorde44c9f2009-04-25 19:10:14 +00001621 return IdentifiersLoaded[ID - 1];
Douglas Gregorc34897d2009-04-09 22:27:44 +00001622}
1623
Steve Naroff9e84d782009-04-23 10:39:46 +00001624Selector PCHReader::DecodeSelector(unsigned ID) {
1625 if (ID == 0)
1626 return Selector();
1627
Douglas Gregor2d711832009-04-25 17:48:32 +00001628 if (!MethodPoolLookupTableData) {
Steve Naroff9e84d782009-04-23 10:39:46 +00001629 Error("No selector table in PCH file");
1630 return Selector();
1631 }
Douglas Gregor2d711832009-04-25 17:48:32 +00001632
1633 if (ID > TotalNumSelectors) {
Steve Naroff9e84d782009-04-23 10:39:46 +00001634 Error("Selector ID out of range");
1635 return Selector();
1636 }
Douglas Gregor2d711832009-04-25 17:48:32 +00001637
1638 unsigned Index = ID - 1;
1639 if (SelectorsLoaded[Index].getAsOpaquePtr() == 0) {
1640 // Load this selector from the selector table.
1641 // FIXME: endianness portability issues with SelectorOffsets table
1642 PCHMethodPoolLookupTrait Trait(*this);
1643 SelectorsLoaded[Index]
1644 = Trait.ReadKey(MethodPoolLookupTableData + SelectorOffsets[Index], 0);
1645 }
1646
1647 return SelectorsLoaded[Index];
Steve Naroff9e84d782009-04-23 10:39:46 +00001648}
1649
Douglas Gregorc34897d2009-04-09 22:27:44 +00001650DeclarationName
1651PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1652 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1653 switch (Kind) {
1654 case DeclarationName::Identifier:
1655 return DeclarationName(GetIdentifierInfo(Record, Idx));
1656
1657 case DeclarationName::ObjCZeroArgSelector:
1658 case DeclarationName::ObjCOneArgSelector:
1659 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff104956f2009-04-23 15:15:40 +00001660 return DeclarationName(GetSelector(Record, Idx));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001661
1662 case DeclarationName::CXXConstructorName:
1663 return Context.DeclarationNames.getCXXConstructorName(
1664 GetType(Record[Idx++]));
1665
1666 case DeclarationName::CXXDestructorName:
1667 return Context.DeclarationNames.getCXXDestructorName(
1668 GetType(Record[Idx++]));
1669
1670 case DeclarationName::CXXConversionFunctionName:
1671 return Context.DeclarationNames.getCXXConversionFunctionName(
1672 GetType(Record[Idx++]));
1673
1674 case DeclarationName::CXXOperatorName:
1675 return Context.DeclarationNames.getCXXOperatorName(
1676 (OverloadedOperatorKind)Record[Idx++]);
1677
1678 case DeclarationName::CXXUsingDirective:
1679 return DeclarationName::getUsingDirectiveName();
1680 }
1681
1682 // Required to silence GCC warning
1683 return DeclarationName();
1684}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001685
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001686/// \brief Read an integral value
1687llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1688 unsigned BitWidth = Record[Idx++];
1689 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1690 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1691 Idx += NumWords;
1692 return Result;
1693}
1694
1695/// \brief Read a signed integral value
1696llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1697 bool isUnsigned = Record[Idx++];
1698 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1699}
1700
Douglas Gregore2f37202009-04-14 21:55:33 +00001701/// \brief Read a floating-point value
1702llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00001703 return llvm::APFloat(ReadAPInt(Record, Idx));
1704}
1705
Douglas Gregor1c507882009-04-15 21:30:51 +00001706// \brief Read a string
1707std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
1708 unsigned Len = Record[Idx++];
1709 std::string Result(&Record[Idx], &Record[Idx] + Len);
1710 Idx += Len;
1711 return Result;
1712}
1713
1714/// \brief Reads attributes from the current stream position.
1715Attr *PCHReader::ReadAttributes() {
Chris Lattner3ef21962009-04-27 05:58:23 +00001716 unsigned Code = DeclsCursor.ReadCode();
Douglas Gregor1c507882009-04-15 21:30:51 +00001717 assert(Code == llvm::bitc::UNABBREV_RECORD &&
1718 "Expected unabbreviated record"); (void)Code;
1719
1720 RecordData Record;
1721 unsigned Idx = 0;
Chris Lattner3ef21962009-04-27 05:58:23 +00001722 unsigned RecCode = DeclsCursor.ReadRecord(Code, Record);
Douglas Gregor1c507882009-04-15 21:30:51 +00001723 assert(RecCode == pch::DECL_ATTR && "Expected attribute record");
1724 (void)RecCode;
1725
1726#define SIMPLE_ATTR(Name) \
1727 case Attr::Name: \
1728 New = ::new (Context) Name##Attr(); \
1729 break
1730
1731#define STRING_ATTR(Name) \
1732 case Attr::Name: \
1733 New = ::new (Context) Name##Attr(ReadString(Record, Idx)); \
1734 break
1735
1736#define UNSIGNED_ATTR(Name) \
1737 case Attr::Name: \
1738 New = ::new (Context) Name##Attr(Record[Idx++]); \
1739 break
1740
1741 Attr *Attrs = 0;
1742 while (Idx < Record.size()) {
1743 Attr *New = 0;
1744 Attr::Kind Kind = (Attr::Kind)Record[Idx++];
1745 bool IsInherited = Record[Idx++];
1746
1747 switch (Kind) {
1748 STRING_ATTR(Alias);
1749 UNSIGNED_ATTR(Aligned);
1750 SIMPLE_ATTR(AlwaysInline);
1751 SIMPLE_ATTR(AnalyzerNoReturn);
1752 STRING_ATTR(Annotate);
1753 STRING_ATTR(AsmLabel);
1754
1755 case Attr::Blocks:
1756 New = ::new (Context) BlocksAttr(
1757 (BlocksAttr::BlocksAttrTypes)Record[Idx++]);
1758 break;
1759
1760 case Attr::Cleanup:
1761 New = ::new (Context) CleanupAttr(
1762 cast<FunctionDecl>(GetDecl(Record[Idx++])));
1763 break;
1764
1765 SIMPLE_ATTR(Const);
1766 UNSIGNED_ATTR(Constructor);
1767 SIMPLE_ATTR(DLLExport);
1768 SIMPLE_ATTR(DLLImport);
1769 SIMPLE_ATTR(Deprecated);
1770 UNSIGNED_ATTR(Destructor);
1771 SIMPLE_ATTR(FastCall);
1772
1773 case Attr::Format: {
1774 std::string Type = ReadString(Record, Idx);
1775 unsigned FormatIdx = Record[Idx++];
1776 unsigned FirstArg = Record[Idx++];
1777 New = ::new (Context) FormatAttr(Type, FormatIdx, FirstArg);
1778 break;
1779 }
1780
Chris Lattner15ce6cc2009-04-20 19:12:28 +00001781 SIMPLE_ATTR(GNUInline);
Douglas Gregor1c507882009-04-15 21:30:51 +00001782
1783 case Attr::IBOutletKind:
1784 New = ::new (Context) IBOutletAttr();
1785 break;
1786
1787 SIMPLE_ATTR(NoReturn);
1788 SIMPLE_ATTR(NoThrow);
1789 SIMPLE_ATTR(Nodebug);
1790 SIMPLE_ATTR(Noinline);
1791
1792 case Attr::NonNull: {
1793 unsigned Size = Record[Idx++];
1794 llvm::SmallVector<unsigned, 16> ArgNums;
1795 ArgNums.insert(ArgNums.end(), &Record[Idx], &Record[Idx] + Size);
1796 Idx += Size;
1797 New = ::new (Context) NonNullAttr(&ArgNums[0], Size);
1798 break;
1799 }
1800
1801 SIMPLE_ATTR(ObjCException);
1802 SIMPLE_ATTR(ObjCNSObject);
Ted Kremenekb98860c2009-04-25 00:17:17 +00001803 SIMPLE_ATTR(ObjCOwnershipRetain);
Ted Kremenekaa6e3182009-04-24 23:09:54 +00001804 SIMPLE_ATTR(ObjCOwnershipReturns);
Douglas Gregor1c507882009-04-15 21:30:51 +00001805 SIMPLE_ATTR(Overloadable);
1806 UNSIGNED_ATTR(Packed);
1807 SIMPLE_ATTR(Pure);
1808 UNSIGNED_ATTR(Regparm);
1809 STRING_ATTR(Section);
1810 SIMPLE_ATTR(StdCall);
1811 SIMPLE_ATTR(TransparentUnion);
1812 SIMPLE_ATTR(Unavailable);
1813 SIMPLE_ATTR(Unused);
1814 SIMPLE_ATTR(Used);
1815
1816 case Attr::Visibility:
1817 New = ::new (Context) VisibilityAttr(
1818 (VisibilityAttr::VisibilityTypes)Record[Idx++]);
1819 break;
1820
1821 SIMPLE_ATTR(WarnUnusedResult);
1822 SIMPLE_ATTR(Weak);
1823 SIMPLE_ATTR(WeakImport);
1824 }
1825
1826 assert(New && "Unable to decode attribute?");
1827 New->setInherited(IsInherited);
1828 New->setNext(Attrs);
1829 Attrs = New;
1830 }
1831#undef UNSIGNED_ATTR
1832#undef STRING_ATTR
1833#undef SIMPLE_ATTR
1834
1835 // The list of attributes was built backwards. Reverse the list
1836 // before returning it.
1837 Attr *PrevAttr = 0, *NextAttr = 0;
1838 while (Attrs) {
1839 NextAttr = Attrs->getNext();
1840 Attrs->setNext(PrevAttr);
1841 PrevAttr = Attrs;
1842 Attrs = NextAttr;
1843 }
1844
1845 return PrevAttr;
1846}
1847
Douglas Gregor179cfb12009-04-10 20:39:37 +00001848DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001849 return Diag(SourceLocation(), DiagID);
1850}
1851
1852DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1853 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001854 Context.getSourceManager()),
1855 DiagID);
1856}
Douglas Gregor9c4782a2009-04-17 00:04:06 +00001857
Douglas Gregorc713da92009-04-21 22:25:48 +00001858/// \brief Retrieve the identifier table associated with the
1859/// preprocessor.
1860IdentifierTable &PCHReader::getIdentifierTable() {
1861 return PP.getIdentifierTable();
1862}
1863
Douglas Gregor9c4782a2009-04-17 00:04:06 +00001864/// \brief Record that the given ID maps to the given switch-case
1865/// statement.
1866void PCHReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
1867 assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
1868 SwitchCaseStmts[ID] = SC;
1869}
1870
1871/// \brief Retrieve the switch-case statement with the given ID.
1872SwitchCase *PCHReader::getSwitchCaseWithID(unsigned ID) {
1873 assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
1874 return SwitchCaseStmts[ID];
1875}
Douglas Gregor6e411bf2009-04-17 18:18:49 +00001876
1877/// \brief Record that the given label statement has been
1878/// deserialized and has the given ID.
1879void PCHReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
1880 assert(LabelStmts.find(ID) == LabelStmts.end() &&
1881 "Deserialized label twice");
1882 LabelStmts[ID] = S;
1883
1884 // If we've already seen any goto statements that point to this
1885 // label, resolve them now.
1886 typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
1887 std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
1888 for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
1889 Goto->second->setLabel(S);
1890 UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
Douglas Gregor95a8fe32009-04-17 18:58:21 +00001891
1892 // If we've already seen any address-label statements that point to
1893 // this label, resolve them now.
1894 typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
1895 std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
1896 = UnresolvedAddrLabelExprs.equal_range(ID);
1897 for (AddrLabelIter AddrLabel = AddrLabels.first;
1898 AddrLabel != AddrLabels.second; ++AddrLabel)
1899 AddrLabel->second->setLabel(S);
1900 UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
Douglas Gregor6e411bf2009-04-17 18:18:49 +00001901}
1902
1903/// \brief Set the label of the given statement to the label
1904/// identified by ID.
1905///
1906/// Depending on the order in which the label and other statements
1907/// referencing that label occur, this operation may complete
1908/// immediately (updating the statement) or it may queue the
1909/// statement to be back-patched later.
1910void PCHReader::SetLabelOf(GotoStmt *S, unsigned ID) {
1911 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
1912 if (Label != LabelStmts.end()) {
1913 // We've already seen this label, so set the label of the goto and
1914 // we're done.
1915 S->setLabel(Label->second);
1916 } else {
1917 // We haven't seen this label yet, so add this goto to the set of
1918 // unresolved goto statements.
1919 UnresolvedGotoStmts.insert(std::make_pair(ID, S));
1920 }
1921}
Douglas Gregor95a8fe32009-04-17 18:58:21 +00001922
1923/// \brief Set the label of the given expression to the label
1924/// identified by ID.
1925///
1926/// Depending on the order in which the label and other statements
1927/// referencing that label occur, this operation may complete
1928/// immediately (updating the statement) or it may queue the
1929/// statement to be back-patched later.
1930void PCHReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
1931 std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
1932 if (Label != LabelStmts.end()) {
1933 // We've already seen this label, so set the label of the
1934 // label-address expression and we're done.
1935 S->setLabel(Label->second);
1936 } else {
1937 // We haven't seen this label yet, so add this label-address
1938 // expression to the set of unresolved label-address expressions.
1939 UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
1940 }
1941}