blob: 67c7dc73371de716b9e38eb792654b5560e7c2cd [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++]);
Douglas Gregor1c507882009-04-15 21:30:51 +000077 if (Record[Idx++])
78 D->addAttr(Reader.ReadAttributes());
Douglas Gregorc34897d2009-04-09 22:27:44 +000079 D->setImplicit(Record[Idx++]);
80 D->setAccess((AccessSpecifier)Record[Idx++]);
81}
82
83void PCHDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
84 VisitDecl(TU);
85}
86
87void PCHDeclReader::VisitNamedDecl(NamedDecl *ND) {
88 VisitDecl(ND);
89 ND->setDeclName(Reader.ReadDeclarationName(Record, Idx));
90}
91
92void PCHDeclReader::VisitTypeDecl(TypeDecl *TD) {
93 VisitNamedDecl(TD);
Douglas Gregorc34897d2009-04-09 22:27:44 +000094 TD->setTypeForDecl(Reader.GetType(Record[Idx++]).getTypePtr());
95}
96
97void PCHDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
Douglas Gregor88fd09d2009-04-13 20:46:52 +000098 // Note that we cannot use VisitTypeDecl here, because we need to
99 // set the underlying type of the typedef *before* we try to read
100 // the type associated with the TypedefDecl.
101 VisitNamedDecl(TD);
102 TD->setUnderlyingType(Reader.GetType(Record[Idx + 1]));
103 TD->setTypeForDecl(Reader.GetType(Record[Idx]).getTypePtr());
104 Idx += 2;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000105}
106
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000107void PCHDeclReader::VisitTagDecl(TagDecl *TD) {
108 VisitTypeDecl(TD);
109 TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
110 TD->setDefinition(Record[Idx++]);
111 TD->setTypedefForAnonDecl(
112 cast_or_null<TypedefDecl>(Reader.GetDecl(Record[Idx++])));
113}
114
115void PCHDeclReader::VisitEnumDecl(EnumDecl *ED) {
116 VisitTagDecl(ED);
117 ED->setIntegerType(Reader.GetType(Record[Idx++]));
118}
119
Douglas Gregor982365e2009-04-13 21:20:57 +0000120void PCHDeclReader::VisitRecordDecl(RecordDecl *RD) {
121 VisitTagDecl(RD);
122 RD->setHasFlexibleArrayMember(Record[Idx++]);
123 RD->setAnonymousStructOrUnion(Record[Idx++]);
124}
125
Douglas Gregorc34897d2009-04-09 22:27:44 +0000126void PCHDeclReader::VisitValueDecl(ValueDecl *VD) {
127 VisitNamedDecl(VD);
128 VD->setType(Reader.GetType(Record[Idx++]));
129}
130
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000131void PCHDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
132 VisitValueDecl(ECD);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000133 if (Record[Idx++])
134 ECD->setInitExpr(Reader.ReadExpr());
Douglas Gregor47f1b2c2009-04-13 18:14:40 +0000135 ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
136}
137
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000138void PCHDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
139 VisitValueDecl(FD);
140 // FIXME: function body
141 FD->setPreviousDeclaration(
142 cast_or_null<FunctionDecl>(Reader.GetDecl(Record[Idx++])));
143 FD->setStorageClass((FunctionDecl::StorageClass)Record[Idx++]);
144 FD->setInline(Record[Idx++]);
145 FD->setVirtual(Record[Idx++]);
146 FD->setPure(Record[Idx++]);
147 FD->setInheritedPrototype(Record[Idx++]);
148 FD->setHasPrototype(Record[Idx++]);
149 FD->setDeleted(Record[Idx++]);
150 FD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
151 unsigned NumParams = Record[Idx++];
152 llvm::SmallVector<ParmVarDecl *, 16> Params;
153 Params.reserve(NumParams);
154 for (unsigned I = 0; I != NumParams; ++I)
155 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
156 FD->setParams(Reader.getContext(), &Params[0], NumParams);
157}
158
Douglas Gregor982365e2009-04-13 21:20:57 +0000159void PCHDeclReader::VisitFieldDecl(FieldDecl *FD) {
160 VisitValueDecl(FD);
161 FD->setMutable(Record[Idx++]);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000162 if (Record[Idx++])
163 FD->setBitWidth(Reader.ReadExpr());
Douglas Gregor982365e2009-04-13 21:20:57 +0000164}
165
Douglas Gregorc34897d2009-04-09 22:27:44 +0000166void PCHDeclReader::VisitVarDecl(VarDecl *VD) {
167 VisitValueDecl(VD);
168 VD->setStorageClass((VarDecl::StorageClass)Record[Idx++]);
169 VD->setThreadSpecified(Record[Idx++]);
170 VD->setCXXDirectInitializer(Record[Idx++]);
171 VD->setDeclaredInCondition(Record[Idx++]);
172 VD->setPreviousDeclaration(
173 cast_or_null<VarDecl>(Reader.GetDecl(Record[Idx++])));
174 VD->setTypeSpecStartLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000175 if (Record[Idx++])
176 VD->setInit(Reader.ReadExpr());
Douglas Gregorc34897d2009-04-09 22:27:44 +0000177}
178
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000179void PCHDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
180 VisitVarDecl(PD);
181 PD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000182 // FIXME: default argument (C++ only)
Douglas Gregor23ce3a52009-04-13 22:18:37 +0000183}
184
185void PCHDeclReader::VisitOriginalParmVarDecl(OriginalParmVarDecl *PD) {
186 VisitParmVarDecl(PD);
187 PD->setOriginalType(Reader.GetType(Record[Idx++]));
188}
189
Douglas Gregor2a491792009-04-13 22:49:25 +0000190void PCHDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
191 VisitDecl(AD);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000192 AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr()));
Douglas Gregor2a491792009-04-13 22:49:25 +0000193}
194
195void PCHDeclReader::VisitBlockDecl(BlockDecl *BD) {
196 VisitDecl(BD);
197 unsigned NumParams = Record[Idx++];
198 llvm::SmallVector<ParmVarDecl *, 16> Params;
199 Params.reserve(NumParams);
200 for (unsigned I = 0; I != NumParams; ++I)
201 Params.push_back(cast<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
202 BD->setParams(Reader.getContext(), &Params[0], NumParams);
203}
204
Douglas Gregorc34897d2009-04-09 22:27:44 +0000205std::pair<uint64_t, uint64_t>
206PCHDeclReader::VisitDeclContext(DeclContext *DC) {
207 uint64_t LexicalOffset = Record[Idx++];
208 uint64_t VisibleOffset = 0;
209 if (DC->getPrimaryContext() == DC)
210 VisibleOffset = Record[Idx++];
211 return std::make_pair(LexicalOffset, VisibleOffset);
212}
213
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000214//===----------------------------------------------------------------------===//
215// Statement/expression deserialization
216//===----------------------------------------------------------------------===//
217namespace {
218 class VISIBILITY_HIDDEN PCHStmtReader
Douglas Gregora151ba42009-04-14 23:32:43 +0000219 : public StmtVisitor<PCHStmtReader, unsigned> {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000220 PCHReader &Reader;
221 const PCHReader::RecordData &Record;
222 unsigned &Idx;
Douglas Gregora151ba42009-04-14 23:32:43 +0000223 llvm::SmallVectorImpl<Expr *> &ExprStack;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000224
225 public:
226 PCHStmtReader(PCHReader &Reader, const PCHReader::RecordData &Record,
Douglas Gregora151ba42009-04-14 23:32:43 +0000227 unsigned &Idx, llvm::SmallVectorImpl<Expr *> &ExprStack)
228 : Reader(Reader), Record(Record), Idx(Idx), ExprStack(ExprStack) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000229
Douglas Gregor596e0932009-04-15 16:35:07 +0000230 /// \brief The number of record fields required for the Expr class
231 /// itself.
232 static const unsigned NumExprFields = 3;
233
Douglas Gregora151ba42009-04-14 23:32:43 +0000234 // Each of the Visit* functions reads in part of the expression
235 // from the given record and the current expression stack, then
236 // return the total number of operands that it read from the
237 // expression stack.
238
239 unsigned VisitExpr(Expr *E);
240 unsigned VisitPredefinedExpr(PredefinedExpr *E);
241 unsigned VisitDeclRefExpr(DeclRefExpr *E);
242 unsigned VisitIntegerLiteral(IntegerLiteral *E);
243 unsigned VisitFloatingLiteral(FloatingLiteral *E);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000244 unsigned VisitImaginaryLiteral(ImaginaryLiteral *E);
Douglas Gregor596e0932009-04-15 16:35:07 +0000245 unsigned VisitStringLiteral(StringLiteral *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000246 unsigned VisitCharacterLiteral(CharacterLiteral *E);
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000247 unsigned VisitParenExpr(ParenExpr *E);
Douglas Gregor12d74052009-04-15 15:58:59 +0000248 unsigned VisitUnaryOperator(UnaryOperator *E);
249 unsigned VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000250 unsigned VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000251 unsigned VisitCallExpr(CallExpr *E);
252 unsigned VisitMemberExpr(MemberExpr *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000253 unsigned VisitCastExpr(CastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000254 unsigned VisitBinaryOperator(BinaryOperator *E);
Douglas Gregorc599bbf2009-04-15 22:40:36 +0000255 unsigned VisitCompoundAssignOperator(CompoundAssignOperator *E);
256 unsigned VisitConditionalOperator(ConditionalOperator *E);
Douglas Gregora151ba42009-04-14 23:32:43 +0000257 unsigned VisitImplicitCastExpr(ImplicitCastExpr *E);
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000258 unsigned VisitExplicitCastExpr(ExplicitCastExpr *E);
259 unsigned VisitCStyleCastExpr(CStyleCastExpr *E);
Douglas Gregorec0b8292009-04-15 23:02:49 +0000260 unsigned VisitExtVectorElementExpr(ExtVectorElementExpr *E);
261 unsigned VisitVAArgExpr(VAArgExpr *E);
Douglas Gregor209d4622009-04-15 23:33:31 +0000262 unsigned VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
263 unsigned VisitChooseExpr(ChooseExpr *E);
264 unsigned VisitGNUNullExpr(GNUNullExpr *E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000265 };
266}
267
Douglas Gregora151ba42009-04-14 23:32:43 +0000268unsigned PCHStmtReader::VisitExpr(Expr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000269 E->setType(Reader.GetType(Record[Idx++]));
270 E->setTypeDependent(Record[Idx++]);
271 E->setValueDependent(Record[Idx++]);
Douglas Gregor596e0932009-04-15 16:35:07 +0000272 assert(Idx == NumExprFields && "Incorrect expression field count");
Douglas Gregora151ba42009-04-14 23:32:43 +0000273 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000274}
275
Douglas Gregora151ba42009-04-14 23:32:43 +0000276unsigned PCHStmtReader::VisitPredefinedExpr(PredefinedExpr *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000277 VisitExpr(E);
278 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
279 E->setIdentType((PredefinedExpr::IdentType)Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000280 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000281}
282
Douglas Gregora151ba42009-04-14 23:32:43 +0000283unsigned PCHStmtReader::VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000284 VisitExpr(E);
285 E->setDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
286 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000287 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000288}
289
Douglas Gregora151ba42009-04-14 23:32:43 +0000290unsigned PCHStmtReader::VisitIntegerLiteral(IntegerLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000291 VisitExpr(E);
292 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
293 E->setValue(Reader.ReadAPInt(Record, Idx));
Douglas Gregora151ba42009-04-14 23:32:43 +0000294 return 0;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000295}
296
Douglas Gregora151ba42009-04-14 23:32:43 +0000297unsigned PCHStmtReader::VisitFloatingLiteral(FloatingLiteral *E) {
Douglas Gregore2f37202009-04-14 21:55:33 +0000298 VisitExpr(E);
299 E->setValue(Reader.ReadAPFloat(Record, Idx));
300 E->setExact(Record[Idx++]);
301 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
Douglas Gregora151ba42009-04-14 23:32:43 +0000302 return 0;
Douglas Gregore2f37202009-04-14 21:55:33 +0000303}
304
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000305unsigned PCHStmtReader::VisitImaginaryLiteral(ImaginaryLiteral *E) {
306 VisitExpr(E);
307 E->setSubExpr(ExprStack.back());
308 return 1;
309}
310
Douglas Gregor596e0932009-04-15 16:35:07 +0000311unsigned PCHStmtReader::VisitStringLiteral(StringLiteral *E) {
312 VisitExpr(E);
313 unsigned Len = Record[Idx++];
314 assert(Record[Idx] == E->getNumConcatenated() &&
315 "Wrong number of concatenated tokens!");
316 ++Idx;
317 E->setWide(Record[Idx++]);
318
319 // Read string data
320 llvm::SmallVector<char, 16> Str(&Record[Idx], &Record[Idx] + Len);
321 E->setStrData(Reader.getContext(), &Str[0], Len);
322 Idx += Len;
323
324 // Read source locations
325 for (unsigned I = 0, N = E->getNumConcatenated(); I != N; ++I)
326 E->setStrTokenLoc(I, SourceLocation::getFromRawEncoding(Record[Idx++]));
327
328 return 0;
329}
330
Douglas Gregora151ba42009-04-14 23:32:43 +0000331unsigned PCHStmtReader::VisitCharacterLiteral(CharacterLiteral *E) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000332 VisitExpr(E);
333 E->setValue(Record[Idx++]);
334 E->setLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
335 E->setWide(Record[Idx++]);
Douglas Gregora151ba42009-04-14 23:32:43 +0000336 return 0;
337}
338
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +0000339unsigned PCHStmtReader::VisitParenExpr(ParenExpr *E) {
340 VisitExpr(E);
341 E->setLParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
342 E->setRParen(SourceLocation::getFromRawEncoding(Record[Idx++]));
343 E->setSubExpr(ExprStack.back());
344 return 1;
345}
346
Douglas Gregor12d74052009-04-15 15:58:59 +0000347unsigned PCHStmtReader::VisitUnaryOperator(UnaryOperator *E) {
348 VisitExpr(E);
349 E->setSubExpr(ExprStack.back());
350 E->setOpcode((UnaryOperator::Opcode)Record[Idx++]);
351 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
352 return 1;
353}
354
355unsigned PCHStmtReader::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
356 VisitExpr(E);
357 E->setSizeof(Record[Idx++]);
358 if (Record[Idx] == 0) {
359 E->setArgument(ExprStack.back());
360 ++Idx;
361 } else {
362 E->setArgument(Reader.GetType(Record[Idx++]));
363 }
364 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
365 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
366 return E->isArgumentType()? 0 : 1;
367}
368
Douglas Gregor21ddd8c2009-04-15 22:19:53 +0000369unsigned PCHStmtReader::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
370 VisitExpr(E);
371 E->setLHS(ExprStack[ExprStack.size() - 2]);
372 E->setRHS(ExprStack[ExprStack.size() - 2]);
373 E->setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
374 return 2;
375}
376
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +0000377unsigned PCHStmtReader::VisitCallExpr(CallExpr *E) {
378 VisitExpr(E);
379 E->setNumArgs(Reader.getContext(), Record[Idx++]);
380 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
381 E->setCallee(ExprStack[ExprStack.size() - E->getNumArgs() - 1]);
382 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
383 E->setArg(I, ExprStack[ExprStack.size() - N + I]);
384 return E->getNumArgs() + 1;
385}
386
387unsigned PCHStmtReader::VisitMemberExpr(MemberExpr *E) {
388 VisitExpr(E);
389 E->setBase(ExprStack.back());
390 E->setMemberDecl(cast<NamedDecl>(Reader.GetDecl(Record[Idx++])));
391 E->setMemberLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
392 E->setArrow(Record[Idx++]);
393 return 1;
394}
395
Douglas Gregora151ba42009-04-14 23:32:43 +0000396unsigned PCHStmtReader::VisitCastExpr(CastExpr *E) {
397 VisitExpr(E);
398 E->setSubExpr(ExprStack.back());
399 return 1;
400}
401
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000402unsigned PCHStmtReader::VisitBinaryOperator(BinaryOperator *E) {
403 VisitExpr(E);
404 E->setLHS(ExprStack.end()[-2]);
405 E->setRHS(ExprStack.end()[-1]);
406 E->setOpcode((BinaryOperator::Opcode)Record[Idx++]);
407 E->setOperatorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
408 return 2;
409}
410
Douglas Gregorc599bbf2009-04-15 22:40:36 +0000411unsigned PCHStmtReader::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
412 VisitBinaryOperator(E);
413 E->setComputationLHSType(Reader.GetType(Record[Idx++]));
414 E->setComputationResultType(Reader.GetType(Record[Idx++]));
415 return 2;
416}
417
418unsigned PCHStmtReader::VisitConditionalOperator(ConditionalOperator *E) {
419 VisitExpr(E);
420 E->setCond(ExprStack[ExprStack.size() - 3]);
421 E->setLHS(ExprStack[ExprStack.size() - 2]);
422 E->setRHS(ExprStack[ExprStack.size() - 1]);
423 return 3;
424}
425
Douglas Gregora151ba42009-04-14 23:32:43 +0000426unsigned PCHStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
427 VisitCastExpr(E);
428 E->setLvalueCast(Record[Idx++]);
429 return 1;
Douglas Gregorc10f86f2009-04-14 21:18:50 +0000430}
431
Douglas Gregorc75d0cb2009-04-15 00:25:59 +0000432unsigned PCHStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
433 VisitCastExpr(E);
434 E->setTypeAsWritten(Reader.GetType(Record[Idx++]));
435 return 1;
436}
437
438unsigned PCHStmtReader::VisitCStyleCastExpr(CStyleCastExpr *E) {
439 VisitExplicitCastExpr(E);
440 E->setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
441 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
442 return 1;
443}
444
Douglas Gregorec0b8292009-04-15 23:02:49 +0000445unsigned PCHStmtReader::VisitExtVectorElementExpr(ExtVectorElementExpr *E) {
446 VisitExpr(E);
447 E->setBase(ExprStack.back());
448 E->setAccessor(Reader.GetIdentifierInfo(Record, Idx));
449 E->setAccessorLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
450 return 1;
451}
452
453unsigned PCHStmtReader::VisitVAArgExpr(VAArgExpr *E) {
454 VisitExpr(E);
455 E->setSubExpr(ExprStack.back());
456 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
457 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
458 return 1;
459}
460
Douglas Gregor209d4622009-04-15 23:33:31 +0000461unsigned PCHStmtReader::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
462 VisitExpr(E);
463 E->setArgType1(Reader.GetType(Record[Idx++]));
464 E->setArgType2(Reader.GetType(Record[Idx++]));
465 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
466 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
467 return 0;
468}
469
470unsigned PCHStmtReader::VisitChooseExpr(ChooseExpr *E) {
471 VisitExpr(E);
472 E->setCond(ExprStack[ExprStack.size() - 3]);
473 E->setLHS(ExprStack[ExprStack.size() - 2]);
474 E->setRHS(ExprStack[ExprStack.size() - 1]);
475 E->setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
476 E->setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
477 return 3;
478}
479
480unsigned PCHStmtReader::VisitGNUNullExpr(GNUNullExpr *E) {
481 VisitExpr(E);
482 E->setTokenLocation(SourceLocation::getFromRawEncoding(Record[Idx++]));
483 return 0;
484}
Douglas Gregorec0b8292009-04-15 23:02:49 +0000485
Douglas Gregorc34897d2009-04-09 22:27:44 +0000486// FIXME: use the diagnostics machinery
487static bool Error(const char *Str) {
488 std::fprintf(stderr, "%s\n", Str);
489 return true;
490}
491
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000492/// \brief Check the contents of the predefines buffer against the
493/// contents of the predefines buffer used to build the PCH file.
494///
495/// The contents of the two predefines buffers should be the same. If
496/// not, then some command-line option changed the preprocessor state
497/// and we must reject the PCH file.
498///
499/// \param PCHPredef The start of the predefines buffer in the PCH
500/// file.
501///
502/// \param PCHPredefLen The length of the predefines buffer in the PCH
503/// file.
504///
505/// \param PCHBufferID The FileID for the PCH predefines buffer.
506///
507/// \returns true if there was a mismatch (in which case the PCH file
508/// should be ignored), or false otherwise.
509bool PCHReader::CheckPredefinesBuffer(const char *PCHPredef,
510 unsigned PCHPredefLen,
511 FileID PCHBufferID) {
512 const char *Predef = PP.getPredefines().c_str();
513 unsigned PredefLen = PP.getPredefines().size();
514
515 // If the two predefines buffers compare equal, we're done!.
516 if (PredefLen == PCHPredefLen &&
517 strncmp(Predef, PCHPredef, PCHPredefLen) == 0)
518 return false;
519
520 // The predefines buffers are different. Produce a reasonable
521 // diagnostic showing where they are different.
522
523 // The source locations (potentially in the two different predefines
524 // buffers)
525 SourceLocation Loc1, Loc2;
526 SourceManager &SourceMgr = PP.getSourceManager();
527
528 // Create a source buffer for our predefines string, so
529 // that we can build a diagnostic that points into that
530 // source buffer.
531 FileID BufferID;
532 if (Predef && Predef[0]) {
533 llvm::MemoryBuffer *Buffer
534 = llvm::MemoryBuffer::getMemBuffer(Predef, Predef + PredefLen,
535 "<built-in>");
536 BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
537 }
538
539 unsigned MinLen = std::min(PredefLen, PCHPredefLen);
540 std::pair<const char *, const char *> Locations
541 = std::mismatch(Predef, Predef + MinLen, PCHPredef);
542
543 if (Locations.first != Predef + MinLen) {
544 // We found the location in the two buffers where there is a
545 // difference. Form source locations to point there (in both
546 // buffers).
547 unsigned Offset = Locations.first - Predef;
548 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
549 .getFileLocWithOffset(Offset);
550 Loc2 = SourceMgr.getLocForStartOfFile(PCHBufferID)
551 .getFileLocWithOffset(Offset);
552 } else if (PredefLen > PCHPredefLen) {
553 Loc1 = SourceMgr.getLocForStartOfFile(BufferID)
554 .getFileLocWithOffset(MinLen);
555 } else {
556 Loc1 = SourceMgr.getLocForStartOfFile(PCHBufferID)
557 .getFileLocWithOffset(MinLen);
558 }
559
560 Diag(Loc1, diag::warn_pch_preprocessor);
561 if (Loc2.isValid())
562 Diag(Loc2, diag::note_predef_in_pch);
563 Diag(diag::note_ignoring_pch) << FileName;
564 return true;
565}
566
Douglas Gregor635f97f2009-04-13 16:31:14 +0000567/// \brief Read the line table in the source manager block.
568/// \returns true if ther was an error.
569static bool ParseLineTable(SourceManager &SourceMgr,
570 llvm::SmallVectorImpl<uint64_t> &Record) {
571 unsigned Idx = 0;
572 LineTableInfo &LineTable = SourceMgr.getLineTable();
573
574 // Parse the file names
Douglas Gregor183ad602009-04-13 17:12:42 +0000575 std::map<int, int> FileIDs;
576 for (int I = 0, N = Record[Idx++]; I != N; ++I) {
Douglas Gregor635f97f2009-04-13 16:31:14 +0000577 // Extract the file name
578 unsigned FilenameLen = Record[Idx++];
579 std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
580 Idx += FilenameLen;
Douglas Gregor183ad602009-04-13 17:12:42 +0000581 FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
582 Filename.size());
Douglas Gregor635f97f2009-04-13 16:31:14 +0000583 }
584
585 // Parse the line entries
586 std::vector<LineEntry> Entries;
587 while (Idx < Record.size()) {
Douglas Gregor183ad602009-04-13 17:12:42 +0000588 int FID = FileIDs[Record[Idx++]];
Douglas Gregor635f97f2009-04-13 16:31:14 +0000589
590 // Extract the line entries
591 unsigned NumEntries = Record[Idx++];
592 Entries.clear();
593 Entries.reserve(NumEntries);
594 for (unsigned I = 0; I != NumEntries; ++I) {
595 unsigned FileOffset = Record[Idx++];
596 unsigned LineNo = Record[Idx++];
597 int FilenameID = Record[Idx++];
598 SrcMgr::CharacteristicKind FileKind
599 = (SrcMgr::CharacteristicKind)Record[Idx++];
600 unsigned IncludeOffset = Record[Idx++];
601 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
602 FileKind, IncludeOffset));
603 }
604 LineTable.AddEntry(FID, Entries);
605 }
606
607 return false;
608}
609
Douglas Gregorab1cef72009-04-10 03:52:48 +0000610/// \brief Read the source manager block
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000611PCHReader::PCHReadResult PCHReader::ReadSourceManagerBlock() {
Douglas Gregorab1cef72009-04-10 03:52:48 +0000612 using namespace SrcMgr;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000613 if (Stream.EnterSubBlock(pch::SOURCE_MANAGER_BLOCK_ID)) {
614 Error("Malformed source manager block record");
615 return Failure;
616 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000617
618 SourceManager &SourceMgr = Context.getSourceManager();
619 RecordData Record;
620 while (true) {
621 unsigned Code = Stream.ReadCode();
622 if (Code == llvm::bitc::END_BLOCK) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000623 if (Stream.ReadBlockEnd()) {
624 Error("Error at end of Source Manager block");
625 return Failure;
626 }
627
628 return Success;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000629 }
630
631 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
632 // No known subblocks, always skip them.
633 Stream.ReadSubBlockID();
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000634 if (Stream.SkipBlock()) {
635 Error("Malformed block record");
636 return Failure;
637 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000638 continue;
639 }
640
641 if (Code == llvm::bitc::DEFINE_ABBREV) {
642 Stream.ReadAbbrevRecord();
643 continue;
644 }
645
646 // Read a record.
647 const char *BlobStart;
648 unsigned BlobLen;
649 Record.clear();
650 switch (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
651 default: // Default behavior: ignore.
652 break;
653
654 case pch::SM_SLOC_FILE_ENTRY: {
655 // FIXME: We would really like to delay the creation of this
656 // FileEntry until it is actually required, e.g., when producing
657 // a diagnostic with a source location in this file.
658 const FileEntry *File
659 = PP.getFileManager().getFile(BlobStart, BlobStart + BlobLen);
660 // FIXME: Error recovery if file cannot be found.
Douglas Gregor635f97f2009-04-13 16:31:14 +0000661 FileID ID = SourceMgr.createFileID(File,
662 SourceLocation::getFromRawEncoding(Record[1]),
663 (CharacteristicKind)Record[2]);
664 if (Record[3])
665 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(ID).getFile())
666 .setHasLineDirectives();
Douglas Gregorab1cef72009-04-10 03:52:48 +0000667 break;
668 }
669
670 case pch::SM_SLOC_BUFFER_ENTRY: {
671 const char *Name = BlobStart;
672 unsigned Code = Stream.ReadCode();
673 Record.clear();
674 unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
675 assert(RecCode == pch::SM_SLOC_BUFFER_BLOB && "Ill-formed PCH file");
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +0000676 (void)RecCode;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000677 llvm::MemoryBuffer *Buffer
678 = llvm::MemoryBuffer::getMemBuffer(BlobStart,
679 BlobStart + BlobLen - 1,
680 Name);
681 FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer);
682
683 if (strcmp(Name, "<built-in>") == 0
684 && CheckPredefinesBuffer(BlobStart, BlobLen - 1, BufferID))
685 return IgnorePCH;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000686 break;
687 }
688
689 case pch::SM_SLOC_INSTANTIATION_ENTRY: {
690 SourceLocation SpellingLoc
691 = SourceLocation::getFromRawEncoding(Record[1]);
692 SourceMgr.createInstantiationLoc(
693 SpellingLoc,
694 SourceLocation::getFromRawEncoding(Record[2]),
695 SourceLocation::getFromRawEncoding(Record[3]),
Douglas Gregor364e5802009-04-15 18:05:10 +0000696 Record[4]);
Douglas Gregorab1cef72009-04-10 03:52:48 +0000697 break;
698 }
699
Chris Lattnere1be6022009-04-14 23:22:57 +0000700 case pch::SM_LINE_TABLE:
Douglas Gregor635f97f2009-04-13 16:31:14 +0000701 if (ParseLineTable(SourceMgr, Record))
702 return Failure;
Chris Lattnere1be6022009-04-14 23:22:57 +0000703 break;
Douglas Gregorab1cef72009-04-10 03:52:48 +0000704 }
705 }
706}
707
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000708bool PCHReader::ReadPreprocessorBlock() {
709 if (Stream.EnterSubBlock(pch::PREPROCESSOR_BLOCK_ID))
710 return Error("Malformed preprocessor block record");
711
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000712 RecordData Record;
713 llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
714 MacroInfo *LastMacro = 0;
715
716 while (true) {
717 unsigned Code = Stream.ReadCode();
718 switch (Code) {
719 case llvm::bitc::END_BLOCK:
720 if (Stream.ReadBlockEnd())
721 return Error("Error at end of preprocessor block");
722 return false;
723
724 case llvm::bitc::ENTER_SUBBLOCK:
725 // No known subblocks, always skip them.
726 Stream.ReadSubBlockID();
727 if (Stream.SkipBlock())
728 return Error("Malformed block record");
729 continue;
730
731 case llvm::bitc::DEFINE_ABBREV:
732 Stream.ReadAbbrevRecord();
733 continue;
734 default: break;
735 }
736
737 // Read a record.
738 Record.clear();
739 pch::PreprocessorRecordTypes RecType =
740 (pch::PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
741 switch (RecType) {
742 default: // Default behavior: ignore unknown records.
743 break;
Chris Lattner4b21c202009-04-13 01:29:17 +0000744 case pch::PP_COUNTER_VALUE:
745 if (!Record.empty())
746 PP.setCounterValue(Record[0]);
747 break;
748
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000749 case pch::PP_MACRO_OBJECT_LIKE:
750 case pch::PP_MACRO_FUNCTION_LIKE: {
Chris Lattner29241862009-04-11 21:15:38 +0000751 IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
752 if (II == 0)
753 return Error("Macro must have a name");
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000754 SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
755 bool isUsed = Record[2];
756
757 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
758 MI->setIsUsed(isUsed);
759
760 if (RecType == pch::PP_MACRO_FUNCTION_LIKE) {
761 // Decode function-like macro info.
762 bool isC99VarArgs = Record[3];
763 bool isGNUVarArgs = Record[4];
764 MacroArgs.clear();
765 unsigned NumArgs = Record[5];
766 for (unsigned i = 0; i != NumArgs; ++i)
Chris Lattner29241862009-04-11 21:15:38 +0000767 MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000768
769 // Install function-like macro info.
770 MI->setIsFunctionLike();
771 if (isC99VarArgs) MI->setIsC99Varargs();
772 if (isGNUVarArgs) MI->setIsGNUVarargs();
773 MI->setArgumentList(&MacroArgs[0], MacroArgs.size(),
774 PP.getPreprocessorAllocator());
775 }
776
777 // Finally, install the macro.
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000778 PP.setMacroInfo(II, MI);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000779
780 // Remember that we saw this macro last so that we add the tokens that
781 // form its body to it.
782 LastMacro = MI;
783 break;
784 }
785
786 case pch::PP_TOKEN: {
787 // If we see a TOKEN before a PP_MACRO_*, then the file is eroneous, just
788 // pretend we didn't see this.
789 if (LastMacro == 0) break;
790
791 Token Tok;
792 Tok.startToken();
793 Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
794 Tok.setLength(Record[1]);
Chris Lattner29241862009-04-11 21:15:38 +0000795 if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
796 Tok.setIdentifierInfo(II);
Chris Lattnerdb1c81b2009-04-10 21:41:48 +0000797 Tok.setKind((tok::TokenKind)Record[3]);
798 Tok.setFlag((Token::TokenFlags)Record[4]);
799 LastMacro->AddTokenToBody(Tok);
800 break;
801 }
802 }
803 }
804}
805
Douglas Gregor179cfb12009-04-10 20:39:37 +0000806PCHReader::PCHReadResult PCHReader::ReadPCHBlock() {
807 if (Stream.EnterSubBlock(pch::PCH_BLOCK_ID)) {
808 Error("Malformed block record");
809 return Failure;
810 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000811
Chris Lattner29241862009-04-11 21:15:38 +0000812 uint64_t PreprocessorBlockBit = 0;
813
Douglas Gregorc34897d2009-04-09 22:27:44 +0000814 // Read all of the records and blocks for the PCH file.
Douglas Gregorac8f2802009-04-10 17:25:41 +0000815 RecordData Record;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000816 while (!Stream.AtEndOfStream()) {
817 unsigned Code = Stream.ReadCode();
818 if (Code == llvm::bitc::END_BLOCK) {
Chris Lattner29241862009-04-11 21:15:38 +0000819 // If we saw the preprocessor block, read it now.
820 if (PreprocessorBlockBit) {
821 uint64_t SavedPos = Stream.GetCurrentBitNo();
822 Stream.JumpToBit(PreprocessorBlockBit);
823 if (ReadPreprocessorBlock()) {
824 Error("Malformed preprocessor block");
825 return Failure;
826 }
827 Stream.JumpToBit(SavedPos);
828 }
829
Douglas Gregor179cfb12009-04-10 20:39:37 +0000830 if (Stream.ReadBlockEnd()) {
831 Error("Error at end of module block");
832 return Failure;
833 }
Chris Lattner29241862009-04-11 21:15:38 +0000834
Douglas Gregor179cfb12009-04-10 20:39:37 +0000835 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000836 }
837
838 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
839 switch (Stream.ReadSubBlockID()) {
840 case pch::DECLS_BLOCK_ID: // Skip decls block (lazily loaded)
841 case pch::TYPES_BLOCK_ID: // Skip types block (lazily loaded)
842 default: // Skip unknown content.
Douglas Gregor179cfb12009-04-10 20:39:37 +0000843 if (Stream.SkipBlock()) {
844 Error("Malformed block record");
845 return Failure;
846 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000847 break;
848
Chris Lattner29241862009-04-11 21:15:38 +0000849 case pch::PREPROCESSOR_BLOCK_ID:
850 // Skip the preprocessor block for now, but remember where it is. We
851 // want to read it in after the identifier table.
852 if (PreprocessorBlockBit) {
853 Error("Multiple preprocessor blocks found.");
854 return Failure;
855 }
856 PreprocessorBlockBit = Stream.GetCurrentBitNo();
857 if (Stream.SkipBlock()) {
858 Error("Malformed block record");
859 return Failure;
860 }
861 break;
862
Douglas Gregorab1cef72009-04-10 03:52:48 +0000863 case pch::SOURCE_MANAGER_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000864 switch (ReadSourceManagerBlock()) {
865 case Success:
866 break;
867
868 case Failure:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000869 Error("Malformed source manager block");
870 return Failure;
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000871
872 case IgnorePCH:
873 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000874 }
Douglas Gregorab1cef72009-04-10 03:52:48 +0000875 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000876 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000877 continue;
878 }
879
880 if (Code == llvm::bitc::DEFINE_ABBREV) {
881 Stream.ReadAbbrevRecord();
882 continue;
883 }
884
885 // Read and process a record.
886 Record.clear();
Douglas Gregorb5887f32009-04-10 21:16:55 +0000887 const char *BlobStart = 0;
888 unsigned BlobLen = 0;
889 switch ((pch::PCHRecordTypes)Stream.ReadRecord(Code, Record,
890 &BlobStart, &BlobLen)) {
Douglas Gregorac8f2802009-04-10 17:25:41 +0000891 default: // Default behavior: ignore.
892 break;
893
894 case pch::TYPE_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000895 if (!TypeOffsets.empty()) {
896 Error("Duplicate TYPE_OFFSET record in PCH file");
897 return Failure;
898 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000899 TypeOffsets.swap(Record);
900 TypeAlreadyLoaded.resize(TypeOffsets.size(), false);
901 break;
902
903 case pch::DECL_OFFSET:
Douglas Gregor179cfb12009-04-10 20:39:37 +0000904 if (!DeclOffsets.empty()) {
905 Error("Duplicate DECL_OFFSET record in PCH file");
906 return Failure;
907 }
Douglas Gregorac8f2802009-04-10 17:25:41 +0000908 DeclOffsets.swap(Record);
909 DeclAlreadyLoaded.resize(DeclOffsets.size(), false);
910 break;
Douglas Gregor179cfb12009-04-10 20:39:37 +0000911
912 case pch::LANGUAGE_OPTIONS:
913 if (ParseLanguageOptions(Record))
914 return IgnorePCH;
915 break;
Douglas Gregorb5887f32009-04-10 21:16:55 +0000916
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000917 case pch::TARGET_TRIPLE: {
Douglas Gregorb5887f32009-04-10 21:16:55 +0000918 std::string TargetTriple(BlobStart, BlobLen);
919 if (TargetTriple != Context.Target.getTargetTriple()) {
920 Diag(diag::warn_pch_target_triple)
921 << TargetTriple << Context.Target.getTargetTriple();
922 Diag(diag::note_ignoring_pch) << FileName;
923 return IgnorePCH;
924 }
925 break;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000926 }
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000927
928 case pch::IDENTIFIER_TABLE:
929 IdentifierTable = BlobStart;
930 break;
931
932 case pch::IDENTIFIER_OFFSET:
933 if (!IdentifierData.empty()) {
934 Error("Duplicate IDENTIFIER_OFFSET record in PCH file");
935 return Failure;
936 }
937 IdentifierData.swap(Record);
938#ifndef NDEBUG
939 for (unsigned I = 0, N = IdentifierData.size(); I != N; ++I) {
940 if ((IdentifierData[I] & 0x01) == 0) {
941 Error("Malformed identifier table in the precompiled header");
942 return Failure;
943 }
944 }
945#endif
946 break;
Douglas Gregor631f6c62009-04-14 00:24:19 +0000947
948 case pch::EXTERNAL_DEFINITIONS:
949 if (!ExternalDefinitions.empty()) {
950 Error("Duplicate EXTERNAL_DEFINITIONS record in PCH file");
951 return Failure;
952 }
953 ExternalDefinitions.swap(Record);
954 break;
Douglas Gregor7a224cf2009-04-11 00:14:32 +0000955 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000956 }
957
Douglas Gregor179cfb12009-04-10 20:39:37 +0000958 Error("Premature end of bitstream");
959 return Failure;
Douglas Gregorc34897d2009-04-09 22:27:44 +0000960}
961
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000962PCHReader::PCHReadResult PCHReader::ReadPCH(const std::string &FileName) {
Douglas Gregor179cfb12009-04-10 20:39:37 +0000963 // Set the PCH file name.
964 this->FileName = FileName;
965
Douglas Gregorc34897d2009-04-09 22:27:44 +0000966 // Open the PCH file.
967 std::string ErrStr;
968 Buffer.reset(llvm::MemoryBuffer::getFile(FileName.c_str(), &ErrStr));
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000969 if (!Buffer) {
970 Error(ErrStr.c_str());
971 return IgnorePCH;
972 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000973
974 // Initialize the stream
975 Stream.init((const unsigned char *)Buffer->getBufferStart(),
976 (const unsigned char *)Buffer->getBufferEnd());
977
978 // Sniff for the signature.
979 if (Stream.Read(8) != 'C' ||
980 Stream.Read(8) != 'P' ||
981 Stream.Read(8) != 'C' ||
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000982 Stream.Read(8) != 'H') {
983 Error("Not a PCH file");
984 return IgnorePCH;
985 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000986
987 // We expect a number of well-defined blocks, though we don't necessarily
988 // need to understand them all.
989 while (!Stream.AtEndOfStream()) {
990 unsigned Code = Stream.ReadCode();
991
Douglas Gregorb3a04c82009-04-10 23:10:45 +0000992 if (Code != llvm::bitc::ENTER_SUBBLOCK) {
993 Error("Invalid record at top-level");
994 return Failure;
995 }
Douglas Gregorc34897d2009-04-09 22:27:44 +0000996
997 unsigned BlockID = Stream.ReadSubBlockID();
998
999 // We only know the PCH subblock ID.
1000 switch (BlockID) {
1001 case llvm::bitc::BLOCKINFO_BLOCK_ID:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001002 if (Stream.ReadBlockInfoBlock()) {
1003 Error("Malformed BlockInfoBlock");
1004 return Failure;
1005 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001006 break;
1007 case pch::PCH_BLOCK_ID:
Douglas Gregor179cfb12009-04-10 20:39:37 +00001008 switch (ReadPCHBlock()) {
1009 case Success:
1010 break;
1011
1012 case Failure:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001013 return Failure;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001014
1015 case IgnorePCH:
Douglas Gregorb5887f32009-04-10 21:16:55 +00001016 // FIXME: We could consider reading through to the end of this
1017 // PCH block, skipping subblocks, to see if there are other
1018 // PCH blocks elsewhere.
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001019 return IgnorePCH;
Douglas Gregor179cfb12009-04-10 20:39:37 +00001020 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001021 break;
1022 default:
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001023 if (Stream.SkipBlock()) {
1024 Error("Malformed block record");
1025 return Failure;
1026 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001027 break;
1028 }
1029 }
1030
1031 // Load the translation unit declaration
1032 ReadDeclRecord(DeclOffsets[0], 0);
1033
Douglas Gregorb3a04c82009-04-10 23:10:45 +00001034 return Success;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001035}
1036
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001037namespace {
1038 /// \brief Helper class that saves the current stream position and
1039 /// then restores it when destroyed.
1040 struct VISIBILITY_HIDDEN SavedStreamPosition {
1041 explicit SavedStreamPosition(llvm::BitstreamReader &Stream)
Douglas Gregor6dc849b2009-04-15 04:54:29 +00001042 : Stream(Stream), Offset(Stream.GetCurrentBitNo()) { }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001043
1044 ~SavedStreamPosition() {
Douglas Gregor6dc849b2009-04-15 04:54:29 +00001045 Stream.JumpToBit(Offset);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001046 }
1047
1048 private:
1049 llvm::BitstreamReader &Stream;
1050 uint64_t Offset;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001051 };
1052}
1053
Douglas Gregor179cfb12009-04-10 20:39:37 +00001054/// \brief Parse the record that corresponds to a LangOptions data
1055/// structure.
1056///
1057/// This routine compares the language options used to generate the
1058/// PCH file against the language options set for the current
1059/// compilation. For each option, we classify differences between the
1060/// two compiler states as either "benign" or "important". Benign
1061/// differences don't matter, and we accept them without complaint
1062/// (and without modifying the language options). Differences between
1063/// the states for important options cause the PCH file to be
1064/// unusable, so we emit a warning and return true to indicate that
1065/// there was an error.
1066///
1067/// \returns true if the PCH file is unacceptable, false otherwise.
1068bool PCHReader::ParseLanguageOptions(
1069 const llvm::SmallVectorImpl<uint64_t> &Record) {
1070 const LangOptions &LangOpts = Context.getLangOptions();
1071#define PARSE_LANGOPT_BENIGN(Option) ++Idx
1072#define PARSE_LANGOPT_IMPORTANT(Option, DiagID) \
1073 if (Record[Idx] != LangOpts.Option) { \
1074 Diag(DiagID) << (unsigned)Record[Idx] << LangOpts.Option; \
1075 Diag(diag::note_ignoring_pch) << FileName; \
1076 return true; \
1077 } \
1078 ++Idx
1079
1080 unsigned Idx = 0;
1081 PARSE_LANGOPT_BENIGN(Trigraphs);
1082 PARSE_LANGOPT_BENIGN(BCPLComment);
1083 PARSE_LANGOPT_BENIGN(DollarIdents);
1084 PARSE_LANGOPT_BENIGN(AsmPreprocessor);
1085 PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
1086 PARSE_LANGOPT_BENIGN(ImplicitInt);
1087 PARSE_LANGOPT_BENIGN(Digraphs);
1088 PARSE_LANGOPT_BENIGN(HexFloats);
1089 PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
1090 PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
1091 PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
1092 PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
1093 PARSE_LANGOPT_IMPORTANT(NoExtensions, diag::warn_pch_extensions);
1094 PARSE_LANGOPT_BENIGN(CXXOperatorName);
1095 PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
1096 PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
1097 PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
1098 PARSE_LANGOPT_BENIGN(PascalStrings);
1099 PARSE_LANGOPT_BENIGN(Boolean);
1100 PARSE_LANGOPT_BENIGN(WritableStrings);
1101 PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
1102 diag::warn_pch_lax_vector_conversions);
1103 PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
1104 PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
1105 PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
1106 PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
1107 PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
1108 diag::warn_pch_thread_safe_statics);
1109 PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
1110 PARSE_LANGOPT_BENIGN(EmitAllDecls);
1111 PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
1112 PARSE_LANGOPT_IMPORTANT(OverflowChecking, diag::warn_pch_overflow_checking);
1113 PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
1114 diag::warn_pch_heinous_extensions);
1115 // FIXME: Most of the options below are benign if the macro wasn't
1116 // used. Unfortunately, this means that a PCH compiled without
1117 // optimization can't be used with optimization turned on, even
1118 // though the only thing that changes is whether __OPTIMIZE__ was
1119 // defined... but if __OPTIMIZE__ never showed up in the header, it
1120 // doesn't matter. We could consider making this some special kind
1121 // of check.
1122 PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
1123 PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
1124 PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
1125 PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
1126 PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
1127 PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
1128 if ((LangOpts.getGCMode() != 0) != (Record[Idx] != 0)) {
1129 Diag(diag::warn_pch_gc_mode)
1130 << (unsigned)Record[Idx] << LangOpts.getGCMode();
1131 Diag(diag::note_ignoring_pch) << FileName;
1132 return true;
1133 }
1134 ++Idx;
1135 PARSE_LANGOPT_BENIGN(getVisibilityMode());
1136 PARSE_LANGOPT_BENIGN(InstantiationDepth);
1137#undef PARSE_LANGOPT_IRRELEVANT
1138#undef PARSE_LANGOPT_BENIGN
1139
1140 return false;
1141}
1142
Douglas Gregorc34897d2009-04-09 22:27:44 +00001143/// \brief Read and return the type at the given offset.
1144///
1145/// This routine actually reads the record corresponding to the type
1146/// at the given offset in the bitstream. It is a helper routine for
1147/// GetType, which deals with reading type IDs.
1148QualType PCHReader::ReadTypeRecord(uint64_t Offset) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001149 // Keep track of where we are in the stream, then jump back there
1150 // after reading this type.
1151 SavedStreamPosition SavedPosition(Stream);
1152
Douglas Gregorc34897d2009-04-09 22:27:44 +00001153 Stream.JumpToBit(Offset);
1154 RecordData Record;
1155 unsigned Code = Stream.ReadCode();
1156 switch ((pch::TypeCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor1c507882009-04-15 21:30:51 +00001157 case pch::TYPE_ATTR:
1158 assert(false && "Should never jump to an attribute block");
1159 return QualType();
1160
Douglas Gregorbdd4ba52009-04-15 22:00:08 +00001161 case pch::TYPE_EXT_QUAL: {
1162 assert(Record.size() == 3 &&
1163 "Incorrect encoding of extended qualifier type");
1164 QualType Base = GetType(Record[0]);
1165 QualType::GCAttrTypes GCAttr = (QualType::GCAttrTypes)Record[1];
1166 unsigned AddressSpace = Record[2];
1167
1168 QualType T = Base;
1169 if (GCAttr != QualType::GCNone)
1170 T = Context.getObjCGCQualType(T, GCAttr);
1171 if (AddressSpace)
1172 T = Context.getAddrSpaceQualType(T, AddressSpace);
1173 return T;
1174 }
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001175
Douglas Gregorc34897d2009-04-09 22:27:44 +00001176 case pch::TYPE_FIXED_WIDTH_INT: {
1177 assert(Record.size() == 2 && "Incorrect encoding of fixed-width int type");
1178 return Context.getFixedWidthIntType(Record[0], Record[1]);
1179 }
1180
1181 case pch::TYPE_COMPLEX: {
1182 assert(Record.size() == 1 && "Incorrect encoding of complex type");
1183 QualType ElemType = GetType(Record[0]);
1184 return Context.getComplexType(ElemType);
1185 }
1186
1187 case pch::TYPE_POINTER: {
1188 assert(Record.size() == 1 && "Incorrect encoding of pointer type");
1189 QualType PointeeType = GetType(Record[0]);
1190 return Context.getPointerType(PointeeType);
1191 }
1192
1193 case pch::TYPE_BLOCK_POINTER: {
1194 assert(Record.size() == 1 && "Incorrect encoding of block pointer type");
1195 QualType PointeeType = GetType(Record[0]);
1196 return Context.getBlockPointerType(PointeeType);
1197 }
1198
1199 case pch::TYPE_LVALUE_REFERENCE: {
1200 assert(Record.size() == 1 && "Incorrect encoding of lvalue reference type");
1201 QualType PointeeType = GetType(Record[0]);
1202 return Context.getLValueReferenceType(PointeeType);
1203 }
1204
1205 case pch::TYPE_RVALUE_REFERENCE: {
1206 assert(Record.size() == 1 && "Incorrect encoding of rvalue reference type");
1207 QualType PointeeType = GetType(Record[0]);
1208 return Context.getRValueReferenceType(PointeeType);
1209 }
1210
1211 case pch::TYPE_MEMBER_POINTER: {
1212 assert(Record.size() == 1 && "Incorrect encoding of member pointer type");
1213 QualType PointeeType = GetType(Record[0]);
1214 QualType ClassType = GetType(Record[1]);
1215 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
1216 }
1217
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001218 case pch::TYPE_CONSTANT_ARRAY: {
1219 QualType ElementType = GetType(Record[0]);
1220 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1221 unsigned IndexTypeQuals = Record[2];
1222 unsigned Idx = 3;
1223 llvm::APInt Size = ReadAPInt(Record, Idx);
1224 return Context.getConstantArrayType(ElementType, Size, ASM, IndexTypeQuals);
1225 }
1226
1227 case pch::TYPE_INCOMPLETE_ARRAY: {
1228 QualType ElementType = GetType(Record[0]);
1229 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1230 unsigned IndexTypeQuals = Record[2];
1231 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
1232 }
1233
1234 case pch::TYPE_VARIABLE_ARRAY: {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001235 QualType ElementType = GetType(Record[0]);
1236 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
1237 unsigned IndexTypeQuals = Record[2];
1238 return Context.getVariableArrayType(ElementType, ReadExpr(),
1239 ASM, IndexTypeQuals);
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001240 }
1241
1242 case pch::TYPE_VECTOR: {
1243 if (Record.size() != 2) {
1244 Error("Incorrect encoding of vector type in PCH file");
1245 return QualType();
1246 }
1247
1248 QualType ElementType = GetType(Record[0]);
1249 unsigned NumElements = Record[1];
1250 return Context.getVectorType(ElementType, NumElements);
1251 }
1252
1253 case pch::TYPE_EXT_VECTOR: {
1254 if (Record.size() != 2) {
1255 Error("Incorrect encoding of extended vector type in PCH file");
1256 return QualType();
1257 }
1258
1259 QualType ElementType = GetType(Record[0]);
1260 unsigned NumElements = Record[1];
1261 return Context.getExtVectorType(ElementType, NumElements);
1262 }
1263
1264 case pch::TYPE_FUNCTION_NO_PROTO: {
1265 if (Record.size() != 1) {
1266 Error("Incorrect encoding of no-proto function type");
1267 return QualType();
1268 }
1269 QualType ResultType = GetType(Record[0]);
1270 return Context.getFunctionNoProtoType(ResultType);
1271 }
1272
1273 case pch::TYPE_FUNCTION_PROTO: {
1274 QualType ResultType = GetType(Record[0]);
1275 unsigned Idx = 1;
1276 unsigned NumParams = Record[Idx++];
1277 llvm::SmallVector<QualType, 16> ParamTypes;
1278 for (unsigned I = 0; I != NumParams; ++I)
1279 ParamTypes.push_back(GetType(Record[Idx++]));
1280 bool isVariadic = Record[Idx++];
1281 unsigned Quals = Record[Idx++];
1282 return Context.getFunctionType(ResultType, &ParamTypes[0], NumParams,
1283 isVariadic, Quals);
1284 }
1285
1286 case pch::TYPE_TYPEDEF:
1287 assert(Record.size() == 1 && "Incorrect encoding of typedef type");
1288 return Context.getTypeDeclType(cast<TypedefDecl>(GetDecl(Record[0])));
1289
1290 case pch::TYPE_TYPEOF_EXPR:
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001291 return Context.getTypeOfExprType(ReadExpr());
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001292
1293 case pch::TYPE_TYPEOF: {
1294 if (Record.size() != 1) {
1295 Error("Incorrect encoding of typeof(type) in PCH file");
1296 return QualType();
1297 }
1298 QualType UnderlyingType = GetType(Record[0]);
1299 return Context.getTypeOfType(UnderlyingType);
1300 }
1301
1302 case pch::TYPE_RECORD:
Douglas Gregor982365e2009-04-13 21:20:57 +00001303 assert(Record.size() == 1 && "Incorrect encoding of record type");
1304 return Context.getTypeDeclType(cast<RecordDecl>(GetDecl(Record[0])));
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001305
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001306 case pch::TYPE_ENUM:
1307 assert(Record.size() == 1 && "Incorrect encoding of enum type");
1308 return Context.getTypeDeclType(cast<EnumDecl>(GetDecl(Record[0])));
1309
Douglas Gregor88fd09d2009-04-13 20:46:52 +00001310 case pch::TYPE_OBJC_INTERFACE:
1311 // FIXME: Deserialize ObjCInterfaceType
1312 assert(false && "Cannot de-serialize ObjC interface types yet");
1313 return QualType();
1314
1315 case pch::TYPE_OBJC_QUALIFIED_INTERFACE:
1316 // FIXME: Deserialize ObjCQualifiedInterfaceType
1317 assert(false && "Cannot de-serialize ObjC qualified interface types yet");
1318 return QualType();
1319
1320 case pch::TYPE_OBJC_QUALIFIED_ID:
1321 // FIXME: Deserialize ObjCQualifiedIdType
1322 assert(false && "Cannot de-serialize ObjC qualified id types yet");
1323 return QualType();
1324
1325 case pch::TYPE_OBJC_QUALIFIED_CLASS:
1326 // FIXME: Deserialize ObjCQualifiedClassType
1327 assert(false && "Cannot de-serialize ObjC qualified class types yet");
1328 return QualType();
Douglas Gregorc34897d2009-04-09 22:27:44 +00001329 }
1330
1331 // Suppress a GCC warning
1332 return QualType();
1333}
1334
1335/// \brief Note that we have loaded the declaration with the given
1336/// Index.
1337///
1338/// This routine notes that this declaration has already been loaded,
1339/// so that future GetDecl calls will return this declaration rather
1340/// than trying to load a new declaration.
1341inline void PCHReader::LoadedDecl(unsigned Index, Decl *D) {
1342 assert(!DeclAlreadyLoaded[Index] && "Decl loaded twice?");
1343 DeclAlreadyLoaded[Index] = true;
1344 DeclOffsets[Index] = reinterpret_cast<uint64_t>(D);
1345}
1346
1347/// \brief Read the declaration at the given offset from the PCH file.
1348Decl *PCHReader::ReadDeclRecord(uint64_t Offset, unsigned Index) {
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001349 // Keep track of where we are in the stream, then jump back there
1350 // after reading this declaration.
1351 SavedStreamPosition SavedPosition(Stream);
1352
Douglas Gregorc34897d2009-04-09 22:27:44 +00001353 Decl *D = 0;
1354 Stream.JumpToBit(Offset);
1355 RecordData Record;
1356 unsigned Code = Stream.ReadCode();
1357 unsigned Idx = 0;
1358 PCHDeclReader Reader(*this, Record, Idx);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001359
Douglas Gregorc34897d2009-04-09 22:27:44 +00001360 switch ((pch::DeclCode)Stream.ReadRecord(Code, Record)) {
Douglas Gregor1c507882009-04-15 21:30:51 +00001361 case pch::DECL_ATTR:
1362 case pch::DECL_CONTEXT_LEXICAL:
1363 case pch::DECL_CONTEXT_VISIBLE:
1364 assert(false && "Record cannot be de-serialized with ReadDeclRecord");
1365 break;
1366
Douglas Gregorc34897d2009-04-09 22:27:44 +00001367 case pch::DECL_TRANSLATION_UNIT:
1368 assert(Index == 0 && "Translation unit must be at index 0");
1369 Reader.VisitTranslationUnitDecl(Context.getTranslationUnitDecl());
1370 D = Context.getTranslationUnitDecl();
1371 LoadedDecl(Index, D);
1372 break;
1373
1374 case pch::DECL_TYPEDEF: {
1375 TypedefDecl *Typedef = TypedefDecl::Create(Context, 0, SourceLocation(),
1376 0, QualType());
1377 LoadedDecl(Index, Typedef);
1378 Reader.VisitTypedefDecl(Typedef);
1379 D = Typedef;
1380 break;
1381 }
1382
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001383 case pch::DECL_ENUM: {
1384 EnumDecl *Enum = EnumDecl::Create(Context, 0, SourceLocation(), 0, 0);
1385 LoadedDecl(Index, Enum);
1386 Reader.VisitEnumDecl(Enum);
1387 D = Enum;
1388 break;
1389 }
1390
Douglas Gregor982365e2009-04-13 21:20:57 +00001391 case pch::DECL_RECORD: {
1392 RecordDecl *Record = RecordDecl::Create(Context, TagDecl::TK_struct,
1393 0, SourceLocation(), 0, 0);
1394 LoadedDecl(Index, Record);
1395 Reader.VisitRecordDecl(Record);
1396 D = Record;
1397 break;
1398 }
1399
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001400 case pch::DECL_ENUM_CONSTANT: {
1401 EnumConstantDecl *ECD = EnumConstantDecl::Create(Context, 0,
1402 SourceLocation(), 0,
1403 QualType(), 0,
1404 llvm::APSInt());
1405 LoadedDecl(Index, ECD);
1406 Reader.VisitEnumConstantDecl(ECD);
1407 D = ECD;
1408 break;
1409 }
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001410
1411 case pch::DECL_FUNCTION: {
1412 FunctionDecl *Function = FunctionDecl::Create(Context, 0, SourceLocation(),
1413 DeclarationName(),
1414 QualType());
1415 LoadedDecl(Index, Function);
1416 Reader.VisitFunctionDecl(Function);
1417 D = Function;
1418 break;
1419 }
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001420
Douglas Gregor982365e2009-04-13 21:20:57 +00001421 case pch::DECL_FIELD: {
1422 FieldDecl *Field = FieldDecl::Create(Context, 0, SourceLocation(), 0,
1423 QualType(), 0, false);
1424 LoadedDecl(Index, Field);
1425 Reader.VisitFieldDecl(Field);
1426 D = Field;
1427 break;
1428 }
1429
Douglas Gregorc34897d2009-04-09 22:27:44 +00001430 case pch::DECL_VAR: {
1431 VarDecl *Var = VarDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
1432 VarDecl::None, SourceLocation());
1433 LoadedDecl(Index, Var);
1434 Reader.VisitVarDecl(Var);
1435 D = Var;
1436 break;
1437 }
1438
Douglas Gregor23ce3a52009-04-13 22:18:37 +00001439 case pch::DECL_PARM_VAR: {
1440 ParmVarDecl *Parm = ParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1441 QualType(), VarDecl::None, 0);
1442 LoadedDecl(Index, Parm);
1443 Reader.VisitParmVarDecl(Parm);
1444 D = Parm;
1445 break;
1446 }
1447
1448 case pch::DECL_ORIGINAL_PARM_VAR: {
1449 OriginalParmVarDecl *Parm
1450 = OriginalParmVarDecl::Create(Context, 0, SourceLocation(), 0,
1451 QualType(), QualType(), VarDecl::None,
1452 0);
1453 LoadedDecl(Index, Parm);
1454 Reader.VisitOriginalParmVarDecl(Parm);
1455 D = Parm;
1456 break;
1457 }
1458
Douglas Gregor2a491792009-04-13 22:49:25 +00001459 case pch::DECL_FILE_SCOPE_ASM: {
1460 FileScopeAsmDecl *Asm = FileScopeAsmDecl::Create(Context, 0,
1461 SourceLocation(), 0);
1462 LoadedDecl(Index, Asm);
1463 Reader.VisitFileScopeAsmDecl(Asm);
1464 D = Asm;
1465 break;
1466 }
1467
1468 case pch::DECL_BLOCK: {
1469 BlockDecl *Block = BlockDecl::Create(Context, 0, SourceLocation());
1470 LoadedDecl(Index, Block);
1471 Reader.VisitBlockDecl(Block);
1472 D = Block;
1473 break;
1474 }
Douglas Gregorc34897d2009-04-09 22:27:44 +00001475 }
1476
1477 // If this declaration is also a declaration context, get the
1478 // offsets for its tables of lexical and visible declarations.
1479 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
1480 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
1481 if (Offsets.first || Offsets.second) {
1482 DC->setHasExternalLexicalStorage(Offsets.first != 0);
1483 DC->setHasExternalVisibleStorage(Offsets.second != 0);
1484 DeclContextOffsets[DC] = Offsets;
1485 }
1486 }
1487 assert(Idx == Record.size());
1488
1489 return D;
1490}
1491
Douglas Gregorac8f2802009-04-10 17:25:41 +00001492QualType PCHReader::GetType(pch::TypeID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001493 unsigned Quals = ID & 0x07;
1494 unsigned Index = ID >> 3;
1495
1496 if (Index < pch::NUM_PREDEF_TYPE_IDS) {
1497 QualType T;
1498 switch ((pch::PredefinedTypeIDs)Index) {
1499 case pch::PREDEF_TYPE_NULL_ID: return QualType();
1500 case pch::PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
1501 case pch::PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
1502
1503 case pch::PREDEF_TYPE_CHAR_U_ID:
1504 case pch::PREDEF_TYPE_CHAR_S_ID:
1505 // FIXME: Check that the signedness of CharTy is correct!
1506 T = Context.CharTy;
1507 break;
1508
1509 case pch::PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
1510 case pch::PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
1511 case pch::PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
1512 case pch::PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
1513 case pch::PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
1514 case pch::PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
1515 case pch::PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
1516 case pch::PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
1517 case pch::PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
1518 case pch::PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
1519 case pch::PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
1520 case pch::PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
1521 case pch::PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
1522 case pch::PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
1523 case pch::PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
1524 case pch::PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
1525 }
1526
1527 assert(!T.isNull() && "Unknown predefined type");
1528 return T.getQualifiedType(Quals);
1529 }
1530
1531 Index -= pch::NUM_PREDEF_TYPE_IDS;
1532 if (!TypeAlreadyLoaded[Index]) {
1533 // Load the type from the PCH file.
1534 TypeOffsets[Index] = reinterpret_cast<uint64_t>(
1535 ReadTypeRecord(TypeOffsets[Index]).getTypePtr());
1536 TypeAlreadyLoaded[Index] = true;
1537 }
1538
1539 return QualType(reinterpret_cast<Type *>(TypeOffsets[Index]), Quals);
1540}
1541
Douglas Gregorac8f2802009-04-10 17:25:41 +00001542Decl *PCHReader::GetDecl(pch::DeclID ID) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001543 if (ID == 0)
1544 return 0;
1545
1546 unsigned Index = ID - 1;
1547 if (DeclAlreadyLoaded[Index])
1548 return reinterpret_cast<Decl *>(DeclOffsets[Index]);
1549
1550 // Load the declaration from the PCH file.
1551 return ReadDeclRecord(DeclOffsets[Index], Index);
1552}
1553
1554bool PCHReader::ReadDeclsLexicallyInContext(DeclContext *DC,
Douglas Gregorac8f2802009-04-10 17:25:41 +00001555 llvm::SmallVectorImpl<pch::DeclID> &Decls) {
Douglas Gregorc34897d2009-04-09 22:27:44 +00001556 assert(DC->hasExternalLexicalStorage() &&
1557 "DeclContext has no lexical decls in storage");
1558 uint64_t Offset = DeclContextOffsets[DC].first;
1559 assert(Offset && "DeclContext has no lexical decls in storage");
1560
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001561 // Keep track of where we are in the stream, then jump back there
1562 // after reading this context.
1563 SavedStreamPosition SavedPosition(Stream);
1564
Douglas Gregorc34897d2009-04-09 22:27:44 +00001565 // Load the record containing all of the declarations lexically in
1566 // this context.
1567 Stream.JumpToBit(Offset);
1568 RecordData Record;
1569 unsigned Code = Stream.ReadCode();
1570 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001571 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001572 assert(RecCode == pch::DECL_CONTEXT_LEXICAL && "Expected lexical block");
1573
1574 // Load all of the declaration IDs
1575 Decls.clear();
1576 Decls.insert(Decls.end(), Record.begin(), Record.end());
1577 return false;
1578}
1579
1580bool PCHReader::ReadDeclsVisibleInContext(DeclContext *DC,
1581 llvm::SmallVectorImpl<VisibleDeclaration> & Decls) {
1582 assert(DC->hasExternalVisibleStorage() &&
1583 "DeclContext has no visible decls in storage");
1584 uint64_t Offset = DeclContextOffsets[DC].second;
1585 assert(Offset && "DeclContext has no visible decls in storage");
1586
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001587 // Keep track of where we are in the stream, then jump back there
1588 // after reading this context.
1589 SavedStreamPosition SavedPosition(Stream);
1590
Douglas Gregorc34897d2009-04-09 22:27:44 +00001591 // Load the record containing all of the declarations visible in
1592 // this context.
1593 Stream.JumpToBit(Offset);
1594 RecordData Record;
1595 unsigned Code = Stream.ReadCode();
1596 unsigned RecCode = Stream.ReadRecord(Code, Record);
Douglas Gregor3c8ff3e2009-04-15 18:43:11 +00001597 (void)RecCode;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001598 assert(RecCode == pch::DECL_CONTEXT_VISIBLE && "Expected visible block");
1599 if (Record.size() == 0)
1600 return false;
1601
1602 Decls.clear();
1603
1604 unsigned Idx = 0;
Douglas Gregorc34897d2009-04-09 22:27:44 +00001605 while (Idx < Record.size()) {
1606 Decls.push_back(VisibleDeclaration());
1607 Decls.back().Name = ReadDeclarationName(Record, Idx);
1608
Douglas Gregorc34897d2009-04-09 22:27:44 +00001609 unsigned Size = Record[Idx++];
1610 llvm::SmallVector<unsigned, 4> & LoadedDecls
1611 = Decls.back().Declarations;
1612 LoadedDecls.reserve(Size);
1613 for (unsigned I = 0; I < Size; ++I)
1614 LoadedDecls.push_back(Record[Idx++]);
1615 }
1616
1617 return false;
1618}
1619
Douglas Gregor631f6c62009-04-14 00:24:19 +00001620void PCHReader::StartTranslationUnit(ASTConsumer *Consumer) {
1621 if (!Consumer)
1622 return;
1623
1624 for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
1625 Decl *D = GetDecl(ExternalDefinitions[I]);
1626 DeclGroupRef DG(D);
1627 Consumer->HandleTopLevelDecl(DG);
1628 }
1629}
1630
Douglas Gregorc34897d2009-04-09 22:27:44 +00001631void PCHReader::PrintStats() {
1632 std::fprintf(stderr, "*** PCH Statistics:\n");
1633
1634 unsigned NumTypesLoaded = std::count(TypeAlreadyLoaded.begin(),
1635 TypeAlreadyLoaded.end(),
1636 true);
1637 unsigned NumDeclsLoaded = std::count(DeclAlreadyLoaded.begin(),
1638 DeclAlreadyLoaded.end(),
1639 true);
Douglas Gregor9cf47422009-04-13 20:50:16 +00001640 unsigned NumIdentifiersLoaded = 0;
1641 for (unsigned I = 0; I < IdentifierData.size(); ++I) {
1642 if ((IdentifierData[I] & 0x01) == 0)
1643 ++NumIdentifiersLoaded;
1644 }
1645
Douglas Gregorc34897d2009-04-09 22:27:44 +00001646 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
1647 NumTypesLoaded, (unsigned)TypeAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001648 ((float)NumTypesLoaded/TypeAlreadyLoaded.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001649 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
1650 NumDeclsLoaded, (unsigned)DeclAlreadyLoaded.size(),
Douglas Gregor9cf47422009-04-13 20:50:16 +00001651 ((float)NumDeclsLoaded/DeclAlreadyLoaded.size() * 100));
1652 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
1653 NumIdentifiersLoaded, (unsigned)IdentifierData.size(),
1654 ((float)NumIdentifiersLoaded/IdentifierData.size() * 100));
Douglas Gregorc34897d2009-04-09 22:27:44 +00001655 std::fprintf(stderr, "\n");
1656}
1657
Chris Lattner29241862009-04-11 21:15:38 +00001658IdentifierInfo *PCHReader::DecodeIdentifierInfo(unsigned ID) {
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001659 if (ID == 0)
1660 return 0;
Chris Lattner29241862009-04-11 21:15:38 +00001661
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001662 if (!IdentifierTable || IdentifierData.empty()) {
1663 Error("No identifier table in PCH file");
1664 return 0;
1665 }
Chris Lattner29241862009-04-11 21:15:38 +00001666
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001667 if (IdentifierData[ID - 1] & 0x01) {
1668 uint64_t Offset = IdentifierData[ID - 1];
1669 IdentifierData[ID - 1] = reinterpret_cast<uint64_t>(
Chris Lattner29241862009-04-11 21:15:38 +00001670 &Context.Idents.get(IdentifierTable + Offset));
Douglas Gregor7a224cf2009-04-11 00:14:32 +00001671 }
Chris Lattner29241862009-04-11 21:15:38 +00001672
1673 return reinterpret_cast<IdentifierInfo *>(IdentifierData[ID - 1]);
Douglas Gregorc34897d2009-04-09 22:27:44 +00001674}
1675
1676DeclarationName
1677PCHReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
1678 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
1679 switch (Kind) {
1680 case DeclarationName::Identifier:
1681 return DeclarationName(GetIdentifierInfo(Record, Idx));
1682
1683 case DeclarationName::ObjCZeroArgSelector:
1684 case DeclarationName::ObjCOneArgSelector:
1685 case DeclarationName::ObjCMultiArgSelector:
1686 assert(false && "Unable to de-serialize Objective-C selectors");
1687 break;
1688
1689 case DeclarationName::CXXConstructorName:
1690 return Context.DeclarationNames.getCXXConstructorName(
1691 GetType(Record[Idx++]));
1692
1693 case DeclarationName::CXXDestructorName:
1694 return Context.DeclarationNames.getCXXDestructorName(
1695 GetType(Record[Idx++]));
1696
1697 case DeclarationName::CXXConversionFunctionName:
1698 return Context.DeclarationNames.getCXXConversionFunctionName(
1699 GetType(Record[Idx++]));
1700
1701 case DeclarationName::CXXOperatorName:
1702 return Context.DeclarationNames.getCXXOperatorName(
1703 (OverloadedOperatorKind)Record[Idx++]);
1704
1705 case DeclarationName::CXXUsingDirective:
1706 return DeclarationName::getUsingDirectiveName();
1707 }
1708
1709 // Required to silence GCC warning
1710 return DeclarationName();
1711}
Douglas Gregor179cfb12009-04-10 20:39:37 +00001712
Douglas Gregor47f1b2c2009-04-13 18:14:40 +00001713/// \brief Read an integral value
1714llvm::APInt PCHReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
1715 unsigned BitWidth = Record[Idx++];
1716 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1717 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
1718 Idx += NumWords;
1719 return Result;
1720}
1721
1722/// \brief Read a signed integral value
1723llvm::APSInt PCHReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
1724 bool isUnsigned = Record[Idx++];
1725 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
1726}
1727
Douglas Gregore2f37202009-04-14 21:55:33 +00001728/// \brief Read a floating-point value
1729llvm::APFloat PCHReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
Douglas Gregore2f37202009-04-14 21:55:33 +00001730 return llvm::APFloat(ReadAPInt(Record, Idx));
1731}
1732
Douglas Gregor1c507882009-04-15 21:30:51 +00001733// \brief Read a string
1734std::string PCHReader::ReadString(const RecordData &Record, unsigned &Idx) {
1735 unsigned Len = Record[Idx++];
1736 std::string Result(&Record[Idx], &Record[Idx] + Len);
1737 Idx += Len;
1738 return Result;
1739}
1740
1741/// \brief Reads attributes from the current stream position.
1742Attr *PCHReader::ReadAttributes() {
1743 unsigned Code = Stream.ReadCode();
1744 assert(Code == llvm::bitc::UNABBREV_RECORD &&
1745 "Expected unabbreviated record"); (void)Code;
1746
1747 RecordData Record;
1748 unsigned Idx = 0;
1749 unsigned RecCode = Stream.ReadRecord(Code, Record);
1750 assert(RecCode == pch::DECL_ATTR && "Expected attribute record");
1751 (void)RecCode;
1752
1753#define SIMPLE_ATTR(Name) \
1754 case Attr::Name: \
1755 New = ::new (Context) Name##Attr(); \
1756 break
1757
1758#define STRING_ATTR(Name) \
1759 case Attr::Name: \
1760 New = ::new (Context) Name##Attr(ReadString(Record, Idx)); \
1761 break
1762
1763#define UNSIGNED_ATTR(Name) \
1764 case Attr::Name: \
1765 New = ::new (Context) Name##Attr(Record[Idx++]); \
1766 break
1767
1768 Attr *Attrs = 0;
1769 while (Idx < Record.size()) {
1770 Attr *New = 0;
1771 Attr::Kind Kind = (Attr::Kind)Record[Idx++];
1772 bool IsInherited = Record[Idx++];
1773
1774 switch (Kind) {
1775 STRING_ATTR(Alias);
1776 UNSIGNED_ATTR(Aligned);
1777 SIMPLE_ATTR(AlwaysInline);
1778 SIMPLE_ATTR(AnalyzerNoReturn);
1779 STRING_ATTR(Annotate);
1780 STRING_ATTR(AsmLabel);
1781
1782 case Attr::Blocks:
1783 New = ::new (Context) BlocksAttr(
1784 (BlocksAttr::BlocksAttrTypes)Record[Idx++]);
1785 break;
1786
1787 case Attr::Cleanup:
1788 New = ::new (Context) CleanupAttr(
1789 cast<FunctionDecl>(GetDecl(Record[Idx++])));
1790 break;
1791
1792 SIMPLE_ATTR(Const);
1793 UNSIGNED_ATTR(Constructor);
1794 SIMPLE_ATTR(DLLExport);
1795 SIMPLE_ATTR(DLLImport);
1796 SIMPLE_ATTR(Deprecated);
1797 UNSIGNED_ATTR(Destructor);
1798 SIMPLE_ATTR(FastCall);
1799
1800 case Attr::Format: {
1801 std::string Type = ReadString(Record, Idx);
1802 unsigned FormatIdx = Record[Idx++];
1803 unsigned FirstArg = Record[Idx++];
1804 New = ::new (Context) FormatAttr(Type, FormatIdx, FirstArg);
1805 break;
1806 }
1807
1808 SIMPLE_ATTR(GNUCInline);
1809
1810 case Attr::IBOutletKind:
1811 New = ::new (Context) IBOutletAttr();
1812 break;
1813
1814 SIMPLE_ATTR(NoReturn);
1815 SIMPLE_ATTR(NoThrow);
1816 SIMPLE_ATTR(Nodebug);
1817 SIMPLE_ATTR(Noinline);
1818
1819 case Attr::NonNull: {
1820 unsigned Size = Record[Idx++];
1821 llvm::SmallVector<unsigned, 16> ArgNums;
1822 ArgNums.insert(ArgNums.end(), &Record[Idx], &Record[Idx] + Size);
1823 Idx += Size;
1824 New = ::new (Context) NonNullAttr(&ArgNums[0], Size);
1825 break;
1826 }
1827
1828 SIMPLE_ATTR(ObjCException);
1829 SIMPLE_ATTR(ObjCNSObject);
1830 SIMPLE_ATTR(Overloadable);
1831 UNSIGNED_ATTR(Packed);
1832 SIMPLE_ATTR(Pure);
1833 UNSIGNED_ATTR(Regparm);
1834 STRING_ATTR(Section);
1835 SIMPLE_ATTR(StdCall);
1836 SIMPLE_ATTR(TransparentUnion);
1837 SIMPLE_ATTR(Unavailable);
1838 SIMPLE_ATTR(Unused);
1839 SIMPLE_ATTR(Used);
1840
1841 case Attr::Visibility:
1842 New = ::new (Context) VisibilityAttr(
1843 (VisibilityAttr::VisibilityTypes)Record[Idx++]);
1844 break;
1845
1846 SIMPLE_ATTR(WarnUnusedResult);
1847 SIMPLE_ATTR(Weak);
1848 SIMPLE_ATTR(WeakImport);
1849 }
1850
1851 assert(New && "Unable to decode attribute?");
1852 New->setInherited(IsInherited);
1853 New->setNext(Attrs);
1854 Attrs = New;
1855 }
1856#undef UNSIGNED_ATTR
1857#undef STRING_ATTR
1858#undef SIMPLE_ATTR
1859
1860 // The list of attributes was built backwards. Reverse the list
1861 // before returning it.
1862 Attr *PrevAttr = 0, *NextAttr = 0;
1863 while (Attrs) {
1864 NextAttr = Attrs->getNext();
1865 Attrs->setNext(PrevAttr);
1866 PrevAttr = Attrs;
1867 Attrs = NextAttr;
1868 }
1869
1870 return PrevAttr;
1871}
1872
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001873Expr *PCHReader::ReadExpr() {
Douglas Gregora151ba42009-04-14 23:32:43 +00001874 // Within the bitstream, expressions are stored in Reverse Polish
1875 // Notation, with each of the subexpressions preceding the
1876 // expression they are stored in. To evaluate expressions, we
1877 // continue reading expressions and placing them on the stack, with
1878 // expressions having operands removing those operands from the
1879 // stack. Evaluation terminates when we see a EXPR_STOP record, and
1880 // the single remaining expression on the stack is our result.
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001881 RecordData Record;
Douglas Gregora151ba42009-04-14 23:32:43 +00001882 unsigned Idx;
1883 llvm::SmallVector<Expr *, 16> ExprStack;
1884 PCHStmtReader Reader(*this, Record, Idx, ExprStack);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001885 Stmt::EmptyShell Empty;
1886
Douglas Gregora151ba42009-04-14 23:32:43 +00001887 while (true) {
1888 unsigned Code = Stream.ReadCode();
1889 if (Code == llvm::bitc::END_BLOCK) {
1890 if (Stream.ReadBlockEnd()) {
1891 Error("Error at end of Source Manager block");
1892 return 0;
1893 }
1894 break;
1895 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001896
Douglas Gregora151ba42009-04-14 23:32:43 +00001897 if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1898 // No known subblocks, always skip them.
1899 Stream.ReadSubBlockID();
1900 if (Stream.SkipBlock()) {
1901 Error("Malformed block record");
1902 return 0;
1903 }
1904 continue;
1905 }
Douglas Gregore2f37202009-04-14 21:55:33 +00001906
Douglas Gregora151ba42009-04-14 23:32:43 +00001907 if (Code == llvm::bitc::DEFINE_ABBREV) {
1908 Stream.ReadAbbrevRecord();
1909 continue;
1910 }
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001911
Douglas Gregora151ba42009-04-14 23:32:43 +00001912 Expr *E = 0;
1913 Idx = 0;
1914 Record.clear();
1915 bool Finished = false;
1916 switch ((pch::StmtCode)Stream.ReadRecord(Code, Record)) {
1917 case pch::EXPR_STOP:
1918 Finished = true;
1919 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001920
Douglas Gregora151ba42009-04-14 23:32:43 +00001921 case pch::EXPR_NULL:
1922 E = 0;
1923 break;
Douglas Gregorc10f86f2009-04-14 21:18:50 +00001924
Douglas Gregora151ba42009-04-14 23:32:43 +00001925 case pch::EXPR_PREDEFINED:
1926 // FIXME: untested (until we can serialize function bodies).
1927 E = new (Context) PredefinedExpr(Empty);
1928 break;
1929
1930 case pch::EXPR_DECL_REF:
1931 E = new (Context) DeclRefExpr(Empty);
1932 break;
1933
1934 case pch::EXPR_INTEGER_LITERAL:
1935 E = new (Context) IntegerLiteral(Empty);
1936 break;
1937
1938 case pch::EXPR_FLOATING_LITERAL:
1939 E = new (Context) FloatingLiteral(Empty);
1940 break;
1941
Douglas Gregor21ddd8c2009-04-15 22:19:53 +00001942 case pch::EXPR_IMAGINARY_LITERAL:
1943 E = new (Context) ImaginaryLiteral(Empty);
1944 break;
1945
Douglas Gregor596e0932009-04-15 16:35:07 +00001946 case pch::EXPR_STRING_LITERAL:
1947 E = StringLiteral::CreateEmpty(Context,
1948 Record[PCHStmtReader::NumExprFields + 1]);
1949 break;
1950
Douglas Gregora151ba42009-04-14 23:32:43 +00001951 case pch::EXPR_CHARACTER_LITERAL:
1952 E = new (Context) CharacterLiteral(Empty);
1953 break;
1954
Douglas Gregor4ea0b1f2009-04-14 23:59:37 +00001955 case pch::EXPR_PAREN:
1956 E = new (Context) ParenExpr(Empty);
1957 break;
1958
Douglas Gregor12d74052009-04-15 15:58:59 +00001959 case pch::EXPR_UNARY_OPERATOR:
1960 E = new (Context) UnaryOperator(Empty);
1961 break;
1962
1963 case pch::EXPR_SIZEOF_ALIGN_OF:
1964 E = new (Context) SizeOfAlignOfExpr(Empty);
1965 break;
1966
Douglas Gregor21ddd8c2009-04-15 22:19:53 +00001967 case pch::EXPR_ARRAY_SUBSCRIPT:
1968 E = new (Context) ArraySubscriptExpr(Empty);
1969 break;
1970
Douglas Gregor7e2b1cd2009-04-15 17:43:59 +00001971 case pch::EXPR_CALL:
1972 E = new (Context) CallExpr(Context, Empty);
1973 break;
1974
1975 case pch::EXPR_MEMBER:
1976 E = new (Context) MemberExpr(Empty);
1977 break;
1978
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001979 case pch::EXPR_BINARY_OPERATOR:
1980 E = new (Context) BinaryOperator(Empty);
1981 break;
1982
Douglas Gregorc599bbf2009-04-15 22:40:36 +00001983 case pch::EXPR_COMPOUND_ASSIGN_OPERATOR:
1984 E = new (Context) CompoundAssignOperator(Empty);
1985 break;
1986
1987 case pch::EXPR_CONDITIONAL_OPERATOR:
1988 E = new (Context) ConditionalOperator(Empty);
1989 break;
1990
Douglas Gregora151ba42009-04-14 23:32:43 +00001991 case pch::EXPR_IMPLICIT_CAST:
1992 E = new (Context) ImplicitCastExpr(Empty);
1993 break;
Douglas Gregorc75d0cb2009-04-15 00:25:59 +00001994
1995 case pch::EXPR_CSTYLE_CAST:
1996 E = new (Context) CStyleCastExpr(Empty);
1997 break;
Douglas Gregorec0b8292009-04-15 23:02:49 +00001998
1999 case pch::EXPR_EXT_VECTOR_ELEMENT:
2000 E = new (Context) ExtVectorElementExpr(Empty);
2001 break;
2002
2003 case pch::EXPR_VA_ARG:
2004 // FIXME: untested; we need function bodies first
2005 E = new (Context) VAArgExpr(Empty);
2006 break;
Douglas Gregor209d4622009-04-15 23:33:31 +00002007
2008 case pch::EXPR_TYPES_COMPATIBLE:
2009 E = new (Context) TypesCompatibleExpr(Empty);
2010 break;
2011
2012 case pch::EXPR_CHOOSE:
2013 E = new (Context) ChooseExpr(Empty);
2014 break;
2015
2016 case pch::EXPR_GNU_NULL:
2017 E = new (Context) GNUNullExpr(Empty);
2018 break;
Douglas Gregora151ba42009-04-14 23:32:43 +00002019 }
2020
2021 // We hit an EXPR_STOP, so we're done with this expression.
2022 if (Finished)
2023 break;
2024
2025 if (E) {
2026 unsigned NumSubExprs = Reader.Visit(E);
2027 while (NumSubExprs > 0) {
2028 ExprStack.pop_back();
2029 --NumSubExprs;
2030 }
2031 }
2032
2033 assert(Idx == Record.size() && "Invalid deserialization of expression");
2034 ExprStack.push_back(E);
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002035 }
Douglas Gregora151ba42009-04-14 23:32:43 +00002036 assert(ExprStack.size() == 1 && "Extra expressions on stack!");
2037 return ExprStack.back();
Douglas Gregorc10f86f2009-04-14 21:18:50 +00002038}
2039
Douglas Gregor179cfb12009-04-10 20:39:37 +00002040DiagnosticBuilder PCHReader::Diag(unsigned DiagID) {
Douglas Gregorb3a04c82009-04-10 23:10:45 +00002041 return Diag(SourceLocation(), DiagID);
2042}
2043
2044DiagnosticBuilder PCHReader::Diag(SourceLocation Loc, unsigned DiagID) {
2045 return PP.getDiagnostics().Report(FullSourceLoc(Loc,
Douglas Gregor179cfb12009-04-10 20:39:37 +00002046 Context.getSourceManager()),
2047 DiagID);
2048}