blob: bc754cb845ffaa71762633bc98494bfc26222747 [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,
485 SourceMgr));
486 break;
487 }
488
Douglas Gregor635f97f2009-04-13 16:31:14 +0000489 case pch::SM_LINE_TABLE: {
490 if (ParseLineTable(SourceMgr, Record))
491 return Failure;
492 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000493 }
494 }
495}
496
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000497bool PCHReader::ReadPreprocessorBlock() {
498 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
499 return Error("Malformed preprocessor block record");
500
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000501 RecordData Record;
502 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
503 MacroInfo *LastMacro = 0;
504
505 while (true) {
506 unsigned Code = Stream.ReadCode();
507 switch (Code) {
508 case llvm::bitc::END_BLOCK:
509 if (Stream.ReadBlockEnd())
510 return Error("Error at end of preprocessor block");
511 return false;
512
513 case llvm::bitc::ENTER_SUBBLOCK:
514 // No known subblocks, always skip them.
515 Stream.ReadSubBlockID();
516 if (Stream.SkipBlock())
517 return Error("Malformed block record");
518 continue;
519
520 case llvm::bitc::DEFINE_ABBREV:
521 Stream.ReadAbbrevRecord();
522 continue;
523 default: break;
524 }
525
526 // Read a record.
527 Record.clear();
528 pch::PreprocessorRecordTypes RecType =
529 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
530 switch (RecType) {
531 default: // Default behavior: ignore unknown records.
532 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000533 case pch::PP_COUNTER_VALUE:
534 if (!Record.empty())
535 PP.setCounterValue(Record[0]);
536 break;
537
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000538 case pch::PP_MACRO_OBJECT_LIKE:
539 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000540 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
541 if (II == 0)
542 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000543 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
544 bool isUsed = Record[2];
545
546 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
547 MI->setIsUsed(isUsed);
548
549 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
550 // Decode function-like macro info.
551 bool isC99VarArgs = Record[3];
552 bool isGNUVarArgs = Record[4];
553 MacroArgs.clear();
554 unsigned NumArgs = Record[5];
555 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000556 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000557
558 // Install function-like macro info.
559 MI->setIsFunctionLike();
560 if (isC99VarArgs) MI->setIsC99Varargs();
561 if (isGNUVarArgs) MI->setIsGNUVarargs();
562 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
563 PP.getPreprocessorAllocator());
564 }
565
566 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000567 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000568
569 // Remember that we saw this macro last so that we add the tokens that
570 // form its body to it.
571 LastMacro = MI;
572 break;
573 }
574
575 case pch::PP_TOKEN: {
576 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
577 // pretend we didn't see this.
578 if (LastMacro == 0) break;
579
580 Token Tok;
581 Tok.startToken();
582 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
583 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000584 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
585 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000586 Tok.setKind((tok::TokenKind)Record[3]);
587 Tok.setFlag((Token::TokenFlags)Record[4]);
588 LastMacro->AddTokenToBody(Tok);
589 break;
590 }
591 }
592 }
593}
594
Douglas Gregor179cfb12009-04-10 20:39:37 +0000595PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
596 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
597 Error("Malformed block record");
598 return Failure;
599 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000600
Chris Lattner29241862009-04-11 21:15:38 +0000601 uint64_t PreprocessorBlockBit = 0;
602
Douglas Gregorc34897d2009-04-09 22:27:44 +0000603 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000604 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000605 while (!Stream.AtEndOfStream()) {
606 unsigned Code = Stream.ReadCode();
607 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000608 // If we saw the preprocessor block, read it now.
609 if (PreprocessorBlockBit) {
610 uint64_t SavedPos = Stream.GetCurrentBitNo();
611 Stream.JumpToBit(PreprocessorBlockBit);
612 if (ReadPreprocessorBlock()) {
613 Error("Malformed preprocessor block");
614 return Failure;
615 }
616 Stream.JumpToBit(SavedPos);
617 }
618
Douglas Gregor179cfb12009-04-10 20:39:37 +0000619 if (Stream.ReadBlockEnd()) {
620 Error("Error at end of module block");
621 return Failure;
622 }
Chris Lattner29241862009-04-11 21:15:38 +0000623
Douglas Gregor179cfb12009-04-10 20:39:37 +0000624 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000625 }
626
627 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
628 switch (Stream.ReadSubBlockID()) {
629 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
630 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
631 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000632 if (Stream.SkipBlock()) {
633 Error("Malformed block record");
634 return Failure;
635 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000636 break;
637
Chris Lattner29241862009-04-11 21:15:38 +0000638 case pch::PREPROCESSOR_BLOCK_ID:
639 // Skip the preprocessor block for now, but remember where it is. We
640 // want to read it in after the identifier table.
641 if (PreprocessorBlockBit) {
642 Error("Multiple preprocessor blocks found.");
643 return Failure;
644 }
645 PreprocessorBlockBit = Stream.GetCurrentBitNo();
646 if (Stream.SkipBlock()) {
647 Error("Malformed block record");
648 return Failure;
649 }
650 break;
651
Douglas Gregorab1cef72009-04-10 03:52:48 +0000652 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000653 switch (ReadSourceManagerBlock()) {
654 case Success:
655 break;
656
657 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000658 Error("Malformed source manager block");
659 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000660
661 case IgnorePCH:
662 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000663 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000664 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000665 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000666 continue;
667 }
668
669 if (Code == llvm::bitc::DEFINE_ABBREV) {
670 Stream.ReadAbbrevRecord();
671 continue;
672 }
673
674 // Read and process a record.
675 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000676 const char *BlobStart = 0;
677 unsigned BlobLen = 0;
678 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
679 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000680 default: // Default behavior: ignore.
681 break;
682
683 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000684 if (!TypeOffsets.empty()) {
685 Error("Duplicate TYPE_OFFSET record in PCH file");
686 return Failure;
687 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000688 TypeOffsets.swap(Record);
689 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
690 break;
691
692 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000693 if (!DeclOffsets.empty()) {
694 Error("Duplicate DECL_OFFSET record in PCH file");
695 return Failure;
696 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000697 DeclOffsets.swap(Record);
698 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
699 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000700
701 case pch::LANGUAGE_OPTIONS:
702 if (ParseLanguageOptions(Record))
703 return IgnorePCH;
704 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000705
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000706 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000707 std::string TargetTriple(BlobStart, BlobLen);
708 if (TargetTriple != Context.Target.getTargetTriple()) {
709 Diag(diag::warn_pch_target_triple)
710 << TargetTriple << Context.Target.getTargetTriple();
711 Diag(diag::note_ignoring_pch) << FileName;
712 return IgnorePCH;
713 }
714 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000715 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000716
717 case pch::IDENTIFIER_TABLE:
718 IdentifierTable = BlobStart;
719 break;
720
721 case pch::IDENTIFIER_OFFSET:
722 if (!IdentifierData.empty()) {
723 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
724 return Failure;
725 }
726 IdentifierData.swap(Record);
727#ifndef NDEBUG
728 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
729 if ((IdentifierData[I] & 0x01) == 0) {
730 Error("Malformed identifier table in the precompiled header");
731 return Failure;
732 }
733 }
734#endif
735 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000736
737 case pch::EXTERNAL_DEFINITIONS:
738 if (!ExternalDefinitions.empty()) {
739 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
740 return Failure;
741 }
742 ExternalDefinitions.swap(Record);
743 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000744 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000745 }
746
Douglas Gregor179cfb12009-04-10 20:39:37 +0000747 Error("Premature end of bitstream");
748 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000749}
750
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000751PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000752 // Set the PCH file name.
753 this->FileName = FileName;
754
Douglas Gregorc34897d2009-04-09 22:27:44 +0000755 // Open the PCH file.
756 std::string ErrStr;
757 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000758 if (!Buffer) {
759 Error(ErrStr.c_str());
760 return IgnorePCH;
761 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000762
763 // Initialize the stream
764 Stream.init((const unsigned char *)Buffer->getBufferStart(),
765 (const unsigned char *)Buffer->getBufferEnd());
766
767 // Sniff for the signature.
768 if (Stream.Read(8) != 'C' ||
769 Stream.Read(8) != 'P' ||
770 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000771 Stream.Read(8) != 'H') {
772 Error("Not a PCH file");
773 return IgnorePCH;
774 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000775
776 // We expect a number of well-defined blocks, though we don't necessarily
777 // need to understand them all.
778 while (!Stream.AtEndOfStream()) {
779 unsigned Code = Stream.ReadCode();
780
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000781 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
782 Error("Invalid record at top-level");
783 return Failure;
784 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000785
786 unsigned BlockID = Stream.ReadSubBlockID();
787
788 // We only know the PCH subblock ID.
789 switch (BlockID) {
790 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000791 if (Stream.ReadBlockInfoBlock()) {
792 Error("Malformed BlockInfoBlock");
793 return Failure;
794 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000795 break;
796 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000797 switch (ReadPCHBlock()) {
798 case Success:
799 break;
800
801 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000802 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000803
804 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000805 // FIXME: We could consider reading through to the end of this
806 // PCH block, skipping subblocks, to see if there are other
807 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000808 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000809 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000810 break;
811 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000812 if (Stream.SkipBlock()) {
813 Error("Malformed block record");
814 return Failure;
815 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000816 break;
817 }
818 }
819
820 // Load the translation unit declaration
821 ReadDeclRecord(DeclOffsets[0], 0);
822
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000823 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000824}
825
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000826namespace {
827 /// \brief Helper class that saves the current stream position and
828 /// then restores it when destroyed.
829 struct VISIBILITY_HIDDEN SavedStreamPosition {
830 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
831 : Stream(Stream), Offset(Stream.GetCurrentBitNo()),
832 EndOfStream(Stream.AtEndOfStream()){ }
833
834 ~SavedStreamPosition() {
835 if (!EndOfStream)
836 Stream.JumpToBit(Offset);
837 }
838
839 private:
840 llvm::BitstreamReader &Stream;
841 uint64_t Offset;
842 bool EndOfStream;
843 };
844}
845
Douglas Gregor179cfb12009-04-10 20:39:37 +0000846/// \brief Parse the record that corresponds to a LangOptions data
847/// structure.
848///
849/// This routine compares the language options used to generate the
850/// PCH file against the language options set for the current
851/// compilation. For each option, we classify differences between the
852/// two compiler states as either "benign" or "important". Benign
853/// differences don't matter, and we accept them without complaint
854/// (and without modifying the language options). Differences between
855/// the states for important options cause the PCH file to be
856/// unusable, so we emit a warning and return true to indicate that
857/// there was an error.
858///
859/// \returns true if the PCH file is unacceptable, false otherwise.
860bool PCHReader::ParseLanguageOptions(
861 const llvm::SmallVectorImpl<uint64_t> &Record) {
862 const LangOptions &LangOpts = Context.getLangOptions();
863#define PARSE_LANGOPT_BENIGN(Option) ++Idx
864#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
865 if (Record[Idx] != LangOpts.Option) { \
866 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
867 Diag(diag::note_ignoring_pch) << FileName; \
868 return true; \
869 } \
870 ++Idx
871
872 unsigned Idx = 0;
873 PARSE_LANGOPT_BENIGN(Trigraphs);
874 PARSE_LANGOPT_BENIGN(BCPLComment);
875 PARSE_LANGOPT_BENIGN(DollarIdents);
876 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
877 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
878 PARSE_LANGOPT_BENIGN(ImplicitInt);
879 PARSE_LANGOPT_BENIGN(Digraphs);
880 PARSE_LANGOPT_BENIGN(HexFloats);
881 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
882 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
883 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
884 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
885 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
886 PARSE_LANGOPT_BENIGN(CXXOperatorName);
887 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
888 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
889 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
890 PARSE_LANGOPT_BENIGN(PascalStrings);
891 PARSE_LANGOPT_BENIGN(Boolean);
892 PARSE_LANGOPT_BENIGN(WritableStrings);
893 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
894 diag::warn_pch_lax_vector_conversions);
895 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
896 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
897 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
898 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
899 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
900 diag::warn_pch_thread_safe_statics);
901 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
902 PARSE_LANGOPT_BENIGN(EmitAllDecls);
903 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
904 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
905 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
906 diag::warn_pch_heinous_extensions);
907 // FIXME: Most of the options below are benign if the macro wasn't
908 // used. Unfortunately, this means that a PCH compiled without
909 // optimization can't be used with optimization turned on, even
910 // though the only thing that changes is whether __OPTIMIZE__ was
911 // defined... but if __OPTIMIZE__ never showed up in the header, it
912 // doesn't matter. We could consider making this some special kind
913 // of check.
914 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
915 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
916 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
917 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
918 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
919 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
920 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
921 Diag(diag::warn_pch_gc_mode)
922 << (unsigned)Record[Idx] << LangOpts.getGCMode();
923 Diag(diag::note_ignoring_pch) << FileName;
924 return true;
925 }
926 ++Idx;
927 PARSE_LANGOPT_BENIGN(getVisibilityMode());
928 PARSE_LANGOPT_BENIGN(InstantiationDepth);
929#undef PARSE_LANGOPT_IRRELEVANT
930#undef PARSE_LANGOPT_BENIGN
931
932 return false;
933}
934
Douglas Gregorc34897d2009-04-09 22:27:44 +0000935/// \brief Read and return the type at the given offset.
936///
937/// This routine actually reads the record corresponding to the type
938/// at the given offset in the bitstream. It is a helper routine for
939/// GetType, which deals with reading type IDs.
940QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000941 // Keep track of where we are in the stream, then jump back there
942 // after reading this type.
943 SavedStreamPosition SavedPosition(Stream);
944
Douglas Gregorc34897d2009-04-09 22:27:44 +0000945 Stream.JumpToBit(Offset);
946 RecordData Record;
947 unsigned Code = Stream.ReadCode();
948 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000949 case pch::TYPE_EXT_QUAL:
950 // FIXME: Deserialize ExtQualType
951 assert(false && "Cannot deserialize qualified types yet");
952 return QualType();
953
Douglas Gregorc34897d2009-04-09 22:27:44 +0000954 case pch::TYPE_FIXED_WIDTH_INT: {
955 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
956 return Context.getFixedWidthIntType(Record[0], Record[1]);
957 }
958
959 case pch::TYPE_COMPLEX: {
960 assert(Record.size() == 1 && "Incorrect encoding of complex type");
961 QualType ElemType = GetType(Record[0]);
962 return Context.getComplexType(ElemType);
963 }
964
965 case pch::TYPE_POINTER: {
966 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
967 QualType PointeeType = GetType(Record[0]);
968 return Context.getPointerType(PointeeType);
969 }
970
971 case pch::TYPE_BLOCK_POINTER: {
972 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
973 QualType PointeeType = GetType(Record[0]);
974 return Context.getBlockPointerType(PointeeType);
975 }
976
977 case pch::TYPE_LVALUE_REFERENCE: {
978 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
979 QualType PointeeType = GetType(Record[0]);
980 return Context.getLValueReferenceType(PointeeType);
981 }
982
983 case pch::TYPE_RVALUE_REFERENCE: {
984 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
985 QualType PointeeType = GetType(Record[0]);
986 return Context.getRValueReferenceType(PointeeType);
987 }
988
989 case pch::TYPE_MEMBER_POINTER: {
990 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
991 QualType PointeeType = GetType(Record[0]);
992 QualType ClassType = GetType(Record[1]);
993 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
994 }
995
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000996 case pch::TYPE_CONSTANT_ARRAY: {
997 QualType ElementType = GetType(Record[0]);
998 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
999 unsigned IndexTypeQuals = Record[2];
1000 unsigned Idx = 3;
1001 llvm::APInt Size = ReadAPInt(Record, Idx);
1002 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1003 }
1004
1005 case pch::TYPE_INCOMPLETE_ARRAY: {
1006 QualType ElementType = GetType(Record[0]);
1007 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1008 unsigned IndexTypeQuals = Record[2];
1009 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1010 }
1011
1012 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001013 QualType ElementType = GetType(Record[0]);
1014 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1015 unsigned IndexTypeQuals = Record[2];
1016 return Context.getVariableArrayType(ElementType, ReadExpr(),
1017 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001018 }
1019
1020 case pch::TYPE_VECTOR: {
1021 if (Record.size() != 2) {
1022 Error("Incorrect encoding of vector type in PCH file");
1023 return QualType();
1024 }
1025
1026 QualType ElementType = GetType(Record[0]);
1027 unsigned NumElements = Record[1];
1028 return Context.getVectorType(ElementType, NumElements);
1029 }
1030
1031 case pch::TYPE_EXT_VECTOR: {
1032 if (Record.size() != 2) {
1033 Error("Incorrect encoding of extended vector type in PCH file");
1034 return QualType();
1035 }
1036
1037 QualType ElementType = GetType(Record[0]);
1038 unsigned NumElements = Record[1];
1039 return Context.getExtVectorType(ElementType, NumElements);
1040 }
1041
1042 case pch::TYPE_FUNCTION_NO_PROTO: {
1043 if (Record.size() != 1) {
1044 Error("Incorrect encoding of no-proto function type");
1045 return QualType();
1046 }
1047 QualType ResultType = GetType(Record[0]);
1048 return Context.getFunctionNoProtoType(ResultType);
1049 }
1050
1051 case pch::TYPE_FUNCTION_PROTO: {
1052 QualType ResultType = GetType(Record[0]);
1053 unsigned Idx = 1;
1054 unsigned NumParams = Record[Idx++];
1055 llvm::SmallVector<QualType, 16> ParamTypes;
1056 for (unsigned I = 0; I != NumParams; ++I)
1057 ParamTypes.push_back(GetType(Record[Idx++]));
1058 bool isVariadic = Record[Idx++];
1059 unsigned Quals = Record[Idx++];
1060 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1061 isVariadic, Quals);
1062 }
1063
1064 case pch::TYPE_TYPEDEF:
1065 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1066 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1067
1068 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001069 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001070
1071 case pch::TYPE_TYPEOF: {
1072 if (Record.size() != 1) {
1073 Error("Incorrect encoding of typeof(type) in PCH file");
1074 return QualType();
1075 }
1076 QualType UnderlyingType = GetType(Record[0]);
1077 return Context.getTypeOfType(UnderlyingType);
1078 }
1079
1080 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001081 assert(Record.size() == 1 && "Incorrect encoding of record type");
1082 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001083
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001084 case pch::TYPE_ENUM:
1085 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1086 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1087
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001088 case pch::TYPE_OBJC_INTERFACE:
1089 // FIXME: Deserialize ObjCInterfaceType
1090 assert(false && "Cannot de-serialize ObjC interface types yet");
1091 return QualType();
1092
1093 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1094 // FIXME: Deserialize ObjCQualifiedInterfaceType
1095 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1096 return QualType();
1097
1098 case pch::TYPE_OBJC_QUALIFIED_ID:
1099 // FIXME: Deserialize ObjCQualifiedIdType
1100 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1101 return QualType();
1102
1103 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1104 // FIXME: Deserialize ObjCQualifiedClassType
1105 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1106 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001107 }
1108
1109 // Suppress a GCC warning
1110 return QualType();
1111}
1112
1113/// \brief Note that we have loaded the declaration with the given
1114/// Index.
1115///
1116/// This routine notes that this declaration has already been loaded,
1117/// so that future GetDecl calls will return this declaration rather
1118/// than trying to load a new declaration.
1119inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1120 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1121 DeclAlreadyLoaded[Index] = true;
1122 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1123}
1124
1125/// \brief Read the declaration at the given offset from the PCH file.
1126Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001127 // Keep track of where we are in the stream, then jump back there
1128 // after reading this declaration.
1129 SavedStreamPosition SavedPosition(Stream);
1130
Douglas Gregorc34897d2009-04-09 22:27:44 +00001131 Decl *D = 0;
1132 Stream.JumpToBit(Offset);
1133 RecordData Record;
1134 unsigned Code = Stream.ReadCode();
1135 unsigned Idx = 0;
1136 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001137
Douglas Gregorc34897d2009-04-09 22:27:44 +00001138 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1139 case pch::DECL_TRANSLATION_UNIT:
1140 assert(Index == 0 && "Translation unit must be at index 0");
1141 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1142 D = Context.getTranslationUnitDecl();
1143 LoadedDecl(Index, D);
1144 break;
1145
1146 case pch::DECL_TYPEDEF: {
1147 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1148 0, QualType());
1149 LoadedDecl(Index, Typedef);
1150 Reader.VisitTypedefDecl(Typedef);
1151 D = Typedef;
1152 break;
1153 }
1154
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001155 case pch::DECL_ENUM: {
1156 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1157 LoadedDecl(Index, Enum);
1158 Reader.VisitEnumDecl(Enum);
1159 D = Enum;
1160 break;
1161 }
1162
Douglas Gregor982365e2009-04-13 21:20:57 +00001163 case pch::DECL_RECORD: {
1164 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1165 0, SourceLocation(), 0, 0);
1166 LoadedDecl(Index, Record);
1167 Reader.VisitRecordDecl(Record);
1168 D = Record;
1169 break;
1170 }
1171
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001172 case pch::DECL_ENUM_CONSTANT: {
1173 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1174 SourceLocation(), 0,
1175 QualType(), 0,
1176 llvm::APSInt());
1177 LoadedDecl(Index, ECD);
1178 Reader.VisitEnumConstantDecl(ECD);
1179 D = ECD;
1180 break;
1181 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001182
1183 case pch::DECL_FUNCTION: {
1184 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1185 DeclarationName(),
1186 QualType());
1187 LoadedDecl(Index, Function);
1188 Reader.VisitFunctionDecl(Function);
1189 D = Function;
1190 break;
1191 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001192
Douglas Gregor982365e2009-04-13 21:20:57 +00001193 case pch::DECL_FIELD: {
1194 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1195 QualType(), 0, false);
1196 LoadedDecl(Index, Field);
1197 Reader.VisitFieldDecl(Field);
1198 D = Field;
1199 break;
1200 }
1201
Douglas Gregorc34897d2009-04-09 22:27:44 +00001202 case pch::DECL_VAR: {
1203 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1204 VarDecl::None, SourceLocation());
1205 LoadedDecl(Index, Var);
1206 Reader.VisitVarDecl(Var);
1207 D = Var;
1208 break;
1209 }
1210
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001211 case pch::DECL_PARM_VAR: {
1212 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1213 QualType(), VarDecl::None, 0);
1214 LoadedDecl(Index, Parm);
1215 Reader.VisitParmVarDecl(Parm);
1216 D = Parm;
1217 break;
1218 }
1219
1220 case pch::DECL_ORIGINAL_PARM_VAR: {
1221 OriginalParmVarDecl *Parm
1222 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1223 QualType(), QualType(), VarDecl::None,
1224 0);
1225 LoadedDecl(Index, Parm);
1226 Reader.VisitOriginalParmVarDecl(Parm);
1227 D = Parm;
1228 break;
1229 }
1230
Douglas Gregor2a491792009-04-13 22:49:25 +00001231 case pch::DECL_FILE_SCOPE_ASM: {
1232 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1233 SourceLocation(), 0);
1234 LoadedDecl(Index, Asm);
1235 Reader.VisitFileScopeAsmDecl(Asm);
1236 D = Asm;
1237 break;
1238 }
1239
1240 case pch::DECL_BLOCK: {
1241 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1242 LoadedDecl(Index, Block);
1243 Reader.VisitBlockDecl(Block);
1244 D = Block;
1245 break;
1246 }
1247
Douglas Gregorc34897d2009-04-09 22:27:44 +00001248 default:
1249 assert(false && "Cannot de-serialize this kind of declaration");
1250 break;
1251 }
1252
1253 // If this declaration is also a declaration context, get the
1254 // offsets for its tables of lexical and visible declarations.
1255 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1256 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1257 if (Offsets.first || Offsets.second) {
1258 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1259 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1260 DeclContextOffsets[DC] = Offsets;
1261 }
1262 }
1263 assert(Idx == Record.size());
1264
1265 return D;
1266}
1267
Douglas Gregorac8f2802009-04-10 17:25:41 +00001268QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001269 unsigned Quals = ID & 0x07;
1270 unsigned Index = ID >> 3;
1271
1272 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1273 QualType T;
1274 switch ((pch::PredefinedTypeIDs)Index) {
1275 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1276 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1277 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1278
1279 case pch::PREDEF_TYPE_CHAR_U_ID:
1280 case pch::PREDEF_TYPE_CHAR_S_ID:
1281 // FIXME: Check that the signedness of CharTy is correct!
1282 T = Context.CharTy;
1283 break;
1284
1285 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1286 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1287 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1288 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1289 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1290 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1291 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1292 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1293 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1294 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1295 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1296 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1297 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1298 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1299 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1300 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1301 }
1302
1303 assert(!T.isNull() && "Unknown predefined type");
1304 return T.getQualifiedType(Quals);
1305 }
1306
1307 Index -= pch::NUM_PREDEF_TYPE_IDS;
1308 if (!TypeAlreadyLoaded[Index]) {
1309 // Load the type from the PCH file.
1310 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1311 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1312 TypeAlreadyLoaded[Index] = true;
1313 }
1314
1315 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1316}
1317
Douglas Gregorac8f2802009-04-10 17:25:41 +00001318Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001319 if (ID == 0)
1320 return 0;
1321
1322 unsigned Index = ID - 1;
1323 if (DeclAlreadyLoaded[Index])
1324 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1325
1326 // Load the declaration from the PCH file.
1327 return ReadDeclRecord(DeclOffsets[Index], Index);
1328}
1329
1330bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001331 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001332 assert(DC->hasExternalLexicalStorage() &&
1333 "DeclContext has no lexical decls in storage");
1334 uint64_t Offset = DeclContextOffsets[DC].first;
1335 assert(Offset && "DeclContext has no lexical decls in storage");
1336
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001337 // Keep track of where we are in the stream, then jump back there
1338 // after reading this context.
1339 SavedStreamPosition SavedPosition(Stream);
1340
Douglas Gregorc34897d2009-04-09 22:27:44 +00001341 // Load the record containing all of the declarations lexically in
1342 // this context.
1343 Stream.JumpToBit(Offset);
1344 RecordData Record;
1345 unsigned Code = Stream.ReadCode();
1346 unsigned RecCode = Stream.ReadRecord(Code, Record);
1347 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1348
1349 // Load all of the declaration IDs
1350 Decls.clear();
1351 Decls.insert(Decls.end(), Record.begin(), Record.end());
1352 return false;
1353}
1354
1355bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1356 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1357 assert(DC->hasExternalVisibleStorage() &&
1358 "DeclContext has no visible decls in storage");
1359 uint64_t Offset = DeclContextOffsets[DC].second;
1360 assert(Offset && "DeclContext has no visible decls in storage");
1361
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001362 // Keep track of where we are in the stream, then jump back there
1363 // after reading this context.
1364 SavedStreamPosition SavedPosition(Stream);
1365
Douglas Gregorc34897d2009-04-09 22:27:44 +00001366 // Load the record containing all of the declarations visible in
1367 // this context.
1368 Stream.JumpToBit(Offset);
1369 RecordData Record;
1370 unsigned Code = Stream.ReadCode();
1371 unsigned RecCode = Stream.ReadRecord(Code, Record);
1372 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1373 if (Record.size() == 0)
1374 return false;
1375
1376 Decls.clear();
1377
1378 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001379 while (Idx < Record.size()) {
1380 Decls.push_back(VisibleDeclaration());
1381 Decls.back().Name = ReadDeclarationName(Record, Idx);
1382
Douglas Gregorc34897d2009-04-09 22:27:44 +00001383 unsigned Size = Record[Idx++];
1384 llvm::SmallVector<unsigned, 4> & LoadedDecls
1385 = Decls.back().Declarations;
1386 LoadedDecls.reserve(Size);
1387 for (unsigned I = 0; I < Size; ++I)
1388 LoadedDecls.push_back(Record[Idx++]);
1389 }
1390
1391 return false;
1392}
1393
Douglas Gregor631f6c62009-04-14 00:24:19 +00001394void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1395 if (!Consumer)
1396 return;
1397
1398 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1399 Decl *D = GetDecl(ExternalDefinitions[I]);
1400 DeclGroupRef DG(D);
1401 Consumer->HandleTopLevelDecl(DG);
1402 }
1403}
1404
Douglas Gregorc34897d2009-04-09 22:27:44 +00001405void PCHReader::PrintStats() {
1406 std::fprintf(stderr, "*** PCH Statistics:\n");
1407
1408 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1409 TypeAlreadyLoaded.end(),
1410 true);
1411 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1412 DeclAlreadyLoaded.end(),
1413 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001414 unsigned NumIdentifiersLoaded = 0;
1415 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1416 if ((IdentifierData[I] & 0x01) == 0)
1417 ++NumIdentifiersLoaded;
1418 }
1419
Douglas Gregorc34897d2009-04-09 22:27:44 +00001420 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1421 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001422 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001423 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1424 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001425 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1426 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1427 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1428 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001429 std::fprintf(stderr, "\n");
1430}
1431
Chris Lattner29241862009-04-11 21:15:38 +00001432IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001433 if (ID == 0)
1434 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001435
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001436 if (!IdentifierTable || IdentifierData.empty()) {
1437 Error("No identifier table in PCH file");
1438 return 0;
1439 }
Chris Lattner29241862009-04-11 21:15:38 +00001440
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001441 if (IdentifierData[ID - 1] & 0x01) {
1442 uint64_t Offset = IdentifierData[ID - 1];
1443 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001444 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001445 }
Chris Lattner29241862009-04-11 21:15:38 +00001446
1447 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001448}
1449
1450DeclarationName
1451PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1452 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1453 switch (Kind) {
1454 case DeclarationName::Identifier:
1455 return DeclarationName(GetIdentifierInfo(Record, Idx));
1456
1457 case DeclarationName::ObjCZeroArgSelector:
1458 case DeclarationName::ObjCOneArgSelector:
1459 case DeclarationName::ObjCMultiArgSelector:
1460 assert(false && "Unable to de-serialize Objective-C selectors");
1461 break;
1462
1463 case DeclarationName::CXXConstructorName:
1464 return Context.DeclarationNames.getCXXConstructorName(
1465 GetType(Record[Idx++]));
1466
1467 case DeclarationName::CXXDestructorName:
1468 return Context.DeclarationNames.getCXXDestructorName(
1469 GetType(Record[Idx++]));
1470
1471 case DeclarationName::CXXConversionFunctionName:
1472 return Context.DeclarationNames.getCXXConversionFunctionName(
1473 GetType(Record[Idx++]));
1474
1475 case DeclarationName::CXXOperatorName:
1476 return Context.DeclarationNames.getCXXOperatorName(
1477 (OverloadedOperatorKind)Record[Idx++]);
1478
1479 case DeclarationName::CXXUsingDirective:
1480 return DeclarationName::getUsingDirectiveName();
1481 }
1482
1483 // Required to silence GCC warning
1484 return DeclarationName();
1485}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001486
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001487/// \brief Read an integral value
1488llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1489 unsigned BitWidth = Record[Idx++];
1490 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1491 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1492 Idx += NumWords;
1493 return Result;
1494}
1495
1496/// \brief Read a signed integral value
1497llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1498 bool isUnsigned = Record[Idx++];
1499 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1500}
1501
Douglas Gregore2f37202009-04-14 21:55:33 +00001502/// \brief Read a floating-point value
1503llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1504 // FIXME: is this really correct?
1505 return llvm::APFloat(ReadAPInt(Record, Idx));
1506}
1507
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001508Expr *PCHReader::ReadExpr() {
1509 RecordData Record;
1510 unsigned Code = Stream.ReadCode();
1511 unsigned Idx = 0;
1512 PCHStmtReader Reader(*this, Record, Idx);
1513 Stmt::EmptyShell Empty;
1514
1515 Expr *E = 0;
1516 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1517 case pch::EXPR_NULL:
1518 E = 0;
1519 break;
1520
Douglas Gregore2f37202009-04-14 21:55:33 +00001521 case pch::EXPR_PREDEFINED:
1522 // FIXME: untested (until we can serialize function bodies).
1523 E = new (Context) PredefinedExpr(Empty);
1524 break;
1525
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001526 case pch::EXPR_DECL_REF:
1527 E = new (Context) DeclRefExpr(Empty);
1528 break;
1529
1530 case pch::EXPR_INTEGER_LITERAL:
1531 E = new (Context) IntegerLiteral(Empty);
1532 break;
1533
Douglas Gregore2f37202009-04-14 21:55:33 +00001534 case pch::EXPR_FLOATING_LITERAL:
1535 E = new (Context) FloatingLiteral(Empty);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001536 break;
1537
Douglas Gregore2f37202009-04-14 21:55:33 +00001538 case pch::EXPR_CHARACTER_LITERAL:
1539 E = new (Context) CharacterLiteral(Empty);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001540 break;
1541 }
1542
1543 if (E)
1544 Reader.Visit(E);
1545
1546 assert(Idx == Record.size() && "Invalid deserialization of expression");
1547
1548 return E;
1549}
1550
Douglas Gregor179cfb12009-04-10 20:39:37 +00001551DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001552 return Diag(SourceLocation(), DiagID);
1553}
1554
1555DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1556 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001557 Context.getSourceManager()),
1558 DiagID);
1559}