blob: 909ecdb100c6d21d648bcf8c5034a4966ebb5993 [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//===----------------------------------------------------------------------===//
13#include "clang/Frontend/PCHReader.h"
Douglas Gregor179cfb12009-04-10 20:39:37 +000014#include "clang/Frontend/FrontendDiagnostic.h"
Douglas Gregor631f6c62009-04-14 00:24:19 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Douglas Gregor631f6c62009-04-14 00:24:19 +000018#include "clang/AST/DeclGroup.h"
Douglas Gregorc10f86f2009-04-14 21:18:50 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/StmtVisitor.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000021#include "clang/AST/Type.h"
Chris Lattnerdb1c81b2009-04-10 21:41:48 +000022#include "clang/Lex/MacroInfo.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Basic/SourceManager.h"
Douglas Gregor635f97f2009-04-13 16:31:14 +000025#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorab1cef72009-04-10 03:52:48 +000026#include "clang/Basic/FileManager.h"
Douglas Gregorb5887f32009-04-10 21:16:55 +000027#include "clang/Basic/TargetInfo.h"
Douglas Gregorc34897d2009-04-09 22:27:44 +000028#include "llvm/Bitcode/BitstreamReader.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/MemoryBuffer.h"
31#include <algorithm>
32#include <cstdio>
33
34using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// Declaration deserialization
38//===----------------------------------------------------------------------===//
39namespace {
40 class VISIBILITY_HIDDEN PCHDeclReader {
41 PCHReader &Reader;
42 const PCHReader::RecordData &Record;
43 unsigned &Idx;
44
45 public:
46 PCHDeclReader(PCHReader &Reader, const PCHReader::RecordData &Record,
47 unsigned &Idx)
48 : Reader(Reader), Record(Record), Idx(Idx) { }
49
50 void VisitDecl(Decl *D);
51 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
52 void VisitNamedDecl(NamedDecl *ND);
53 void VisitTypeDecl(TypeDecl *TD);
54 void VisitTypedefDecl(TypedefDecl *TD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000055 void VisitTagDecl(TagDecl *TD);
56 void VisitEnumDecl(EnumDecl *ED);
Douglas Gregor982365e2009-04-13 21:20:57 +000057 void VisitRecordDecl(RecordDecl *RD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000058 void VisitValueDecl(ValueDecl *VD);
Douglas Gregor47f1b2c2009-04-13 18:14:40 +000059 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000060 void VisitFunctionDecl(FunctionDecl *FD);
Douglas Gregor982365e2009-04-13 21:20:57 +000061 void VisitFieldDecl(FieldDecl *FD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000062 void VisitVarDecl(VarDecl *VD);
Douglas Gregor23ce3a52009-04-13 22:18:37 +000063 void VisitParmVarDecl(ParmVarDecl *PD);
64 void VisitOriginalParmVarDecl(OriginalParmVarDecl *PD);
Douglas Gregor2a491792009-04-13 22:49:25 +000065 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
66 void VisitBlockDecl(BlockDecl *BD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000067 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
68 };
69}
70
71void PCHDeclReader::VisitDecl(Decl *D) {
72 D->setDeclContext(cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
73 D->setLexicalDeclContext(
74 cast_or_null<DeclContext>(Reader.GetDecl(Record[Idx++])));
75 D->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
76 D->setInvalidDecl(Record[Idx++]);
77 // FIXME: hasAttrs
78 D->setImplicit(Record[Idx++]);
79 D->setAccess((AccessSpecifier)Record[Idx++]);
80}
81
82void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
83 VisitDecl(TU);
84}
85
86void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
87 VisitDecl(ND);
88 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
89}
90
91void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
92 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000093 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
94}
95
96void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000097 // Note that we cannot use VisitTypeDecl here, because we need to
98 // set the underlying type of the typedef *before* we try to read
99 // the type associated with the TypedefDecl.
100 VisitNamedDecl(TD);
101 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
102 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
103 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000104}
105
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000106void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
107 VisitTypeDecl(TD);
108 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
109 TD->setDefinition(Record[Idx++]);
110 TD->setTypedefForAnonDecl(
111 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
112}
113
114void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
115 VisitTagDecl(ED);
116 ED->setIntegerType(Reader.GetType(Record[Idx++]));
117}
118
Douglas Gregor982365e2009-04-13 21:20:57 +0000119void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
120 VisitTagDecl(RD);
121 RD->setHasFlexibleArrayMember(Record[Idx++]);
122 RD->setAnonymousStructOrUnion(Record[Idx++]);
123}
124
Douglas Gregorc34897d2009-04-09 22:27:44 +0000125void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
126 VisitNamedDecl(VD);
127 VD->setType(Reader.GetType(Record[Idx++]));
128}
129
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000130void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
131 VisitValueDecl(ECD);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000132 if (Record[Idx++])
133 ECD->setInitExpr(Reader.ReadExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000134 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
135}
136
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000137void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
138 VisitValueDecl(FD);
139 // FIXME: function body
140 FD->setPreviousDeclaration(
141 cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++])));
142 FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]);
143 FD->setInline(Record[Idx++]);
144 FD->setVirtual(Record[Idx++]);
145 FD->setPure(Record[Idx++]);
146 FD->setInheritedPrototype(Record[Idx++]);
147 FD->setHasPrototype(Record[Idx++]);
148 FD->setDeleted(Record[Idx++]);
149 FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
150 unsigned NumParams = Record[Idx++];
151 llvm::SmallVector<ParmVarDecl *, 16> Params;
152 Params.reserve(NumParams);
153 for (unsigned I = 0; I != NumParams; ++I)
154 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
155 FD->setParams(Reader.getContext(), &Params[0], NumParams);
156}
157
Douglas Gregor982365e2009-04-13 21:20:57 +0000158void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
159 VisitValueDecl(FD);
160 FD->setMutable(Record[Idx++]);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000161 if (Record[Idx++])
162 FD->setBitWidth(Reader.ReadExpr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000163}
164
Douglas Gregorc34897d2009-04-09 22:27:44 +0000165void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
166 VisitValueDecl(VD);
167 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
168 VD->setThreadSpecified(Record[Idx++]);
169 VD->setCXXDirectInitializer(Record[Idx++]);
170 VD->setDeclaredInCondition(Record[Idx++]);
171 VD->setPreviousDeclaration(
172 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
173 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000174 if (Record[Idx++])
175 VD->setInit(Reader.ReadExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000176}
177
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000178void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
179 VisitVarDecl(PD);
180 PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
181 // FIXME: default argument
182}
183
184void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) {
185 VisitParmVarDecl(PD);
186 PD->setOriginalType(Reader.GetType(Record[Idx++]));
187}
188
Douglas Gregor2a491792009-04-13 22:49:25 +0000189void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
190 VisitDecl(AD);
191 // FIXME: read asm string
192}
193
194void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) {
195 VisitDecl(BD);
196 unsigned NumParams = Record[Idx++];
197 llvm::SmallVector<ParmVarDecl *, 16> Params;
198 Params.reserve(NumParams);
199 for (unsigned I = 0; I != NumParams; ++I)
200 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
201 BD->setParams(Reader.getContext(), &Params[0], NumParams);
202}
203
Douglas Gregorc34897d2009-04-09 22:27:44 +0000204std::pair<uint64_t, uint64_t>
205PCHDeclReader::VisitDeclContext(DeclContext *DC) {
206 uint64_t LexicalOffset = Record[Idx++];
207 uint64_t VisibleOffset = 0;
208 if (DC->getPrimaryContext() == DC)
209 VisibleOffset = Record[Idx++];
210 return std::make_pair(LexicalOffset, VisibleOffset);
211}
212
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000213//===----------------------------------------------------------------------===//
214// Statement/expression deserialization
215//===----------------------------------------------------------------------===//
216namespace {
217 class VISIBILITY_HIDDEN PCHStmtReader
218 : public StmtVisitor<PCHStmtReader, void> {
219 PCHReader &Reader;
220 const PCHReader::RecordData &Record;
221 unsigned &Idx;
222
223 public:
224 PCHStmtReader(PCHReader &Reader, const PCHReader::RecordData &Record,
225 unsigned &Idx)
226 : Reader(Reader), Record(Record), Idx(Idx) { }
227
228 void VisitExpr(Expr *E);
229 void VisitDeclRefExpr(DeclRefExpr *E);
230 void VisitIntegerLiteral(IntegerLiteral *E);
231 void VisitCharacterLiteral(CharacterLiteral *E);
232 };
233}
234
235void PCHStmtReader::VisitExpr(Expr *E) {
236 E->setType(Reader.GetType(Record[Idx++]));
237 E->setTypeDependent(Record[Idx++]);
238 E->setValueDependent(Record[Idx++]);
239}
240
241void PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
242 VisitExpr(E);
243 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
244 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
245}
246
247void PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
248 VisitExpr(E);
249 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
250 E->setValue(Reader.ReadAPInt(Record, Idx));
251}
252
253void PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
254 VisitExpr(E);
255 E->setValue(Record[Idx++]);
256 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
257 E->setWide(Record[Idx++]);
258}
259
Douglas Gregorc34897d2009-04-09 22:27:44 +0000260// FIXME: use the diagnostics machinery
261static bool Error(const char *Str) {
262 std::fprintf(stderr, "%s\n", Str);
263 return true;
264}
265
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000266/// \brief Check the contents of the predefines buffer against the
267/// contents of the predefines buffer used to build the PCH file.
268///
269/// The contents of the two predefines buffers should be the same. If
270/// not, then some command-line option changed the preprocessor state
271/// and we must reject the PCH file.
272///
273/// \param PCHPredef The start of the predefines buffer in the PCH
274/// file.
275///
276/// \param PCHPredefLen The length of the predefines buffer in the PCH
277/// file.
278///
279/// \param PCHBufferID The FileID for the PCH predefines buffer.
280///
281/// \returns true if there was a mismatch (in which case the PCH file
282/// should be ignored), or false otherwise.
283bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
284 unsigned PCHPredefLen,
285 FileID PCHBufferID) {
286 const char *Predef = PP.getPredefines().c_str();
287 unsigned PredefLen = PP.getPredefines().size();
288
289 // If the two predefines buffers compare equal, we're done!.
290 if (PredefLen == PCHPredefLen &&
291 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
292 return false;
293
294 // The predefines buffers are different. Produce a reasonable
295 // diagnostic showing where they are different.
296
297 // The source locations (potentially in the two different predefines
298 // buffers)
299 SourceLocation Loc1, Loc2;
300 SourceManager &SourceMgr = PP.getSourceManager();
301
302 // Create a source buffer for our predefines string, so
303 // that we can build a diagnostic that points into that
304 // source buffer.
305 FileID BufferID;
306 if (Predef && Predef[0]) {
307 llvm::MemoryBuffer *Buffer
308 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
309 "<built-in>");
310 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
311 }
312
313 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
314 std::pair<const char *, const char *> Locations
315 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
316
317 if (Locations.first != Predef + MinLen) {
318 // We found the location in the two buffers where there is a
319 // difference. Form source locations to point there (in both
320 // buffers).
321 unsigned Offset = Locations.first - Predef;
322 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
323 .getFileLocWithOffset(Offset);
324 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
325 .getFileLocWithOffset(Offset);
326 } else if (PredefLen > PCHPredefLen) {
327 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
328 .getFileLocWithOffset(MinLen);
329 } else {
330 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
331 .getFileLocWithOffset(MinLen);
332 }
333
334 Diag(Loc1, diag::warn_pch_preprocessor);
335 if (Loc2.isValid())
336 Diag(Loc2, diag::note_predef_in_pch);
337 Diag(diag::note_ignoring_pch) << FileName;
338 return true;
339}
340
Douglas Gregor635f97f2009-04-13 16:31:14 +0000341/// \brief Read the line table in the source manager block.
342/// \returns true if ther was an error.
343static bool ParseLineTable(SourceManager &SourceMgr,
344 llvm::SmallVectorImpl<uint64_t> &Record) {
345 unsigned Idx = 0;
346 LineTableInfo &LineTable = SourceMgr.getLineTable();
347
348 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000349 std::map<int, int> FileIDs;
350 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000351 // Extract the file name
352 unsigned FilenameLen = Record[Idx++];
353 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
354 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000355 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
356 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000357 }
358
359 // Parse the line entries
360 std::vector<LineEntry> Entries;
361 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000362 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000363
364 // Extract the line entries
365 unsigned NumEntries = Record[Idx++];
366 Entries.clear();
367 Entries.reserve(NumEntries);
368 for (unsigned I = 0; I != NumEntries; ++I) {
369 unsigned FileOffset = Record[Idx++];
370 unsigned LineNo = Record[Idx++];
371 int FilenameID = Record[Idx++];
372 SrcMgr::CharacteristicKind FileKind
373 = (SrcMgr::CharacteristicKind)Record[Idx++];
374 unsigned IncludeOffset = Record[Idx++];
375 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
376 FileKind, IncludeOffset));
377 }
378 LineTable.AddEntry(FID, Entries);
379 }
380
381 return false;
382}
383
Douglas Gregorab1cef72009-04-10 03:52:48 +0000384/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000385PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000386 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000387 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
388 Error("Malformed source manager block record");
389 return Failure;
390 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000391
392 SourceManager &SourceMgr = Context.getSourceManager();
393 RecordData Record;
394 while (true) {
395 unsigned Code = Stream.ReadCode();
396 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000397 if (Stream.ReadBlockEnd()) {
398 Error("Error at end of Source Manager block");
399 return Failure;
400 }
401
402 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000403 }
404
405 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
406 // No known subblocks, always skip them.
407 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000408 if (Stream.SkipBlock()) {
409 Error("Malformed block record");
410 return Failure;
411 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000412 continue;
413 }
414
415 if (Code == llvm::bitc::DEFINE_ABBREV) {
416 Stream.ReadAbbrevRecord();
417 continue;
418 }
419
420 // Read a record.
421 const char *BlobStart;
422 unsigned BlobLen;
423 Record.clear();
424 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
425 default: // Default behavior: ignore.
426 break;
427
428 case pch::SM_SLOC_FILE_ENTRY: {
429 // FIXME: We would really like to delay the creation of this
430 // FileEntry until it is actually required, e.g., when producing
431 // a diagnostic with a source location in this file.
432 const FileEntry *File
433 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
434 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000435 FileID ID = SourceMgr.createFileID(File,
436 SourceLocation::getFromRawEncoding(Record[1]),
437 (CharacteristicKind)Record[2]);
438 if (Record[3])
439 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
440 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000441 break;
442 }
443
444 case pch::SM_SLOC_BUFFER_ENTRY: {
445 const char *Name = BlobStart;
446 unsigned Code = Stream.ReadCode();
447 Record.clear();
448 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
449 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000450 llvm::MemoryBuffer *Buffer
451 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
452 BlobStart + BlobLen - 1,
453 Name);
454 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
455
456 if (strcmp(Name, "<built-in>") == 0
457 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
458 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000459 break;
460 }
461
462 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
463 SourceLocation SpellingLoc
464 = SourceLocation::getFromRawEncoding(Record[1]);
465 SourceMgr.createInstantiationLoc(
466 SpellingLoc,
467 SourceLocation::getFromRawEncoding(Record[2]),
468 SourceLocation::getFromRawEncoding(Record[3]),
469 Lexer::MeasureTokenLength(SpellingLoc,
470 SourceMgr));
471 break;
472 }
473
Douglas Gregor635f97f2009-04-13 16:31:14 +0000474 case pch::SM_LINE_TABLE: {
475 if (ParseLineTable(SourceMgr, Record))
476 return Failure;
477 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000478 }
479 }
480}
481
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000482bool PCHReader::ReadPreprocessorBlock() {
483 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
484 return Error("Malformed preprocessor block record");
485
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000486 RecordData Record;
487 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
488 MacroInfo *LastMacro = 0;
489
490 while (true) {
491 unsigned Code = Stream.ReadCode();
492 switch (Code) {
493 case llvm::bitc::END_BLOCK:
494 if (Stream.ReadBlockEnd())
495 return Error("Error at end of preprocessor block");
496 return false;
497
498 case llvm::bitc::ENTER_SUBBLOCK:
499 // No known subblocks, always skip them.
500 Stream.ReadSubBlockID();
501 if (Stream.SkipBlock())
502 return Error("Malformed block record");
503 continue;
504
505 case llvm::bitc::DEFINE_ABBREV:
506 Stream.ReadAbbrevRecord();
507 continue;
508 default: break;
509 }
510
511 // Read a record.
512 Record.clear();
513 pch::PreprocessorRecordTypes RecType =
514 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
515 switch (RecType) {
516 default: // Default behavior: ignore unknown records.
517 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000518 case pch::PP_COUNTER_VALUE:
519 if (!Record.empty())
520 PP.setCounterValue(Record[0]);
521 break;
522
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000523 case pch::PP_MACRO_OBJECT_LIKE:
524 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000525 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
526 if (II == 0)
527 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000528 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
529 bool isUsed = Record[2];
530
531 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
532 MI->setIsUsed(isUsed);
533
534 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
535 // Decode function-like macro info.
536 bool isC99VarArgs = Record[3];
537 bool isGNUVarArgs = Record[4];
538 MacroArgs.clear();
539 unsigned NumArgs = Record[5];
540 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000541 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000542
543 // Install function-like macro info.
544 MI->setIsFunctionLike();
545 if (isC99VarArgs) MI->setIsC99Varargs();
546 if (isGNUVarArgs) MI->setIsGNUVarargs();
547 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
548 PP.getPreprocessorAllocator());
549 }
550
551 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000552 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000553
554 // Remember that we saw this macro last so that we add the tokens that
555 // form its body to it.
556 LastMacro = MI;
557 break;
558 }
559
560 case pch::PP_TOKEN: {
561 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
562 // pretend we didn't see this.
563 if (LastMacro == 0) break;
564
565 Token Tok;
566 Tok.startToken();
567 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
568 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000569 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
570 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000571 Tok.setKind((tok::TokenKind)Record[3]);
572 Tok.setFlag((Token::TokenFlags)Record[4]);
573 LastMacro->AddTokenToBody(Tok);
574 break;
575 }
576 }
577 }
578}
579
Douglas Gregor179cfb12009-04-10 20:39:37 +0000580PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
581 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
582 Error("Malformed block record");
583 return Failure;
584 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000585
Chris Lattner29241862009-04-11 21:15:38 +0000586 uint64_t PreprocessorBlockBit = 0;
587
Douglas Gregorc34897d2009-04-09 22:27:44 +0000588 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000589 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000590 while (!Stream.AtEndOfStream()) {
591 unsigned Code = Stream.ReadCode();
592 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000593 // If we saw the preprocessor block, read it now.
594 if (PreprocessorBlockBit) {
595 uint64_t SavedPos = Stream.GetCurrentBitNo();
596 Stream.JumpToBit(PreprocessorBlockBit);
597 if (ReadPreprocessorBlock()) {
598 Error("Malformed preprocessor block");
599 return Failure;
600 }
601 Stream.JumpToBit(SavedPos);
602 }
603
Douglas Gregor179cfb12009-04-10 20:39:37 +0000604 if (Stream.ReadBlockEnd()) {
605 Error("Error at end of module block");
606 return Failure;
607 }
Chris Lattner29241862009-04-11 21:15:38 +0000608
Douglas Gregor179cfb12009-04-10 20:39:37 +0000609 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000610 }
611
612 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
613 switch (Stream.ReadSubBlockID()) {
614 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
615 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
616 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000617 if (Stream.SkipBlock()) {
618 Error("Malformed block record");
619 return Failure;
620 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000621 break;
622
Chris Lattner29241862009-04-11 21:15:38 +0000623 case pch::PREPROCESSOR_BLOCK_ID:
624 // Skip the preprocessor block for now, but remember where it is. We
625 // want to read it in after the identifier table.
626 if (PreprocessorBlockBit) {
627 Error("Multiple preprocessor blocks found.");
628 return Failure;
629 }
630 PreprocessorBlockBit = Stream.GetCurrentBitNo();
631 if (Stream.SkipBlock()) {
632 Error("Malformed block record");
633 return Failure;
634 }
635 break;
636
Douglas Gregorab1cef72009-04-10 03:52:48 +0000637 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000638 switch (ReadSourceManagerBlock()) {
639 case Success:
640 break;
641
642 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000643 Error("Malformed source manager block");
644 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000645
646 case IgnorePCH:
647 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000648 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000649 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000650 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000651 continue;
652 }
653
654 if (Code == llvm::bitc::DEFINE_ABBREV) {
655 Stream.ReadAbbrevRecord();
656 continue;
657 }
658
659 // Read and process a record.
660 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000661 const char *BlobStart = 0;
662 unsigned BlobLen = 0;
663 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
664 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000665 default: // Default behavior: ignore.
666 break;
667
668 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000669 if (!TypeOffsets.empty()) {
670 Error("Duplicate TYPE_OFFSET record in PCH file");
671 return Failure;
672 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000673 TypeOffsets.swap(Record);
674 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
675 break;
676
677 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000678 if (!DeclOffsets.empty()) {
679 Error("Duplicate DECL_OFFSET record in PCH file");
680 return Failure;
681 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000682 DeclOffsets.swap(Record);
683 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
684 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000685
686 case pch::LANGUAGE_OPTIONS:
687 if (ParseLanguageOptions(Record))
688 return IgnorePCH;
689 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000690
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000691 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000692 std::string TargetTriple(BlobStart, BlobLen);
693 if (TargetTriple != Context.Target.getTargetTriple()) {
694 Diag(diag::warn_pch_target_triple)
695 << TargetTriple << Context.Target.getTargetTriple();
696 Diag(diag::note_ignoring_pch) << FileName;
697 return IgnorePCH;
698 }
699 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000700 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000701
702 case pch::IDENTIFIER_TABLE:
703 IdentifierTable = BlobStart;
704 break;
705
706 case pch::IDENTIFIER_OFFSET:
707 if (!IdentifierData.empty()) {
708 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
709 return Failure;
710 }
711 IdentifierData.swap(Record);
712#ifndef NDEBUG
713 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
714 if ((IdentifierData[I] & 0x01) == 0) {
715 Error("Malformed identifier table in the precompiled header");
716 return Failure;
717 }
718 }
719#endif
720 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000721
722 case pch::EXTERNAL_DEFINITIONS:
723 if (!ExternalDefinitions.empty()) {
724 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
725 return Failure;
726 }
727 ExternalDefinitions.swap(Record);
728 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000729 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000730 }
731
Douglas Gregor179cfb12009-04-10 20:39:37 +0000732 Error("Premature end of bitstream");
733 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000734}
735
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000736PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000737 // Set the PCH file name.
738 this->FileName = FileName;
739
Douglas Gregorc34897d2009-04-09 22:27:44 +0000740 // Open the PCH file.
741 std::string ErrStr;
742 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000743 if (!Buffer) {
744 Error(ErrStr.c_str());
745 return IgnorePCH;
746 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000747
748 // Initialize the stream
749 Stream.init((const unsigned char *)Buffer->getBufferStart(),
750 (const unsigned char *)Buffer->getBufferEnd());
751
752 // Sniff for the signature.
753 if (Stream.Read(8) != 'C' ||
754 Stream.Read(8) != 'P' ||
755 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000756 Stream.Read(8) != 'H') {
757 Error("Not a PCH file");
758 return IgnorePCH;
759 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000760
761 // We expect a number of well-defined blocks, though we don't necessarily
762 // need to understand them all.
763 while (!Stream.AtEndOfStream()) {
764 unsigned Code = Stream.ReadCode();
765
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000766 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
767 Error("Invalid record at top-level");
768 return Failure;
769 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000770
771 unsigned BlockID = Stream.ReadSubBlockID();
772
773 // We only know the PCH subblock ID.
774 switch (BlockID) {
775 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000776 if (Stream.ReadBlockInfoBlock()) {
777 Error("Malformed BlockInfoBlock");
778 return Failure;
779 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000780 break;
781 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000782 switch (ReadPCHBlock()) {
783 case Success:
784 break;
785
786 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000787 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000788
789 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000790 // FIXME: We could consider reading through to the end of this
791 // PCH block, skipping subblocks, to see if there are other
792 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000793 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000794 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000795 break;
796 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000797 if (Stream.SkipBlock()) {
798 Error("Malformed block record");
799 return Failure;
800 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000801 break;
802 }
803 }
804
805 // Load the translation unit declaration
806 ReadDeclRecord(DeclOffsets[0], 0);
807
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000808 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000809}
810
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000811namespace {
812 /// \brief Helper class that saves the current stream position and
813 /// then restores it when destroyed.
814 struct VISIBILITY_HIDDEN SavedStreamPosition {
815 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
816 : Stream(Stream), Offset(Stream.GetCurrentBitNo()),
817 EndOfStream(Stream.AtEndOfStream()){ }
818
819 ~SavedStreamPosition() {
820 if (!EndOfStream)
821 Stream.JumpToBit(Offset);
822 }
823
824 private:
825 llvm::BitstreamReader &Stream;
826 uint64_t Offset;
827 bool EndOfStream;
828 };
829}
830
Douglas Gregor179cfb12009-04-10 20:39:37 +0000831/// \brief Parse the record that corresponds to a LangOptions data
832/// structure.
833///
834/// This routine compares the language options used to generate the
835/// PCH file against the language options set for the current
836/// compilation. For each option, we classify differences between the
837/// two compiler states as either "benign" or "important". Benign
838/// differences don't matter, and we accept them without complaint
839/// (and without modifying the language options). Differences between
840/// the states for important options cause the PCH file to be
841/// unusable, so we emit a warning and return true to indicate that
842/// there was an error.
843///
844/// \returns true if the PCH file is unacceptable, false otherwise.
845bool PCHReader::ParseLanguageOptions(
846 const llvm::SmallVectorImpl<uint64_t> &Record) {
847 const LangOptions &LangOpts = Context.getLangOptions();
848#define PARSE_LANGOPT_BENIGN(Option) ++Idx
849#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
850 if (Record[Idx] != LangOpts.Option) { \
851 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
852 Diag(diag::note_ignoring_pch) << FileName; \
853 return true; \
854 } \
855 ++Idx
856
857 unsigned Idx = 0;
858 PARSE_LANGOPT_BENIGN(Trigraphs);
859 PARSE_LANGOPT_BENIGN(BCPLComment);
860 PARSE_LANGOPT_BENIGN(DollarIdents);
861 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
862 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
863 PARSE_LANGOPT_BENIGN(ImplicitInt);
864 PARSE_LANGOPT_BENIGN(Digraphs);
865 PARSE_LANGOPT_BENIGN(HexFloats);
866 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
867 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
868 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
869 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
870 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
871 PARSE_LANGOPT_BENIGN(CXXOperatorName);
872 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
873 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
874 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
875 PARSE_LANGOPT_BENIGN(PascalStrings);
876 PARSE_LANGOPT_BENIGN(Boolean);
877 PARSE_LANGOPT_BENIGN(WritableStrings);
878 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
879 diag::warn_pch_lax_vector_conversions);
880 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
881 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
882 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
883 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
884 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
885 diag::warn_pch_thread_safe_statics);
886 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
887 PARSE_LANGOPT_BENIGN(EmitAllDecls);
888 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
889 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
890 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
891 diag::warn_pch_heinous_extensions);
892 // FIXME: Most of the options below are benign if the macro wasn't
893 // used. Unfortunately, this means that a PCH compiled without
894 // optimization can't be used with optimization turned on, even
895 // though the only thing that changes is whether __OPTIMIZE__ was
896 // defined... but if __OPTIMIZE__ never showed up in the header, it
897 // doesn't matter. We could consider making this some special kind
898 // of check.
899 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
900 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
901 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
902 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
903 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
904 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
905 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
906 Diag(diag::warn_pch_gc_mode)
907 << (unsigned)Record[Idx] << LangOpts.getGCMode();
908 Diag(diag::note_ignoring_pch) << FileName;
909 return true;
910 }
911 ++Idx;
912 PARSE_LANGOPT_BENIGN(getVisibilityMode());
913 PARSE_LANGOPT_BENIGN(InstantiationDepth);
914#undef PARSE_LANGOPT_IRRELEVANT
915#undef PARSE_LANGOPT_BENIGN
916
917 return false;
918}
919
Douglas Gregorc34897d2009-04-09 22:27:44 +0000920/// \brief Read and return the type at the given offset.
921///
922/// This routine actually reads the record corresponding to the type
923/// at the given offset in the bitstream. It is a helper routine for
924/// GetType, which deals with reading type IDs.
925QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000926 // Keep track of where we are in the stream, then jump back there
927 // after reading this type.
928 SavedStreamPosition SavedPosition(Stream);
929
Douglas Gregorc34897d2009-04-09 22:27:44 +0000930 Stream.JumpToBit(Offset);
931 RecordData Record;
932 unsigned Code = Stream.ReadCode();
933 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000934 case pch::TYPE_EXT_QUAL:
935 // FIXME: Deserialize ExtQualType
936 assert(false && "Cannot deserialize qualified types yet");
937 return QualType();
938
Douglas Gregorc34897d2009-04-09 22:27:44 +0000939 case pch::TYPE_FIXED_WIDTH_INT: {
940 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
941 return Context.getFixedWidthIntType(Record[0], Record[1]);
942 }
943
944 case pch::TYPE_COMPLEX: {
945 assert(Record.size() == 1 && "Incorrect encoding of complex type");
946 QualType ElemType = GetType(Record[0]);
947 return Context.getComplexType(ElemType);
948 }
949
950 case pch::TYPE_POINTER: {
951 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
952 QualType PointeeType = GetType(Record[0]);
953 return Context.getPointerType(PointeeType);
954 }
955
956 case pch::TYPE_BLOCK_POINTER: {
957 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
958 QualType PointeeType = GetType(Record[0]);
959 return Context.getBlockPointerType(PointeeType);
960 }
961
962 case pch::TYPE_LVALUE_REFERENCE: {
963 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
964 QualType PointeeType = GetType(Record[0]);
965 return Context.getLValueReferenceType(PointeeType);
966 }
967
968 case pch::TYPE_RVALUE_REFERENCE: {
969 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
970 QualType PointeeType = GetType(Record[0]);
971 return Context.getRValueReferenceType(PointeeType);
972 }
973
974 case pch::TYPE_MEMBER_POINTER: {
975 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
976 QualType PointeeType = GetType(Record[0]);
977 QualType ClassType = GetType(Record[1]);
978 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
979 }
980
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000981 case pch::TYPE_CONSTANT_ARRAY: {
982 QualType ElementType = GetType(Record[0]);
983 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
984 unsigned IndexTypeQuals = Record[2];
985 unsigned Idx = 3;
986 llvm::APInt Size = ReadAPInt(Record, Idx);
987 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
988 }
989
990 case pch::TYPE_INCOMPLETE_ARRAY: {
991 QualType ElementType = GetType(Record[0]);
992 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
993 unsigned IndexTypeQuals = Record[2];
994 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
995 }
996
997 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000998 QualType ElementType = GetType(Record[0]);
999 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1000 unsigned IndexTypeQuals = Record[2];
1001 return Context.getVariableArrayType(ElementType, ReadExpr(),
1002 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001003 }
1004
1005 case pch::TYPE_VECTOR: {
1006 if (Record.size() != 2) {
1007 Error("Incorrect encoding of vector type in PCH file");
1008 return QualType();
1009 }
1010
1011 QualType ElementType = GetType(Record[0]);
1012 unsigned NumElements = Record[1];
1013 return Context.getVectorType(ElementType, NumElements);
1014 }
1015
1016 case pch::TYPE_EXT_VECTOR: {
1017 if (Record.size() != 2) {
1018 Error("Incorrect encoding of extended vector type in PCH file");
1019 return QualType();
1020 }
1021
1022 QualType ElementType = GetType(Record[0]);
1023 unsigned NumElements = Record[1];
1024 return Context.getExtVectorType(ElementType, NumElements);
1025 }
1026
1027 case pch::TYPE_FUNCTION_NO_PROTO: {
1028 if (Record.size() != 1) {
1029 Error("Incorrect encoding of no-proto function type");
1030 return QualType();
1031 }
1032 QualType ResultType = GetType(Record[0]);
1033 return Context.getFunctionNoProtoType(ResultType);
1034 }
1035
1036 case pch::TYPE_FUNCTION_PROTO: {
1037 QualType ResultType = GetType(Record[0]);
1038 unsigned Idx = 1;
1039 unsigned NumParams = Record[Idx++];
1040 llvm::SmallVector<QualType, 16> ParamTypes;
1041 for (unsigned I = 0; I != NumParams; ++I)
1042 ParamTypes.push_back(GetType(Record[Idx++]));
1043 bool isVariadic = Record[Idx++];
1044 unsigned Quals = Record[Idx++];
1045 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1046 isVariadic, Quals);
1047 }
1048
1049 case pch::TYPE_TYPEDEF:
1050 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1051 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1052
1053 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001054 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001055
1056 case pch::TYPE_TYPEOF: {
1057 if (Record.size() != 1) {
1058 Error("Incorrect encoding of typeof(type) in PCH file");
1059 return QualType();
1060 }
1061 QualType UnderlyingType = GetType(Record[0]);
1062 return Context.getTypeOfType(UnderlyingType);
1063 }
1064
1065 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001066 assert(Record.size() == 1 && "Incorrect encoding of record type");
1067 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001068
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001069 case pch::TYPE_ENUM:
1070 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1071 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1072
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001073 case pch::TYPE_OBJC_INTERFACE:
1074 // FIXME: Deserialize ObjCInterfaceType
1075 assert(false && "Cannot de-serialize ObjC interface types yet");
1076 return QualType();
1077
1078 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1079 // FIXME: Deserialize ObjCQualifiedInterfaceType
1080 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1081 return QualType();
1082
1083 case pch::TYPE_OBJC_QUALIFIED_ID:
1084 // FIXME: Deserialize ObjCQualifiedIdType
1085 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1086 return QualType();
1087
1088 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1089 // FIXME: Deserialize ObjCQualifiedClassType
1090 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1091 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001092 }
1093
1094 // Suppress a GCC warning
1095 return QualType();
1096}
1097
1098/// \brief Note that we have loaded the declaration with the given
1099/// Index.
1100///
1101/// This routine notes that this declaration has already been loaded,
1102/// so that future GetDecl calls will return this declaration rather
1103/// than trying to load a new declaration.
1104inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1105 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1106 DeclAlreadyLoaded[Index] = true;
1107 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1108}
1109
1110/// \brief Read the declaration at the given offset from the PCH file.
1111Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001112 // Keep track of where we are in the stream, then jump back there
1113 // after reading this declaration.
1114 SavedStreamPosition SavedPosition(Stream);
1115
Douglas Gregorc34897d2009-04-09 22:27:44 +00001116 Decl *D = 0;
1117 Stream.JumpToBit(Offset);
1118 RecordData Record;
1119 unsigned Code = Stream.ReadCode();
1120 unsigned Idx = 0;
1121 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001122
Douglas Gregorc34897d2009-04-09 22:27:44 +00001123 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1124 case pch::DECL_TRANSLATION_UNIT:
1125 assert(Index == 0 && "Translation unit must be at index 0");
1126 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1127 D = Context.getTranslationUnitDecl();
1128 LoadedDecl(Index, D);
1129 break;
1130
1131 case pch::DECL_TYPEDEF: {
1132 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1133 0, QualType());
1134 LoadedDecl(Index, Typedef);
1135 Reader.VisitTypedefDecl(Typedef);
1136 D = Typedef;
1137 break;
1138 }
1139
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001140 case pch::DECL_ENUM: {
1141 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1142 LoadedDecl(Index, Enum);
1143 Reader.VisitEnumDecl(Enum);
1144 D = Enum;
1145 break;
1146 }
1147
Douglas Gregor982365e2009-04-13 21:20:57 +00001148 case pch::DECL_RECORD: {
1149 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1150 0, SourceLocation(), 0, 0);
1151 LoadedDecl(Index, Record);
1152 Reader.VisitRecordDecl(Record);
1153 D = Record;
1154 break;
1155 }
1156
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001157 case pch::DECL_ENUM_CONSTANT: {
1158 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1159 SourceLocation(), 0,
1160 QualType(), 0,
1161 llvm::APSInt());
1162 LoadedDecl(Index, ECD);
1163 Reader.VisitEnumConstantDecl(ECD);
1164 D = ECD;
1165 break;
1166 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001167
1168 case pch::DECL_FUNCTION: {
1169 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1170 DeclarationName(),
1171 QualType());
1172 LoadedDecl(Index, Function);
1173 Reader.VisitFunctionDecl(Function);
1174 D = Function;
1175 break;
1176 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001177
Douglas Gregor982365e2009-04-13 21:20:57 +00001178 case pch::DECL_FIELD: {
1179 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1180 QualType(), 0, false);
1181 LoadedDecl(Index, Field);
1182 Reader.VisitFieldDecl(Field);
1183 D = Field;
1184 break;
1185 }
1186
Douglas Gregorc34897d2009-04-09 22:27:44 +00001187 case pch::DECL_VAR: {
1188 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1189 VarDecl::None, SourceLocation());
1190 LoadedDecl(Index, Var);
1191 Reader.VisitVarDecl(Var);
1192 D = Var;
1193 break;
1194 }
1195
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001196 case pch::DECL_PARM_VAR: {
1197 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1198 QualType(), VarDecl::None, 0);
1199 LoadedDecl(Index, Parm);
1200 Reader.VisitParmVarDecl(Parm);
1201 D = Parm;
1202 break;
1203 }
1204
1205 case pch::DECL_ORIGINAL_PARM_VAR: {
1206 OriginalParmVarDecl *Parm
1207 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1208 QualType(), QualType(), VarDecl::None,
1209 0);
1210 LoadedDecl(Index, Parm);
1211 Reader.VisitOriginalParmVarDecl(Parm);
1212 D = Parm;
1213 break;
1214 }
1215
Douglas Gregor2a491792009-04-13 22:49:25 +00001216 case pch::DECL_FILE_SCOPE_ASM: {
1217 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1218 SourceLocation(), 0);
1219 LoadedDecl(Index, Asm);
1220 Reader.VisitFileScopeAsmDecl(Asm);
1221 D = Asm;
1222 break;
1223 }
1224
1225 case pch::DECL_BLOCK: {
1226 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1227 LoadedDecl(Index, Block);
1228 Reader.VisitBlockDecl(Block);
1229 D = Block;
1230 break;
1231 }
1232
Douglas Gregorc34897d2009-04-09 22:27:44 +00001233 default:
1234 assert(false && "Cannot de-serialize this kind of declaration");
1235 break;
1236 }
1237
1238 // If this declaration is also a declaration context, get the
1239 // offsets for its tables of lexical and visible declarations.
1240 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1241 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1242 if (Offsets.first || Offsets.second) {
1243 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1244 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1245 DeclContextOffsets[DC] = Offsets;
1246 }
1247 }
1248 assert(Idx == Record.size());
1249
1250 return D;
1251}
1252
Douglas Gregorac8f2802009-04-10 17:25:41 +00001253QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001254 unsigned Quals = ID & 0x07;
1255 unsigned Index = ID >> 3;
1256
1257 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1258 QualType T;
1259 switch ((pch::PredefinedTypeIDs)Index) {
1260 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1261 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1262 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1263
1264 case pch::PREDEF_TYPE_CHAR_U_ID:
1265 case pch::PREDEF_TYPE_CHAR_S_ID:
1266 // FIXME: Check that the signedness of CharTy is correct!
1267 T = Context.CharTy;
1268 break;
1269
1270 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1271 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1272 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1273 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1274 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1275 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1276 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1277 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1278 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1279 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1280 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1281 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1282 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1283 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1284 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1285 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1286 }
1287
1288 assert(!T.isNull() && "Unknown predefined type");
1289 return T.getQualifiedType(Quals);
1290 }
1291
1292 Index -= pch::NUM_PREDEF_TYPE_IDS;
1293 if (!TypeAlreadyLoaded[Index]) {
1294 // Load the type from the PCH file.
1295 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1296 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1297 TypeAlreadyLoaded[Index] = true;
1298 }
1299
1300 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1301}
1302
Douglas Gregorac8f2802009-04-10 17:25:41 +00001303Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001304 if (ID == 0)
1305 return 0;
1306
1307 unsigned Index = ID - 1;
1308 if (DeclAlreadyLoaded[Index])
1309 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1310
1311 // Load the declaration from the PCH file.
1312 return ReadDeclRecord(DeclOffsets[Index], Index);
1313}
1314
1315bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001316 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001317 assert(DC->hasExternalLexicalStorage() &&
1318 "DeclContext has no lexical decls in storage");
1319 uint64_t Offset = DeclContextOffsets[DC].first;
1320 assert(Offset && "DeclContext has no lexical decls in storage");
1321
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001322 // Keep track of where we are in the stream, then jump back there
1323 // after reading this context.
1324 SavedStreamPosition SavedPosition(Stream);
1325
Douglas Gregorc34897d2009-04-09 22:27:44 +00001326 // Load the record containing all of the declarations lexically in
1327 // this context.
1328 Stream.JumpToBit(Offset);
1329 RecordData Record;
1330 unsigned Code = Stream.ReadCode();
1331 unsigned RecCode = Stream.ReadRecord(Code, Record);
1332 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1333
1334 // Load all of the declaration IDs
1335 Decls.clear();
1336 Decls.insert(Decls.end(), Record.begin(), Record.end());
1337 return false;
1338}
1339
1340bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1341 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1342 assert(DC->hasExternalVisibleStorage() &&
1343 "DeclContext has no visible decls in storage");
1344 uint64_t Offset = DeclContextOffsets[DC].second;
1345 assert(Offset && "DeclContext has no visible decls in storage");
1346
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001347 // Keep track of where we are in the stream, then jump back there
1348 // after reading this context.
1349 SavedStreamPosition SavedPosition(Stream);
1350
Douglas Gregorc34897d2009-04-09 22:27:44 +00001351 // Load the record containing all of the declarations visible in
1352 // this context.
1353 Stream.JumpToBit(Offset);
1354 RecordData Record;
1355 unsigned Code = Stream.ReadCode();
1356 unsigned RecCode = Stream.ReadRecord(Code, Record);
1357 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1358 if (Record.size() == 0)
1359 return false;
1360
1361 Decls.clear();
1362
1363 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001364 while (Idx < Record.size()) {
1365 Decls.push_back(VisibleDeclaration());
1366 Decls.back().Name = ReadDeclarationName(Record, Idx);
1367
Douglas Gregorc34897d2009-04-09 22:27:44 +00001368 unsigned Size = Record[Idx++];
1369 llvm::SmallVector<unsigned, 4> & LoadedDecls
1370 = Decls.back().Declarations;
1371 LoadedDecls.reserve(Size);
1372 for (unsigned I = 0; I < Size; ++I)
1373 LoadedDecls.push_back(Record[Idx++]);
1374 }
1375
1376 return false;
1377}
1378
Douglas Gregor631f6c62009-04-14 00:24:19 +00001379void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1380 if (!Consumer)
1381 return;
1382
1383 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1384 Decl *D = GetDecl(ExternalDefinitions[I]);
1385 DeclGroupRef DG(D);
1386 Consumer->HandleTopLevelDecl(DG);
1387 }
1388}
1389
Douglas Gregorc34897d2009-04-09 22:27:44 +00001390void PCHReader::PrintStats() {
1391 std::fprintf(stderr, "*** PCH Statistics:\n");
1392
1393 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1394 TypeAlreadyLoaded.end(),
1395 true);
1396 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1397 DeclAlreadyLoaded.end(),
1398 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001399 unsigned NumIdentifiersLoaded = 0;
1400 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1401 if ((IdentifierData[I] & 0x01) == 0)
1402 ++NumIdentifiersLoaded;
1403 }
1404
Douglas Gregorc34897d2009-04-09 22:27:44 +00001405 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1406 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001407 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001408 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1409 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001410 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1411 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1412 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1413 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001414 std::fprintf(stderr, "\n");
1415}
1416
Chris Lattner29241862009-04-11 21:15:38 +00001417IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001418 if (ID == 0)
1419 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001420
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001421 if (!IdentifierTable || IdentifierData.empty()) {
1422 Error("No identifier table in PCH file");
1423 return 0;
1424 }
Chris Lattner29241862009-04-11 21:15:38 +00001425
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001426 if (IdentifierData[ID - 1] & 0x01) {
1427 uint64_t Offset = IdentifierData[ID - 1];
1428 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001429 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001430 }
Chris Lattner29241862009-04-11 21:15:38 +00001431
1432 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001433}
1434
1435DeclarationName
1436PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1437 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1438 switch (Kind) {
1439 case DeclarationName::Identifier:
1440 return DeclarationName(GetIdentifierInfo(Record, Idx));
1441
1442 case DeclarationName::ObjCZeroArgSelector:
1443 case DeclarationName::ObjCOneArgSelector:
1444 case DeclarationName::ObjCMultiArgSelector:
1445 assert(false && "Unable to de-serialize Objective-C selectors");
1446 break;
1447
1448 case DeclarationName::CXXConstructorName:
1449 return Context.DeclarationNames.getCXXConstructorName(
1450 GetType(Record[Idx++]));
1451
1452 case DeclarationName::CXXDestructorName:
1453 return Context.DeclarationNames.getCXXDestructorName(
1454 GetType(Record[Idx++]));
1455
1456 case DeclarationName::CXXConversionFunctionName:
1457 return Context.DeclarationNames.getCXXConversionFunctionName(
1458 GetType(Record[Idx++]));
1459
1460 case DeclarationName::CXXOperatorName:
1461 return Context.DeclarationNames.getCXXOperatorName(
1462 (OverloadedOperatorKind)Record[Idx++]);
1463
1464 case DeclarationName::CXXUsingDirective:
1465 return DeclarationName::getUsingDirectiveName();
1466 }
1467
1468 // Required to silence GCC warning
1469 return DeclarationName();
1470}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001471
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001472/// \brief Read an integral value
1473llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1474 unsigned BitWidth = Record[Idx++];
1475 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1476 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1477 Idx += NumWords;
1478 return Result;
1479}
1480
1481/// \brief Read a signed integral value
1482llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1483 bool isUnsigned = Record[Idx++];
1484 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1485}
1486
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001487Expr *PCHReader::ReadExpr() {
1488 RecordData Record;
1489 unsigned Code = Stream.ReadCode();
1490 unsigned Idx = 0;
1491 PCHStmtReader Reader(*this, Record, Idx);
1492 Stmt::EmptyShell Empty;
1493
1494 Expr *E = 0;
1495 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1496 case pch::EXPR_NULL:
1497 E = 0;
1498 break;
1499
1500 case pch::EXPR_DECL_REF:
1501 E = new (Context) DeclRefExpr(Empty);
1502 break;
1503
1504 case pch::EXPR_INTEGER_LITERAL:
1505 E = new (Context) IntegerLiteral(Empty);
1506 break;
1507
1508 case pch::EXPR_CHARACTER_LITERAL:
1509 E = new (Context) CharacterLiteral(Empty);
1510 break;
1511
1512 default:
1513 assert(false && "Unhandled expression kind");
1514 break;
1515 }
1516
1517 if (E)
1518 Reader.Visit(E);
1519
1520 assert(Idx == Record.size() && "Invalid deserialization of expression");
1521
1522 return E;
1523}
1524
Douglas Gregor179cfb12009-04-10 20:39:37 +00001525DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001526 return Diag(SourceLocation(), DiagID);
1527}
1528
1529DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1530 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001531 Context.getSourceManager()),
1532 DiagID);
1533}