blob: b2a192927fc3e411c803e3741d97f87e26919da5 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
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 implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
45struct EvalInfo {
46 ASTContext &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +000047
Anders Carlsson54da0492008-11-30 16:38:33 +000048 /// EvalResult - Contains information about the evaluation.
49 Expr::EvalResult &EvalResult;
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +000050
John McCall42c8f872010-05-10 23:27:23 +000051 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult)
52 : Ctx(ctx), EvalResult(evalresult) {}
Chris Lattner87eae5e2008-07-11 22:52:41 +000053};
54
John McCallf4cf1a12010-05-07 17:22:02 +000055namespace {
56 struct ComplexValue {
57 private:
58 bool IsInt;
59
60 public:
61 APSInt IntReal, IntImag;
62 APFloat FloatReal, FloatImag;
63
64 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
65
66 void makeComplexFloat() { IsInt = false; }
67 bool isComplexFloat() const { return !IsInt; }
68 APFloat &getComplexFloatReal() { return FloatReal; }
69 APFloat &getComplexFloatImag() { return FloatImag; }
70
71 void makeComplexInt() { IsInt = true; }
72 bool isComplexInt() const { return IsInt; }
73 APSInt &getComplexIntReal() { return IntReal; }
74 APSInt &getComplexIntImag() { return IntImag; }
75
76 void moveInto(APValue &v) {
77 if (isComplexFloat())
78 v = APValue(FloatReal, FloatImag);
79 else
80 v = APValue(IntReal, IntImag);
81 }
82 };
John McCallefdb83e2010-05-07 21:00:08 +000083
84 struct LValue {
85 Expr *Base;
86 CharUnits Offset;
87
88 Expr *getLValueBase() { return Base; }
89 CharUnits getLValueOffset() { return Offset; }
90
91 void moveInto(APValue &v) {
92 v = APValue(Base, Offset);
93 }
94 };
John McCallf4cf1a12010-05-07 17:22:02 +000095}
Chris Lattner87eae5e2008-07-11 22:52:41 +000096
John McCallefdb83e2010-05-07 21:00:08 +000097static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
98static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +000099static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000100static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
101 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000102static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000103static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000104
105//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000106// Misc utilities
107//===----------------------------------------------------------------------===//
108
John McCall42c8f872010-05-10 23:27:23 +0000109static bool IsGlobalLValue(LValue &Value) {
110 const Expr *E = Value.Base;
111 if (!E) return true;
112
113 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
114 if (isa<FunctionDecl>(DRE->getDecl()))
115 return true;
116 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
117 return VD->hasGlobalStorage();
118 return false;
119 }
120
121 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
122 return CLE->isFileScope();
123
124 return true;
125}
126
John McCallefdb83e2010-05-07 21:00:08 +0000127static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
128 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000129
John McCall35542832010-05-07 21:34:32 +0000130 // A null base expression indicates a null pointer. These are always
131 // evaluatable, and they are false unless the offset is zero.
132 if (!Base) {
133 Result = !Value.Offset.isZero();
134 return true;
135 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000136
John McCall42c8f872010-05-10 23:27:23 +0000137 // Require the base expression to be a global l-value.
138 if (!IsGlobalLValue(Value)) return false;
139
John McCall35542832010-05-07 21:34:32 +0000140 // We have a non-null base expression. These are generally known to
141 // be true, but if it'a decl-ref to a weak symbol it can be null at
142 // runtime.
John McCall35542832010-05-07 21:34:32 +0000143 Result = true;
144
145 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000146 if (!DeclRef)
147 return true;
148
John McCall35542832010-05-07 21:34:32 +0000149 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000150 const ValueDecl* Decl = DeclRef->getDecl();
151 if (Decl->hasAttr<WeakAttr>() ||
152 Decl->hasAttr<WeakRefAttr>() ||
153 Decl->hasAttr<WeakImportAttr>())
154 return false;
155
Eli Friedman5bc86102009-06-14 02:17:33 +0000156 return true;
157}
158
John McCallcd7a4452010-01-05 23:42:56 +0000159static bool HandleConversionToBool(const Expr* E, bool& Result,
160 EvalInfo &Info) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000161 if (E->getType()->isIntegralType()) {
162 APSInt IntResult;
163 if (!EvaluateInteger(E, IntResult, Info))
164 return false;
165 Result = IntResult != 0;
166 return true;
167 } else if (E->getType()->isRealFloatingType()) {
168 APFloat FloatResult(0.0);
169 if (!EvaluateFloat(E, FloatResult, Info))
170 return false;
171 Result = !FloatResult.isZero();
172 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000173 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000174 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000175 if (!EvaluatePointer(E, PointerResult, Info))
176 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000177 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000178 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000179 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000180 if (!EvaluateComplex(E, ComplexResult, Info))
181 return false;
182 if (ComplexResult.isComplexFloat()) {
183 Result = !ComplexResult.getComplexFloatReal().isZero() ||
184 !ComplexResult.getComplexFloatImag().isZero();
185 } else {
186 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
187 ComplexResult.getComplexIntImag().getBoolValue();
188 }
189 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000190 }
191
192 return false;
193}
194
Mike Stump1eb44332009-09-09 15:08:12 +0000195static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000196 APFloat &Value, ASTContext &Ctx) {
197 unsigned DestWidth = Ctx.getIntWidth(DestType);
198 // Determine whether we are converting to unsigned or signed.
199 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000201 // FIXME: Warning for overflow.
202 uint64_t Space[4];
203 bool ignored;
204 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
205 llvm::APFloat::rmTowardZero, &ignored);
206 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
207}
208
Mike Stump1eb44332009-09-09 15:08:12 +0000209static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000210 APFloat &Value, ASTContext &Ctx) {
211 bool ignored;
212 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000213 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000214 APFloat::rmNearestTiesToEven, &ignored);
215 return Result;
216}
217
Mike Stump1eb44332009-09-09 15:08:12 +0000218static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000219 APSInt &Value, ASTContext &Ctx) {
220 unsigned DestWidth = Ctx.getIntWidth(DestType);
221 APSInt Result = Value;
222 // Figure out if this is a truncate, extend or noop cast.
223 // If the input is signed, do a sign extend, noop, or truncate.
224 Result.extOrTrunc(DestWidth);
225 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
226 return Result;
227}
228
Mike Stump1eb44332009-09-09 15:08:12 +0000229static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000230 APSInt &Value, ASTContext &Ctx) {
231
232 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
233 Result.convertFromAPInt(Value, Value.isSigned(),
234 APFloat::rmNearestTiesToEven);
235 return Result;
236}
237
Mike Stumpc4c90452009-10-27 22:09:17 +0000238namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000239class HasSideEffect
Mike Stumpc4c90452009-10-27 22:09:17 +0000240 : public StmtVisitor<HasSideEffect, bool> {
241 EvalInfo &Info;
242public:
243
244 HasSideEffect(EvalInfo &info) : Info(info) {}
245
246 // Unhandled nodes conservatively default to having side effects.
247 bool VisitStmt(Stmt *S) {
248 return true;
249 }
250
251 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
252 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000253 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000254 return true;
255 return false;
256 }
257 // We don't want to evaluate BlockExprs multiple times, as they generate
258 // a ton of code.
259 bool VisitBlockExpr(BlockExpr *E) { return true; }
260 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
261 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
262 { return Visit(E->getInitializer()); }
263 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
264 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
265 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
266 bool VisitStringLiteral(StringLiteral *E) { return false; }
267 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
268 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
269 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000270 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000271 bool VisitChooseExpr(ChooseExpr *E)
272 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
273 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
274 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000275 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000276 bool VisitBinaryOperator(BinaryOperator *E)
277 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000278 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
279 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
280 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
281 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
282 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000283 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000284 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000285 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000286 }
287 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000288
289 // Has side effects if any element does.
290 bool VisitInitListExpr(InitListExpr *E) {
291 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
292 if (Visit(E->getInit(i))) return true;
293 return false;
294 }
Mike Stumpc4c90452009-10-27 22:09:17 +0000295};
296
Mike Stumpc4c90452009-10-27 22:09:17 +0000297} // end anonymous namespace
298
Eli Friedman4efaa272008-11-12 09:44:48 +0000299//===----------------------------------------------------------------------===//
300// LValue Evaluation
301//===----------------------------------------------------------------------===//
302namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000303class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000304 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000305 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000306 LValue &Result;
307
308 bool Success(Expr *E) {
309 Result.Base = E;
310 Result.Offset = CharUnits::Zero();
311 return true;
312 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000313public:
Mike Stump1eb44332009-09-09 15:08:12 +0000314
John McCallefdb83e2010-05-07 21:00:08 +0000315 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
316 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000317
John McCallefdb83e2010-05-07 21:00:08 +0000318 bool VisitStmt(Stmt *S) {
319 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000320 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000321
John McCallefdb83e2010-05-07 21:00:08 +0000322 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
323 bool VisitDeclRefExpr(DeclRefExpr *E);
324 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
325 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
326 bool VisitMemberExpr(MemberExpr *E);
327 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
328 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
329 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
330 bool VisitUnaryDeref(UnaryOperator *E);
331 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000332 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000333 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000334 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000335
John McCallefdb83e2010-05-07 21:00:08 +0000336 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000337 switch (E->getCastKind()) {
338 default:
John McCallefdb83e2010-05-07 21:00:08 +0000339 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000340
341 case CastExpr::CK_NoOp:
342 return Visit(E->getSubExpr());
343 }
344 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000345 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000346};
347} // end anonymous namespace
348
John McCallefdb83e2010-05-07 21:00:08 +0000349static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
350 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000351}
352
John McCallefdb83e2010-05-07 21:00:08 +0000353bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000354 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000355 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000356 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
357 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000358 return Success(E);
Eli Friedmand933a012009-08-29 19:09:59 +0000359 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000360 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000361 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000362 }
363
John McCallefdb83e2010-05-07 21:00:08 +0000364 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000365}
366
John McCallefdb83e2010-05-07 21:00:08 +0000367bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000368 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000369}
370
John McCallefdb83e2010-05-07 21:00:08 +0000371bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000372 QualType Ty;
373 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000374 if (!EvaluatePointer(E->getBase(), Result, Info))
375 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000376 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000377 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000378 if (!Visit(E->getBase()))
379 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000380 Ty = E->getBase()->getType();
381 }
382
Ted Kremenek6217b802009-07-29 21:53:49 +0000383 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000384 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000385
386 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
387 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000388 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000389
390 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000391 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000392
Eli Friedman4efaa272008-11-12 09:44:48 +0000393 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000394 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000395 for (RecordDecl::field_iterator Field = RD->field_begin(),
396 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000397 Field != FieldEnd; (void)++Field, ++i) {
398 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000399 break;
400 }
401
John McCallefdb83e2010-05-07 21:00:08 +0000402 Result.Offset += CharUnits::fromQuantity(RL.getFieldOffset(i) / 8);
403 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000404}
405
John McCallefdb83e2010-05-07 21:00:08 +0000406bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000407 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000408 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Anders Carlsson3068d112008-11-16 19:01:22 +0000410 APSInt Index;
411 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000412 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000413
Ken Dyck199c3d62010-01-11 17:06:35 +0000414 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000415 Result.Offset += Index.getSExtValue() * ElementSize;
416 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000417}
Eli Friedman4efaa272008-11-12 09:44:48 +0000418
John McCallefdb83e2010-05-07 21:00:08 +0000419bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
420 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000421}
422
Eli Friedman4efaa272008-11-12 09:44:48 +0000423//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000424// Pointer Evaluation
425//===----------------------------------------------------------------------===//
426
Anders Carlssonc754aa62008-07-08 05:13:58 +0000427namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000428class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000429 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000430 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000431 LValue &Result;
432
433 bool Success(Expr *E) {
434 Result.Base = E;
435 Result.Offset = CharUnits::Zero();
436 return true;
437 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000438public:
Mike Stump1eb44332009-09-09 15:08:12 +0000439
John McCallefdb83e2010-05-07 21:00:08 +0000440 PointerExprEvaluator(EvalInfo &info, LValue &Result)
441 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000442
John McCallefdb83e2010-05-07 21:00:08 +0000443 bool VisitStmt(Stmt *S) {
444 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000445 }
446
John McCallefdb83e2010-05-07 21:00:08 +0000447 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000448
John McCallefdb83e2010-05-07 21:00:08 +0000449 bool VisitBinaryOperator(const BinaryOperator *E);
450 bool VisitCastExpr(CastExpr* E);
451 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000452 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000453 bool VisitUnaryAddrOf(const UnaryOperator *E);
454 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
455 { return Success(E); }
456 bool VisitAddrLabelExpr(AddrLabelExpr *E)
457 { return Success(E); }
458 bool VisitCallExpr(CallExpr *E);
459 bool VisitBlockExpr(BlockExpr *E) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000460 if (!E->hasBlockDeclRefExprs())
John McCallefdb83e2010-05-07 21:00:08 +0000461 return Success(E);
462 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000463 }
John McCallefdb83e2010-05-07 21:00:08 +0000464 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
465 { return Success((Expr*)0); }
466 bool VisitConditionalOperator(ConditionalOperator *E);
467 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000468 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000469 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
470 { return Success((Expr*)0); }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000471 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000472};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000473} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000474
John McCallefdb83e2010-05-07 21:00:08 +0000475static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000476 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000477 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000478}
479
John McCallefdb83e2010-05-07 21:00:08 +0000480bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000481 if (E->getOpcode() != BinaryOperator::Add &&
482 E->getOpcode() != BinaryOperator::Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000483 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000485 const Expr *PExp = E->getLHS();
486 const Expr *IExp = E->getRHS();
487 if (IExp->getType()->isPointerType())
488 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000489
John McCallefdb83e2010-05-07 21:00:08 +0000490 if (!EvaluatePointer(PExp, Result, Info))
491 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000492
John McCallefdb83e2010-05-07 21:00:08 +0000493 llvm::APSInt Offset;
494 if (!EvaluateInteger(IExp, Offset, Info))
495 return false;
496 int64_t AdditionalOffset
497 = Offset.isSigned() ? Offset.getSExtValue()
498 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000499
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000500 // Compute the new offset in the appropriate width.
501
502 QualType PointeeType =
503 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000504 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000506 // Explicitly handle GNU void* and function pointer arithmetic extensions.
507 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000508 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000509 else
John McCallefdb83e2010-05-07 21:00:08 +0000510 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000511
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000512 if (E->getOpcode() == BinaryOperator::Add)
John McCallefdb83e2010-05-07 21:00:08 +0000513 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000514 else
John McCallefdb83e2010-05-07 21:00:08 +0000515 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000516
John McCallefdb83e2010-05-07 21:00:08 +0000517 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000518}
Eli Friedman4efaa272008-11-12 09:44:48 +0000519
John McCallefdb83e2010-05-07 21:00:08 +0000520bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
521 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000522}
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000524
John McCallefdb83e2010-05-07 21:00:08 +0000525bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000526 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000527
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000528 switch (E->getCastKind()) {
529 default:
530 break;
531
532 case CastExpr::CK_Unknown: {
533 // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
534
535 // Check for pointer->pointer cast
536 if (SubExpr->getType()->isPointerType() ||
537 SubExpr->getType()->isObjCObjectPointerType() ||
538 SubExpr->getType()->isNullPtrType() ||
539 SubExpr->getType()->isBlockPointerType())
540 return Visit(SubExpr);
541
542 if (SubExpr->getType()->isIntegralType()) {
John McCallefdb83e2010-05-07 21:00:08 +0000543 APValue Value;
544 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000545 break;
546
John McCallefdb83e2010-05-07 21:00:08 +0000547 if (Value.isInt()) {
548 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
549 Result.Base = 0;
550 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
551 return true;
552 } else {
553 Result.Base = Value.getLValueBase();
554 Result.Offset = Value.getLValueOffset();
555 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000556 }
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000557 }
558 break;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000561 case CastExpr::CK_NoOp:
562 case CastExpr::CK_BitCast:
563 case CastExpr::CK_AnyPointerToObjCPointerCast:
564 case CastExpr::CK_AnyPointerToBlockPointerCast:
565 return Visit(SubExpr);
566
567 case CastExpr::CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000568 APValue Value;
569 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000570 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000571
John McCallefdb83e2010-05-07 21:00:08 +0000572 if (Value.isInt()) {
573 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
574 Result.Base = 0;
575 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
576 return true;
577 } else {
578 // Cast is of an lvalue, no need to change value.
579 Result.Base = Value.getLValueBase();
580 Result.Offset = Value.getLValueOffset();
581 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000582 }
583 }
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000584 case CastExpr::CK_ArrayToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000585 case CastExpr::CK_FunctionToPointerDecay:
586 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000587 }
588
John McCallefdb83e2010-05-07 21:00:08 +0000589 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000590}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000591
John McCallefdb83e2010-05-07 21:00:08 +0000592bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000593 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000594 Builtin::BI__builtin___CFStringMakeConstantString ||
595 E->isBuiltinCall(Info.Ctx) ==
596 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000597 return Success(E);
598 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000599}
600
John McCallefdb83e2010-05-07 21:00:08 +0000601bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000602 bool BoolResult;
603 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000604 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000605
606 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000607 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000608}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000609
610//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000611// Vector Evaluation
612//===----------------------------------------------------------------------===//
613
614namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000615 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000616 : public StmtVisitor<VectorExprEvaluator, APValue> {
617 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000618 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000619 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Nate Begeman59b5da62009-01-18 03:20:47 +0000621 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Nate Begeman59b5da62009-01-18 03:20:47 +0000623 APValue VisitStmt(Stmt *S) {
624 return APValue();
625 }
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Eli Friedman91110ee2009-02-23 04:23:56 +0000627 APValue VisitParenExpr(ParenExpr *E)
628 { return Visit(E->getSubExpr()); }
629 APValue VisitUnaryExtension(const UnaryOperator *E)
630 { return Visit(E->getSubExpr()); }
631 APValue VisitUnaryPlus(const UnaryOperator *E)
632 { return Visit(E->getSubExpr()); }
633 APValue VisitUnaryReal(const UnaryOperator *E)
634 { return Visit(E->getSubExpr()); }
635 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
636 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000637 APValue VisitCastExpr(const CastExpr* E);
638 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
639 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000640 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000641 APValue VisitChooseExpr(const ChooseExpr *E)
642 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000643 APValue VisitUnaryImag(const UnaryOperator *E);
644 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000645 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000646 // shufflevector, ExtVectorElementExpr
647 // (Note that these require implementing conversions
648 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000649 };
650} // end anonymous namespace
651
652static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
653 if (!E->getType()->isVectorType())
654 return false;
655 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
656 return !Result.isUninit();
657}
658
659APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000660 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000661 QualType EltTy = VTy->getElementType();
662 unsigned NElts = VTy->getNumElements();
663 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Nate Begeman59b5da62009-01-18 03:20:47 +0000665 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000666 QualType SETy = SE->getType();
667 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000668
Nate Begemane8c9e922009-06-26 18:22:18 +0000669 // Check for vector->vector bitcast and scalar->vector splat.
670 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000671 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000672 } else if (SETy->isIntegerType()) {
673 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000674 if (!EvaluateInteger(SE, IntResult, Info))
675 return APValue();
676 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000677 } else if (SETy->isRealFloatingType()) {
678 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000679 if (!EvaluateFloat(SE, F, Info))
680 return APValue();
681 Result = APValue(F);
682 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000683 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000684
Nate Begemanc0b8b192009-07-01 07:50:47 +0000685 // For casts of a scalar to ExtVector, convert the scalar to the element type
686 // and splat it to all elements.
687 if (E->getType()->isExtVectorType()) {
688 if (EltTy->isIntegerType() && Result.isInt())
689 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
690 Info.Ctx));
691 else if (EltTy->isIntegerType())
692 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
693 Info.Ctx));
694 else if (EltTy->isRealFloatingType() && Result.isInt())
695 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
696 Info.Ctx));
697 else if (EltTy->isRealFloatingType())
698 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
699 Info.Ctx));
700 else
701 return APValue();
702
703 // Splat and create vector APValue.
704 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
705 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000706 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000707
708 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
709 // to the vector. To construct the APValue vector initializer, bitcast the
710 // initializing value to an APInt, and shift out the bits pertaining to each
711 // element.
712 APSInt Init;
713 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Nate Begemanc0b8b192009-07-01 07:50:47 +0000715 llvm::SmallVector<APValue, 4> Elts;
716 for (unsigned i = 0; i != NElts; ++i) {
717 APSInt Tmp = Init;
718 Tmp.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Nate Begemanc0b8b192009-07-01 07:50:47 +0000720 if (EltTy->isIntegerType())
721 Elts.push_back(APValue(Tmp));
722 else if (EltTy->isRealFloatingType())
723 Elts.push_back(APValue(APFloat(Tmp)));
724 else
725 return APValue();
726
727 Init >>= EltWidth;
728 }
729 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000730}
731
Mike Stump1eb44332009-09-09 15:08:12 +0000732APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000733VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
734 return this->Visit(const_cast<Expr*>(E->getInitializer()));
735}
736
Mike Stump1eb44332009-09-09 15:08:12 +0000737APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000738VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000739 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000740 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000741 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Nate Begeman59b5da62009-01-18 03:20:47 +0000743 QualType EltTy = VT->getElementType();
744 llvm::SmallVector<APValue, 4> Elements;
745
Eli Friedman91110ee2009-02-23 04:23:56 +0000746 for (unsigned i = 0; i < NumElements; i++) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000747 if (EltTy->isIntegerType()) {
748 llvm::APSInt sInt(32);
Eli Friedman91110ee2009-02-23 04:23:56 +0000749 if (i < NumInits) {
750 if (!EvaluateInteger(E->getInit(i), sInt, Info))
751 return APValue();
752 } else {
753 sInt = Info.Ctx.MakeIntValue(0, EltTy);
754 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000755 Elements.push_back(APValue(sInt));
756 } else {
757 llvm::APFloat f(0.0);
Eli Friedman91110ee2009-02-23 04:23:56 +0000758 if (i < NumInits) {
759 if (!EvaluateFloat(E->getInit(i), f, Info))
760 return APValue();
761 } else {
762 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
763 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000764 Elements.push_back(APValue(f));
765 }
766 }
767 return APValue(&Elements[0], Elements.size());
768}
769
Mike Stump1eb44332009-09-09 15:08:12 +0000770APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000771VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000772 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000773 QualType EltTy = VT->getElementType();
774 APValue ZeroElement;
775 if (EltTy->isIntegerType())
776 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
777 else
778 ZeroElement =
779 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
780
781 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
782 return APValue(&Elements[0], Elements.size());
783}
784
785APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
786 bool BoolResult;
787 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
788 return APValue();
789
790 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
791
792 APValue Result;
793 if (EvaluateVector(EvalExpr, Result, Info))
794 return Result;
795 return APValue();
796}
797
Eli Friedman91110ee2009-02-23 04:23:56 +0000798APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
799 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
800 Info.EvalResult.HasSideEffects = true;
801 return GetZeroVector(E->getType());
802}
803
Nate Begeman59b5da62009-01-18 03:20:47 +0000804//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000805// Integer Evaluation
806//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000807
808namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000809class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000810 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000811 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000812 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000813public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000814 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000815 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000816
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000817 bool Success(const llvm::APSInt &SI, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000818 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000819 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000820 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000821 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000822 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000823 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000824 return true;
825 }
826
Daniel Dunbar131eb432009-02-19 09:06:44 +0000827 bool Success(const llvm::APInt &I, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000828 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000829 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000830 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000831 Result = APValue(APSInt(I));
832 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000833 return true;
834 }
835
836 bool Success(uint64_t Value, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000837 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000838 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000839 return true;
840 }
841
Anders Carlsson82206e22008-11-30 18:14:57 +0000842 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000843 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000844 if (Info.EvalResult.Diag == 0) {
845 Info.EvalResult.DiagLoc = L;
846 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000847 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000848 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000849 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Anders Carlssonc754aa62008-07-08 05:13:58 +0000852 //===--------------------------------------------------------------------===//
853 // Visitor Methods
854 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattner32fea9d2008-11-12 07:43:42 +0000856 bool VisitStmt(Stmt *) {
857 assert(0 && "This should be called on integers, stmts are not integers");
858 return false;
859 }
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Chris Lattner32fea9d2008-11-12 07:43:42 +0000861 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000862 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Chris Lattnerb542afe2008-07-11 19:10:17 +0000865 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000866
Chris Lattner4c4867e2008-07-12 00:38:25 +0000867 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000868 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000869 }
870 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000871 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000872 }
873 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarac620de2008-10-24 08:07:57 +0000874 // Per gcc docs "this built-in function ignores top level
875 // qualifiers". We need to use the canonical version to properly
876 // be able to strip CRV qualifiers from the type.
877 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
878 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Mike Stump1eb44332009-09-09 15:08:12 +0000879 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
Daniel Dunbar131eb432009-02-19 09:06:44 +0000880 T1.getUnqualifiedType()),
881 E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000882 }
Eli Friedman04309752009-11-24 05:28:59 +0000883
884 bool CheckReferencedDecl(const Expr *E, const Decl *D);
885 bool VisitDeclRefExpr(const DeclRefExpr *E) {
886 return CheckReferencedDecl(E, E->getDecl());
887 }
888 bool VisitMemberExpr(const MemberExpr *E) {
889 if (CheckReferencedDecl(E, E->getMemberDecl())) {
890 // Conservatively assume a MemberExpr will have side-effects
891 Info.EvalResult.HasSideEffects = true;
892 return true;
893 }
894 return false;
895 }
896
Eli Friedmanc4a26382010-02-13 00:10:10 +0000897 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000898 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000899 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000900 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000901 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000902
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000903 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000904 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
905
Anders Carlsson3068d112008-11-16 19:01:22 +0000906 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000907 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000908 }
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Anders Carlsson3f704562008-12-21 22:39:40 +0000910 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000911 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Anders Carlsson3068d112008-11-16 19:01:22 +0000914 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000915 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000916 }
917
Eli Friedman664a1042009-02-27 04:45:43 +0000918 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
919 return Success(0, E);
920 }
921
Sebastian Redl64b45f72009-01-05 20:52:13 +0000922 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +0000923 return Success(E->EvaluateTrait(Info.Ctx), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000924 }
925
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000926 bool VisitChooseExpr(const ChooseExpr *E) {
927 return Visit(E->getChosenSubExpr(Info.Ctx));
928 }
929
Eli Friedman722c7172009-02-28 03:59:05 +0000930 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000931 bool VisitUnaryImag(const UnaryOperator *E);
932
Chris Lattnerfcee0012008-07-11 21:24:13 +0000933private:
Ken Dyck8b752f12010-01-27 17:10:57 +0000934 CharUnits GetAlignOfExpr(const Expr *E);
935 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +0000936 static QualType GetObjectType(const Expr *E);
937 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000938 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000939};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000940} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000941
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000942static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000943 assert(E->getType()->isIntegralType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000944 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
945}
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000946
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000947static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000948 assert(E->getType()->isIntegralType());
949
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000950 APValue Val;
951 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
952 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000953 Result = Val.getInt();
954 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +0000955}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000956
Eli Friedman04309752009-11-24 05:28:59 +0000957bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000958 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +0000959 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
960 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000961
962 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +0000963 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000964 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
965 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +0000966
967 if (isa<ParmVarDecl>(D))
968 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
969
Eli Friedman04309752009-11-24 05:28:59 +0000970 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000971 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +0000972 if (APValue *V = VD->getEvaluatedValue()) {
973 if (V->isInt())
974 return Success(V->getInt(), E);
975 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
976 }
977
978 if (VD->isEvaluatingValue())
979 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
980
981 VD->setEvaluatingValue();
982
Douglas Gregor78d15832009-05-26 18:54:04 +0000983 if (Visit(const_cast<Expr*>(Init))) {
984 // Cache the evaluated value in the variable declaration.
Eli Friedmanc0131182009-12-03 20:31:57 +0000985 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +0000986 return true;
987 }
988
Eli Friedmanc0131182009-12-03 20:31:57 +0000989 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +0000990 return false;
991 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000992 }
993 }
994
Chris Lattner4c4867e2008-07-12 00:38:25 +0000995 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000996 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000997}
998
Chris Lattnera4d55d82008-10-06 06:40:35 +0000999/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1000/// as GCC.
1001static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1002 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001003 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001004 enum gcc_type_class {
1005 no_type_class = -1,
1006 void_type_class, integer_type_class, char_type_class,
1007 enumeral_type_class, boolean_type_class,
1008 pointer_type_class, reference_type_class, offset_type_class,
1009 real_type_class, complex_type_class,
1010 function_type_class, method_type_class,
1011 record_type_class, union_type_class,
1012 array_type_class, string_type_class,
1013 lang_type_class
1014 };
Mike Stump1eb44332009-09-09 15:08:12 +00001015
1016 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001017 // ideal, however it is what gcc does.
1018 if (E->getNumArgs() == 0)
1019 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Chris Lattnera4d55d82008-10-06 06:40:35 +00001021 QualType ArgTy = E->getArg(0)->getType();
1022 if (ArgTy->isVoidType())
1023 return void_type_class;
1024 else if (ArgTy->isEnumeralType())
1025 return enumeral_type_class;
1026 else if (ArgTy->isBooleanType())
1027 return boolean_type_class;
1028 else if (ArgTy->isCharType())
1029 return string_type_class; // gcc doesn't appear to use char_type_class
1030 else if (ArgTy->isIntegerType())
1031 return integer_type_class;
1032 else if (ArgTy->isPointerType())
1033 return pointer_type_class;
1034 else if (ArgTy->isReferenceType())
1035 return reference_type_class;
1036 else if (ArgTy->isRealType())
1037 return real_type_class;
1038 else if (ArgTy->isComplexType())
1039 return complex_type_class;
1040 else if (ArgTy->isFunctionType())
1041 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001042 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001043 return record_type_class;
1044 else if (ArgTy->isUnionType())
1045 return union_type_class;
1046 else if (ArgTy->isArrayType())
1047 return array_type_class;
1048 else if (ArgTy->isUnionType())
1049 return union_type_class;
1050 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1051 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1052 return -1;
1053}
1054
John McCall42c8f872010-05-10 23:27:23 +00001055/// Retrieves the "underlying object type" of the given expression,
1056/// as used by __builtin_object_size.
1057QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1058 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1059 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1060 return VD->getType();
1061 } else if (isa<CompoundLiteralExpr>(E)) {
1062 return E->getType();
1063 }
1064
1065 return QualType();
1066}
1067
1068bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1069 // TODO: Perhaps we should let LLVM lower this?
1070 LValue Base;
1071 if (!EvaluatePointer(E->getArg(0), Base, Info))
1072 return false;
1073
1074 // If we can prove the base is null, lower to zero now.
1075 const Expr *LVBase = Base.getLValueBase();
1076 if (!LVBase) return Success(0, E);
1077
1078 QualType T = GetObjectType(LVBase);
1079 if (T.isNull() ||
1080 T->isIncompleteType() ||
1081 !T->isObjectType() ||
1082 T->isVariablyModifiedType() ||
1083 T->isDependentType())
1084 return false;
1085
1086 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1087 CharUnits Offset = Base.getLValueOffset();
1088
1089 if (!Offset.isNegative() && Offset <= Size)
1090 Size -= Offset;
1091 else
1092 Size = CharUnits::Zero();
1093 return Success(Size.getQuantity(), E);
1094}
1095
Eli Friedmanc4a26382010-02-13 00:10:10 +00001096bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001097 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001098 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001099 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001100
1101 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001102 if (TryEvaluateBuiltinObjectSize(E))
1103 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001104
Eric Christopherb2aaf512010-01-19 22:58:35 +00001105 // If evaluating the argument has side-effects we can't determine
1106 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001107 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001108 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001109 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001110 return Success(0, E);
1111 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001112
Mike Stump64eda9e2009-10-26 18:35:08 +00001113 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1114 }
1115
Chris Lattner019f4e82008-10-06 05:28:25 +00001116 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001117 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001119 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001120 // __builtin_constant_p always has one operand: it returns true if that
1121 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001122 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001123
1124 case Builtin::BI__builtin_eh_return_data_regno: {
1125 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1126 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1127 return Success(Operand, E);
1128 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001129
1130 case Builtin::BI__builtin_expect:
1131 return Visit(E->getArg(0));
Chris Lattner019f4e82008-10-06 05:28:25 +00001132 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001133}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001134
Chris Lattnerb542afe2008-07-11 19:10:17 +00001135bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001136 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001137 if (!Visit(E->getRHS()))
1138 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001139
Eli Friedman33ef1452009-02-26 10:19:36 +00001140 // If we can't evaluate the LHS, it might have side effects;
1141 // conservatively mark it.
1142 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1143 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001144
Anders Carlsson027f62e2008-12-01 02:07:06 +00001145 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001146 }
1147
1148 if (E->isLogicalOp()) {
1149 // These need to be handled specially because the operands aren't
1150 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001151 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001153 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001154 // We were able to evaluate the LHS, see if we can get away with not
1155 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Eli Friedman33ef1452009-02-26 10:19:36 +00001156 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001157 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001158
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001159 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001160 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001161 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001162 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001163 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001164 }
1165 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001166 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001167 // We can't evaluate the LHS; however, sometimes the result
1168 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Mike Stump1eb44332009-09-09 15:08:12 +00001169 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001170 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001171 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001172 // must have had side effects.
1173 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001174
1175 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001176 }
1177 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001178 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001179
Eli Friedmana6afa762008-11-13 06:09:17 +00001180 return false;
1181 }
1182
Anders Carlsson286f85e2008-11-16 07:17:21 +00001183 QualType LHSTy = E->getLHS()->getType();
1184 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001185
1186 if (LHSTy->isAnyComplexType()) {
1187 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001188 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001189
1190 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1191 return false;
1192
1193 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1194 return false;
1195
1196 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001197 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001198 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001199 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001200 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1201
Daniel Dunbar4087e242009-01-29 06:43:41 +00001202 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001203 return Success((CR_r == APFloat::cmpEqual &&
1204 CR_i == APFloat::cmpEqual), E);
1205 else {
1206 assert(E->getOpcode() == BinaryOperator::NE &&
1207 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001208 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001209 CR_r == APFloat::cmpLessThan ||
1210 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001211 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001212 CR_i == APFloat::cmpLessThan ||
1213 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001214 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001215 } else {
Daniel Dunbar4087e242009-01-29 06:43:41 +00001216 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001217 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1218 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1219 else {
1220 assert(E->getOpcode() == BinaryOperator::NE &&
1221 "Invalid compex comparison.");
1222 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1223 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1224 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001225 }
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Anders Carlsson286f85e2008-11-16 07:17:21 +00001228 if (LHSTy->isRealFloatingType() &&
1229 RHSTy->isRealFloatingType()) {
1230 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Anders Carlsson286f85e2008-11-16 07:17:21 +00001232 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1233 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Anders Carlsson286f85e2008-11-16 07:17:21 +00001235 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1236 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Anders Carlsson286f85e2008-11-16 07:17:21 +00001238 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001239
Anders Carlsson286f85e2008-11-16 07:17:21 +00001240 switch (E->getOpcode()) {
1241 default:
1242 assert(0 && "Invalid binary operator!");
1243 case BinaryOperator::LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001244 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001245 case BinaryOperator::GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001246 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001247 case BinaryOperator::LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001248 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001249 case BinaryOperator::GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001250 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001251 E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001252 case BinaryOperator::EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001253 return Success(CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001254 case BinaryOperator::NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001255 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001256 || CR == APFloat::cmpLessThan
1257 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001258 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001259 }
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001261 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1262 if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001263 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001264 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1265 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001266
John McCallefdb83e2010-05-07 21:00:08 +00001267 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001268 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1269 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001270
Eli Friedman5bc86102009-06-14 02:17:33 +00001271 // Reject any bases from the normal codepath; we special-case comparisons
1272 // to null.
1273 if (LHSValue.getLValueBase()) {
1274 if (!E->isEqualityOp())
1275 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001276 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001277 return false;
1278 bool bres;
1279 if (!EvalPointerValueAsBool(LHSValue, bres))
1280 return false;
1281 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1282 } else if (RHSValue.getLValueBase()) {
1283 if (!E->isEqualityOp())
1284 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001285 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001286 return false;
1287 bool bres;
1288 if (!EvalPointerValueAsBool(RHSValue, bres))
1289 return false;
1290 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1291 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001292
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001293 if (E->getOpcode() == BinaryOperator::Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001294 QualType Type = E->getLHS()->getType();
1295 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001296
Ken Dycka7305832010-01-15 12:37:54 +00001297 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001298 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001299 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001300
Ken Dycka7305832010-01-15 12:37:54 +00001301 CharUnits Diff = LHSValue.getLValueOffset() -
1302 RHSValue.getLValueOffset();
1303 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001304 }
1305 bool Result;
1306 if (E->getOpcode() == BinaryOperator::EQ) {
1307 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001308 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001309 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1310 }
1311 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001312 }
1313 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001314 if (!LHSTy->isIntegralType() ||
1315 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001316 // We can't continue from here for non-integral types, and they
1317 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001318 return false;
1319 }
1320
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001321 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001322 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001323 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001324
Eli Friedman42edd0d2009-03-24 01:14:50 +00001325 APValue RHSVal;
1326 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001327 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001328
1329 // Handle cases like (unsigned long)&a + 4.
1330 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001331 CharUnits Offset = Result.getLValueOffset();
1332 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1333 RHSVal.getInt().getZExtValue());
Eli Friedman42edd0d2009-03-24 01:14:50 +00001334 if (E->getOpcode() == BinaryOperator::Add)
Ken Dycka7305832010-01-15 12:37:54 +00001335 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001336 else
Ken Dycka7305832010-01-15 12:37:54 +00001337 Offset -= AdditionalOffset;
1338 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001339 return true;
1340 }
1341
1342 // Handle cases like 4 + (unsigned long)&a
1343 if (E->getOpcode() == BinaryOperator::Add &&
1344 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001345 CharUnits Offset = RHSVal.getLValueOffset();
1346 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1347 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001348 return true;
1349 }
1350
1351 // All the following cases expect both operands to be an integer
1352 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001353 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001354
Eli Friedman42edd0d2009-03-24 01:14:50 +00001355 APSInt& RHS = RHSVal.getInt();
1356
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001357 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001358 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001359 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001360 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1361 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1362 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1363 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1364 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1365 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001366 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001367 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001368 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001369 return Success(Result.getInt() / RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001370 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001371 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001372 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001373 return Success(Result.getInt() % RHS, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001374 case BinaryOperator::Shl: {
Chris Lattner54176fd2008-07-12 00:14:42 +00001375 // FIXME: Warn about out of range shift amounts!
Mike Stump1eb44332009-09-09 15:08:12 +00001376 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001377 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1378 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001379 }
1380 case BinaryOperator::Shr: {
Mike Stump1eb44332009-09-09 15:08:12 +00001381 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001382 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1383 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001384 }
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001386 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1387 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1388 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1389 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1390 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1391 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001392 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001393}
1394
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001395bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001396 bool Cond;
1397 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001398 return false;
1399
Nuno Lopesa25bd552008-11-16 22:06:39 +00001400 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001401}
1402
Ken Dyck8b752f12010-01-27 17:10:57 +00001403CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001404 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1405 // the result is the size of the referenced type."
1406 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1407 // result shall be the alignment of the referenced type."
1408 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1409 T = Ref->getPointeeType();
1410
Chris Lattnere9feb472009-01-24 21:09:06 +00001411 // Get information about the alignment.
1412 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregor18857642009-04-30 17:32:17 +00001413
Eli Friedman2be58612009-05-30 21:09:44 +00001414 // __alignof is defined to return the preferred alignment.
Ken Dyck8b752f12010-01-27 17:10:57 +00001415 return CharUnits::fromQuantity(
1416 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattnere9feb472009-01-24 21:09:06 +00001417}
1418
Ken Dyck8b752f12010-01-27 17:10:57 +00001419CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001420 E = E->IgnoreParens();
1421
1422 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001423 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001424 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001425 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1426 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001427
Chris Lattneraf707ab2009-01-24 21:53:27 +00001428 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001429 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1430 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001431
Chris Lattnere9feb472009-01-24 21:09:06 +00001432 return GetAlignOfType(E->getType());
1433}
1434
1435
Sebastian Redl05189992008-11-11 17:56:53 +00001436/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1437/// expression's type.
1438bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001439 // Handle alignof separately.
1440 if (!E->isSizeOf()) {
1441 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001442 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001443 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001444 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001445 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001446
Sebastian Redl05189992008-11-11 17:56:53 +00001447 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001448 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1449 // the result is the size of the referenced type."
1450 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1451 // result shall be the alignment of the referenced type."
1452 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1453 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001454
Daniel Dunbar131eb432009-02-19 09:06:44 +00001455 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1456 // extension.
1457 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1458 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001459
Chris Lattnerfcee0012008-07-11 21:24:13 +00001460 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001461 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001462 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001463
Chris Lattnere9feb472009-01-24 21:09:06 +00001464 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001465 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001466}
1467
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001468bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1469 CharUnits Result;
1470 unsigned n = E->getNumComponents();
1471 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1472 if (n == 0)
1473 return false;
1474 QualType CurrentType = E->getTypeSourceInfo()->getType();
1475 for (unsigned i = 0; i != n; ++i) {
1476 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1477 switch (ON.getKind()) {
1478 case OffsetOfExpr::OffsetOfNode::Array: {
1479 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1480 APSInt IdxResult;
1481 if (!EvaluateInteger(Idx, IdxResult, Info))
1482 return false;
1483 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1484 if (!AT)
1485 return false;
1486 CurrentType = AT->getElementType();
1487 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1488 Result += IdxResult.getSExtValue() * ElementSize;
1489 break;
1490 }
1491
1492 case OffsetOfExpr::OffsetOfNode::Field: {
1493 FieldDecl *MemberDecl = ON.getField();
1494 const RecordType *RT = CurrentType->getAs<RecordType>();
1495 if (!RT)
1496 return false;
1497 RecordDecl *RD = RT->getDecl();
1498 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1499 unsigned i = 0;
1500 // FIXME: It would be nice if we didn't have to loop here!
1501 for (RecordDecl::field_iterator Field = RD->field_begin(),
1502 FieldEnd = RD->field_end();
1503 Field != FieldEnd; (void)++Field, ++i) {
1504 if (*Field == MemberDecl)
1505 break;
1506 }
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001507 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1508 Result += CharUnits::fromQuantity(
1509 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001510 CurrentType = MemberDecl->getType().getNonReferenceType();
1511 break;
1512 }
1513
1514 case OffsetOfExpr::OffsetOfNode::Identifier:
1515 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001516 return false;
1517
1518 case OffsetOfExpr::OffsetOfNode::Base: {
1519 CXXBaseSpecifier *BaseSpec = ON.getBase();
1520 if (BaseSpec->isVirtual())
1521 return false;
1522
1523 // Find the layout of the class whose base we are looking into.
1524 const RecordType *RT = CurrentType->getAs<RecordType>();
1525 if (!RT)
1526 return false;
1527 RecordDecl *RD = RT->getDecl();
1528 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1529
1530 // Find the base class itself.
1531 CurrentType = BaseSpec->getType();
1532 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1533 if (!BaseRT)
1534 return false;
1535
1536 // Add the offset to the base.
1537 Result += CharUnits::fromQuantity(
1538 RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()))
1539 / Info.Ctx.getCharWidth());
1540 break;
1541 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001542 }
1543 }
1544 return Success(Result.getQuantity(), E);
1545}
1546
Chris Lattnerb542afe2008-07-11 19:10:17 +00001547bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001548 // Special case unary operators that do not need their subexpression
1549 // evaluated. offsetof/sizeof/alignof are all special.
Eli Friedman35183ac2009-02-27 06:44:11 +00001550 if (E->isOffsetOfOp()) {
1551 // The AST for offsetof is defined in such a way that we can just
1552 // directly Evaluate it as an l-value.
John McCallefdb83e2010-05-07 21:00:08 +00001553 LValue LV;
Eli Friedman35183ac2009-02-27 06:44:11 +00001554 if (!EvaluateLValue(E->getSubExpr(), LV, Info))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001555 return false;
Eli Friedman35183ac2009-02-27 06:44:11 +00001556 if (LV.getLValueBase())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001557 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001558 return Success(LV.getLValueOffset().getQuantity(), E);
Eli Friedman35183ac2009-02-27 06:44:11 +00001559 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001560
Eli Friedmana6afa762008-11-13 06:09:17 +00001561 if (E->getOpcode() == UnaryOperator::LNot) {
1562 // LNot's operand isn't necessarily an integer, so we handle it specially.
1563 bool bres;
1564 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1565 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001566 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001567 }
1568
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001569 // Only handle integral operations...
1570 if (!E->getSubExpr()->getType()->isIntegralType())
1571 return false;
1572
Chris Lattner87eae5e2008-07-11 22:52:41 +00001573 // Get the operand value into 'Result'.
1574 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001575 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001576
Chris Lattner75a48812008-07-11 22:15:16 +00001577 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001578 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001579 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1580 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001581 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001582 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001583 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1584 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001585 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001586 case UnaryOperator::Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001587 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001588 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001589 case UnaryOperator::Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001590 if (!Result.isInt()) return false;
1591 return Success(-Result.getInt(), E);
Chris Lattner75a48812008-07-11 22:15:16 +00001592 case UnaryOperator::Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001593 if (!Result.isInt()) return false;
1594 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001595 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001596}
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Chris Lattner732b2232008-07-12 01:15:53 +00001598/// HandleCast - This is used to evaluate implicit or explicit casts where the
1599/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001600bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001601 Expr *SubExpr = E->getSubExpr();
1602 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001603 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001604
Eli Friedman4efaa272008-11-12 09:44:48 +00001605 if (DestType->isBooleanType()) {
1606 bool BoolResult;
1607 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1608 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001609 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001610 }
1611
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001612 // Handle simple integer->integer casts.
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001613 if (SrcType->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001614 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001615 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001616
Eli Friedmanbe265702009-02-20 01:15:07 +00001617 if (!Result.isInt()) {
1618 // Only allow casts of lvalues if they are lossless.
1619 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1620 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001621
Daniel Dunbardd211642009-02-19 22:24:01 +00001622 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001623 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Chris Lattner732b2232008-07-12 01:15:53 +00001626 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001627 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001628 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001629 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001630 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001631
Daniel Dunbardd211642009-02-19 22:24:01 +00001632 if (LV.getLValueBase()) {
1633 // Only allow based lvalue casts if they are lossless.
1634 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1635 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001636
John McCallefdb83e2010-05-07 21:00:08 +00001637 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001638 return true;
1639 }
1640
Ken Dycka7305832010-01-15 12:37:54 +00001641 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1642 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001643 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001644 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001645
Eli Friedmanbe265702009-02-20 01:15:07 +00001646 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1647 // This handles double-conversion cases, where there's both
1648 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001649 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001650 if (!EvaluateLValue(SubExpr, LV, Info))
1651 return false;
1652
1653 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1654 return false;
1655
John McCallefdb83e2010-05-07 21:00:08 +00001656 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001657 return true;
1658 }
1659
Eli Friedman1725f682009-04-22 19:23:09 +00001660 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001661 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001662 if (!EvaluateComplex(SubExpr, C, Info))
1663 return false;
1664 if (C.isComplexFloat())
1665 return Success(HandleFloatToIntCast(DestType, SrcType,
1666 C.getComplexFloatReal(), Info.Ctx),
1667 E);
1668 else
1669 return Success(HandleIntToIntCast(DestType, SrcType,
1670 C.getComplexIntReal(), Info.Ctx), E);
1671 }
Eli Friedman2217c872009-02-22 11:46:18 +00001672 // FIXME: Handle vectors
1673
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001674 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001675 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001676
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001677 APFloat F(0.0);
1678 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001679 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001681 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001682}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001683
Eli Friedman722c7172009-02-28 03:59:05 +00001684bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1685 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001686 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001687 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1688 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1689 return Success(LV.getComplexIntReal(), E);
1690 }
1691
1692 return Visit(E->getSubExpr());
1693}
1694
Eli Friedman664a1042009-02-27 04:45:43 +00001695bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001696 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001697 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001698 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1699 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1700 return Success(LV.getComplexIntImag(), E);
1701 }
1702
Eli Friedman664a1042009-02-27 04:45:43 +00001703 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1704 Info.EvalResult.HasSideEffects = true;
1705 return Success(0, E);
1706}
1707
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001708//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001709// Float Evaluation
1710//===----------------------------------------------------------------------===//
1711
1712namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001713class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001714 : public StmtVisitor<FloatExprEvaluator, bool> {
1715 EvalInfo &Info;
1716 APFloat &Result;
1717public:
1718 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1719 : Info(info), Result(result) {}
1720
1721 bool VisitStmt(Stmt *S) {
1722 return false;
1723 }
1724
1725 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001726 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001727
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001728 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001729 bool VisitBinaryOperator(const BinaryOperator *E);
1730 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001731 bool VisitCastExpr(CastExpr *E);
1732 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001733 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001734
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001735 bool VisitChooseExpr(const ChooseExpr *E)
1736 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1737 bool VisitUnaryExtension(const UnaryOperator *E)
1738 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001739 bool VisitUnaryReal(const UnaryOperator *E);
1740 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001741
John McCallabd3a852010-05-07 22:08:54 +00001742 // FIXME: Missing: array subscript of vector, member of vector,
1743 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001744};
1745} // end anonymous namespace
1746
1747static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001748 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001749 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1750}
1751
John McCalldb7b72a2010-02-28 13:00:19 +00001752static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1753 QualType ResultTy,
1754 const Expr *Arg,
1755 bool SNaN,
1756 llvm::APFloat &Result) {
1757 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1758 if (!S) return false;
1759
1760 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1761
1762 llvm::APInt fill;
1763
1764 // Treat empty strings as if they were zero.
1765 if (S->getString().empty())
1766 fill = llvm::APInt(32, 0);
1767 else if (S->getString().getAsInteger(0, fill))
1768 return false;
1769
1770 if (SNaN)
1771 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1772 else
1773 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1774 return true;
1775}
1776
Chris Lattner019f4e82008-10-06 05:28:25 +00001777bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001778 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001779 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001780 case Builtin::BI__builtin_huge_val:
1781 case Builtin::BI__builtin_huge_valf:
1782 case Builtin::BI__builtin_huge_vall:
1783 case Builtin::BI__builtin_inf:
1784 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001785 case Builtin::BI__builtin_infl: {
1786 const llvm::fltSemantics &Sem =
1787 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001788 Result = llvm::APFloat::getInf(Sem);
1789 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001790 }
Mike Stump1eb44332009-09-09 15:08:12 +00001791
John McCalldb7b72a2010-02-28 13:00:19 +00001792 case Builtin::BI__builtin_nans:
1793 case Builtin::BI__builtin_nansf:
1794 case Builtin::BI__builtin_nansl:
1795 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1796 true, Result);
1797
Chris Lattner9e621712008-10-06 06:31:58 +00001798 case Builtin::BI__builtin_nan:
1799 case Builtin::BI__builtin_nanf:
1800 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001801 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001802 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001803 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1804 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001805
1806 case Builtin::BI__builtin_fabs:
1807 case Builtin::BI__builtin_fabsf:
1808 case Builtin::BI__builtin_fabsl:
1809 if (!EvaluateFloat(E->getArg(0), Result, Info))
1810 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001812 if (Result.isNegative())
1813 Result.changeSign();
1814 return true;
1815
Mike Stump1eb44332009-09-09 15:08:12 +00001816 case Builtin::BI__builtin_copysign:
1817 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001818 case Builtin::BI__builtin_copysignl: {
1819 APFloat RHS(0.);
1820 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1821 !EvaluateFloat(E->getArg(1), RHS, Info))
1822 return false;
1823 Result.copySign(RHS);
1824 return true;
1825 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001826 }
1827}
1828
John McCallabd3a852010-05-07 22:08:54 +00001829bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1830 ComplexValue CV;
1831 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1832 return false;
1833 Result = CV.FloatReal;
1834 return true;
1835}
1836
1837bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1838 ComplexValue CV;
1839 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1840 return false;
1841 Result = CV.FloatImag;
1842 return true;
1843}
1844
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001845bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +00001846 if (E->getOpcode() == UnaryOperator::Deref)
1847 return false;
1848
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001849 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1850 return false;
1851
1852 switch (E->getOpcode()) {
1853 default: return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001854 case UnaryOperator::Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001855 return true;
1856 case UnaryOperator::Minus:
1857 Result.changeSign();
1858 return true;
1859 }
1860}
Chris Lattner019f4e82008-10-06 05:28:25 +00001861
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001862bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman7f92f032009-11-16 04:25:37 +00001863 if (E->getOpcode() == BinaryOperator::Comma) {
1864 if (!EvaluateFloat(E->getRHS(), Result, Info))
1865 return false;
1866
1867 // If we can't evaluate the LHS, it might have side effects;
1868 // conservatively mark it.
1869 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1870 Info.EvalResult.HasSideEffects = true;
1871
1872 return true;
1873 }
1874
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001875 // FIXME: Diagnostics? I really don't understand how the warnings
1876 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001877 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001878 if (!EvaluateFloat(E->getLHS(), Result, Info))
1879 return false;
1880 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1881 return false;
1882
1883 switch (E->getOpcode()) {
1884 default: return false;
1885 case BinaryOperator::Mul:
1886 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1887 return true;
1888 case BinaryOperator::Add:
1889 Result.add(RHS, APFloat::rmNearestTiesToEven);
1890 return true;
1891 case BinaryOperator::Sub:
1892 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1893 return true;
1894 case BinaryOperator::Div:
1895 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1896 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001897 }
1898}
1899
1900bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1901 Result = E->getValue();
1902 return true;
1903}
1904
Eli Friedman4efaa272008-11-12 09:44:48 +00001905bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1906 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Eli Friedman4efaa272008-11-12 09:44:48 +00001908 if (SubExpr->getType()->isIntegralType()) {
1909 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001910 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00001911 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001912 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001913 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001914 return true;
1915 }
1916 if (SubExpr->getType()->isRealFloatingType()) {
1917 if (!Visit(SubExpr))
1918 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001919 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1920 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001921 return true;
1922 }
Eli Friedman2217c872009-02-22 11:46:18 +00001923 // FIXME: Handle complex types
Eli Friedman4efaa272008-11-12 09:44:48 +00001924
1925 return false;
1926}
1927
1928bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1929 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1930 return true;
1931}
1932
Eli Friedman67f85fc2009-12-04 02:12:53 +00001933bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1934 bool Cond;
1935 if (!HandleConversionToBool(E->getCond(), Cond, Info))
1936 return false;
1937
1938 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1939}
1940
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001941//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001942// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001943//===----------------------------------------------------------------------===//
1944
1945namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001946class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00001947 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001948 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00001949 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001951public:
John McCallf4cf1a12010-05-07 17:22:02 +00001952 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
1953 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001955 //===--------------------------------------------------------------------===//
1956 // Visitor Methods
1957 //===--------------------------------------------------------------------===//
1958
John McCallf4cf1a12010-05-07 17:22:02 +00001959 bool VisitStmt(Stmt *S) {
1960 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001961 }
Mike Stump1eb44332009-09-09 15:08:12 +00001962
John McCallf4cf1a12010-05-07 17:22:02 +00001963 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001964
John McCallf4cf1a12010-05-07 17:22:02 +00001965 bool VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001966 Expr* SubExpr = E->getSubExpr();
1967
1968 if (SubExpr->getType()->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001969 Result.makeComplexFloat();
1970 APFloat &Imag = Result.FloatImag;
1971 if (!EvaluateFloat(SubExpr, Imag, Info))
1972 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001973
John McCallf4cf1a12010-05-07 17:22:02 +00001974 Result.FloatReal = APFloat(Imag.getSemantics());
1975 return true;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001976 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001977 assert(SubExpr->getType()->isIntegerType() &&
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001978 "Unexpected imaginary literal.");
1979
John McCallf4cf1a12010-05-07 17:22:02 +00001980 Result.makeComplexInt();
1981 APSInt &Imag = Result.IntImag;
1982 if (!EvaluateInteger(SubExpr, Imag, Info))
1983 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001984
John McCallf4cf1a12010-05-07 17:22:02 +00001985 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
1986 return true;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001987 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001988 }
1989
John McCallf4cf1a12010-05-07 17:22:02 +00001990 bool VisitCastExpr(CastExpr *E) {
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001991 Expr* SubExpr = E->getSubExpr();
John McCall183700f2009-09-21 23:43:11 +00001992 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001993 QualType SubType = SubExpr->getType();
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001994
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001995 if (SubType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001996 APFloat &Real = Result.FloatReal;
1997 if (!EvaluateFloat(SubExpr, Real, Info))
1998 return false;
Eli Friedman1725f682009-04-22 19:23:09 +00001999
2000 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002001 Result.makeComplexFloat();
2002 Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
2003 Result.FloatImag = APFloat(Real.getSemantics());
2004 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00002005 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002006 Result.makeComplexInt();
2007 Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
2008 Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
2009 !Result.IntReal.isSigned());
2010 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00002011 }
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002012 } else if (SubType->isIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002013 APSInt &Real = Result.IntReal;
2014 if (!EvaluateInteger(SubExpr, Real, Info))
2015 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002016
Eli Friedman1725f682009-04-22 19:23:09 +00002017 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002018 Result.makeComplexFloat();
2019 Result.FloatReal
2020 = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
2021 Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
2022 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00002023 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002024 Result.makeComplexInt();
2025 Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
2026 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2027 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00002028 }
John McCall183700f2009-09-21 23:43:11 +00002029 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002030 if (!Visit(SubExpr))
2031 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002032
2033 QualType SrcType = CT->getElementType();
2034
John McCallf4cf1a12010-05-07 17:22:02 +00002035 if (Result.isComplexFloat()) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002036 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002037 Result.makeComplexFloat();
2038 Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
2039 Result.FloatReal,
2040 Info.Ctx);
2041 Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
2042 Result.FloatImag,
2043 Info.Ctx);
2044 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002045 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002046 Result.makeComplexInt();
2047 Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
2048 Result.FloatReal,
2049 Info.Ctx);
2050 Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
2051 Result.FloatImag,
2052 Info.Ctx);
2053 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002054 }
2055 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002056 assert(Result.isComplexInt() && "Invalid evaluate result.");
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002057 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002058 Result.makeComplexFloat();
2059 Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
2060 Result.IntReal,
2061 Info.Ctx);
2062 Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
2063 Result.IntImag,
2064 Info.Ctx);
2065 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002066 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002067 Result.makeComplexInt();
2068 Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2069 Result.IntReal,
2070 Info.Ctx);
2071 Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2072 Result.IntImag,
2073 Info.Ctx);
2074 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002075 }
2076 }
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002077 }
2078
2079 // FIXME: Handle more casts.
John McCallf4cf1a12010-05-07 17:22:02 +00002080 return false;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002081 }
Mike Stump1eb44332009-09-09 15:08:12 +00002082
John McCallf4cf1a12010-05-07 17:22:02 +00002083 bool VisitBinaryOperator(const BinaryOperator *E);
2084 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002085 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002086 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002087 { return Visit(E->getSubExpr()); }
2088 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
Eli Friedman2217c872009-02-22 11:46:18 +00002089 // conditional ?:, comma
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002090};
2091} // end anonymous namespace
2092
John McCallf4cf1a12010-05-07 17:22:02 +00002093static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2094 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002095 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002096 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002097}
2098
John McCallf4cf1a12010-05-07 17:22:02 +00002099bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2100 if (!Visit(E->getLHS()))
2101 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002102
John McCallf4cf1a12010-05-07 17:22:02 +00002103 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002104 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002105 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002106
Daniel Dunbar3f279872009-01-29 01:32:56 +00002107 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2108 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002109 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002110 default: return false;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002111 case BinaryOperator::Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002112 if (Result.isComplexFloat()) {
2113 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2114 APFloat::rmNearestTiesToEven);
2115 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2116 APFloat::rmNearestTiesToEven);
2117 } else {
2118 Result.getComplexIntReal() += RHS.getComplexIntReal();
2119 Result.getComplexIntImag() += RHS.getComplexIntImag();
2120 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002121 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002122 case BinaryOperator::Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002123 if (Result.isComplexFloat()) {
2124 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2125 APFloat::rmNearestTiesToEven);
2126 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2127 APFloat::rmNearestTiesToEven);
2128 } else {
2129 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2130 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2131 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002132 break;
2133 case BinaryOperator::Mul:
2134 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002135 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002136 APFloat &LHS_r = LHS.getComplexFloatReal();
2137 APFloat &LHS_i = LHS.getComplexFloatImag();
2138 APFloat &RHS_r = RHS.getComplexFloatReal();
2139 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Daniel Dunbar3f279872009-01-29 01:32:56 +00002141 APFloat Tmp = LHS_r;
2142 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2143 Result.getComplexFloatReal() = Tmp;
2144 Tmp = LHS_i;
2145 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2146 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2147
2148 Tmp = LHS_r;
2149 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2150 Result.getComplexFloatImag() = Tmp;
2151 Tmp = LHS_i;
2152 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2153 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2154 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002155 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002156 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002157 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2158 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002159 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002160 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2161 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2162 }
2163 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002164 }
2165
John McCallf4cf1a12010-05-07 17:22:02 +00002166 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002167}
2168
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002169//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002170// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002171//===----------------------------------------------------------------------===//
2172
John McCall42c8f872010-05-10 23:27:23 +00002173/// Evaluate - Return true if this is a constant which we can fold using
2174/// any crazy technique (that has nothing to do with language standards) that
2175/// we want to. If this function returns true, it returns the folded constant
2176/// in Result.
2177bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2178 const Expr *E = this;
2179 EvalInfo Info(Ctx, Result);
John McCallefdb83e2010-05-07 21:00:08 +00002180 if (E->getType()->isVectorType()) {
2181 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002182 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002183 } else if (E->getType()->isIntegerType()) {
2184 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002185 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002186 } else if (E->getType()->hasPointerRepresentation()) {
2187 LValue LV;
2188 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002189 return false;
John McCall42c8f872010-05-10 23:27:23 +00002190 if (!IsGlobalLValue(LV))
2191 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002192 LV.moveInto(Info.EvalResult.Val);
2193 } else if (E->getType()->isRealFloatingType()) {
2194 llvm::APFloat F(0.0);
2195 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002196 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002197
John McCallefdb83e2010-05-07 21:00:08 +00002198 Info.EvalResult.Val = APValue(F);
2199 } else if (E->getType()->isAnyComplexType()) {
2200 ComplexValue C;
2201 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002202 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002203 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002204 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002205 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002206
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002207 return true;
2208}
2209
John McCallcd7a4452010-01-05 23:42:56 +00002210bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2211 EvalResult Scratch;
2212 EvalInfo Info(Ctx, Scratch);
2213
2214 return HandleConversionToBool(this, Result, Info);
2215}
2216
Anders Carlsson1b782762009-04-10 04:54:13 +00002217bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2218 EvalInfo Info(Ctx, Result);
2219
John McCallefdb83e2010-05-07 21:00:08 +00002220 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002221 if (EvaluateLValue(this, LV, Info) &&
2222 !Result.HasSideEffects &&
2223 IsGlobalLValue(LV)) {
John McCallefdb83e2010-05-07 21:00:08 +00002224 LV.moveInto(Result.Val);
2225 return true;
2226 }
2227 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002228}
2229
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002230/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002231/// folded, but discard the result.
2232bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002233 EvalResult Result;
2234 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002235}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002236
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002237bool Expr::HasSideEffects(ASTContext &Ctx) const {
2238 Expr::EvalResult Result;
2239 EvalInfo Info(Ctx, Result);
2240 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2241}
2242
Anders Carlsson51fe9962008-11-22 21:04:56 +00002243APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002244 EvalResult EvalResult;
2245 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00002246 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002247 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002248 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002249
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002250 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002251}
John McCalld905f5a2010-05-07 05:32:02 +00002252
2253/// isIntegerConstantExpr - this recursive routine will test if an expression is
2254/// an integer constant expression.
2255
2256/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2257/// comma, etc
2258///
2259/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2260/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2261/// cast+dereference.
2262
2263// CheckICE - This function does the fundamental ICE checking: the returned
2264// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2265// Note that to reduce code duplication, this helper does no evaluation
2266// itself; the caller checks whether the expression is evaluatable, and
2267// in the rare cases where CheckICE actually cares about the evaluated
2268// value, it calls into Evalute.
2269//
2270// Meanings of Val:
2271// 0: This expression is an ICE if it can be evaluated by Evaluate.
2272// 1: This expression is not an ICE, but if it isn't evaluated, it's
2273// a legal subexpression for an ICE. This return value is used to handle
2274// the comma operator in C99 mode.
2275// 2: This expression is not an ICE, and is not a legal subexpression for one.
2276
2277struct ICEDiag {
2278 unsigned Val;
2279 SourceLocation Loc;
2280
2281 public:
2282 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2283 ICEDiag() : Val(0) {}
2284};
2285
2286ICEDiag NoDiag() { return ICEDiag(); }
2287
2288static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2289 Expr::EvalResult EVResult;
2290 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2291 !EVResult.Val.isInt()) {
2292 return ICEDiag(2, E->getLocStart());
2293 }
2294 return NoDiag();
2295}
2296
2297static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2298 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
2299 if (!E->getType()->isIntegralType()) {
2300 return ICEDiag(2, E->getLocStart());
2301 }
2302
2303 switch (E->getStmtClass()) {
2304#define STMT(Node, Base) case Expr::Node##Class:
2305#define EXPR(Node, Base)
2306#include "clang/AST/StmtNodes.inc"
2307 case Expr::PredefinedExprClass:
2308 case Expr::FloatingLiteralClass:
2309 case Expr::ImaginaryLiteralClass:
2310 case Expr::StringLiteralClass:
2311 case Expr::ArraySubscriptExprClass:
2312 case Expr::MemberExprClass:
2313 case Expr::CompoundAssignOperatorClass:
2314 case Expr::CompoundLiteralExprClass:
2315 case Expr::ExtVectorElementExprClass:
2316 case Expr::InitListExprClass:
2317 case Expr::DesignatedInitExprClass:
2318 case Expr::ImplicitValueInitExprClass:
2319 case Expr::ParenListExprClass:
2320 case Expr::VAArgExprClass:
2321 case Expr::AddrLabelExprClass:
2322 case Expr::StmtExprClass:
2323 case Expr::CXXMemberCallExprClass:
2324 case Expr::CXXDynamicCastExprClass:
2325 case Expr::CXXTypeidExprClass:
2326 case Expr::CXXNullPtrLiteralExprClass:
2327 case Expr::CXXThisExprClass:
2328 case Expr::CXXThrowExprClass:
2329 case Expr::CXXNewExprClass:
2330 case Expr::CXXDeleteExprClass:
2331 case Expr::CXXPseudoDestructorExprClass:
2332 case Expr::UnresolvedLookupExprClass:
2333 case Expr::DependentScopeDeclRefExprClass:
2334 case Expr::CXXConstructExprClass:
2335 case Expr::CXXBindTemporaryExprClass:
2336 case Expr::CXXBindReferenceExprClass:
2337 case Expr::CXXExprWithTemporariesClass:
2338 case Expr::CXXTemporaryObjectExprClass:
2339 case Expr::CXXUnresolvedConstructExprClass:
2340 case Expr::CXXDependentScopeMemberExprClass:
2341 case Expr::UnresolvedMemberExprClass:
2342 case Expr::ObjCStringLiteralClass:
2343 case Expr::ObjCEncodeExprClass:
2344 case Expr::ObjCMessageExprClass:
2345 case Expr::ObjCSelectorExprClass:
2346 case Expr::ObjCProtocolExprClass:
2347 case Expr::ObjCIvarRefExprClass:
2348 case Expr::ObjCPropertyRefExprClass:
2349 case Expr::ObjCImplicitSetterGetterRefExprClass:
2350 case Expr::ObjCSuperExprClass:
2351 case Expr::ObjCIsaExprClass:
2352 case Expr::ShuffleVectorExprClass:
2353 case Expr::BlockExprClass:
2354 case Expr::BlockDeclRefExprClass:
2355 case Expr::NoStmtClass:
2356 return ICEDiag(2, E->getLocStart());
2357
2358 case Expr::GNUNullExprClass:
2359 // GCC considers the GNU __null value to be an integral constant expression.
2360 return NoDiag();
2361
2362 case Expr::ParenExprClass:
2363 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2364 case Expr::IntegerLiteralClass:
2365 case Expr::CharacterLiteralClass:
2366 case Expr::CXXBoolLiteralExprClass:
2367 case Expr::CXXZeroInitValueExprClass:
2368 case Expr::TypesCompatibleExprClass:
2369 case Expr::UnaryTypeTraitExprClass:
2370 return NoDiag();
2371 case Expr::CallExprClass:
2372 case Expr::CXXOperatorCallExprClass: {
2373 const CallExpr *CE = cast<CallExpr>(E);
2374 if (CE->isBuiltinCall(Ctx))
2375 return CheckEvalInICE(E, Ctx);
2376 return ICEDiag(2, E->getLocStart());
2377 }
2378 case Expr::DeclRefExprClass:
2379 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2380 return NoDiag();
2381 if (Ctx.getLangOptions().CPlusPlus &&
2382 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2383 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2384
2385 // Parameter variables are never constants. Without this check,
2386 // getAnyInitializer() can find a default argument, which leads
2387 // to chaos.
2388 if (isa<ParmVarDecl>(D))
2389 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2390
2391 // C++ 7.1.5.1p2
2392 // A variable of non-volatile const-qualified integral or enumeration
2393 // type initialized by an ICE can be used in ICEs.
2394 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2395 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2396 if (Quals.hasVolatile() || !Quals.hasConst())
2397 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2398
2399 // Look for a declaration of this variable that has an initializer.
2400 const VarDecl *ID = 0;
2401 const Expr *Init = Dcl->getAnyInitializer(ID);
2402 if (Init) {
2403 if (ID->isInitKnownICE()) {
2404 // We have already checked whether this subexpression is an
2405 // integral constant expression.
2406 if (ID->isInitICE())
2407 return NoDiag();
2408 else
2409 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2410 }
2411
2412 // It's an ICE whether or not the definition we found is
2413 // out-of-line. See DR 721 and the discussion in Clang PR
2414 // 6206 for details.
2415
2416 if (Dcl->isCheckingICE()) {
2417 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2418 }
2419
2420 Dcl->setCheckingICE();
2421 ICEDiag Result = CheckICE(Init, Ctx);
2422 // Cache the result of the ICE test.
2423 Dcl->setInitKnownICE(Result.Val == 0);
2424 return Result;
2425 }
2426 }
2427 }
2428 return ICEDiag(2, E->getLocStart());
2429 case Expr::UnaryOperatorClass: {
2430 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2431 switch (Exp->getOpcode()) {
2432 case UnaryOperator::PostInc:
2433 case UnaryOperator::PostDec:
2434 case UnaryOperator::PreInc:
2435 case UnaryOperator::PreDec:
2436 case UnaryOperator::AddrOf:
2437 case UnaryOperator::Deref:
2438 return ICEDiag(2, E->getLocStart());
2439 case UnaryOperator::Extension:
2440 case UnaryOperator::LNot:
2441 case UnaryOperator::Plus:
2442 case UnaryOperator::Minus:
2443 case UnaryOperator::Not:
2444 case UnaryOperator::Real:
2445 case UnaryOperator::Imag:
2446 return CheckICE(Exp->getSubExpr(), Ctx);
2447 case UnaryOperator::OffsetOf:
2448 break;
2449 }
2450
2451 // OffsetOf falls through here.
2452 }
2453 case Expr::OffsetOfExprClass: {
2454 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2455 // Evaluate matches the proposed gcc behavior for cases like
2456 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2457 // compliance: we should warn earlier for offsetof expressions with
2458 // array subscripts that aren't ICEs, and if the array subscripts
2459 // are ICEs, the value of the offsetof must be an integer constant.
2460 return CheckEvalInICE(E, Ctx);
2461 }
2462 case Expr::SizeOfAlignOfExprClass: {
2463 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2464 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2465 return ICEDiag(2, E->getLocStart());
2466 return NoDiag();
2467 }
2468 case Expr::BinaryOperatorClass: {
2469 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2470 switch (Exp->getOpcode()) {
2471 case BinaryOperator::PtrMemD:
2472 case BinaryOperator::PtrMemI:
2473 case BinaryOperator::Assign:
2474 case BinaryOperator::MulAssign:
2475 case BinaryOperator::DivAssign:
2476 case BinaryOperator::RemAssign:
2477 case BinaryOperator::AddAssign:
2478 case BinaryOperator::SubAssign:
2479 case BinaryOperator::ShlAssign:
2480 case BinaryOperator::ShrAssign:
2481 case BinaryOperator::AndAssign:
2482 case BinaryOperator::XorAssign:
2483 case BinaryOperator::OrAssign:
2484 return ICEDiag(2, E->getLocStart());
2485
2486 case BinaryOperator::Mul:
2487 case BinaryOperator::Div:
2488 case BinaryOperator::Rem:
2489 case BinaryOperator::Add:
2490 case BinaryOperator::Sub:
2491 case BinaryOperator::Shl:
2492 case BinaryOperator::Shr:
2493 case BinaryOperator::LT:
2494 case BinaryOperator::GT:
2495 case BinaryOperator::LE:
2496 case BinaryOperator::GE:
2497 case BinaryOperator::EQ:
2498 case BinaryOperator::NE:
2499 case BinaryOperator::And:
2500 case BinaryOperator::Xor:
2501 case BinaryOperator::Or:
2502 case BinaryOperator::Comma: {
2503 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2504 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2505 if (Exp->getOpcode() == BinaryOperator::Div ||
2506 Exp->getOpcode() == BinaryOperator::Rem) {
2507 // Evaluate gives an error for undefined Div/Rem, so make sure
2508 // we don't evaluate one.
2509 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2510 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2511 if (REval == 0)
2512 return ICEDiag(1, E->getLocStart());
2513 if (REval.isSigned() && REval.isAllOnesValue()) {
2514 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2515 if (LEval.isMinSignedValue())
2516 return ICEDiag(1, E->getLocStart());
2517 }
2518 }
2519 }
2520 if (Exp->getOpcode() == BinaryOperator::Comma) {
2521 if (Ctx.getLangOptions().C99) {
2522 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2523 // if it isn't evaluated.
2524 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2525 return ICEDiag(1, E->getLocStart());
2526 } else {
2527 // In both C89 and C++, commas in ICEs are illegal.
2528 return ICEDiag(2, E->getLocStart());
2529 }
2530 }
2531 if (LHSResult.Val >= RHSResult.Val)
2532 return LHSResult;
2533 return RHSResult;
2534 }
2535 case BinaryOperator::LAnd:
2536 case BinaryOperator::LOr: {
2537 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2538 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2539 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2540 // Rare case where the RHS has a comma "side-effect"; we need
2541 // to actually check the condition to see whether the side
2542 // with the comma is evaluated.
2543 if ((Exp->getOpcode() == BinaryOperator::LAnd) !=
2544 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2545 return RHSResult;
2546 return NoDiag();
2547 }
2548
2549 if (LHSResult.Val >= RHSResult.Val)
2550 return LHSResult;
2551 return RHSResult;
2552 }
2553 }
2554 }
2555 case Expr::ImplicitCastExprClass:
2556 case Expr::CStyleCastExprClass:
2557 case Expr::CXXFunctionalCastExprClass:
2558 case Expr::CXXStaticCastExprClass:
2559 case Expr::CXXReinterpretCastExprClass:
2560 case Expr::CXXConstCastExprClass: {
2561 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
2562 if (SubExpr->getType()->isIntegralType())
2563 return CheckICE(SubExpr, Ctx);
2564 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2565 return NoDiag();
2566 return ICEDiag(2, E->getLocStart());
2567 }
2568 case Expr::ConditionalOperatorClass: {
2569 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2570 // If the condition (ignoring parens) is a __builtin_constant_p call,
2571 // then only the true side is actually considered in an integer constant
2572 // expression, and it is fully evaluated. This is an important GNU
2573 // extension. See GCC PR38377 for discussion.
2574 if (const CallExpr *CallCE
2575 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2576 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2577 Expr::EvalResult EVResult;
2578 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2579 !EVResult.Val.isInt()) {
2580 return ICEDiag(2, E->getLocStart());
2581 }
2582 return NoDiag();
2583 }
2584 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2585 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2586 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2587 if (CondResult.Val == 2)
2588 return CondResult;
2589 if (TrueResult.Val == 2)
2590 return TrueResult;
2591 if (FalseResult.Val == 2)
2592 return FalseResult;
2593 if (CondResult.Val == 1)
2594 return CondResult;
2595 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2596 return NoDiag();
2597 // Rare case where the diagnostics depend on which side is evaluated
2598 // Note that if we get here, CondResult is 0, and at least one of
2599 // TrueResult and FalseResult is non-zero.
2600 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2601 return FalseResult;
2602 }
2603 return TrueResult;
2604 }
2605 case Expr::CXXDefaultArgExprClass:
2606 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2607 case Expr::ChooseExprClass: {
2608 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2609 }
2610 }
2611
2612 // Silence a GCC warning
2613 return ICEDiag(2, E->getLocStart());
2614}
2615
2616bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2617 SourceLocation *Loc, bool isEvaluated) const {
2618 ICEDiag d = CheckICE(this, Ctx);
2619 if (d.Val != 0) {
2620 if (Loc) *Loc = d.Loc;
2621 return false;
2622 }
2623 EvalResult EvalResult;
2624 if (!Evaluate(EvalResult, Ctx))
2625 llvm_unreachable("ICE cannot be evaluated!");
2626 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2627 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2628 Result = EvalResult.Val.getInt();
2629 return true;
2630}