blob: 056c5d50d9bd91823811808fd0ce63d2cba3fdc8 [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
Douglas Gregora151ba42009-04-14 23:32:43 +0000218 : public StmtVisitor<PCHStmtReader, unsigned> {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000219 PCHReader &Reader;
220 const PCHReader::RecordData &Record;
221 unsigned &Idx;
Douglas Gregora151ba42009-04-14 23:32:43 +0000222 llvm::SmallVectorImpl<Expr *> &ExprStack;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000223
224 public:
225 PCHStmtReader(PCHReader &Reader, const PCHReader::RecordData &Record,
Douglas Gregora151ba42009-04-14 23:32:43 +0000226 unsigned &Idx, llvm::SmallVectorImpl<Expr *> &ExprStack)
227 : Reader(Reader), Record(Record), Idx(Idx), ExprStack(ExprStack) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000228
Douglas Gregora151ba42009-04-14 23:32:43 +0000229 // Each of the Visit* functions reads in part of the expression
230 // from the given record and the current expression stack, then
231 // return the total number of operands that it read from the
232 // expression stack.
233
234 unsigned VisitExpr(Expr *E);
235 unsigned VisitPredefinedExpr(PredefinedExpr *E);
236 unsigned VisitDeclRefExpr(DeclRefExpr *E);
237 unsigned VisitIntegerLiteral(IntegerLiteral *E);
238 unsigned VisitFloatingLiteral(FloatingLiteral *E);
239 unsigned VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000240 unsigned VisitParenExpr(ParenExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000241 unsigned VisitCastExpr(CastExpr *E);
242 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000243 };
244}
245
Douglas Gregora151ba42009-04-14 23:32:43 +0000246unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000247 E->setType(Reader.GetType(Record[Idx++]));
248 E->setTypeDependent(Record[Idx++]);
249 E->setValueDependent(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000250 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000251}
252
Douglas Gregora151ba42009-04-14 23:32:43 +0000253unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000254 VisitExpr(E);
255 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
256 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000257 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000258}
259
Douglas Gregora151ba42009-04-14 23:32:43 +0000260unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000261 VisitExpr(E);
262 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
263 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000264 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000265}
266
Douglas Gregora151ba42009-04-14 23:32:43 +0000267unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000268 VisitExpr(E);
269 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
270 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000271 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000272}
273
Douglas Gregora151ba42009-04-14 23:32:43 +0000274unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000275 VisitExpr(E);
276 E->setValue(Reader.ReadAPFloat(Record, Idx));
277 E->setExact(Record[Idx++]);
278 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000279 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000280}
281
Douglas Gregora151ba42009-04-14 23:32:43 +0000282unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000283 VisitExpr(E);
284 E->setValue(Record[Idx++]);
285 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
286 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000287 return 0;
288}
289
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000290unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
291 VisitExpr(E);
292 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
293 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
294 E->setSubExpr(ExprStack.back());
295 return 1;
296}
297
Douglas Gregora151ba42009-04-14 23:32:43 +0000298unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
299 VisitExpr(E);
300 E->setSubExpr(ExprStack.back());
301 return 1;
302}
303
304unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
305 VisitCastExpr(E);
306 E->setLvalueCast(Record[Idx++]);
307 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000308}
309
Douglas Gregorc34897d2009-04-09 22:27:44 +0000310// FIXME: use the diagnostics machinery
311static bool Error(const char *Str) {
312 std::fprintf(stderr, "%s\n", Str);
313 return true;
314}
315
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000316/// \brief Check the contents of the predefines buffer against the
317/// contents of the predefines buffer used to build the PCH file.
318///
319/// The contents of the two predefines buffers should be the same. If
320/// not, then some command-line option changed the preprocessor state
321/// and we must reject the PCH file.
322///
323/// \param PCHPredef The start of the predefines buffer in the PCH
324/// file.
325///
326/// \param PCHPredefLen The length of the predefines buffer in the PCH
327/// file.
328///
329/// \param PCHBufferID The FileID for the PCH predefines buffer.
330///
331/// \returns true if there was a mismatch (in which case the PCH file
332/// should be ignored), or false otherwise.
333bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
334 unsigned PCHPredefLen,
335 FileID PCHBufferID) {
336 const char *Predef = PP.getPredefines().c_str();
337 unsigned PredefLen = PP.getPredefines().size();
338
339 // If the two predefines buffers compare equal, we're done!.
340 if (PredefLen == PCHPredefLen &&
341 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
342 return false;
343
344 // The predefines buffers are different. Produce a reasonable
345 // diagnostic showing where they are different.
346
347 // The source locations (potentially in the two different predefines
348 // buffers)
349 SourceLocation Loc1, Loc2;
350 SourceManager &SourceMgr = PP.getSourceManager();
351
352 // Create a source buffer for our predefines string, so
353 // that we can build a diagnostic that points into that
354 // source buffer.
355 FileID BufferID;
356 if (Predef && Predef[0]) {
357 llvm::MemoryBuffer *Buffer
358 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
359 "<built-in>");
360 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
361 }
362
363 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
364 std::pair<const char *, const char *> Locations
365 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
366
367 if (Locations.first != Predef + MinLen) {
368 // We found the location in the two buffers where there is a
369 // difference. Form source locations to point there (in both
370 // buffers).
371 unsigned Offset = Locations.first - Predef;
372 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
373 .getFileLocWithOffset(Offset);
374 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
375 .getFileLocWithOffset(Offset);
376 } else if (PredefLen > PCHPredefLen) {
377 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
378 .getFileLocWithOffset(MinLen);
379 } else {
380 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
381 .getFileLocWithOffset(MinLen);
382 }
383
384 Diag(Loc1, diag::warn_pch_preprocessor);
385 if (Loc2.isValid())
386 Diag(Loc2, diag::note_predef_in_pch);
387 Diag(diag::note_ignoring_pch) << FileName;
388 return true;
389}
390
Douglas Gregor635f97f2009-04-13 16:31:14 +0000391/// \brief Read the line table in the source manager block.
392/// \returns true if ther was an error.
393static bool ParseLineTable(SourceManager &SourceMgr,
394 llvm::SmallVectorImpl<uint64_t> &Record) {
395 unsigned Idx = 0;
396 LineTableInfo &LineTable = SourceMgr.getLineTable();
397
398 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000399 std::map<int, int> FileIDs;
400 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000401 // Extract the file name
402 unsigned FilenameLen = Record[Idx++];
403 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
404 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000405 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
406 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000407 }
408
409 // Parse the line entries
410 std::vector<LineEntry> Entries;
411 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000412 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000413
414 // Extract the line entries
415 unsigned NumEntries = Record[Idx++];
416 Entries.clear();
417 Entries.reserve(NumEntries);
418 for (unsigned I = 0; I != NumEntries; ++I) {
419 unsigned FileOffset = Record[Idx++];
420 unsigned LineNo = Record[Idx++];
421 int FilenameID = Record[Idx++];
422 SrcMgr::CharacteristicKind FileKind
423 = (SrcMgr::CharacteristicKind)Record[Idx++];
424 unsigned IncludeOffset = Record[Idx++];
425 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
426 FileKind, IncludeOffset));
427 }
428 LineTable.AddEntry(FID, Entries);
429 }
430
431 return false;
432}
433
Douglas Gregorab1cef72009-04-10 03:52:48 +0000434/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000435PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000436 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000437 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
438 Error("Malformed source manager block record");
439 return Failure;
440 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000441
442 SourceManager &SourceMgr = Context.getSourceManager();
443 RecordData Record;
444 while (true) {
445 unsigned Code = Stream.ReadCode();
446 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000447 if (Stream.ReadBlockEnd()) {
448 Error("Error at end of Source Manager block");
449 return Failure;
450 }
451
452 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000453 }
454
455 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
456 // No known subblocks, always skip them.
457 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000458 if (Stream.SkipBlock()) {
459 Error("Malformed block record");
460 return Failure;
461 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000462 continue;
463 }
464
465 if (Code == llvm::bitc::DEFINE_ABBREV) {
466 Stream.ReadAbbrevRecord();
467 continue;
468 }
469
470 // Read a record.
471 const char *BlobStart;
472 unsigned BlobLen;
473 Record.clear();
474 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
475 default: // Default behavior: ignore.
476 break;
477
478 case pch::SM_SLOC_FILE_ENTRY: {
479 // FIXME: We would really like to delay the creation of this
480 // FileEntry until it is actually required, e.g., when producing
481 // a diagnostic with a source location in this file.
482 const FileEntry *File
483 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
484 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000485 FileID ID = SourceMgr.createFileID(File,
486 SourceLocation::getFromRawEncoding(Record[1]),
487 (CharacteristicKind)Record[2]);
488 if (Record[3])
489 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
490 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000491 break;
492 }
493
494 case pch::SM_SLOC_BUFFER_ENTRY: {
495 const char *Name = BlobStart;
496 unsigned Code = Stream.ReadCode();
497 Record.clear();
498 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
499 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000500 llvm::MemoryBuffer *Buffer
501 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
502 BlobStart + BlobLen - 1,
503 Name);
504 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
505
506 if (strcmp(Name, "<built-in>") == 0
507 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
508 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000509 break;
510 }
511
512 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
513 SourceLocation SpellingLoc
514 = SourceLocation::getFromRawEncoding(Record[1]);
515 SourceMgr.createInstantiationLoc(
516 SpellingLoc,
517 SourceLocation::getFromRawEncoding(Record[2]),
518 SourceLocation::getFromRawEncoding(Record[3]),
519 Lexer::MeasureTokenLength(SpellingLoc,
Chris Lattnere1be6022009-04-14 23:22:57 +0000520 SourceMgr,
521 PP.getLangOptions()));
Douglas Gregorab1cef72009-04-10 03:52:48 +0000522 break;
523 }
524
Chris Lattnere1be6022009-04-14 23:22:57 +0000525 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000526 if (ParseLineTable(SourceMgr, Record))
527 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000528 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000529 }
530 }
531}
532
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000533bool PCHReader::ReadPreprocessorBlock() {
534 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
535 return Error("Malformed preprocessor block record");
536
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000537 RecordData Record;
538 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
539 MacroInfo *LastMacro = 0;
540
541 while (true) {
542 unsigned Code = Stream.ReadCode();
543 switch (Code) {
544 case llvm::bitc::END_BLOCK:
545 if (Stream.ReadBlockEnd())
546 return Error("Error at end of preprocessor block");
547 return false;
548
549 case llvm::bitc::ENTER_SUBBLOCK:
550 // No known subblocks, always skip them.
551 Stream.ReadSubBlockID();
552 if (Stream.SkipBlock())
553 return Error("Malformed block record");
554 continue;
555
556 case llvm::bitc::DEFINE_ABBREV:
557 Stream.ReadAbbrevRecord();
558 continue;
559 default: break;
560 }
561
562 // Read a record.
563 Record.clear();
564 pch::PreprocessorRecordTypes RecType =
565 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
566 switch (RecType) {
567 default: // Default behavior: ignore unknown records.
568 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000569 case pch::PP_COUNTER_VALUE:
570 if (!Record.empty())
571 PP.setCounterValue(Record[0]);
572 break;
573
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000574 case pch::PP_MACRO_OBJECT_LIKE:
575 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000576 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
577 if (II == 0)
578 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000579 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
580 bool isUsed = Record[2];
581
582 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
583 MI->setIsUsed(isUsed);
584
585 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
586 // Decode function-like macro info.
587 bool isC99VarArgs = Record[3];
588 bool isGNUVarArgs = Record[4];
589 MacroArgs.clear();
590 unsigned NumArgs = Record[5];
591 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000592 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000593
594 // Install function-like macro info.
595 MI->setIsFunctionLike();
596 if (isC99VarArgs) MI->setIsC99Varargs();
597 if (isGNUVarArgs) MI->setIsGNUVarargs();
598 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
599 PP.getPreprocessorAllocator());
600 }
601
602 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000603 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000604
605 // Remember that we saw this macro last so that we add the tokens that
606 // form its body to it.
607 LastMacro = MI;
608 break;
609 }
610
611 case pch::PP_TOKEN: {
612 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
613 // pretend we didn't see this.
614 if (LastMacro == 0) break;
615
616 Token Tok;
617 Tok.startToken();
618 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
619 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000620 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
621 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000622 Tok.setKind((tok::TokenKind)Record[3]);
623 Tok.setFlag((Token::TokenFlags)Record[4]);
624 LastMacro->AddTokenToBody(Tok);
625 break;
626 }
627 }
628 }
629}
630
Douglas Gregor179cfb12009-04-10 20:39:37 +0000631PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
632 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
633 Error("Malformed block record");
634 return Failure;
635 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000636
Chris Lattner29241862009-04-11 21:15:38 +0000637 uint64_t PreprocessorBlockBit = 0;
638
Douglas Gregorc34897d2009-04-09 22:27:44 +0000639 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000640 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000641 while (!Stream.AtEndOfStream()) {
642 unsigned Code = Stream.ReadCode();
643 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000644 // If we saw the preprocessor block, read it now.
645 if (PreprocessorBlockBit) {
646 uint64_t SavedPos = Stream.GetCurrentBitNo();
647 Stream.JumpToBit(PreprocessorBlockBit);
648 if (ReadPreprocessorBlock()) {
649 Error("Malformed preprocessor block");
650 return Failure;
651 }
652 Stream.JumpToBit(SavedPos);
653 }
654
Douglas Gregor179cfb12009-04-10 20:39:37 +0000655 if (Stream.ReadBlockEnd()) {
656 Error("Error at end of module block");
657 return Failure;
658 }
Chris Lattner29241862009-04-11 21:15:38 +0000659
Douglas Gregor179cfb12009-04-10 20:39:37 +0000660 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000661 }
662
663 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
664 switch (Stream.ReadSubBlockID()) {
665 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
666 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
667 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000668 if (Stream.SkipBlock()) {
669 Error("Malformed block record");
670 return Failure;
671 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000672 break;
673
Chris Lattner29241862009-04-11 21:15:38 +0000674 case pch::PREPROCESSOR_BLOCK_ID:
675 // Skip the preprocessor block for now, but remember where it is. We
676 // want to read it in after the identifier table.
677 if (PreprocessorBlockBit) {
678 Error("Multiple preprocessor blocks found.");
679 return Failure;
680 }
681 PreprocessorBlockBit = Stream.GetCurrentBitNo();
682 if (Stream.SkipBlock()) {
683 Error("Malformed block record");
684 return Failure;
685 }
686 break;
687
Douglas Gregorab1cef72009-04-10 03:52:48 +0000688 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000689 switch (ReadSourceManagerBlock()) {
690 case Success:
691 break;
692
693 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000694 Error("Malformed source manager block");
695 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000696
697 case IgnorePCH:
698 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000699 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000700 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000701 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000702 continue;
703 }
704
705 if (Code == llvm::bitc::DEFINE_ABBREV) {
706 Stream.ReadAbbrevRecord();
707 continue;
708 }
709
710 // Read and process a record.
711 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000712 const char *BlobStart = 0;
713 unsigned BlobLen = 0;
714 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
715 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000716 default: // Default behavior: ignore.
717 break;
718
719 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000720 if (!TypeOffsets.empty()) {
721 Error("Duplicate TYPE_OFFSET record in PCH file");
722 return Failure;
723 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000724 TypeOffsets.swap(Record);
725 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
726 break;
727
728 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000729 if (!DeclOffsets.empty()) {
730 Error("Duplicate DECL_OFFSET record in PCH file");
731 return Failure;
732 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000733 DeclOffsets.swap(Record);
734 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
735 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000736
737 case pch::LANGUAGE_OPTIONS:
738 if (ParseLanguageOptions(Record))
739 return IgnorePCH;
740 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000741
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000742 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000743 std::string TargetTriple(BlobStart, BlobLen);
744 if (TargetTriple != Context.Target.getTargetTriple()) {
745 Diag(diag::warn_pch_target_triple)
746 << TargetTriple << Context.Target.getTargetTriple();
747 Diag(diag::note_ignoring_pch) << FileName;
748 return IgnorePCH;
749 }
750 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000751 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000752
753 case pch::IDENTIFIER_TABLE:
754 IdentifierTable = BlobStart;
755 break;
756
757 case pch::IDENTIFIER_OFFSET:
758 if (!IdentifierData.empty()) {
759 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
760 return Failure;
761 }
762 IdentifierData.swap(Record);
763#ifndef NDEBUG
764 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
765 if ((IdentifierData[I] & 0x01) == 0) {
766 Error("Malformed identifier table in the precompiled header");
767 return Failure;
768 }
769 }
770#endif
771 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000772
773 case pch::EXTERNAL_DEFINITIONS:
774 if (!ExternalDefinitions.empty()) {
775 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
776 return Failure;
777 }
778 ExternalDefinitions.swap(Record);
779 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000780 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000781 }
782
Douglas Gregor179cfb12009-04-10 20:39:37 +0000783 Error("Premature end of bitstream");
784 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000785}
786
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000787PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000788 // Set the PCH file name.
789 this->FileName = FileName;
790
Douglas Gregorc34897d2009-04-09 22:27:44 +0000791 // Open the PCH file.
792 std::string ErrStr;
793 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000794 if (!Buffer) {
795 Error(ErrStr.c_str());
796 return IgnorePCH;
797 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000798
799 // Initialize the stream
800 Stream.init((const unsigned char *)Buffer->getBufferStart(),
801 (const unsigned char *)Buffer->getBufferEnd());
802
803 // Sniff for the signature.
804 if (Stream.Read(8) != 'C' ||
805 Stream.Read(8) != 'P' ||
806 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000807 Stream.Read(8) != 'H') {
808 Error("Not a PCH file");
809 return IgnorePCH;
810 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000811
812 // We expect a number of well-defined blocks, though we don't necessarily
813 // need to understand them all.
814 while (!Stream.AtEndOfStream()) {
815 unsigned Code = Stream.ReadCode();
816
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000817 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
818 Error("Invalid record at top-level");
819 return Failure;
820 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000821
822 unsigned BlockID = Stream.ReadSubBlockID();
823
824 // We only know the PCH subblock ID.
825 switch (BlockID) {
826 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000827 if (Stream.ReadBlockInfoBlock()) {
828 Error("Malformed BlockInfoBlock");
829 return Failure;
830 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000831 break;
832 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000833 switch (ReadPCHBlock()) {
834 case Success:
835 break;
836
837 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000838 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000839
840 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000841 // FIXME: We could consider reading through to the end of this
842 // PCH block, skipping subblocks, to see if there are other
843 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000844 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000845 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000846 break;
847 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000848 if (Stream.SkipBlock()) {
849 Error("Malformed block record");
850 return Failure;
851 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000852 break;
853 }
854 }
855
856 // Load the translation unit declaration
857 ReadDeclRecord(DeclOffsets[0], 0);
858
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000859 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000860}
861
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000862namespace {
863 /// \brief Helper class that saves the current stream position and
864 /// then restores it when destroyed.
865 struct VISIBILITY_HIDDEN SavedStreamPosition {
866 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
867 : Stream(Stream), Offset(Stream.GetCurrentBitNo()),
868 EndOfStream(Stream.AtEndOfStream()){ }
869
870 ~SavedStreamPosition() {
871 if (!EndOfStream)
872 Stream.JumpToBit(Offset);
873 }
874
875 private:
876 llvm::BitstreamReader &Stream;
877 uint64_t Offset;
878 bool EndOfStream;
879 };
880}
881
Douglas Gregor179cfb12009-04-10 20:39:37 +0000882/// \brief Parse the record that corresponds to a LangOptions data
883/// structure.
884///
885/// This routine compares the language options used to generate the
886/// PCH file against the language options set for the current
887/// compilation. For each option, we classify differences between the
888/// two compiler states as either "benign" or "important". Benign
889/// differences don't matter, and we accept them without complaint
890/// (and without modifying the language options). Differences between
891/// the states for important options cause the PCH file to be
892/// unusable, so we emit a warning and return true to indicate that
893/// there was an error.
894///
895/// \returns true if the PCH file is unacceptable, false otherwise.
896bool PCHReader::ParseLanguageOptions(
897 const llvm::SmallVectorImpl<uint64_t> &Record) {
898 const LangOptions &LangOpts = Context.getLangOptions();
899#define PARSE_LANGOPT_BENIGN(Option) ++Idx
900#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
901 if (Record[Idx] != LangOpts.Option) { \
902 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
903 Diag(diag::note_ignoring_pch) << FileName; \
904 return true; \
905 } \
906 ++Idx
907
908 unsigned Idx = 0;
909 PARSE_LANGOPT_BENIGN(Trigraphs);
910 PARSE_LANGOPT_BENIGN(BCPLComment);
911 PARSE_LANGOPT_BENIGN(DollarIdents);
912 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
913 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
914 PARSE_LANGOPT_BENIGN(ImplicitInt);
915 PARSE_LANGOPT_BENIGN(Digraphs);
916 PARSE_LANGOPT_BENIGN(HexFloats);
917 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
918 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
919 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
920 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
921 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
922 PARSE_LANGOPT_BENIGN(CXXOperatorName);
923 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
924 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
925 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
926 PARSE_LANGOPT_BENIGN(PascalStrings);
927 PARSE_LANGOPT_BENIGN(Boolean);
928 PARSE_LANGOPT_BENIGN(WritableStrings);
929 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
930 diag::warn_pch_lax_vector_conversions);
931 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
932 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
933 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
934 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
935 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
936 diag::warn_pch_thread_safe_statics);
937 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
938 PARSE_LANGOPT_BENIGN(EmitAllDecls);
939 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
940 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
941 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
942 diag::warn_pch_heinous_extensions);
943 // FIXME: Most of the options below are benign if the macro wasn't
944 // used. Unfortunately, this means that a PCH compiled without
945 // optimization can't be used with optimization turned on, even
946 // though the only thing that changes is whether __OPTIMIZE__ was
947 // defined... but if __OPTIMIZE__ never showed up in the header, it
948 // doesn't matter. We could consider making this some special kind
949 // of check.
950 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
951 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
952 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
953 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
954 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
955 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
956 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
957 Diag(diag::warn_pch_gc_mode)
958 << (unsigned)Record[Idx] << LangOpts.getGCMode();
959 Diag(diag::note_ignoring_pch) << FileName;
960 return true;
961 }
962 ++Idx;
963 PARSE_LANGOPT_BENIGN(getVisibilityMode());
964 PARSE_LANGOPT_BENIGN(InstantiationDepth);
965#undef PARSE_LANGOPT_IRRELEVANT
966#undef PARSE_LANGOPT_BENIGN
967
968 return false;
969}
970
Douglas Gregorc34897d2009-04-09 22:27:44 +0000971/// \brief Read and return the type at the given offset.
972///
973/// This routine actually reads the record corresponding to the type
974/// at the given offset in the bitstream. It is a helper routine for
975/// GetType, which deals with reading type IDs.
976QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000977 // Keep track of where we are in the stream, then jump back there
978 // after reading this type.
979 SavedStreamPosition SavedPosition(Stream);
980
Douglas Gregorc34897d2009-04-09 22:27:44 +0000981 Stream.JumpToBit(Offset);
982 RecordData Record;
983 unsigned Code = Stream.ReadCode();
984 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +0000985 case pch::TYPE_EXT_QUAL:
986 // FIXME: Deserialize ExtQualType
987 assert(false && "Cannot deserialize qualified types yet");
988 return QualType();
989
Douglas Gregorc34897d2009-04-09 22:27:44 +0000990 case pch::TYPE_FIXED_WIDTH_INT: {
991 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
992 return Context.getFixedWidthIntType(Record[0], Record[1]);
993 }
994
995 case pch::TYPE_COMPLEX: {
996 assert(Record.size() == 1 && "Incorrect encoding of complex type");
997 QualType ElemType = GetType(Record[0]);
998 return Context.getComplexType(ElemType);
999 }
1000
1001 case pch::TYPE_POINTER: {
1002 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1003 QualType PointeeType = GetType(Record[0]);
1004 return Context.getPointerType(PointeeType);
1005 }
1006
1007 case pch::TYPE_BLOCK_POINTER: {
1008 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1009 QualType PointeeType = GetType(Record[0]);
1010 return Context.getBlockPointerType(PointeeType);
1011 }
1012
1013 case pch::TYPE_LVALUE_REFERENCE: {
1014 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1015 QualType PointeeType = GetType(Record[0]);
1016 return Context.getLValueReferenceType(PointeeType);
1017 }
1018
1019 case pch::TYPE_RVALUE_REFERENCE: {
1020 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1021 QualType PointeeType = GetType(Record[0]);
1022 return Context.getRValueReferenceType(PointeeType);
1023 }
1024
1025 case pch::TYPE_MEMBER_POINTER: {
1026 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1027 QualType PointeeType = GetType(Record[0]);
1028 QualType ClassType = GetType(Record[1]);
1029 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1030 }
1031
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001032 case pch::TYPE_CONSTANT_ARRAY: {
1033 QualType ElementType = GetType(Record[0]);
1034 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1035 unsigned IndexTypeQuals = Record[2];
1036 unsigned Idx = 3;
1037 llvm::APInt Size = ReadAPInt(Record, Idx);
1038 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1039 }
1040
1041 case pch::TYPE_INCOMPLETE_ARRAY: {
1042 QualType ElementType = GetType(Record[0]);
1043 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1044 unsigned IndexTypeQuals = Record[2];
1045 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1046 }
1047
1048 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001049 QualType ElementType = GetType(Record[0]);
1050 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1051 unsigned IndexTypeQuals = Record[2];
1052 return Context.getVariableArrayType(ElementType, ReadExpr(),
1053 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001054 }
1055
1056 case pch::TYPE_VECTOR: {
1057 if (Record.size() != 2) {
1058 Error("Incorrect encoding of vector type in PCH file");
1059 return QualType();
1060 }
1061
1062 QualType ElementType = GetType(Record[0]);
1063 unsigned NumElements = Record[1];
1064 return Context.getVectorType(ElementType, NumElements);
1065 }
1066
1067 case pch::TYPE_EXT_VECTOR: {
1068 if (Record.size() != 2) {
1069 Error("Incorrect encoding of extended vector type in PCH file");
1070 return QualType();
1071 }
1072
1073 QualType ElementType = GetType(Record[0]);
1074 unsigned NumElements = Record[1];
1075 return Context.getExtVectorType(ElementType, NumElements);
1076 }
1077
1078 case pch::TYPE_FUNCTION_NO_PROTO: {
1079 if (Record.size() != 1) {
1080 Error("Incorrect encoding of no-proto function type");
1081 return QualType();
1082 }
1083 QualType ResultType = GetType(Record[0]);
1084 return Context.getFunctionNoProtoType(ResultType);
1085 }
1086
1087 case pch::TYPE_FUNCTION_PROTO: {
1088 QualType ResultType = GetType(Record[0]);
1089 unsigned Idx = 1;
1090 unsigned NumParams = Record[Idx++];
1091 llvm::SmallVector<QualType, 16> ParamTypes;
1092 for (unsigned I = 0; I != NumParams; ++I)
1093 ParamTypes.push_back(GetType(Record[Idx++]));
1094 bool isVariadic = Record[Idx++];
1095 unsigned Quals = Record[Idx++];
1096 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1097 isVariadic, Quals);
1098 }
1099
1100 case pch::TYPE_TYPEDEF:
1101 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1102 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1103
1104 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001105 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001106
1107 case pch::TYPE_TYPEOF: {
1108 if (Record.size() != 1) {
1109 Error("Incorrect encoding of typeof(type) in PCH file");
1110 return QualType();
1111 }
1112 QualType UnderlyingType = GetType(Record[0]);
1113 return Context.getTypeOfType(UnderlyingType);
1114 }
1115
1116 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001117 assert(Record.size() == 1 && "Incorrect encoding of record type");
1118 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001119
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001120 case pch::TYPE_ENUM:
1121 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1122 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1123
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001124 case pch::TYPE_OBJC_INTERFACE:
1125 // FIXME: Deserialize ObjCInterfaceType
1126 assert(false && "Cannot de-serialize ObjC interface types yet");
1127 return QualType();
1128
1129 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1130 // FIXME: Deserialize ObjCQualifiedInterfaceType
1131 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1132 return QualType();
1133
1134 case pch::TYPE_OBJC_QUALIFIED_ID:
1135 // FIXME: Deserialize ObjCQualifiedIdType
1136 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1137 return QualType();
1138
1139 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1140 // FIXME: Deserialize ObjCQualifiedClassType
1141 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1142 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001143 }
1144
1145 // Suppress a GCC warning
1146 return QualType();
1147}
1148
1149/// \brief Note that we have loaded the declaration with the given
1150/// Index.
1151///
1152/// This routine notes that this declaration has already been loaded,
1153/// so that future GetDecl calls will return this declaration rather
1154/// than trying to load a new declaration.
1155inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1156 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1157 DeclAlreadyLoaded[Index] = true;
1158 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1159}
1160
1161/// \brief Read the declaration at the given offset from the PCH file.
1162Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001163 // Keep track of where we are in the stream, then jump back there
1164 // after reading this declaration.
1165 SavedStreamPosition SavedPosition(Stream);
1166
Douglas Gregorc34897d2009-04-09 22:27:44 +00001167 Decl *D = 0;
1168 Stream.JumpToBit(Offset);
1169 RecordData Record;
1170 unsigned Code = Stream.ReadCode();
1171 unsigned Idx = 0;
1172 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001173
Douglas Gregorc34897d2009-04-09 22:27:44 +00001174 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1175 case pch::DECL_TRANSLATION_UNIT:
1176 assert(Index == 0 && "Translation unit must be at index 0");
1177 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1178 D = Context.getTranslationUnitDecl();
1179 LoadedDecl(Index, D);
1180 break;
1181
1182 case pch::DECL_TYPEDEF: {
1183 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1184 0, QualType());
1185 LoadedDecl(Index, Typedef);
1186 Reader.VisitTypedefDecl(Typedef);
1187 D = Typedef;
1188 break;
1189 }
1190
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001191 case pch::DECL_ENUM: {
1192 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1193 LoadedDecl(Index, Enum);
1194 Reader.VisitEnumDecl(Enum);
1195 D = Enum;
1196 break;
1197 }
1198
Douglas Gregor982365e2009-04-13 21:20:57 +00001199 case pch::DECL_RECORD: {
1200 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1201 0, SourceLocation(), 0, 0);
1202 LoadedDecl(Index, Record);
1203 Reader.VisitRecordDecl(Record);
1204 D = Record;
1205 break;
1206 }
1207
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001208 case pch::DECL_ENUM_CONSTANT: {
1209 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1210 SourceLocation(), 0,
1211 QualType(), 0,
1212 llvm::APSInt());
1213 LoadedDecl(Index, ECD);
1214 Reader.VisitEnumConstantDecl(ECD);
1215 D = ECD;
1216 break;
1217 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001218
1219 case pch::DECL_FUNCTION: {
1220 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1221 DeclarationName(),
1222 QualType());
1223 LoadedDecl(Index, Function);
1224 Reader.VisitFunctionDecl(Function);
1225 D = Function;
1226 break;
1227 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001228
Douglas Gregor982365e2009-04-13 21:20:57 +00001229 case pch::DECL_FIELD: {
1230 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1231 QualType(), 0, false);
1232 LoadedDecl(Index, Field);
1233 Reader.VisitFieldDecl(Field);
1234 D = Field;
1235 break;
1236 }
1237
Douglas Gregorc34897d2009-04-09 22:27:44 +00001238 case pch::DECL_VAR: {
1239 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1240 VarDecl::None, SourceLocation());
1241 LoadedDecl(Index, Var);
1242 Reader.VisitVarDecl(Var);
1243 D = Var;
1244 break;
1245 }
1246
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001247 case pch::DECL_PARM_VAR: {
1248 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1249 QualType(), VarDecl::None, 0);
1250 LoadedDecl(Index, Parm);
1251 Reader.VisitParmVarDecl(Parm);
1252 D = Parm;
1253 break;
1254 }
1255
1256 case pch::DECL_ORIGINAL_PARM_VAR: {
1257 OriginalParmVarDecl *Parm
1258 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1259 QualType(), QualType(), VarDecl::None,
1260 0);
1261 LoadedDecl(Index, Parm);
1262 Reader.VisitOriginalParmVarDecl(Parm);
1263 D = Parm;
1264 break;
1265 }
1266
Douglas Gregor2a491792009-04-13 22:49:25 +00001267 case pch::DECL_FILE_SCOPE_ASM: {
1268 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1269 SourceLocation(), 0);
1270 LoadedDecl(Index, Asm);
1271 Reader.VisitFileScopeAsmDecl(Asm);
1272 D = Asm;
1273 break;
1274 }
1275
1276 case pch::DECL_BLOCK: {
1277 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1278 LoadedDecl(Index, Block);
1279 Reader.VisitBlockDecl(Block);
1280 D = Block;
1281 break;
1282 }
1283
Douglas Gregorc34897d2009-04-09 22:27:44 +00001284 default:
1285 assert(false && "Cannot de-serialize this kind of declaration");
1286 break;
1287 }
1288
1289 // If this declaration is also a declaration context, get the
1290 // offsets for its tables of lexical and visible declarations.
1291 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1292 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1293 if (Offsets.first || Offsets.second) {
1294 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1295 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1296 DeclContextOffsets[DC] = Offsets;
1297 }
1298 }
1299 assert(Idx == Record.size());
1300
1301 return D;
1302}
1303
Douglas Gregorac8f2802009-04-10 17:25:41 +00001304QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001305 unsigned Quals = ID & 0x07;
1306 unsigned Index = ID >> 3;
1307
1308 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1309 QualType T;
1310 switch ((pch::PredefinedTypeIDs)Index) {
1311 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1312 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1313 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1314
1315 case pch::PREDEF_TYPE_CHAR_U_ID:
1316 case pch::PREDEF_TYPE_CHAR_S_ID:
1317 // FIXME: Check that the signedness of CharTy is correct!
1318 T = Context.CharTy;
1319 break;
1320
1321 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1322 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1323 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1324 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1325 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1326 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1327 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1328 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1329 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1330 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1331 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1332 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1333 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1334 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1335 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1336 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1337 }
1338
1339 assert(!T.isNull() && "Unknown predefined type");
1340 return T.getQualifiedType(Quals);
1341 }
1342
1343 Index -= pch::NUM_PREDEF_TYPE_IDS;
1344 if (!TypeAlreadyLoaded[Index]) {
1345 // Load the type from the PCH file.
1346 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1347 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1348 TypeAlreadyLoaded[Index] = true;
1349 }
1350
1351 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1352}
1353
Douglas Gregorac8f2802009-04-10 17:25:41 +00001354Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001355 if (ID == 0)
1356 return 0;
1357
1358 unsigned Index = ID - 1;
1359 if (DeclAlreadyLoaded[Index])
1360 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1361
1362 // Load the declaration from the PCH file.
1363 return ReadDeclRecord(DeclOffsets[Index], Index);
1364}
1365
1366bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001367 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001368 assert(DC->hasExternalLexicalStorage() &&
1369 "DeclContext has no lexical decls in storage");
1370 uint64_t Offset = DeclContextOffsets[DC].first;
1371 assert(Offset && "DeclContext has no lexical decls in storage");
1372
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001373 // Keep track of where we are in the stream, then jump back there
1374 // after reading this context.
1375 SavedStreamPosition SavedPosition(Stream);
1376
Douglas Gregorc34897d2009-04-09 22:27:44 +00001377 // Load the record containing all of the declarations lexically in
1378 // this context.
1379 Stream.JumpToBit(Offset);
1380 RecordData Record;
1381 unsigned Code = Stream.ReadCode();
1382 unsigned RecCode = Stream.ReadRecord(Code, Record);
1383 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1384
1385 // Load all of the declaration IDs
1386 Decls.clear();
1387 Decls.insert(Decls.end(), Record.begin(), Record.end());
1388 return false;
1389}
1390
1391bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1392 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1393 assert(DC->hasExternalVisibleStorage() &&
1394 "DeclContext has no visible decls in storage");
1395 uint64_t Offset = DeclContextOffsets[DC].second;
1396 assert(Offset && "DeclContext has no visible decls in storage");
1397
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001398 // Keep track of where we are in the stream, then jump back there
1399 // after reading this context.
1400 SavedStreamPosition SavedPosition(Stream);
1401
Douglas Gregorc34897d2009-04-09 22:27:44 +00001402 // Load the record containing all of the declarations visible in
1403 // this context.
1404 Stream.JumpToBit(Offset);
1405 RecordData Record;
1406 unsigned Code = Stream.ReadCode();
1407 unsigned RecCode = Stream.ReadRecord(Code, Record);
1408 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1409 if (Record.size() == 0)
1410 return false;
1411
1412 Decls.clear();
1413
1414 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001415 while (Idx < Record.size()) {
1416 Decls.push_back(VisibleDeclaration());
1417 Decls.back().Name = ReadDeclarationName(Record, Idx);
1418
Douglas Gregorc34897d2009-04-09 22:27:44 +00001419 unsigned Size = Record[Idx++];
1420 llvm::SmallVector<unsigned, 4> & LoadedDecls
1421 = Decls.back().Declarations;
1422 LoadedDecls.reserve(Size);
1423 for (unsigned I = 0; I < Size; ++I)
1424 LoadedDecls.push_back(Record[Idx++]);
1425 }
1426
1427 return false;
1428}
1429
Douglas Gregor631f6c62009-04-14 00:24:19 +00001430void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1431 if (!Consumer)
1432 return;
1433
1434 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1435 Decl *D = GetDecl(ExternalDefinitions[I]);
1436 DeclGroupRef DG(D);
1437 Consumer->HandleTopLevelDecl(DG);
1438 }
1439}
1440
Douglas Gregorc34897d2009-04-09 22:27:44 +00001441void PCHReader::PrintStats() {
1442 std::fprintf(stderr, "*** PCH Statistics:\n");
1443
1444 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1445 TypeAlreadyLoaded.end(),
1446 true);
1447 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1448 DeclAlreadyLoaded.end(),
1449 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001450 unsigned NumIdentifiersLoaded = 0;
1451 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1452 if ((IdentifierData[I] & 0x01) == 0)
1453 ++NumIdentifiersLoaded;
1454 }
1455
Douglas Gregorc34897d2009-04-09 22:27:44 +00001456 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1457 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001458 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001459 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1460 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001461 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1462 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1463 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1464 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001465 std::fprintf(stderr, "\n");
1466}
1467
Chris Lattner29241862009-04-11 21:15:38 +00001468IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001469 if (ID == 0)
1470 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001471
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001472 if (!IdentifierTable || IdentifierData.empty()) {
1473 Error("No identifier table in PCH file");
1474 return 0;
1475 }
Chris Lattner29241862009-04-11 21:15:38 +00001476
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001477 if (IdentifierData[ID - 1] & 0x01) {
1478 uint64_t Offset = IdentifierData[ID - 1];
1479 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001480 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001481 }
Chris Lattner29241862009-04-11 21:15:38 +00001482
1483 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001484}
1485
1486DeclarationName
1487PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1488 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1489 switch (Kind) {
1490 case DeclarationName::Identifier:
1491 return DeclarationName(GetIdentifierInfo(Record, Idx));
1492
1493 case DeclarationName::ObjCZeroArgSelector:
1494 case DeclarationName::ObjCOneArgSelector:
1495 case DeclarationName::ObjCMultiArgSelector:
1496 assert(false && "Unable to de-serialize Objective-C selectors");
1497 break;
1498
1499 case DeclarationName::CXXConstructorName:
1500 return Context.DeclarationNames.getCXXConstructorName(
1501 GetType(Record[Idx++]));
1502
1503 case DeclarationName::CXXDestructorName:
1504 return Context.DeclarationNames.getCXXDestructorName(
1505 GetType(Record[Idx++]));
1506
1507 case DeclarationName::CXXConversionFunctionName:
1508 return Context.DeclarationNames.getCXXConversionFunctionName(
1509 GetType(Record[Idx++]));
1510
1511 case DeclarationName::CXXOperatorName:
1512 return Context.DeclarationNames.getCXXOperatorName(
1513 (OverloadedOperatorKind)Record[Idx++]);
1514
1515 case DeclarationName::CXXUsingDirective:
1516 return DeclarationName::getUsingDirectiveName();
1517 }
1518
1519 // Required to silence GCC warning
1520 return DeclarationName();
1521}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001522
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001523/// \brief Read an integral value
1524llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1525 unsigned BitWidth = Record[Idx++];
1526 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1527 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1528 Idx += NumWords;
1529 return Result;
1530}
1531
1532/// \brief Read a signed integral value
1533llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1534 bool isUnsigned = Record[Idx++];
1535 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1536}
1537
Douglas Gregore2f37202009-04-14 21:55:33 +00001538/// \brief Read a floating-point value
1539llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1540 // FIXME: is this really correct?
1541 return llvm::APFloat(ReadAPInt(Record, Idx));
1542}
1543
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001544Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001545 // Within the bitstream, expressions are stored in Reverse Polish
1546 // Notation, with each of the subexpressions preceding the
1547 // expression they are stored in. To evaluate expressions, we
1548 // continue reading expressions and placing them on the stack, with
1549 // expressions having operands removing those operands from the
1550 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1551 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001552 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001553 unsigned Idx;
1554 llvm::SmallVector<Expr *, 16> ExprStack;
1555 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001556 Stmt::EmptyShell Empty;
1557
Douglas Gregora151ba42009-04-14 23:32:43 +00001558 while (true) {
1559 unsigned Code = Stream.ReadCode();
1560 if (Code == llvm::bitc::END_BLOCK) {
1561 if (Stream.ReadBlockEnd()) {
1562 Error("Error at end of Source Manager block");
1563 return 0;
1564 }
1565 break;
1566 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001567
Douglas Gregora151ba42009-04-14 23:32:43 +00001568 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1569 // No known subblocks, always skip them.
1570 Stream.ReadSubBlockID();
1571 if (Stream.SkipBlock()) {
1572 Error("Malformed block record");
1573 return 0;
1574 }
1575 continue;
1576 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001577
Douglas Gregora151ba42009-04-14 23:32:43 +00001578 if (Code == llvm::bitc::DEFINE_ABBREV) {
1579 Stream.ReadAbbrevRecord();
1580 continue;
1581 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001582
Douglas Gregora151ba42009-04-14 23:32:43 +00001583 Expr *E = 0;
1584 Idx = 0;
1585 Record.clear();
1586 bool Finished = false;
1587 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1588 case pch::EXPR_STOP:
1589 Finished = true;
1590 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001591
Douglas Gregora151ba42009-04-14 23:32:43 +00001592 case pch::EXPR_NULL:
1593 E = 0;
1594 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001595
Douglas Gregora151ba42009-04-14 23:32:43 +00001596 case pch::EXPR_PREDEFINED:
1597 // FIXME: untested (until we can serialize function bodies).
1598 E = new (Context) PredefinedExpr(Empty);
1599 break;
1600
1601 case pch::EXPR_DECL_REF:
1602 E = new (Context) DeclRefExpr(Empty);
1603 break;
1604
1605 case pch::EXPR_INTEGER_LITERAL:
1606 E = new (Context) IntegerLiteral(Empty);
1607 break;
1608
1609 case pch::EXPR_FLOATING_LITERAL:
1610 E = new (Context) FloatingLiteral(Empty);
1611 break;
1612
1613 case pch::EXPR_CHARACTER_LITERAL:
1614 E = new (Context) CharacterLiteral(Empty);
1615 break;
1616
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00001617 case pch::EXPR_PAREN:
1618 E = new (Context) ParenExpr(Empty);
1619 break;
1620
Douglas Gregora151ba42009-04-14 23:32:43 +00001621 case pch::EXPR_IMPLICIT_CAST:
1622 E = new (Context) ImplicitCastExpr(Empty);
1623 break;
1624 }
1625
1626 // We hit an EXPR_STOP, so we're done with this expression.
1627 if (Finished)
1628 break;
1629
1630 if (E) {
1631 unsigned NumSubExprs = Reader.Visit(E);
1632 while (NumSubExprs > 0) {
1633 ExprStack.pop_back();
1634 --NumSubExprs;
1635 }
1636 }
1637
1638 assert(Idx == Record.size() && "Invalid deserialization of expression");
1639 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001640 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001641 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
1642 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001643}
1644
Douglas Gregor179cfb12009-04-10 20:39:37 +00001645DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001646 return Diag(SourceLocation(), DiagID);
1647}
1648
1649DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1650 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001651 Context.getSourceManager()),
1652 DiagID);
1653}