blob: b0b35e491b417d16fbddbdcd5e13a26227f7144c [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);
Douglas Gregore2f37202009-04-14 21:55:33 +0000229 void VisitPredefinedExpr(PredefinedExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000230 void VisitDeclRefExpr(DeclRefExpr *E);
231 void VisitIntegerLiteral(IntegerLiteral *E);
Douglas Gregore2f37202009-04-14 21:55:33 +0000232 void VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000233 void VisitCharacterLiteral(CharacterLiteral *E);
234 };
235}
236
237void PCHStmtReader::VisitExpr(Expr *E) {
238 E->setType(Reader.GetType(Record[Idx++]));
239 E->setTypeDependent(Record[Idx++]);
240 E->setValueDependent(Record[Idx++]);
241}
242
Douglas Gregore2f37202009-04-14 21:55:33 +0000243void PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
244 VisitExpr(E);
245 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
246 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
247}
248
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000249void PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
250 VisitExpr(E);
251 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
252 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
253}
254
255void PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
256 VisitExpr(E);
257 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
258 E->setValue(Reader.ReadAPInt(Record, Idx));
259}
260
Douglas Gregore2f37202009-04-14 21:55:33 +0000261void PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
262 VisitExpr(E);
263 E->setValue(Reader.ReadAPFloat(Record, Idx));
264 E->setExact(Record[Idx++]);
265 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
266}
267
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000268void PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
269 VisitExpr(E);
270 E->setValue(Record[Idx++]);
271 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
272 E->setWide(Record[Idx++]);
273}
274
Douglas Gregorc34897d2009-04-09 22:27:44 +0000275// FIXME: use the diagnostics machinery
276static bool Error(const char *Str) {
277 std::fprintf(stderr, "%s\n", Str);
278 return true;
279}
280
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000281/// \brief Check the contents of the predefines buffer against the
282/// contents of the predefines buffer used to build the PCH file.
283///
284/// The contents of the two predefines buffers should be the same. If
285/// not, then some command-line option changed the preprocessor state
286/// and we must reject the PCH file.
287///
288/// \param PCHPredef The start of the predefines buffer in the PCH
289/// file.
290///
291/// \param PCHPredefLen The length of the predefines buffer in the PCH
292/// file.
293///
294/// \param PCHBufferID The FileID for the PCH predefines buffer.
295///
296/// \returns true if there was a mismatch (in which case the PCH file
297/// should be ignored), or false otherwise.
298bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
299 unsigned PCHPredefLen,
300 FileID PCHBufferID) {
301 const char *Predef = PP.getPredefines().c_str();
302 unsigned PredefLen = PP.getPredefines().size();
303
304 // If the two predefines buffers compare equal, we're done!.
305 if (PredefLen == PCHPredefLen &&
306 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
307 return false;
308
309 // The predefines buffers are different. Produce a reasonable
310 // diagnostic showing where they are different.
311
312 // The source locations (potentially in the two different predefines
313 // buffers)
314 SourceLocation Loc1, Loc2;
315 SourceManager &SourceMgr = PP.getSourceManager();
316
317 // Create a source buffer for our predefines string, so
318 // that we can build a diagnostic that points into that
319 // source buffer.
320 FileID BufferID;
321 if (Predef && Predef[0]) {
322 llvm::MemoryBuffer *Buffer
323 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
324 "<built-in>");
325 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
326 }
327
328 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
329 std::pair<const char *, const char *> Locations
330 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
331
332 if (Locations.first != Predef + MinLen) {
333 // We found the location in the two buffers where there is a
334 // difference. Form source locations to point there (in both
335 // buffers).
336 unsigned Offset = Locations.first - Predef;
337 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
338 .getFileLocWithOffset(Offset);
339 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
340 .getFileLocWithOffset(Offset);
341 } else if (PredefLen > PCHPredefLen) {
342 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
343 .getFileLocWithOffset(MinLen);
344 } else {
345 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
346 .getFileLocWithOffset(MinLen);
347 }
348
349 Diag(Loc1, diag::warn_pch_preprocessor);
350 if (Loc2.isValid())
351 Diag(Loc2, diag::note_predef_in_pch);
352 Diag(diag::note_ignoring_pch) << FileName;
353 return true;
354}
355
Douglas Gregor635f97f2009-04-13 16:31:14 +0000356/// \brief Read the line table in the source manager block.
357/// \returns true if ther was an error.
358static bool ParseLineTable(SourceManager &SourceMgr,
359 llvm::SmallVectorImpl<uint64_t> &Record) {
360 unsigned Idx = 0;
361 LineTableInfo &LineTable = SourceMgr.getLineTable();
362
363 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000364 std::map<int, int> FileIDs;
365 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000366 // Extract the file name
367 unsigned FilenameLen = Record[Idx++];
368 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
369 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000370 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
371 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000372 }
373
374 // Parse the line entries
375 std::vector<LineEntry> Entries;
376 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000377 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000378
379 // Extract the line entries
380 unsigned NumEntries = Record[Idx++];
381 Entries.clear();
382 Entries.reserve(NumEntries);
383 for (unsigned I = 0; I != NumEntries; ++I) {
384 unsigned FileOffset = Record[Idx++];
385 unsigned LineNo = Record[Idx++];
386 int FilenameID = Record[Idx++];
387 SrcMgr::CharacteristicKind FileKind
388 = (SrcMgr::CharacteristicKind)Record[Idx++];
389 unsigned IncludeOffset = Record[Idx++];
390 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
391 FileKind, IncludeOffset));
392 }
393 LineTable.AddEntry(FID, Entries);
394 }
395
396 return false;
397}
398
Douglas Gregorab1cef72009-04-10 03:52:48 +0000399/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000400PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000401 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000402 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
403 Error("Malformed source manager block record");
404 return Failure;
405 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000406
407 SourceManager &SourceMgr = Context.getSourceManager();
408 RecordData Record;
409 while (true) {
410 unsigned Code = Stream.ReadCode();
411 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000412 if (Stream.ReadBlockEnd()) {
413 Error("Error at end of Source Manager block");
414 return Failure;
415 }
416
417 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000418 }
419
420 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
421 // No known subblocks, always skip them.
422 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000423 if (Stream.SkipBlock()) {
424 Error("Malformed block record");
425 return Failure;
426 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000427 continue;
428 }
429
430 if (Code == llvm::bitc::DEFINE_ABBREV) {
431 Stream.ReadAbbrevRecord();
432 continue;
433 }
434
435 // Read a record.
436 const char *BlobStart;
437 unsigned BlobLen;
438 Record.clear();
439 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
440 default: // Default behavior: ignore.
441 break;
442
443 case pch::SM_SLOC_FILE_ENTRY: {
444 // FIXME: We would really like to delay the creation of this
445 // FileEntry until it is actually required, e.g., when producing
446 // a diagnostic with a source location in this file.
447 const FileEntry *File
448 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
449 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000450 FileID ID = SourceMgr.createFileID(File,
451 SourceLocation::getFromRawEncoding(Record[1]),
452 (CharacteristicKind)Record[2]);
453 if (Record[3])
454 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
455 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000456 break;
457 }
458
459 case pch::SM_SLOC_BUFFER_ENTRY: {
460 const char *Name = BlobStart;
461 unsigned Code = Stream.ReadCode();
462 Record.clear();
463 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
464 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000465 llvm::MemoryBuffer *Buffer
466 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
467 BlobStart + BlobLen - 1,
468 Name);
469 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
470
471 if (strcmp(Name, "<built-in>") == 0
472 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
473 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000474 break;
475 }
476
477 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
478 SourceLocation SpellingLoc
479 = SourceLocation::getFromRawEncoding(Record[1]);
480 SourceMgr.createInstantiationLoc(
481 SpellingLoc,
482 SourceLocation::getFromRawEncoding(Record[2]),
483 SourceLocation::getFromRawEncoding(Record[3]),
484 Lexer::MeasureTokenLength(SpellingLoc,
Chris Lattnere1be6022009-04-14 23:22:57 +0000485 SourceMgr,
486 PP.getLangOptions()));
Douglas Gregorab1cef72009-04-10 03:52:48 +0000487 break;
488 }
489
Chris Lattnere1be6022009-04-14 23:22:57 +0000490 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000491 if (ParseLineTable(SourceMgr, Record))
492 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000493 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000494 }
495 }
496}
497
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000498bool PCHReader::ReadPreprocessorBlock() {
499 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
500 return Error("Malformed preprocessor block record");
501
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000502 RecordData Record;
503 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
504 MacroInfo *LastMacro = 0;
505
506 while (true) {
507 unsigned Code = Stream.ReadCode();
508 switch (Code) {
509 case llvm::bitc::END_BLOCK:
510 if (Stream.ReadBlockEnd())
511 return Error("Error at end of preprocessor block");
512 return false;
513
514 case llvm::bitc::ENTER_SUBBLOCK:
515 // No known subblocks, always skip them.
516 Stream.ReadSubBlockID();
517 if (Stream.SkipBlock())
518 return Error("Malformed block record");
519 continue;
520
521 case llvm::bitc::DEFINE_ABBREV:
522 Stream.ReadAbbrevRecord();
523 continue;
524 default: break;
525 }
526
527 // Read a record.
528 Record.clear();
529 pch::PreprocessorRecordTypes RecType =
530 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
531 switch (RecType) {
532 default: // Default behavior: ignore unknown records.
533 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000534 case pch::PP_COUNTER_VALUE:
535 if (!Record.empty())
536 PP.setCounterValue(Record[0]);
537 break;
538
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000539 case pch::PP_MACRO_OBJECT_LIKE:
540 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000541 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
542 if (II == 0)
543 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000544 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
545 bool isUsed = Record[2];
546
547 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
548 MI->setIsUsed(isUsed);
549
550 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
551 // Decode function-like macro info.
552 bool isC99VarArgs = Record[3];
553 bool isGNUVarArgs = Record[4];
554 MacroArgs.clear();
555 unsigned NumArgs = Record[5];
556 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000557 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000558
559 // Install function-like macro info.
560 MI->setIsFunctionLike();
561 if (isC99VarArgs) MI->setIsC99Varargs();
562 if (isGNUVarArgs) MI->setIsGNUVarargs();
563 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
564 PP.getPreprocessorAllocator());
565 }
566
567 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000568 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000569
570 // Remember that we saw this macro last so that we add the tokens that
571 // form its body to it.
572 LastMacro = MI;
573 break;
574 }
575
576 case pch::PP_TOKEN: {
577 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
578 // pretend we didn't see this.
579 if (LastMacro == 0) break;
580
581 Token Tok;
582 Tok.startToken();
583 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
584 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000585 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
586 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000587 Tok.setKind((tok::TokenKind)Record[3]);
588 Tok.setFlag((Token::TokenFlags)Record[4]);
589 LastMacro->AddTokenToBody(Tok);
590 break;
591 }
592 }
593 }
594}
595
Douglas Gregor179cfb12009-04-10 20:39:37 +0000596PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
597 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
598 Error("Malformed block record");
599 return Failure;
600 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000601
Chris Lattner29241862009-04-11 21:15:38 +0000602 uint64_t PreprocessorBlockBit = 0;
603
Douglas Gregorc34897d2009-04-09 22:27:44 +0000604 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000605 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000606 while (!Stream.AtEndOfStream()) {
607 unsigned Code = Stream.ReadCode();
608 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000609 // If we saw the preprocessor block, read it now.
610 if (PreprocessorBlockBit) {
611 uint64_t SavedPos = Stream.GetCurrentBitNo();
612 Stream.JumpToBit(PreprocessorBlockBit);
613 if (ReadPreprocessorBlock()) {
614 Error("Malformed preprocessor block");
615 return Failure;
616 }
617 Stream.JumpToBit(SavedPos);
618 }
619
Douglas Gregor179cfb12009-04-10 20:39:37 +0000620 if (Stream.ReadBlockEnd()) {
621 Error("Error at end of module block");
622 return Failure;
623 }
Chris Lattner29241862009-04-11 21:15:38 +0000624
Douglas Gregor179cfb12009-04-10 20:39:37 +0000625 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000626 }
627
628 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
629 switch (Stream.ReadSubBlockID()) {
630 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
631 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
632 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000633 if (Stream.SkipBlock()) {
634 Error("Malformed block record");
635 return Failure;
636 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000637 break;
638
Chris Lattner29241862009-04-11 21:15:38 +0000639 case pch::PREPROCESSOR_BLOCK_ID:
640 // Skip the preprocessor block for now, but remember where it is. We
641 // want to read it in after the identifier table.
642 if (PreprocessorBlockBit) {
643 Error("Multiple preprocessor blocks found.");
644 return Failure;
645 }
646 PreprocessorBlockBit = Stream.GetCurrentBitNo();
647 if (Stream.SkipBlock()) {
648 Error("Malformed block record");
649 return Failure;
650 }
651 break;
652
Douglas Gregorab1cef72009-04-10 03:52:48 +0000653 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000654 switch (ReadSourceManagerBlock()) {
655 case Success:
656 break;
657
658 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000659 Error("Malformed source manager block");
660 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000661
662 case IgnorePCH:
663 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000664 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000665 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000666 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000667 continue;
668 }
669
670 if (Code == llvm::bitc::DEFINE_ABBREV) {
671 Stream.ReadAbbrevRecord();
672 continue;
673 }
674
675 // Read and process a record.
676 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000677 const char *BlobStart = 0;
678 unsigned BlobLen = 0;
679 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
680 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000681 default: // Default behavior: ignore.
682 break;
683
684 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000685 if (!TypeOffsets.empty()) {
686 Error("Duplicate TYPE_OFFSET record in PCH file");
687 return Failure;
688 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000689 TypeOffsets.swap(Record);
690 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
691 break;
692
693 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000694 if (!DeclOffsets.empty()) {
695 Error("Duplicate DECL_OFFSET record in PCH file");
696 return Failure;
697 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000698 DeclOffsets.swap(Record);
699 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
700 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000701
702 case pch::LANGUAGE_OPTIONS:
703 if (ParseLanguageOptions(Record))
704 return IgnorePCH;
705 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000706
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000707 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000708 std::string TargetTriple(BlobStart, BlobLen);
709 if (TargetTriple != Context.Target.getTargetTriple()) {
710 Diag(diag::warn_pch_target_triple)
711 << TargetTriple << Context.Target.getTargetTriple();
712 Diag(diag::note_ignoring_pch) << FileName;
713 return IgnorePCH;
714 }
715 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000716 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000717
718 case pch::IDENTIFIER_TABLE:
719 IdentifierTable = BlobStart;
720 break;
721
722 case pch::IDENTIFIER_OFFSET:
723 if (!IdentifierData.empty()) {
724 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
725 return Failure;
726 }
727 IdentifierData.swap(Record);
728#ifndef NDEBUG
729 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
730 if ((IdentifierData[I] & 0x01) == 0) {
731 Error("Malformed identifier table in the precompiled header");
732 return Failure;
733 }
734 }
735#endif
736 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000737
738 case pch::EXTERNAL_DEFINITIONS:
739 if (!ExternalDefinitions.empty()) {
740 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
741 return Failure;
742 }
743 ExternalDefinitions.swap(Record);
744 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000745 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000746 }
747
Douglas Gregor179cfb12009-04-10 20:39:37 +0000748 Error("Premature end of bitstream");
749 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000750}
751
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000752PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000753 // Set the PCH file name.
754 this->FileName = FileName;
755
Douglas Gregorc34897d2009-04-09 22:27:44 +0000756 // Open the PCH file.
757 std::string ErrStr;
758 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000759 if (!Buffer) {
760 Error(ErrStr.c_str());
761 return IgnorePCH;
762 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000763
764 // Initialize the stream
765 Stream.init((const unsigned char *)Buffer->getBufferStart(),
766 (const unsigned char *)Buffer->getBufferEnd());
767
768 // Sniff for the signature.
769 if (Stream.Read(8) != 'C' ||
770 Stream.Read(8) != 'P' ||
771 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000772 Stream.Read(8) != 'H') {
773 Error("Not a PCH file");
774 return IgnorePCH;
775 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000776
777 // We expect a number of well-defined blocks, though we don't necessarily
778 // need to understand them all.
779 while (!Stream.AtEndOfStream()) {
780 unsigned Code = Stream.ReadCode();
781
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000782 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
783 Error("Invalid record at top-level");
784 return Failure;
785 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000786
787 unsigned BlockID = Stream.ReadSubBlockID();
788
789 // We only know the PCH subblock ID.
790 switch (BlockID) {
791 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000792 if (Stream.ReadBlockInfoBlock()) {
793 Error("Malformed BlockInfoBlock");
794 return Failure;
795 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000796 break;
797 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000798 switch (ReadPCHBlock()) {
799 case Success:
800 break;
801
802 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000803 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000804
805 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000806 // FIXME: We could consider reading through to the end of this
807 // PCH block, skipping subblocks, to see if there are other
808 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000809 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000810 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000811 break;
812 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000813 if (Stream.SkipBlock()) {
814 Error("Malformed block record");
815 return Failure;
816 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000817 break;
818 }
819 }
820
821 // Load the translation unit declaration
822 ReadDeclRecord(DeclOffsets[0], 0);
823
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000824 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000825}
826
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000827namespace {
828 /// \brief Helper class that saves the current stream position and
829 /// then restores it when destroyed.
830 struct VISIBILITY_HIDDEN SavedStreamPosition {
831 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
832 : Stream(Stream), Offset(Stream.GetCurrentBitNo()),
833 EndOfStream(Stream.AtEndOfStream()){ }
834
835 ~SavedStreamPosition() {
836 if (!EndOfStream)
837 Stream.JumpToBit(Offset);
838 }
839
840 private:
841 llvm::BitstreamReader &Stream;
842 uint64_t Offset;
843 bool EndOfStream;
844 };
845}
846
Douglas Gregor179cfb12009-04-10 20:39:37 +0000847/// \brief Parse the record that corresponds to a LangOptions data
848/// structure.
849///
850/// This routine compares the language options used to generate the
851/// PCH file against the language options set for the current
852/// compilation. For each option, we classify differences between the
853/// two compiler states as either "benign" or "important". Benign
854/// differences don't matter, and we accept them without complaint
855/// (and without modifying the language options). Differences between
856/// the states for important options cause the PCH file to be
857/// unusable, so we emit a warning and return true to indicate that
858/// there was an error.
859///
860/// \returns true if the PCH file is unacceptable, false otherwise.
861bool PCHReader::ParseLanguageOptions(
862 const llvm::SmallVectorImpl<uint64_t> &Record) {
863 const LangOptions &LangOpts = Context.getLangOptions();
864#define PARSE_LANGOPT_BENIGN(Option) ++Idx
865#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
866 if (Record[Idx] != LangOpts.Option) { \
867 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
868 Diag(diag::note_ignoring_pch) << FileName; \
869 return true; \
870 } \
871 ++Idx
872
873 unsigned Idx = 0;
874 PARSE_LANGOPT_BENIGN(Trigraphs);
875 PARSE_LANGOPT_BENIGN(BCPLComment);
876 PARSE_LANGOPT_BENIGN(DollarIdents);
877 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
878 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
879 PARSE_LANGOPT_BENIGN(ImplicitInt);
880 PARSE_LANGOPT_BENIGN(Digraphs);
881 PARSE_LANGOPT_BENIGN(HexFloats);
882 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
883 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
884 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
885 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
886 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
887 PARSE_LANGOPT_BENIGN(CXXOperatorName);
888 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
889 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
890 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
891 PARSE_LANGOPT_BENIGN(PascalStrings);
892 PARSE_LANGOPT_BENIGN(Boolean);
893 PARSE_LANGOPT_BENIGN(WritableStrings);
894 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
895 diag::warn_pch_lax_vector_conversions);
896 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
897 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
898 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
899 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
900 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
901 diag::warn_pch_thread_safe_statics);
902 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
903 PARSE_LANGOPT_BENIGN(EmitAllDecls);
904 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
905 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
906 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
907 diag::warn_pch_heinous_extensions);
908 // FIXME: Most of the options below are benign if the macro wasn't
909 // used. Unfortunately, this means that a PCH compiled without
910 // optimization can't be used with optimization turned on, even
911 // though the only thing that changes is whether __OPTIMIZE__ was
912 // defined... but if __OPTIMIZE__ never showed up in the header, it
913 // doesn't matter. We could consider making this some special kind
914 // of check.
915 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
916 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
917 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
918 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
919 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
920 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
921 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
922 Diag(diag::warn_pch_gc_mode)
923 << (unsigned)Record[Idx] << LangOpts.getGCMode();
924 Diag(diag::note_ignoring_pch) << FileName;
925 return true;
926 }
927 ++Idx;
928 PARSE_LANGOPT_BENIGN(getVisibilityMode());
929 PARSE_LANGOPT_BENIGN(InstantiationDepth);
930#undef PARSE_LANGOPT_IRRELEVANT
931#undef PARSE_LANGOPT_BENIGN
932
933 return false;
934}
935
Douglas Gregorc34897d2009-04-09 22:27:44 +0000936/// \brief Read and return the type at the given offset.
937///
938/// This routine actually reads the record corresponding to the type
939/// at the given offset in the bitstream. It is a helper routine for
940/// GetType, which deals with reading type IDs.
941QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000942 // Keep track of where we are in the stream, then jump back there
943 // after reading this type.
944 SavedStreamPosition SavedPosition(Stream);
945
Douglas Gregorc34897d2009-04-09 22:27:44 +0000946 Stream.JumpToBit(Offset);
947 RecordData Record;
948 unsigned Code = Stream.ReadCode();
949 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000950 case pch::TYPE_EXT_QUAL:
951 // FIXME: Deserialize ExtQualType
952 assert(false && "Cannot deserialize qualified types yet");
953 return QualType();
954
Douglas Gregorc34897d2009-04-09 22:27:44 +0000955 case pch::TYPE_FIXED_WIDTH_INT: {
956 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
957 return Context.getFixedWidthIntType(Record[0], Record[1]);
958 }
959
960 case pch::TYPE_COMPLEX: {
961 assert(Record.size() == 1 && "Incorrect encoding of complex type");
962 QualType ElemType = GetType(Record[0]);
963 return Context.getComplexType(ElemType);
964 }
965
966 case pch::TYPE_POINTER: {
967 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
968 QualType PointeeType = GetType(Record[0]);
969 return Context.getPointerType(PointeeType);
970 }
971
972 case pch::TYPE_BLOCK_POINTER: {
973 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
974 QualType PointeeType = GetType(Record[0]);
975 return Context.getBlockPointerType(PointeeType);
976 }
977
978 case pch::TYPE_LVALUE_REFERENCE: {
979 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
980 QualType PointeeType = GetType(Record[0]);
981 return Context.getLValueReferenceType(PointeeType);
982 }
983
984 case pch::TYPE_RVALUE_REFERENCE: {
985 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
986 QualType PointeeType = GetType(Record[0]);
987 return Context.getRValueReferenceType(PointeeType);
988 }
989
990 case pch::TYPE_MEMBER_POINTER: {
991 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
992 QualType PointeeType = GetType(Record[0]);
993 QualType ClassType = GetType(Record[1]);
994 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
995 }
996
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000997 case pch::TYPE_CONSTANT_ARRAY: {
998 QualType ElementType = GetType(Record[0]);
999 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1000 unsigned IndexTypeQuals = Record[2];
1001 unsigned Idx = 3;
1002 llvm::APInt Size = ReadAPInt(Record, Idx);
1003 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1004 }
1005
1006 case pch::TYPE_INCOMPLETE_ARRAY: {
1007 QualType ElementType = GetType(Record[0]);
1008 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1009 unsigned IndexTypeQuals = Record[2];
1010 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1011 }
1012
1013 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001014 QualType ElementType = GetType(Record[0]);
1015 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1016 unsigned IndexTypeQuals = Record[2];
1017 return Context.getVariableArrayType(ElementType, ReadExpr(),
1018 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001019 }
1020
1021 case pch::TYPE_VECTOR: {
1022 if (Record.size() != 2) {
1023 Error("Incorrect encoding of vector type in PCH file");
1024 return QualType();
1025 }
1026
1027 QualType ElementType = GetType(Record[0]);
1028 unsigned NumElements = Record[1];
1029 return Context.getVectorType(ElementType, NumElements);
1030 }
1031
1032 case pch::TYPE_EXT_VECTOR: {
1033 if (Record.size() != 2) {
1034 Error("Incorrect encoding of extended vector type in PCH file");
1035 return QualType();
1036 }
1037
1038 QualType ElementType = GetType(Record[0]);
1039 unsigned NumElements = Record[1];
1040 return Context.getExtVectorType(ElementType, NumElements);
1041 }
1042
1043 case pch::TYPE_FUNCTION_NO_PROTO: {
1044 if (Record.size() != 1) {
1045 Error("Incorrect encoding of no-proto function type");
1046 return QualType();
1047 }
1048 QualType ResultType = GetType(Record[0]);
1049 return Context.getFunctionNoProtoType(ResultType);
1050 }
1051
1052 case pch::TYPE_FUNCTION_PROTO: {
1053 QualType ResultType = GetType(Record[0]);
1054 unsigned Idx = 1;
1055 unsigned NumParams = Record[Idx++];
1056 llvm::SmallVector<QualType, 16> ParamTypes;
1057 for (unsigned I = 0; I != NumParams; ++I)
1058 ParamTypes.push_back(GetType(Record[Idx++]));
1059 bool isVariadic = Record[Idx++];
1060 unsigned Quals = Record[Idx++];
1061 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1062 isVariadic, Quals);
1063 }
1064
1065 case pch::TYPE_TYPEDEF:
1066 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1067 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1068
1069 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001070 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001071
1072 case pch::TYPE_TYPEOF: {
1073 if (Record.size() != 1) {
1074 Error("Incorrect encoding of typeof(type) in PCH file");
1075 return QualType();
1076 }
1077 QualType UnderlyingType = GetType(Record[0]);
1078 return Context.getTypeOfType(UnderlyingType);
1079 }
1080
1081 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001082 assert(Record.size() == 1 && "Incorrect encoding of record type");
1083 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001084
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001085 case pch::TYPE_ENUM:
1086 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1087 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1088
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001089 case pch::TYPE_OBJC_INTERFACE:
1090 // FIXME: Deserialize ObjCInterfaceType
1091 assert(false && "Cannot de-serialize ObjC interface types yet");
1092 return QualType();
1093
1094 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1095 // FIXME: Deserialize ObjCQualifiedInterfaceType
1096 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1097 return QualType();
1098
1099 case pch::TYPE_OBJC_QUALIFIED_ID:
1100 // FIXME: Deserialize ObjCQualifiedIdType
1101 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1102 return QualType();
1103
1104 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1105 // FIXME: Deserialize ObjCQualifiedClassType
1106 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1107 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001108 }
1109
1110 // Suppress a GCC warning
1111 return QualType();
1112}
1113
1114/// \brief Note that we have loaded the declaration with the given
1115/// Index.
1116///
1117/// This routine notes that this declaration has already been loaded,
1118/// so that future GetDecl calls will return this declaration rather
1119/// than trying to load a new declaration.
1120inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1121 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1122 DeclAlreadyLoaded[Index] = true;
1123 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1124}
1125
1126/// \brief Read the declaration at the given offset from the PCH file.
1127Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001128 // Keep track of where we are in the stream, then jump back there
1129 // after reading this declaration.
1130 SavedStreamPosition SavedPosition(Stream);
1131
Douglas Gregorc34897d2009-04-09 22:27:44 +00001132 Decl *D = 0;
1133 Stream.JumpToBit(Offset);
1134 RecordData Record;
1135 unsigned Code = Stream.ReadCode();
1136 unsigned Idx = 0;
1137 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001138
Douglas Gregorc34897d2009-04-09 22:27:44 +00001139 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1140 case pch::DECL_TRANSLATION_UNIT:
1141 assert(Index == 0 && "Translation unit must be at index 0");
1142 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1143 D = Context.getTranslationUnitDecl();
1144 LoadedDecl(Index, D);
1145 break;
1146
1147 case pch::DECL_TYPEDEF: {
1148 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1149 0, QualType());
1150 LoadedDecl(Index, Typedef);
1151 Reader.VisitTypedefDecl(Typedef);
1152 D = Typedef;
1153 break;
1154 }
1155
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001156 case pch::DECL_ENUM: {
1157 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1158 LoadedDecl(Index, Enum);
1159 Reader.VisitEnumDecl(Enum);
1160 D = Enum;
1161 break;
1162 }
1163
Douglas Gregor982365e2009-04-13 21:20:57 +00001164 case pch::DECL_RECORD: {
1165 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1166 0, SourceLocation(), 0, 0);
1167 LoadedDecl(Index, Record);
1168 Reader.VisitRecordDecl(Record);
1169 D = Record;
1170 break;
1171 }
1172
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001173 case pch::DECL_ENUM_CONSTANT: {
1174 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1175 SourceLocation(), 0,
1176 QualType(), 0,
1177 llvm::APSInt());
1178 LoadedDecl(Index, ECD);
1179 Reader.VisitEnumConstantDecl(ECD);
1180 D = ECD;
1181 break;
1182 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001183
1184 case pch::DECL_FUNCTION: {
1185 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1186 DeclarationName(),
1187 QualType());
1188 LoadedDecl(Index, Function);
1189 Reader.VisitFunctionDecl(Function);
1190 D = Function;
1191 break;
1192 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001193
Douglas Gregor982365e2009-04-13 21:20:57 +00001194 case pch::DECL_FIELD: {
1195 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1196 QualType(), 0, false);
1197 LoadedDecl(Index, Field);
1198 Reader.VisitFieldDecl(Field);
1199 D = Field;
1200 break;
1201 }
1202
Douglas Gregorc34897d2009-04-09 22:27:44 +00001203 case pch::DECL_VAR: {
1204 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1205 VarDecl::None, SourceLocation());
1206 LoadedDecl(Index, Var);
1207 Reader.VisitVarDecl(Var);
1208 D = Var;
1209 break;
1210 }
1211
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001212 case pch::DECL_PARM_VAR: {
1213 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1214 QualType(), VarDecl::None, 0);
1215 LoadedDecl(Index, Parm);
1216 Reader.VisitParmVarDecl(Parm);
1217 D = Parm;
1218 break;
1219 }
1220
1221 case pch::DECL_ORIGINAL_PARM_VAR: {
1222 OriginalParmVarDecl *Parm
1223 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1224 QualType(), QualType(), VarDecl::None,
1225 0);
1226 LoadedDecl(Index, Parm);
1227 Reader.VisitOriginalParmVarDecl(Parm);
1228 D = Parm;
1229 break;
1230 }
1231
Douglas Gregor2a491792009-04-13 22:49:25 +00001232 case pch::DECL_FILE_SCOPE_ASM: {
1233 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1234 SourceLocation(), 0);
1235 LoadedDecl(Index, Asm);
1236 Reader.VisitFileScopeAsmDecl(Asm);
1237 D = Asm;
1238 break;
1239 }
1240
1241 case pch::DECL_BLOCK: {
1242 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1243 LoadedDecl(Index, Block);
1244 Reader.VisitBlockDecl(Block);
1245 D = Block;
1246 break;
1247 }
1248
Douglas Gregorc34897d2009-04-09 22:27:44 +00001249 default:
1250 assert(false && "Cannot de-serialize this kind of declaration");
1251 break;
1252 }
1253
1254 // If this declaration is also a declaration context, get the
1255 // offsets for its tables of lexical and visible declarations.
1256 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1257 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1258 if (Offsets.first || Offsets.second) {
1259 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1260 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1261 DeclContextOffsets[DC] = Offsets;
1262 }
1263 }
1264 assert(Idx == Record.size());
1265
1266 return D;
1267}
1268
Douglas Gregorac8f2802009-04-10 17:25:41 +00001269QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001270 unsigned Quals = ID & 0x07;
1271 unsigned Index = ID >> 3;
1272
1273 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1274 QualType T;
1275 switch ((pch::PredefinedTypeIDs)Index) {
1276 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1277 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1278 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1279
1280 case pch::PREDEF_TYPE_CHAR_U_ID:
1281 case pch::PREDEF_TYPE_CHAR_S_ID:
1282 // FIXME: Check that the signedness of CharTy is correct!
1283 T = Context.CharTy;
1284 break;
1285
1286 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1287 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1288 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1289 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1290 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1291 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1292 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1293 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1294 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1295 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1296 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1297 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1298 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1299 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1300 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1301 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1302 }
1303
1304 assert(!T.isNull() && "Unknown predefined type");
1305 return T.getQualifiedType(Quals);
1306 }
1307
1308 Index -= pch::NUM_PREDEF_TYPE_IDS;
1309 if (!TypeAlreadyLoaded[Index]) {
1310 // Load the type from the PCH file.
1311 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1312 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1313 TypeAlreadyLoaded[Index] = true;
1314 }
1315
1316 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1317}
1318
Douglas Gregorac8f2802009-04-10 17:25:41 +00001319Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001320 if (ID == 0)
1321 return 0;
1322
1323 unsigned Index = ID - 1;
1324 if (DeclAlreadyLoaded[Index])
1325 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1326
1327 // Load the declaration from the PCH file.
1328 return ReadDeclRecord(DeclOffsets[Index], Index);
1329}
1330
1331bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001332 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001333 assert(DC->hasExternalLexicalStorage() &&
1334 "DeclContext has no lexical decls in storage");
1335 uint64_t Offset = DeclContextOffsets[DC].first;
1336 assert(Offset && "DeclContext has no lexical decls in storage");
1337
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001338 // Keep track of where we are in the stream, then jump back there
1339 // after reading this context.
1340 SavedStreamPosition SavedPosition(Stream);
1341
Douglas Gregorc34897d2009-04-09 22:27:44 +00001342 // Load the record containing all of the declarations lexically in
1343 // this context.
1344 Stream.JumpToBit(Offset);
1345 RecordData Record;
1346 unsigned Code = Stream.ReadCode();
1347 unsigned RecCode = Stream.ReadRecord(Code, Record);
1348 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1349
1350 // Load all of the declaration IDs
1351 Decls.clear();
1352 Decls.insert(Decls.end(), Record.begin(), Record.end());
1353 return false;
1354}
1355
1356bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1357 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1358 assert(DC->hasExternalVisibleStorage() &&
1359 "DeclContext has no visible decls in storage");
1360 uint64_t Offset = DeclContextOffsets[DC].second;
1361 assert(Offset && "DeclContext has no visible decls in storage");
1362
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001363 // Keep track of where we are in the stream, then jump back there
1364 // after reading this context.
1365 SavedStreamPosition SavedPosition(Stream);
1366
Douglas Gregorc34897d2009-04-09 22:27:44 +00001367 // Load the record containing all of the declarations visible in
1368 // this context.
1369 Stream.JumpToBit(Offset);
1370 RecordData Record;
1371 unsigned Code = Stream.ReadCode();
1372 unsigned RecCode = Stream.ReadRecord(Code, Record);
1373 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1374 if (Record.size() == 0)
1375 return false;
1376
1377 Decls.clear();
1378
1379 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001380 while (Idx < Record.size()) {
1381 Decls.push_back(VisibleDeclaration());
1382 Decls.back().Name = ReadDeclarationName(Record, Idx);
1383
Douglas Gregorc34897d2009-04-09 22:27:44 +00001384 unsigned Size = Record[Idx++];
1385 llvm::SmallVector<unsigned, 4> & LoadedDecls
1386 = Decls.back().Declarations;
1387 LoadedDecls.reserve(Size);
1388 for (unsigned I = 0; I < Size; ++I)
1389 LoadedDecls.push_back(Record[Idx++]);
1390 }
1391
1392 return false;
1393}
1394
Douglas Gregor631f6c62009-04-14 00:24:19 +00001395void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1396 if (!Consumer)
1397 return;
1398
1399 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1400 Decl *D = GetDecl(ExternalDefinitions[I]);
1401 DeclGroupRef DG(D);
1402 Consumer->HandleTopLevelDecl(DG);
1403 }
1404}
1405
Douglas Gregorc34897d2009-04-09 22:27:44 +00001406void PCHReader::PrintStats() {
1407 std::fprintf(stderr, "*** PCH Statistics:\n");
1408
1409 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1410 TypeAlreadyLoaded.end(),
1411 true);
1412 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1413 DeclAlreadyLoaded.end(),
1414 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001415 unsigned NumIdentifiersLoaded = 0;
1416 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1417 if ((IdentifierData[I] & 0x01) == 0)
1418 ++NumIdentifiersLoaded;
1419 }
1420
Douglas Gregorc34897d2009-04-09 22:27:44 +00001421 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1422 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001423 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001424 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1425 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001426 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1427 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1428 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1429 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001430 std::fprintf(stderr, "\n");
1431}
1432
Chris Lattner29241862009-04-11 21:15:38 +00001433IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001434 if (ID == 0)
1435 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001436
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001437 if (!IdentifierTable || IdentifierData.empty()) {
1438 Error("No identifier table in PCH file");
1439 return 0;
1440 }
Chris Lattner29241862009-04-11 21:15:38 +00001441
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001442 if (IdentifierData[ID - 1] & 0x01) {
1443 uint64_t Offset = IdentifierData[ID - 1];
1444 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001445 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001446 }
Chris Lattner29241862009-04-11 21:15:38 +00001447
1448 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001449}
1450
1451DeclarationName
1452PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1453 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1454 switch (Kind) {
1455 case DeclarationName::Identifier:
1456 return DeclarationName(GetIdentifierInfo(Record, Idx));
1457
1458 case DeclarationName::ObjCZeroArgSelector:
1459 case DeclarationName::ObjCOneArgSelector:
1460 case DeclarationName::ObjCMultiArgSelector:
1461 assert(false && "Unable to de-serialize Objective-C selectors");
1462 break;
1463
1464 case DeclarationName::CXXConstructorName:
1465 return Context.DeclarationNames.getCXXConstructorName(
1466 GetType(Record[Idx++]));
1467
1468 case DeclarationName::CXXDestructorName:
1469 return Context.DeclarationNames.getCXXDestructorName(
1470 GetType(Record[Idx++]));
1471
1472 case DeclarationName::CXXConversionFunctionName:
1473 return Context.DeclarationNames.getCXXConversionFunctionName(
1474 GetType(Record[Idx++]));
1475
1476 case DeclarationName::CXXOperatorName:
1477 return Context.DeclarationNames.getCXXOperatorName(
1478 (OverloadedOperatorKind)Record[Idx++]);
1479
1480 case DeclarationName::CXXUsingDirective:
1481 return DeclarationName::getUsingDirectiveName();
1482 }
1483
1484 // Required to silence GCC warning
1485 return DeclarationName();
1486}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001487
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001488/// \brief Read an integral value
1489llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1490 unsigned BitWidth = Record[Idx++];
1491 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1492 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1493 Idx += NumWords;
1494 return Result;
1495}
1496
1497/// \brief Read a signed integral value
1498llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1499 bool isUnsigned = Record[Idx++];
1500 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1501}
1502
Douglas Gregore2f37202009-04-14 21:55:33 +00001503/// \brief Read a floating-point value
1504llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1505 // FIXME: is this really correct?
1506 return llvm::APFloat(ReadAPInt(Record, Idx));
1507}
1508
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001509Expr *PCHReader::ReadExpr() {
1510 RecordData Record;
1511 unsigned Code = Stream.ReadCode();
1512 unsigned Idx = 0;
1513 PCHStmtReader Reader(*this, Record, Idx);
1514 Stmt::EmptyShell Empty;
1515
1516 Expr *E = 0;
1517 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1518 case pch::EXPR_NULL:
1519 E = 0;
1520 break;
1521
Douglas Gregore2f37202009-04-14 21:55:33 +00001522 case pch::EXPR_PREDEFINED:
1523 // FIXME: untested (until we can serialize function bodies).
1524 E = new (Context) PredefinedExpr(Empty);
1525 break;
1526
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001527 case pch::EXPR_DECL_REF:
1528 E = new (Context) DeclRefExpr(Empty);
1529 break;
1530
1531 case pch::EXPR_INTEGER_LITERAL:
1532 E = new (Context) IntegerLiteral(Empty);
1533 break;
1534
Douglas Gregore2f37202009-04-14 21:55:33 +00001535 case pch::EXPR_FLOATING_LITERAL:
1536 E = new (Context) FloatingLiteral(Empty);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001537 break;
1538
Douglas Gregore2f37202009-04-14 21:55:33 +00001539 case pch::EXPR_CHARACTER_LITERAL:
1540 E = new (Context) CharacterLiteral(Empty);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001541 break;
1542 }
1543
1544 if (E)
1545 Reader.Visit(E);
1546
1547 assert(Idx == Record.size() && "Invalid deserialization of expression");
1548
1549 return E;
1550}
1551
Douglas Gregor179cfb12009-04-10 20:39:37 +00001552DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001553 return Diag(SourceLocation(), DiagID);
1554}
1555
1556DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1557 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001558 Context.getSourceManager()),
1559 DiagID);
1560}