blob: 5a01aee8b8b6c701e0cac9696757fb06b455e9ee [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 Gregor596e0932009-04-15 16:35:07 +0000229 /// \brief The number of record fields required for the Expr class
230 /// itself.
231 static const unsigned NumExprFields = 3;
232
Douglas Gregora151ba42009-04-14 23:32:43 +0000233 // Each of the Visit* functions reads in part of the expression
234 // from the given record and the current expression stack, then
235 // return the total number of operands that it read from the
236 // expression stack.
237
238 unsigned VisitExpr(Expr *E);
239 unsigned VisitPredefinedExpr(PredefinedExpr *E);
240 unsigned VisitDeclRefExpr(DeclRefExpr *E);
241 unsigned VisitIntegerLiteral(IntegerLiteral *E);
242 unsigned VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregor596e0932009-04-15 16:35:07 +0000243 unsigned VisitStringLiteral(StringLiteral *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000244 unsigned VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000245 unsigned VisitParenExpr(ParenExpr *E);
Douglas Gregor12d74052009-04-15 15:58:59 +0000246 unsigned VisitUnaryOperator(UnaryOperator *E);
247 unsigned VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000248 unsigned VisitCallExpr(CallExpr *E);
249 unsigned VisitMemberExpr(MemberExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000250 unsigned VisitCastExpr(CastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000251 unsigned VisitBinaryOperator(BinaryOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000252 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000253 unsigned VisitExplicitCastExpr(ExplicitCastExpr *E);
254 unsigned VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000255 };
256}
257
Douglas Gregora151ba42009-04-14 23:32:43 +0000258unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000259 E->setType(Reader.GetType(Record[Idx++]));
260 E->setTypeDependent(Record[Idx++]);
261 E->setValueDependent(Record[Idx++]);
Douglas Gregor596e0932009-04-15 16:35:07 +0000262 assert(Idx == NumExprFields && "Incorrect expression field count");
Douglas Gregora151ba42009-04-14 23:32:43 +0000263 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000264}
265
Douglas Gregora151ba42009-04-14 23:32:43 +0000266unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000267 VisitExpr(E);
268 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
269 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000270 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000271}
272
Douglas Gregora151ba42009-04-14 23:32:43 +0000273unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000274 VisitExpr(E);
275 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
276 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000277 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000278}
279
Douglas Gregora151ba42009-04-14 23:32:43 +0000280unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000281 VisitExpr(E);
282 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
283 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000284 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000285}
286
Douglas Gregora151ba42009-04-14 23:32:43 +0000287unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000288 VisitExpr(E);
289 E->setValue(Reader.ReadAPFloat(Record, Idx));
290 E->setExact(Record[Idx++]);
291 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000292 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000293}
294
Douglas Gregor596e0932009-04-15 16:35:07 +0000295unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) {
296 VisitExpr(E);
297 unsigned Len = Record[Idx++];
298 assert(Record[Idx] == E->getNumConcatenated() &&
299 "Wrong number of concatenated tokens!");
300 ++Idx;
301 E->setWide(Record[Idx++]);
302
303 // Read string data
304 llvm::SmallVector<char, 16> Str(&Record[Idx], &Record[Idx] + Len);
305 E->setStrData(Reader.getContext(), &Str[0], Len);
306 Idx += Len;
307
308 // Read source locations
309 for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I)
310 E->setStrTokenLoc(I, SourceLocation::getFromRawEncoding(Record[Idx++]));
311
312 return 0;
313}
314
Douglas Gregora151ba42009-04-14 23:32:43 +0000315unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000316 VisitExpr(E);
317 E->setValue(Record[Idx++]);
318 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
319 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000320 return 0;
321}
322
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000323unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
324 VisitExpr(E);
325 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
326 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
327 E->setSubExpr(ExprStack.back());
328 return 1;
329}
330
Douglas Gregor12d74052009-04-15 15:58:59 +0000331unsigned PCHStmtReader::VisitUnaryOperator(UnaryOperator *E) {
332 VisitExpr(E);
333 E->setSubExpr(ExprStack.back());
334 E->setOpcode((UnaryOperator::Opcode)Record[Idx++]);
335 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
336 return 1;
337}
338
339unsigned PCHStmtReader::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
340 VisitExpr(E);
341 E->setSizeof(Record[Idx++]);
342 if (Record[Idx] == 0) {
343 E->setArgument(ExprStack.back());
344 ++Idx;
345 } else {
346 E->setArgument(Reader.GetType(Record[Idx++]));
347 }
348 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
349 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
350 return E->isArgumentType()? 0 : 1;
351}
352
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000353unsigned PCHStmtReader::VisitCallExpr(CallExpr *E) {
354 VisitExpr(E);
355 E->setNumArgs(Reader.getContext(), Record[Idx++]);
356 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
357 E->setCallee(ExprStack[ExprStack.size() - E->getNumArgs() - 1]);
358 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
359 E->setArg(I, ExprStack[ExprStack.size() - N + I]);
360 return E->getNumArgs() + 1;
361}
362
363unsigned PCHStmtReader::VisitMemberExpr(MemberExpr *E) {
364 VisitExpr(E);
365 E->setBase(ExprStack.back());
366 E->setMemberDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
367 E->setMemberLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
368 E->setArrow(Record[Idx++]);
369 return 1;
370}
371
Douglas Gregora151ba42009-04-14 23:32:43 +0000372unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
373 VisitExpr(E);
374 E->setSubExpr(ExprStack.back());
375 return 1;
376}
377
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000378unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) {
379 VisitExpr(E);
380 E->setLHS(ExprStack.end()[-2]);
381 E->setRHS(ExprStack.end()[-1]);
382 E->setOpcode((BinaryOperator::Opcode)Record[Idx++]);
383 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
384 return 2;
385}
386
Douglas Gregora151ba42009-04-14 23:32:43 +0000387unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
388 VisitCastExpr(E);
389 E->setLvalueCast(Record[Idx++]);
390 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000391}
392
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000393unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
394 VisitCastExpr(E);
395 E->setTypeAsWritten(Reader.GetType(Record[Idx++]));
396 return 1;
397}
398
399unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
400 VisitExplicitCastExpr(E);
401 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
402 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
403 return 1;
404}
405
Douglas Gregorc34897d2009-04-09 22:27:44 +0000406// FIXME: use the diagnostics machinery
407static bool Error(const char *Str) {
408 std::fprintf(stderr, "%s\n", Str);
409 return true;
410}
411
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000412/// \brief Check the contents of the predefines buffer against the
413/// contents of the predefines buffer used to build the PCH file.
414///
415/// The contents of the two predefines buffers should be the same. If
416/// not, then some command-line option changed the preprocessor state
417/// and we must reject the PCH file.
418///
419/// \param PCHPredef The start of the predefines buffer in the PCH
420/// file.
421///
422/// \param PCHPredefLen The length of the predefines buffer in the PCH
423/// file.
424///
425/// \param PCHBufferID The FileID for the PCH predefines buffer.
426///
427/// \returns true if there was a mismatch (in which case the PCH file
428/// should be ignored), or false otherwise.
429bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
430 unsigned PCHPredefLen,
431 FileID PCHBufferID) {
432 const char *Predef = PP.getPredefines().c_str();
433 unsigned PredefLen = PP.getPredefines().size();
434
435 // If the two predefines buffers compare equal, we're done!.
436 if (PredefLen == PCHPredefLen &&
437 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
438 return false;
439
440 // The predefines buffers are different. Produce a reasonable
441 // diagnostic showing where they are different.
442
443 // The source locations (potentially in the two different predefines
444 // buffers)
445 SourceLocation Loc1, Loc2;
446 SourceManager &SourceMgr = PP.getSourceManager();
447
448 // Create a source buffer for our predefines string, so
449 // that we can build a diagnostic that points into that
450 // source buffer.
451 FileID BufferID;
452 if (Predef && Predef[0]) {
453 llvm::MemoryBuffer *Buffer
454 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
455 "<built-in>");
456 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
457 }
458
459 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
460 std::pair<const char *, const char *> Locations
461 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
462
463 if (Locations.first != Predef + MinLen) {
464 // We found the location in the two buffers where there is a
465 // difference. Form source locations to point there (in both
466 // buffers).
467 unsigned Offset = Locations.first - Predef;
468 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
469 .getFileLocWithOffset(Offset);
470 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
471 .getFileLocWithOffset(Offset);
472 } else if (PredefLen > PCHPredefLen) {
473 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
474 .getFileLocWithOffset(MinLen);
475 } else {
476 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
477 .getFileLocWithOffset(MinLen);
478 }
479
480 Diag(Loc1, diag::warn_pch_preprocessor);
481 if (Loc2.isValid())
482 Diag(Loc2, diag::note_predef_in_pch);
483 Diag(diag::note_ignoring_pch) << FileName;
484 return true;
485}
486
Douglas Gregor635f97f2009-04-13 16:31:14 +0000487/// \brief Read the line table in the source manager block.
488/// \returns true if ther was an error.
489static bool ParseLineTable(SourceManager &SourceMgr,
490 llvm::SmallVectorImpl<uint64_t> &Record) {
491 unsigned Idx = 0;
492 LineTableInfo &LineTable = SourceMgr.getLineTable();
493
494 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000495 std::map<int, int> FileIDs;
496 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000497 // Extract the file name
498 unsigned FilenameLen = Record[Idx++];
499 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
500 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000501 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
502 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000503 }
504
505 // Parse the line entries
506 std::vector<LineEntry> Entries;
507 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000508 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000509
510 // Extract the line entries
511 unsigned NumEntries = Record[Idx++];
512 Entries.clear();
513 Entries.reserve(NumEntries);
514 for (unsigned I = 0; I != NumEntries; ++I) {
515 unsigned FileOffset = Record[Idx++];
516 unsigned LineNo = Record[Idx++];
517 int FilenameID = Record[Idx++];
518 SrcMgr::CharacteristicKind FileKind
519 = (SrcMgr::CharacteristicKind)Record[Idx++];
520 unsigned IncludeOffset = Record[Idx++];
521 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
522 FileKind, IncludeOffset));
523 }
524 LineTable.AddEntry(FID, Entries);
525 }
526
527 return false;
528}
529
Douglas Gregorab1cef72009-04-10 03:52:48 +0000530/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000531PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000532 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000533 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
534 Error("Malformed source manager block record");
535 return Failure;
536 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000537
538 SourceManager &SourceMgr = Context.getSourceManager();
539 RecordData Record;
540 while (true) {
541 unsigned Code = Stream.ReadCode();
542 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000543 if (Stream.ReadBlockEnd()) {
544 Error("Error at end of Source Manager block");
545 return Failure;
546 }
547
548 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000549 }
550
551 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
552 // No known subblocks, always skip them.
553 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000554 if (Stream.SkipBlock()) {
555 Error("Malformed block record");
556 return Failure;
557 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000558 continue;
559 }
560
561 if (Code == llvm::bitc::DEFINE_ABBREV) {
562 Stream.ReadAbbrevRecord();
563 continue;
564 }
565
566 // Read a record.
567 const char *BlobStart;
568 unsigned BlobLen;
569 Record.clear();
570 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
571 default: // Default behavior: ignore.
572 break;
573
574 case pch::SM_SLOC_FILE_ENTRY: {
575 // FIXME: We would really like to delay the creation of this
576 // FileEntry until it is actually required, e.g., when producing
577 // a diagnostic with a source location in this file.
578 const FileEntry *File
579 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
580 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000581 FileID ID = SourceMgr.createFileID(File,
582 SourceLocation::getFromRawEncoding(Record[1]),
583 (CharacteristicKind)Record[2]);
584 if (Record[3])
585 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
586 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000587 break;
588 }
589
590 case pch::SM_SLOC_BUFFER_ENTRY: {
591 const char *Name = BlobStart;
592 unsigned Code = Stream.ReadCode();
593 Record.clear();
594 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
595 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000596 llvm::MemoryBuffer *Buffer
597 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
598 BlobStart + BlobLen - 1,
599 Name);
600 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
601
602 if (strcmp(Name, "<built-in>") == 0
603 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
604 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000605 break;
606 }
607
608 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
609 SourceLocation SpellingLoc
610 = SourceLocation::getFromRawEncoding(Record[1]);
611 SourceMgr.createInstantiationLoc(
612 SpellingLoc,
613 SourceLocation::getFromRawEncoding(Record[2]),
614 SourceLocation::getFromRawEncoding(Record[3]),
Douglas Gregor364e5802009-04-15 18:05:10 +0000615 Record[4]);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000616 break;
617 }
618
Chris Lattnere1be6022009-04-14 23:22:57 +0000619 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000620 if (ParseLineTable(SourceMgr, Record))
621 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000622 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000623 }
624 }
625}
626
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000627bool PCHReader::ReadPreprocessorBlock() {
628 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
629 return Error("Malformed preprocessor block record");
630
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000631 RecordData Record;
632 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
633 MacroInfo *LastMacro = 0;
634
635 while (true) {
636 unsigned Code = Stream.ReadCode();
637 switch (Code) {
638 case llvm::bitc::END_BLOCK:
639 if (Stream.ReadBlockEnd())
640 return Error("Error at end of preprocessor block");
641 return false;
642
643 case llvm::bitc::ENTER_SUBBLOCK:
644 // No known subblocks, always skip them.
645 Stream.ReadSubBlockID();
646 if (Stream.SkipBlock())
647 return Error("Malformed block record");
648 continue;
649
650 case llvm::bitc::DEFINE_ABBREV:
651 Stream.ReadAbbrevRecord();
652 continue;
653 default: break;
654 }
655
656 // Read a record.
657 Record.clear();
658 pch::PreprocessorRecordTypes RecType =
659 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
660 switch (RecType) {
661 default: // Default behavior: ignore unknown records.
662 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000663 case pch::PP_COUNTER_VALUE:
664 if (!Record.empty())
665 PP.setCounterValue(Record[0]);
666 break;
667
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000668 case pch::PP_MACRO_OBJECT_LIKE:
669 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000670 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
671 if (II == 0)
672 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000673 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
674 bool isUsed = Record[2];
675
676 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
677 MI->setIsUsed(isUsed);
678
679 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
680 // Decode function-like macro info.
681 bool isC99VarArgs = Record[3];
682 bool isGNUVarArgs = Record[4];
683 MacroArgs.clear();
684 unsigned NumArgs = Record[5];
685 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000686 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000687
688 // Install function-like macro info.
689 MI->setIsFunctionLike();
690 if (isC99VarArgs) MI->setIsC99Varargs();
691 if (isGNUVarArgs) MI->setIsGNUVarargs();
692 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
693 PP.getPreprocessorAllocator());
694 }
695
696 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000697 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000698
699 // Remember that we saw this macro last so that we add the tokens that
700 // form its body to it.
701 LastMacro = MI;
702 break;
703 }
704
705 case pch::PP_TOKEN: {
706 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
707 // pretend we didn't see this.
708 if (LastMacro == 0) break;
709
710 Token Tok;
711 Tok.startToken();
712 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
713 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000714 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
715 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000716 Tok.setKind((tok::TokenKind)Record[3]);
717 Tok.setFlag((Token::TokenFlags)Record[4]);
718 LastMacro->AddTokenToBody(Tok);
719 break;
720 }
721 }
722 }
723}
724
Douglas Gregor179cfb12009-04-10 20:39:37 +0000725PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
726 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
727 Error("Malformed block record");
728 return Failure;
729 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000730
Chris Lattner29241862009-04-11 21:15:38 +0000731 uint64_t PreprocessorBlockBit = 0;
732
Douglas Gregorc34897d2009-04-09 22:27:44 +0000733 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000734 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000735 while (!Stream.AtEndOfStream()) {
736 unsigned Code = Stream.ReadCode();
737 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000738 // If we saw the preprocessor block, read it now.
739 if (PreprocessorBlockBit) {
740 uint64_t SavedPos = Stream.GetCurrentBitNo();
741 Stream.JumpToBit(PreprocessorBlockBit);
742 if (ReadPreprocessorBlock()) {
743 Error("Malformed preprocessor block");
744 return Failure;
745 }
746 Stream.JumpToBit(SavedPos);
747 }
748
Douglas Gregor179cfb12009-04-10 20:39:37 +0000749 if (Stream.ReadBlockEnd()) {
750 Error("Error at end of module block");
751 return Failure;
752 }
Chris Lattner29241862009-04-11 21:15:38 +0000753
Douglas Gregor179cfb12009-04-10 20:39:37 +0000754 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000755 }
756
757 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
758 switch (Stream.ReadSubBlockID()) {
759 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
760 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
761 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000762 if (Stream.SkipBlock()) {
763 Error("Malformed block record");
764 return Failure;
765 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000766 break;
767
Chris Lattner29241862009-04-11 21:15:38 +0000768 case pch::PREPROCESSOR_BLOCK_ID:
769 // Skip the preprocessor block for now, but remember where it is. We
770 // want to read it in after the identifier table.
771 if (PreprocessorBlockBit) {
772 Error("Multiple preprocessor blocks found.");
773 return Failure;
774 }
775 PreprocessorBlockBit = Stream.GetCurrentBitNo();
776 if (Stream.SkipBlock()) {
777 Error("Malformed block record");
778 return Failure;
779 }
780 break;
781
Douglas Gregorab1cef72009-04-10 03:52:48 +0000782 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000783 switch (ReadSourceManagerBlock()) {
784 case Success:
785 break;
786
787 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000788 Error("Malformed source manager block");
789 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000790
791 case IgnorePCH:
792 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000793 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000794 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000795 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000796 continue;
797 }
798
799 if (Code == llvm::bitc::DEFINE_ABBREV) {
800 Stream.ReadAbbrevRecord();
801 continue;
802 }
803
804 // Read and process a record.
805 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000806 const char *BlobStart = 0;
807 unsigned BlobLen = 0;
808 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
809 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000810 default: // Default behavior: ignore.
811 break;
812
813 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000814 if (!TypeOffsets.empty()) {
815 Error("Duplicate TYPE_OFFSET record in PCH file");
816 return Failure;
817 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000818 TypeOffsets.swap(Record);
819 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
820 break;
821
822 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000823 if (!DeclOffsets.empty()) {
824 Error("Duplicate DECL_OFFSET record in PCH file");
825 return Failure;
826 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000827 DeclOffsets.swap(Record);
828 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
829 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000830
831 case pch::LANGUAGE_OPTIONS:
832 if (ParseLanguageOptions(Record))
833 return IgnorePCH;
834 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000835
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000836 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000837 std::string TargetTriple(BlobStart, BlobLen);
838 if (TargetTriple != Context.Target.getTargetTriple()) {
839 Diag(diag::warn_pch_target_triple)
840 << TargetTriple << Context.Target.getTargetTriple();
841 Diag(diag::note_ignoring_pch) << FileName;
842 return IgnorePCH;
843 }
844 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000845 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000846
847 case pch::IDENTIFIER_TABLE:
848 IdentifierTable = BlobStart;
849 break;
850
851 case pch::IDENTIFIER_OFFSET:
852 if (!IdentifierData.empty()) {
853 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
854 return Failure;
855 }
856 IdentifierData.swap(Record);
857#ifndef NDEBUG
858 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
859 if ((IdentifierData[I] & 0x01) == 0) {
860 Error("Malformed identifier table in the precompiled header");
861 return Failure;
862 }
863 }
864#endif
865 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000866
867 case pch::EXTERNAL_DEFINITIONS:
868 if (!ExternalDefinitions.empty()) {
869 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
870 return Failure;
871 }
872 ExternalDefinitions.swap(Record);
873 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000874 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000875 }
876
Douglas Gregor179cfb12009-04-10 20:39:37 +0000877 Error("Premature end of bitstream");
878 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000879}
880
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000881PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000882 // Set the PCH file name.
883 this->FileName = FileName;
884
Douglas Gregorc34897d2009-04-09 22:27:44 +0000885 // Open the PCH file.
886 std::string ErrStr;
887 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000888 if (!Buffer) {
889 Error(ErrStr.c_str());
890 return IgnorePCH;
891 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000892
893 // Initialize the stream
894 Stream.init((const unsigned char *)Buffer->getBufferStart(),
895 (const unsigned char *)Buffer->getBufferEnd());
896
897 // Sniff for the signature.
898 if (Stream.Read(8) != 'C' ||
899 Stream.Read(8) != 'P' ||
900 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000901 Stream.Read(8) != 'H') {
902 Error("Not a PCH file");
903 return IgnorePCH;
904 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000905
906 // We expect a number of well-defined blocks, though we don't necessarily
907 // need to understand them all.
908 while (!Stream.AtEndOfStream()) {
909 unsigned Code = Stream.ReadCode();
910
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000911 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
912 Error("Invalid record at top-level");
913 return Failure;
914 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000915
916 unsigned BlockID = Stream.ReadSubBlockID();
917
918 // We only know the PCH subblock ID.
919 switch (BlockID) {
920 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000921 if (Stream.ReadBlockInfoBlock()) {
922 Error("Malformed BlockInfoBlock");
923 return Failure;
924 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000925 break;
926 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000927 switch (ReadPCHBlock()) {
928 case Success:
929 break;
930
931 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000932 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000933
934 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +0000935 // FIXME: We could consider reading through to the end of this
936 // PCH block, skipping subblocks, to see if there are other
937 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000938 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000939 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000940 break;
941 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000942 if (Stream.SkipBlock()) {
943 Error("Malformed block record");
944 return Failure;
945 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000946 break;
947 }
948 }
949
950 // Load the translation unit declaration
951 ReadDeclRecord(DeclOffsets[0], 0);
952
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000953 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000954}
955
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000956namespace {
957 /// \brief Helper class that saves the current stream position and
958 /// then restores it when destroyed.
959 struct VISIBILITY_HIDDEN SavedStreamPosition {
960 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000961 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000962
963 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +0000964 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000965 }
966
967 private:
968 llvm::BitstreamReader &Stream;
969 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000970 };
971}
972
Douglas Gregor179cfb12009-04-10 20:39:37 +0000973/// \brief Parse the record that corresponds to a LangOptions data
974/// structure.
975///
976/// This routine compares the language options used to generate the
977/// PCH file against the language options set for the current
978/// compilation. For each option, we classify differences between the
979/// two compiler states as either "benign" or "important". Benign
980/// differences don't matter, and we accept them without complaint
981/// (and without modifying the language options). Differences between
982/// the states for important options cause the PCH file to be
983/// unusable, so we emit a warning and return true to indicate that
984/// there was an error.
985///
986/// \returns true if the PCH file is unacceptable, false otherwise.
987bool PCHReader::ParseLanguageOptions(
988 const llvm::SmallVectorImpl<uint64_t> &Record) {
989 const LangOptions &LangOpts = Context.getLangOptions();
990#define PARSE_LANGOPT_BENIGN(Option) ++Idx
991#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
992 if (Record[Idx] != LangOpts.Option) { \
993 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
994 Diag(diag::note_ignoring_pch) << FileName; \
995 return true; \
996 } \
997 ++Idx
998
999 unsigned Idx = 0;
1000 PARSE_LANGOPT_BENIGN(Trigraphs);
1001 PARSE_LANGOPT_BENIGN(BCPLComment);
1002 PARSE_LANGOPT_BENIGN(DollarIdents);
1003 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1004 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1005 PARSE_LANGOPT_BENIGN(ImplicitInt);
1006 PARSE_LANGOPT_BENIGN(Digraphs);
1007 PARSE_LANGOPT_BENIGN(HexFloats);
1008 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1009 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1010 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1011 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1012 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1013 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1014 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1015 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1016 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1017 PARSE_LANGOPT_BENIGN(PascalStrings);
1018 PARSE_LANGOPT_BENIGN(Boolean);
1019 PARSE_LANGOPT_BENIGN(WritableStrings);
1020 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1021 diag::warn_pch_lax_vector_conversions);
1022 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1023 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1024 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1025 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1026 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1027 diag::warn_pch_thread_safe_statics);
1028 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1029 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1030 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1031 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1032 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1033 diag::warn_pch_heinous_extensions);
1034 // FIXME: Most of the options below are benign if the macro wasn't
1035 // used. Unfortunately, this means that a PCH compiled without
1036 // optimization can't be used with optimization turned on, even
1037 // though the only thing that changes is whether __OPTIMIZE__ was
1038 // defined... but if __OPTIMIZE__ never showed up in the header, it
1039 // doesn't matter. We could consider making this some special kind
1040 // of check.
1041 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1042 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1043 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1044 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1045 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1046 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1047 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1048 Diag(diag::warn_pch_gc_mode)
1049 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1050 Diag(diag::note_ignoring_pch) << FileName;
1051 return true;
1052 }
1053 ++Idx;
1054 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1055 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1056#undef PARSE_LANGOPT_IRRELEVANT
1057#undef PARSE_LANGOPT_BENIGN
1058
1059 return false;
1060}
1061
Douglas Gregorc34897d2009-04-09 22:27:44 +00001062/// \brief Read and return the type at the given offset.
1063///
1064/// This routine actually reads the record corresponding to the type
1065/// at the given offset in the bitstream. It is a helper routine for
1066/// GetType, which deals with reading type IDs.
1067QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001068 // Keep track of where we are in the stream, then jump back there
1069 // after reading this type.
1070 SavedStreamPosition SavedPosition(Stream);
1071
Douglas Gregorc34897d2009-04-09 22:27:44 +00001072 Stream.JumpToBit(Offset);
1073 RecordData Record;
1074 unsigned Code = Stream.ReadCode();
1075 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001076 case pch::TYPE_EXT_QUAL:
1077 // FIXME: Deserialize ExtQualType
1078 assert(false && "Cannot deserialize qualified types yet");
1079 return QualType();
1080
Douglas Gregorc34897d2009-04-09 22:27:44 +00001081 case pch::TYPE_FIXED_WIDTH_INT: {
1082 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1083 return Context.getFixedWidthIntType(Record[0], Record[1]);
1084 }
1085
1086 case pch::TYPE_COMPLEX: {
1087 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1088 QualType ElemType = GetType(Record[0]);
1089 return Context.getComplexType(ElemType);
1090 }
1091
1092 case pch::TYPE_POINTER: {
1093 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1094 QualType PointeeType = GetType(Record[0]);
1095 return Context.getPointerType(PointeeType);
1096 }
1097
1098 case pch::TYPE_BLOCK_POINTER: {
1099 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1100 QualType PointeeType = GetType(Record[0]);
1101 return Context.getBlockPointerType(PointeeType);
1102 }
1103
1104 case pch::TYPE_LVALUE_REFERENCE: {
1105 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1106 QualType PointeeType = GetType(Record[0]);
1107 return Context.getLValueReferenceType(PointeeType);
1108 }
1109
1110 case pch::TYPE_RVALUE_REFERENCE: {
1111 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1112 QualType PointeeType = GetType(Record[0]);
1113 return Context.getRValueReferenceType(PointeeType);
1114 }
1115
1116 case pch::TYPE_MEMBER_POINTER: {
1117 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1118 QualType PointeeType = GetType(Record[0]);
1119 QualType ClassType = GetType(Record[1]);
1120 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1121 }
1122
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001123 case pch::TYPE_CONSTANT_ARRAY: {
1124 QualType ElementType = GetType(Record[0]);
1125 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1126 unsigned IndexTypeQuals = Record[2];
1127 unsigned Idx = 3;
1128 llvm::APInt Size = ReadAPInt(Record, Idx);
1129 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1130 }
1131
1132 case pch::TYPE_INCOMPLETE_ARRAY: {
1133 QualType ElementType = GetType(Record[0]);
1134 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1135 unsigned IndexTypeQuals = Record[2];
1136 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1137 }
1138
1139 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001140 QualType ElementType = GetType(Record[0]);
1141 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1142 unsigned IndexTypeQuals = Record[2];
1143 return Context.getVariableArrayType(ElementType, ReadExpr(),
1144 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001145 }
1146
1147 case pch::TYPE_VECTOR: {
1148 if (Record.size() != 2) {
1149 Error("Incorrect encoding of vector type in PCH file");
1150 return QualType();
1151 }
1152
1153 QualType ElementType = GetType(Record[0]);
1154 unsigned NumElements = Record[1];
1155 return Context.getVectorType(ElementType, NumElements);
1156 }
1157
1158 case pch::TYPE_EXT_VECTOR: {
1159 if (Record.size() != 2) {
1160 Error("Incorrect encoding of extended vector type in PCH file");
1161 return QualType();
1162 }
1163
1164 QualType ElementType = GetType(Record[0]);
1165 unsigned NumElements = Record[1];
1166 return Context.getExtVectorType(ElementType, NumElements);
1167 }
1168
1169 case pch::TYPE_FUNCTION_NO_PROTO: {
1170 if (Record.size() != 1) {
1171 Error("Incorrect encoding of no-proto function type");
1172 return QualType();
1173 }
1174 QualType ResultType = GetType(Record[0]);
1175 return Context.getFunctionNoProtoType(ResultType);
1176 }
1177
1178 case pch::TYPE_FUNCTION_PROTO: {
1179 QualType ResultType = GetType(Record[0]);
1180 unsigned Idx = 1;
1181 unsigned NumParams = Record[Idx++];
1182 llvm::SmallVector<QualType, 16> ParamTypes;
1183 for (unsigned I = 0; I != NumParams; ++I)
1184 ParamTypes.push_back(GetType(Record[Idx++]));
1185 bool isVariadic = Record[Idx++];
1186 unsigned Quals = Record[Idx++];
1187 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1188 isVariadic, Quals);
1189 }
1190
1191 case pch::TYPE_TYPEDEF:
1192 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1193 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1194
1195 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001196 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001197
1198 case pch::TYPE_TYPEOF: {
1199 if (Record.size() != 1) {
1200 Error("Incorrect encoding of typeof(type) in PCH file");
1201 return QualType();
1202 }
1203 QualType UnderlyingType = GetType(Record[0]);
1204 return Context.getTypeOfType(UnderlyingType);
1205 }
1206
1207 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001208 assert(Record.size() == 1 && "Incorrect encoding of record type");
1209 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001210
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001211 case pch::TYPE_ENUM:
1212 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1213 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1214
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001215 case pch::TYPE_OBJC_INTERFACE:
1216 // FIXME: Deserialize ObjCInterfaceType
1217 assert(false && "Cannot de-serialize ObjC interface types yet");
1218 return QualType();
1219
1220 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1221 // FIXME: Deserialize ObjCQualifiedInterfaceType
1222 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1223 return QualType();
1224
1225 case pch::TYPE_OBJC_QUALIFIED_ID:
1226 // FIXME: Deserialize ObjCQualifiedIdType
1227 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1228 return QualType();
1229
1230 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1231 // FIXME: Deserialize ObjCQualifiedClassType
1232 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1233 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001234 }
1235
1236 // Suppress a GCC warning
1237 return QualType();
1238}
1239
1240/// \brief Note that we have loaded the declaration with the given
1241/// Index.
1242///
1243/// This routine notes that this declaration has already been loaded,
1244/// so that future GetDecl calls will return this declaration rather
1245/// than trying to load a new declaration.
1246inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1247 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1248 DeclAlreadyLoaded[Index] = true;
1249 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1250}
1251
1252/// \brief Read the declaration at the given offset from the PCH file.
1253Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001254 // Keep track of where we are in the stream, then jump back there
1255 // after reading this declaration.
1256 SavedStreamPosition SavedPosition(Stream);
1257
Douglas Gregorc34897d2009-04-09 22:27:44 +00001258 Decl *D = 0;
1259 Stream.JumpToBit(Offset);
1260 RecordData Record;
1261 unsigned Code = Stream.ReadCode();
1262 unsigned Idx = 0;
1263 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001264
Douglas Gregorc34897d2009-04-09 22:27:44 +00001265 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
1266 case pch::DECL_TRANSLATION_UNIT:
1267 assert(Index == 0 && "Translation unit must be at index 0");
1268 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1269 D = Context.getTranslationUnitDecl();
1270 LoadedDecl(Index, D);
1271 break;
1272
1273 case pch::DECL_TYPEDEF: {
1274 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1275 0, QualType());
1276 LoadedDecl(Index, Typedef);
1277 Reader.VisitTypedefDecl(Typedef);
1278 D = Typedef;
1279 break;
1280 }
1281
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001282 case pch::DECL_ENUM: {
1283 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1284 LoadedDecl(Index, Enum);
1285 Reader.VisitEnumDecl(Enum);
1286 D = Enum;
1287 break;
1288 }
1289
Douglas Gregor982365e2009-04-13 21:20:57 +00001290 case pch::DECL_RECORD: {
1291 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1292 0, SourceLocation(), 0, 0);
1293 LoadedDecl(Index, Record);
1294 Reader.VisitRecordDecl(Record);
1295 D = Record;
1296 break;
1297 }
1298
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001299 case pch::DECL_ENUM_CONSTANT: {
1300 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1301 SourceLocation(), 0,
1302 QualType(), 0,
1303 llvm::APSInt());
1304 LoadedDecl(Index, ECD);
1305 Reader.VisitEnumConstantDecl(ECD);
1306 D = ECD;
1307 break;
1308 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001309
1310 case pch::DECL_FUNCTION: {
1311 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1312 DeclarationName(),
1313 QualType());
1314 LoadedDecl(Index, Function);
1315 Reader.VisitFunctionDecl(Function);
1316 D = Function;
1317 break;
1318 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001319
Douglas Gregor982365e2009-04-13 21:20:57 +00001320 case pch::DECL_FIELD: {
1321 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1322 QualType(), 0, false);
1323 LoadedDecl(Index, Field);
1324 Reader.VisitFieldDecl(Field);
1325 D = Field;
1326 break;
1327 }
1328
Douglas Gregorc34897d2009-04-09 22:27:44 +00001329 case pch::DECL_VAR: {
1330 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1331 VarDecl::None, SourceLocation());
1332 LoadedDecl(Index, Var);
1333 Reader.VisitVarDecl(Var);
1334 D = Var;
1335 break;
1336 }
1337
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001338 case pch::DECL_PARM_VAR: {
1339 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1340 QualType(), VarDecl::None, 0);
1341 LoadedDecl(Index, Parm);
1342 Reader.VisitParmVarDecl(Parm);
1343 D = Parm;
1344 break;
1345 }
1346
1347 case pch::DECL_ORIGINAL_PARM_VAR: {
1348 OriginalParmVarDecl *Parm
1349 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1350 QualType(), QualType(), VarDecl::None,
1351 0);
1352 LoadedDecl(Index, Parm);
1353 Reader.VisitOriginalParmVarDecl(Parm);
1354 D = Parm;
1355 break;
1356 }
1357
Douglas Gregor2a491792009-04-13 22:49:25 +00001358 case pch::DECL_FILE_SCOPE_ASM: {
1359 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1360 SourceLocation(), 0);
1361 LoadedDecl(Index, Asm);
1362 Reader.VisitFileScopeAsmDecl(Asm);
1363 D = Asm;
1364 break;
1365 }
1366
1367 case pch::DECL_BLOCK: {
1368 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1369 LoadedDecl(Index, Block);
1370 Reader.VisitBlockDecl(Block);
1371 D = Block;
1372 break;
1373 }
1374
Douglas Gregorc34897d2009-04-09 22:27:44 +00001375 default:
1376 assert(false && "Cannot de-serialize this kind of declaration");
1377 break;
1378 }
1379
1380 // If this declaration is also a declaration context, get the
1381 // offsets for its tables of lexical and visible declarations.
1382 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1383 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1384 if (Offsets.first || Offsets.second) {
1385 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1386 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1387 DeclContextOffsets[DC] = Offsets;
1388 }
1389 }
1390 assert(Idx == Record.size());
1391
1392 return D;
1393}
1394
Douglas Gregorac8f2802009-04-10 17:25:41 +00001395QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001396 unsigned Quals = ID & 0x07;
1397 unsigned Index = ID >> 3;
1398
1399 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1400 QualType T;
1401 switch ((pch::PredefinedTypeIDs)Index) {
1402 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1403 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1404 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1405
1406 case pch::PREDEF_TYPE_CHAR_U_ID:
1407 case pch::PREDEF_TYPE_CHAR_S_ID:
1408 // FIXME: Check that the signedness of CharTy is correct!
1409 T = Context.CharTy;
1410 break;
1411
1412 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1413 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1414 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1415 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1416 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1417 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1418 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1419 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1420 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1421 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1422 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1423 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1424 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1425 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1426 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1427 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1428 }
1429
1430 assert(!T.isNull() && "Unknown predefined type");
1431 return T.getQualifiedType(Quals);
1432 }
1433
1434 Index -= pch::NUM_PREDEF_TYPE_IDS;
1435 if (!TypeAlreadyLoaded[Index]) {
1436 // Load the type from the PCH file.
1437 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1438 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1439 TypeAlreadyLoaded[Index] = true;
1440 }
1441
1442 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1443}
1444
Douglas Gregorac8f2802009-04-10 17:25:41 +00001445Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001446 if (ID == 0)
1447 return 0;
1448
1449 unsigned Index = ID - 1;
1450 if (DeclAlreadyLoaded[Index])
1451 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1452
1453 // Load the declaration from the PCH file.
1454 return ReadDeclRecord(DeclOffsets[Index], Index);
1455}
1456
1457bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001458 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001459 assert(DC->hasExternalLexicalStorage() &&
1460 "DeclContext has no lexical decls in storage");
1461 uint64_t Offset = DeclContextOffsets[DC].first;
1462 assert(Offset && "DeclContext has no lexical decls in storage");
1463
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001464 // Keep track of where we are in the stream, then jump back there
1465 // after reading this context.
1466 SavedStreamPosition SavedPosition(Stream);
1467
Douglas Gregorc34897d2009-04-09 22:27:44 +00001468 // Load the record containing all of the declarations lexically in
1469 // this context.
1470 Stream.JumpToBit(Offset);
1471 RecordData Record;
1472 unsigned Code = Stream.ReadCode();
1473 unsigned RecCode = Stream.ReadRecord(Code, Record);
1474 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1475
1476 // Load all of the declaration IDs
1477 Decls.clear();
1478 Decls.insert(Decls.end(), Record.begin(), Record.end());
1479 return false;
1480}
1481
1482bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1483 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1484 assert(DC->hasExternalVisibleStorage() &&
1485 "DeclContext has no visible decls in storage");
1486 uint64_t Offset = DeclContextOffsets[DC].second;
1487 assert(Offset && "DeclContext has no visible decls in storage");
1488
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001489 // Keep track of where we are in the stream, then jump back there
1490 // after reading this context.
1491 SavedStreamPosition SavedPosition(Stream);
1492
Douglas Gregorc34897d2009-04-09 22:27:44 +00001493 // Load the record containing all of the declarations visible in
1494 // this context.
1495 Stream.JumpToBit(Offset);
1496 RecordData Record;
1497 unsigned Code = Stream.ReadCode();
1498 unsigned RecCode = Stream.ReadRecord(Code, Record);
1499 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1500 if (Record.size() == 0)
1501 return false;
1502
1503 Decls.clear();
1504
1505 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001506 while (Idx < Record.size()) {
1507 Decls.push_back(VisibleDeclaration());
1508 Decls.back().Name = ReadDeclarationName(Record, Idx);
1509
Douglas Gregorc34897d2009-04-09 22:27:44 +00001510 unsigned Size = Record[Idx++];
1511 llvm::SmallVector<unsigned, 4> & LoadedDecls
1512 = Decls.back().Declarations;
1513 LoadedDecls.reserve(Size);
1514 for (unsigned I = 0; I < Size; ++I)
1515 LoadedDecls.push_back(Record[Idx++]);
1516 }
1517
1518 return false;
1519}
1520
Douglas Gregor631f6c62009-04-14 00:24:19 +00001521void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1522 if (!Consumer)
1523 return;
1524
1525 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1526 Decl *D = GetDecl(ExternalDefinitions[I]);
1527 DeclGroupRef DG(D);
1528 Consumer->HandleTopLevelDecl(DG);
1529 }
1530}
1531
Douglas Gregorc34897d2009-04-09 22:27:44 +00001532void PCHReader::PrintStats() {
1533 std::fprintf(stderr, "*** PCH Statistics:\n");
1534
1535 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1536 TypeAlreadyLoaded.end(),
1537 true);
1538 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1539 DeclAlreadyLoaded.end(),
1540 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001541 unsigned NumIdentifiersLoaded = 0;
1542 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1543 if ((IdentifierData[I] & 0x01) == 0)
1544 ++NumIdentifiersLoaded;
1545 }
1546
Douglas Gregorc34897d2009-04-09 22:27:44 +00001547 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1548 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001549 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001550 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1551 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001552 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1553 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1554 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1555 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001556 std::fprintf(stderr, "\n");
1557}
1558
Chris Lattner29241862009-04-11 21:15:38 +00001559IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001560 if (ID == 0)
1561 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001562
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001563 if (!IdentifierTable || IdentifierData.empty()) {
1564 Error("No identifier table in PCH file");
1565 return 0;
1566 }
Chris Lattner29241862009-04-11 21:15:38 +00001567
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001568 if (IdentifierData[ID - 1] & 0x01) {
1569 uint64_t Offset = IdentifierData[ID - 1];
1570 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001571 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001572 }
Chris Lattner29241862009-04-11 21:15:38 +00001573
1574 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001575}
1576
1577DeclarationName
1578PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1579 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1580 switch (Kind) {
1581 case DeclarationName::Identifier:
1582 return DeclarationName(GetIdentifierInfo(Record, Idx));
1583
1584 case DeclarationName::ObjCZeroArgSelector:
1585 case DeclarationName::ObjCOneArgSelector:
1586 case DeclarationName::ObjCMultiArgSelector:
1587 assert(false && "Unable to de-serialize Objective-C selectors");
1588 break;
1589
1590 case DeclarationName::CXXConstructorName:
1591 return Context.DeclarationNames.getCXXConstructorName(
1592 GetType(Record[Idx++]));
1593
1594 case DeclarationName::CXXDestructorName:
1595 return Context.DeclarationNames.getCXXDestructorName(
1596 GetType(Record[Idx++]));
1597
1598 case DeclarationName::CXXConversionFunctionName:
1599 return Context.DeclarationNames.getCXXConversionFunctionName(
1600 GetType(Record[Idx++]));
1601
1602 case DeclarationName::CXXOperatorName:
1603 return Context.DeclarationNames.getCXXOperatorName(
1604 (OverloadedOperatorKind)Record[Idx++]);
1605
1606 case DeclarationName::CXXUsingDirective:
1607 return DeclarationName::getUsingDirectiveName();
1608 }
1609
1610 // Required to silence GCC warning
1611 return DeclarationName();
1612}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001613
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001614/// \brief Read an integral value
1615llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1616 unsigned BitWidth = Record[Idx++];
1617 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1618 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1619 Idx += NumWords;
1620 return Result;
1621}
1622
1623/// \brief Read a signed integral value
1624llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1625 bool isUnsigned = Record[Idx++];
1626 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1627}
1628
Douglas Gregore2f37202009-04-14 21:55:33 +00001629/// \brief Read a floating-point value
1630llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
1631 // FIXME: is this really correct?
1632 return llvm::APFloat(ReadAPInt(Record, Idx));
1633}
1634
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001635Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001636 // Within the bitstream, expressions are stored in Reverse Polish
1637 // Notation, with each of the subexpressions preceding the
1638 // expression they are stored in. To evaluate expressions, we
1639 // continue reading expressions and placing them on the stack, with
1640 // expressions having operands removing those operands from the
1641 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1642 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001643 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001644 unsigned Idx;
1645 llvm::SmallVector<Expr *, 16> ExprStack;
1646 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001647 Stmt::EmptyShell Empty;
1648
Douglas Gregora151ba42009-04-14 23:32:43 +00001649 while (true) {
1650 unsigned Code = Stream.ReadCode();
1651 if (Code == llvm::bitc::END_BLOCK) {
1652 if (Stream.ReadBlockEnd()) {
1653 Error("Error at end of Source Manager block");
1654 return 0;
1655 }
1656 break;
1657 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001658
Douglas Gregora151ba42009-04-14 23:32:43 +00001659 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1660 // No known subblocks, always skip them.
1661 Stream.ReadSubBlockID();
1662 if (Stream.SkipBlock()) {
1663 Error("Malformed block record");
1664 return 0;
1665 }
1666 continue;
1667 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001668
Douglas Gregora151ba42009-04-14 23:32:43 +00001669 if (Code == llvm::bitc::DEFINE_ABBREV) {
1670 Stream.ReadAbbrevRecord();
1671 continue;
1672 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001673
Douglas Gregora151ba42009-04-14 23:32:43 +00001674 Expr *E = 0;
1675 Idx = 0;
1676 Record.clear();
1677 bool Finished = false;
1678 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1679 case pch::EXPR_STOP:
1680 Finished = true;
1681 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001682
Douglas Gregora151ba42009-04-14 23:32:43 +00001683 case pch::EXPR_NULL:
1684 E = 0;
1685 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001686
Douglas Gregora151ba42009-04-14 23:32:43 +00001687 case pch::EXPR_PREDEFINED:
1688 // FIXME: untested (until we can serialize function bodies).
1689 E = new (Context) PredefinedExpr(Empty);
1690 break;
1691
1692 case pch::EXPR_DECL_REF:
1693 E = new (Context) DeclRefExpr(Empty);
1694 break;
1695
1696 case pch::EXPR_INTEGER_LITERAL:
1697 E = new (Context) IntegerLiteral(Empty);
1698 break;
1699
1700 case pch::EXPR_FLOATING_LITERAL:
1701 E = new (Context) FloatingLiteral(Empty);
1702 break;
1703
Douglas Gregor596e0932009-04-15 16:35:07 +00001704 case pch::EXPR_STRING_LITERAL:
1705 E = StringLiteral::CreateEmpty(Context,
1706 Record[PCHStmtReader::NumExprFields + 1]);
1707 break;
1708
Douglas Gregora151ba42009-04-14 23:32:43 +00001709 case pch::EXPR_CHARACTER_LITERAL:
1710 E = new (Context) CharacterLiteral(Empty);
1711 break;
1712
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00001713 case pch::EXPR_PAREN:
1714 E = new (Context) ParenExpr(Empty);
1715 break;
1716
Douglas Gregor12d74052009-04-15 15:58:59 +00001717 case pch::EXPR_UNARY_OPERATOR:
1718 E = new (Context) UnaryOperator(Empty);
1719 break;
1720
1721 case pch::EXPR_SIZEOF_ALIGN_OF:
1722 E = new (Context) SizeOfAlignOfExpr(Empty);
1723 break;
1724
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +00001725 case pch::EXPR_CALL:
1726 E = new (Context) CallExpr(Context, Empty);
1727 break;
1728
1729 case pch::EXPR_MEMBER:
1730 E = new (Context) MemberExpr(Empty);
1731 break;
1732
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001733 case pch::EXPR_BINARY_OPERATOR:
1734 E = new (Context) BinaryOperator(Empty);
1735 break;
1736
Douglas Gregora151ba42009-04-14 23:32:43 +00001737 case pch::EXPR_IMPLICIT_CAST:
1738 E = new (Context) ImplicitCastExpr(Empty);
1739 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001740
1741 case pch::EXPR_CSTYLE_CAST:
1742 E = new (Context) CStyleCastExpr(Empty);
1743 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00001744 }
1745
1746 // We hit an EXPR_STOP, so we're done with this expression.
1747 if (Finished)
1748 break;
1749
1750 if (E) {
1751 unsigned NumSubExprs = Reader.Visit(E);
1752 while (NumSubExprs > 0) {
1753 ExprStack.pop_back();
1754 --NumSubExprs;
1755 }
1756 }
1757
1758 assert(Idx == Record.size() && "Invalid deserialization of expression");
1759 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001760 }
Douglas Gregora151ba42009-04-14 23:32:43 +00001761 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
1762 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001763}
1764
Douglas Gregor179cfb12009-04-10 20:39:37 +00001765DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001766 return Diag(SourceLocation(), DiagID);
1767}
1768
1769DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
1770 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00001771 Context.getSourceManager()),
1772 DiagID);
1773}