blob: df33f7afc3f1977f61b46783c9c240e26f60f44c [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.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Benjamin Kramerc54061a2011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCallf4cf1a12010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCall56ca35d2011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCall56ca35d2011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCallf4cf1a12010-05-07 17:22:02 +0000102 };
John McCallefdb83e2010-05-07 21:00:08 +0000103
104 struct LValue {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000105 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCallefdb83e2010-05-07 21:00:08 +0000109 CharUnits getLValueOffset() { return Offset; }
110
John McCall56ca35d2011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCall56ca35d2011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCallefdb83e2010-05-07 21:00:08 +0000119 };
John McCallf4cf1a12010-05-07 17:22:02 +0000120}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000121
John McCall56ca35d2011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCallefdb83e2010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000154
John McCall35542832010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000161
John McCall42c8f872010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000164
John McCall35542832010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCall35542832010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCall35542832010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman5bc86102009-06-14 02:17:33 +0000181 return true;
182}
183
John McCallcd7a4452010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
227 uint64_t Space[4];
228 bool ignored;
229 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
230 llvm::APFloat::rmTowardZero, &ignored);
231 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
232}
233
Mike Stump1eb44332009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump1eb44332009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000245 unsigned DestWidth = Ctx.getIntWidth(DestType);
246 APSInt Result = Value;
247 // Figure out if this is a truncate, extend or noop cast.
248 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000251 return Result;
252}
253
Mike Stump1eb44332009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000256
257 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
258 Result.convertFromAPInt(Value, Value.isSigned(),
259 APFloat::rmNearestTiesToEven);
260 return Result;
261}
262
Mike Stumpc4c90452009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000264class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000265 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stumpc4c90452009-10-27 22:09:17 +0000266 EvalInfo &Info;
267public:
268
269 HasSideEffect(EvalInfo &info) : Info(info) {}
270
271 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000272 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000273 return true;
274 }
275
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000276 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
277 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000278 return Visit(E->getResultExpr());
279 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000280 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
John McCallf85e1932011-06-15 23:02:42 +0000285 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
286 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
287 return true;
288 return false;
289 }
290 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
291 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
292 return true;
293 return false;
294 }
295
Mike Stumpc4c90452009-10-27 22:09:17 +0000296 // We don't want to evaluate BlockExprs multiple times, as they generate
297 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000298 bool VisitBlockExpr(const BlockExpr *E) { return true; }
299 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
300 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000301 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000302 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
303 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
304 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
305 bool VisitStringLiteral(const StringLiteral *E) { return false; }
306 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
307 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000308 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000309 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000310 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000311 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000312 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000313 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
314 bool VisitBinAssign(const BinaryOperator *E) { return true; }
315 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
316 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +0000317 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000318 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
319 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
321 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
322 bool VisitUnaryDeref(const UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000323 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000324 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000325 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000326 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000327 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000328
329 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000330 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +0000331 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
332 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000333 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000334 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000335 return false;
336 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000337
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000338 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000339};
340
John McCall56ca35d2011-02-17 10:25:35 +0000341class OpaqueValueEvaluation {
342 EvalInfo &info;
343 OpaqueValueExpr *opaqueValue;
344
345public:
346 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
347 Expr *value)
348 : info(info), opaqueValue(opaqueValue) {
349
350 // If evaluation fails, fail immediately.
351 if (!Evaluate(info, value)) {
352 this->opaqueValue = 0;
353 return;
354 }
355 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
356 }
357
358 bool hasError() const { return opaqueValue == 0; }
359
360 ~OpaqueValueEvaluation() {
361 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
362 }
363};
364
Mike Stumpc4c90452009-10-27 22:09:17 +0000365} // end anonymous namespace
366
Eli Friedman4efaa272008-11-12 09:44:48 +0000367//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000368// Generic Evaluation
369//===----------------------------------------------------------------------===//
370namespace {
371
372template <class Derived, typename RetTy=void>
373class ExprEvaluatorBase
374 : public ConstStmtVisitor<Derived, RetTy> {
375private:
376 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
377 return static_cast<Derived*>(this)->Success(V, E);
378 }
379 RetTy DerivedError(const Expr *E) {
380 return static_cast<Derived*>(this)->Error(E);
381 }
382
383protected:
384 EvalInfo &Info;
385 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
386 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
387
388public:
389 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
390
391 RetTy VisitStmt(const Stmt *) {
392 assert(0 && "Expression evaluator should not be called on stmts");
393 return DerivedError(0);
394 }
395 RetTy VisitExpr(const Expr *E) {
396 return DerivedError(E);
397 }
398
399 RetTy VisitParenExpr(const ParenExpr *E)
400 { return StmtVisitorTy::Visit(E->getSubExpr()); }
401 RetTy VisitUnaryExtension(const UnaryOperator *E)
402 { return StmtVisitorTy::Visit(E->getSubExpr()); }
403 RetTy VisitUnaryPlus(const UnaryOperator *E)
404 { return StmtVisitorTy::Visit(E->getSubExpr()); }
405 RetTy VisitChooseExpr(const ChooseExpr *E)
406 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
407 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
408 { return StmtVisitorTy::Visit(E->getResultExpr()); }
409
410 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
411 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
412 if (opaque.hasError())
413 return DerivedError(E);
414
415 bool cond;
416 if (!HandleConversionToBool(E->getCond(), cond, Info))
417 return DerivedError(E);
418
419 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
420 }
421
422 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
423 bool BoolResult;
424 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
425 return DerivedError(E);
426
427 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
428 return StmtVisitorTy::Visit(EvalExpr);
429 }
430
431 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
432 const APValue *value = Info.getOpaqueValue(E);
433 if (!value)
434 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
435 : DerivedError(E));
436 return DerivedSuccess(*value, E);
437 }
438};
439
440}
441
442//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000443// LValue Evaluation
444//===----------------------------------------------------------------------===//
445namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000446class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000447 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000448 LValue &Result;
449
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000450 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000451 Result.Base = E;
452 Result.Offset = CharUnits::Zero();
453 return true;
454 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000455public:
Mike Stump1eb44332009-09-09 15:08:12 +0000456
John McCallefdb83e2010-05-07 21:00:08 +0000457 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000458 ExprEvaluatorBaseTy(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000459
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000460 bool Success(const APValue &V, const Expr *E) {
461 Result.setFrom(V);
462 return true;
463 }
464 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000465 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000466 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000467
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000468 bool VisitDeclRefExpr(const DeclRefExpr *E);
469 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
470 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
471 bool VisitMemberExpr(const MemberExpr *E);
472 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
473 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
474 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
475 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000476
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000477 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000478 switch (E->getCastKind()) {
479 default:
John McCallefdb83e2010-05-07 21:00:08 +0000480 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000481
John McCall2de56d12010-08-25 11:45:40 +0000482 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000483 return Visit(E->getSubExpr());
484 }
485 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000486 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000487
Eli Friedman4efaa272008-11-12 09:44:48 +0000488};
489} // end anonymous namespace
490
John McCallefdb83e2010-05-07 21:00:08 +0000491static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000492 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000493}
494
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000495bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000496 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000497 return Success(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000498 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000499 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000500 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000501 // Reference parameters can refer to anything even if they have an
502 // "initializer" in the form of a default argument.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000503 if (!isa<ParmVarDecl>(VD))
504 // FIXME: Check whether VD might be overridden!
505 if (const Expr *Init = VD->getAnyInitializer())
506 return Visit(Init);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000507 }
508
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000509 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlsson35873c42008-11-24 04:41:22 +0000510}
511
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000512bool
513LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000514 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000515}
516
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000517bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000518 QualType Ty;
519 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000520 if (!EvaluatePointer(E->getBase(), Result, Info))
521 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000522 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000523 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000524 if (!Visit(E->getBase()))
525 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000526 Ty = E->getBase()->getType();
527 }
528
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000529 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000530 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000531
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000532 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +0000533 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000534 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000535
536 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000537 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000538
Eli Friedman4efaa272008-11-12 09:44:48 +0000539 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000540 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000541 for (RecordDecl::field_iterator Field = RD->field_begin(),
542 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000543 Field != FieldEnd; (void)++Field, ++i) {
544 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000545 break;
546 }
547
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000548 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000549 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000550}
551
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000552bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000553 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000554 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Anders Carlsson3068d112008-11-16 19:01:22 +0000556 APSInt Index;
557 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000558 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000559
Ken Dyck199c3d62010-01-11 17:06:35 +0000560 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000561 Result.Offset += Index.getSExtValue() * ElementSize;
562 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000563}
Eli Friedman4efaa272008-11-12 09:44:48 +0000564
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000565bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000566 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000567}
568
Eli Friedman4efaa272008-11-12 09:44:48 +0000569//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000570// Pointer Evaluation
571//===----------------------------------------------------------------------===//
572
Anders Carlssonc754aa62008-07-08 05:13:58 +0000573namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000574class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000575 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000576 LValue &Result;
577
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000578 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000579 Result.Base = E;
580 Result.Offset = CharUnits::Zero();
581 return true;
582 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000583public:
Mike Stump1eb44332009-09-09 15:08:12 +0000584
John McCallefdb83e2010-05-07 21:00:08 +0000585 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000586 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000587
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000588 bool Success(const APValue &V, const Expr *E) {
589 Result.setFrom(V);
590 return true;
591 }
592 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000593 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000594 }
595
John McCallefdb83e2010-05-07 21:00:08 +0000596 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000597 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000598 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000599 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000600 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000601 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000602 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000603 bool VisitCallExpr(const CallExpr *E);
604 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000605 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000606 return Success(E);
607 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000608 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000609 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000610 { return Success((Expr*)0); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000611 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000612 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000613
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000614 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000615};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000616} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000617
John McCallefdb83e2010-05-07 21:00:08 +0000618static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000619 assert(E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000620 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000621}
622
John McCallefdb83e2010-05-07 21:00:08 +0000623bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000624 if (E->getOpcode() != BO_Add &&
625 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000626 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000628 const Expr *PExp = E->getLHS();
629 const Expr *IExp = E->getRHS();
630 if (IExp->getType()->isPointerType())
631 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000632
John McCallefdb83e2010-05-07 21:00:08 +0000633 if (!EvaluatePointer(PExp, Result, Info))
634 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000635
John McCallefdb83e2010-05-07 21:00:08 +0000636 llvm::APSInt Offset;
637 if (!EvaluateInteger(IExp, Offset, Info))
638 return false;
639 int64_t AdditionalOffset
640 = Offset.isSigned() ? Offset.getSExtValue()
641 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000642
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000643 // Compute the new offset in the appropriate width.
644
645 QualType PointeeType =
646 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000647 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000649 // Explicitly handle GNU void* and function pointer arithmetic extensions.
650 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000651 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000652 else
John McCallefdb83e2010-05-07 21:00:08 +0000653 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000654
John McCall2de56d12010-08-25 11:45:40 +0000655 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000656 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000657 else
John McCallefdb83e2010-05-07 21:00:08 +0000658 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000659
John McCallefdb83e2010-05-07 21:00:08 +0000660 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000661}
Eli Friedman4efaa272008-11-12 09:44:48 +0000662
John McCallefdb83e2010-05-07 21:00:08 +0000663bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
664 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000665}
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000667
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000668bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
669 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000670
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000671 switch (E->getCastKind()) {
672 default:
673 break;
674
John McCall2de56d12010-08-25 11:45:40 +0000675 case CK_NoOp:
676 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000677 case CK_AnyPointerToObjCPointerCast:
678 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000679 return Visit(SubExpr);
680
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000681 case CK_DerivedToBase:
682 case CK_UncheckedDerivedToBase: {
683 LValue BaseLV;
684 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
685 return false;
686
687 // Now figure out the necessary offset to add to the baseLV to get from
688 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000689 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000690
691 QualType Ty = E->getSubExpr()->getType();
692 const CXXRecordDecl *DerivedDecl =
693 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
694
695 for (CastExpr::path_const_iterator PathI = E->path_begin(),
696 PathE = E->path_end(); PathI != PathE; ++PathI) {
697 const CXXBaseSpecifier *Base = *PathI;
698
699 // FIXME: If the base is virtual, we'd need to determine the type of the
700 // most derived class and we don't support that right now.
701 if (Base->isVirtual())
702 return false;
703
704 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
705 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
706
Ken Dyck7c7f8202011-01-26 02:17:08 +0000707 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000708 DerivedDecl = BaseDecl;
709 }
710
711 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000712 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000713 return true;
714 }
715
John McCall404cd162010-11-13 01:35:44 +0000716 case CK_NullToPointer: {
717 Result.Base = 0;
718 Result.Offset = CharUnits::Zero();
719 return true;
720 }
721
John McCall2de56d12010-08-25 11:45:40 +0000722 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000723 APValue Value;
724 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000725 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000726
John McCallefdb83e2010-05-07 21:00:08 +0000727 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000728 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000729 Result.Base = 0;
730 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
731 return true;
732 } else {
733 // Cast is of an lvalue, no need to change value.
734 Result.Base = Value.getLValueBase();
735 Result.Offset = Value.getLValueOffset();
736 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000737 }
738 }
John McCall2de56d12010-08-25 11:45:40 +0000739 case CK_ArrayToPointerDecay:
740 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000741 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000742 }
743
John McCallefdb83e2010-05-07 21:00:08 +0000744 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000745}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000746
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000747bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000748 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000749 Builtin::BI__builtin___CFStringMakeConstantString ||
750 E->isBuiltinCall(Info.Ctx) ==
751 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000752 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000753
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000754 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000755}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000756
757//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000758// Vector Evaluation
759//===----------------------------------------------------------------------===//
760
761namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000762 class VectorExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000763 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman91110ee2009-02-23 04:23:56 +0000764 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000765 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000767 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000769 APValue Success(const APValue &V, const Expr *E) { return V; }
770 APValue Error(const Expr *E) { return APValue(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Eli Friedman91110ee2009-02-23 04:23:56 +0000772 APValue VisitUnaryReal(const UnaryOperator *E)
773 { return Visit(E->getSubExpr()); }
774 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
775 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000776 APValue VisitCastExpr(const CastExpr* E);
777 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
778 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000779 APValue VisitUnaryImag(const UnaryOperator *E);
780 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000781 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000782 // shufflevector, ExtVectorElementExpr
783 // (Note that these require implementing conversions
784 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000785 };
786} // end anonymous namespace
787
788static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
789 if (!E->getType()->isVectorType())
790 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000791 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000792 return !Result.isUninit();
793}
794
795APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000796 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000797 QualType EltTy = VTy->getElementType();
798 unsigned NElts = VTy->getNumElements();
799 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Nate Begeman59b5da62009-01-18 03:20:47 +0000801 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000802 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000803
Eli Friedman46a52322011-03-25 00:43:55 +0000804 switch (E->getCastKind()) {
805 case CK_VectorSplat: {
806 APValue Result = APValue();
807 if (SETy->isIntegerType()) {
808 APSInt IntResult;
809 if (!EvaluateInteger(SE, IntResult, Info))
810 return APValue();
811 Result = APValue(IntResult);
812 } else if (SETy->isRealFloatingType()) {
813 APFloat F(0.0);
814 if (!EvaluateFloat(SE, F, Info))
815 return APValue();
816 Result = APValue(F);
817 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000818 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000819 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000820
821 // Splat and create vector APValue.
822 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
823 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000824 }
Eli Friedman46a52322011-03-25 00:43:55 +0000825 case CK_BitCast: {
826 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000827 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000828
Eli Friedman46a52322011-03-25 00:43:55 +0000829 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000830 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Eli Friedman46a52322011-03-25 00:43:55 +0000832 APSInt Init;
833 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000834 return APValue();
835
Eli Friedman46a52322011-03-25 00:43:55 +0000836 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
837 "Vectors must be composed of ints or floats");
838
839 llvm::SmallVector<APValue, 4> Elts;
840 for (unsigned i = 0; i != NElts; ++i) {
841 APSInt Tmp = Init.extOrTrunc(EltWidth);
842
843 if (EltTy->isIntegerType())
844 Elts.push_back(APValue(Tmp));
845 else
846 Elts.push_back(APValue(APFloat(Tmp)));
847
848 Init >>= EltWidth;
849 }
850 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000851 }
Eli Friedman46a52322011-03-25 00:43:55 +0000852 case CK_LValueToRValue:
853 case CK_NoOp:
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000854 return Visit(SE);
Eli Friedman46a52322011-03-25 00:43:55 +0000855 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000856 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000857 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000858}
859
Mike Stump1eb44332009-09-09 15:08:12 +0000860APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000861VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000862 return this->Visit(E->getInitializer());
Nate Begeman59b5da62009-01-18 03:20:47 +0000863}
864
Mike Stump1eb44332009-09-09 15:08:12 +0000865APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000866VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000867 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000868 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000869 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Nate Begeman59b5da62009-01-18 03:20:47 +0000871 QualType EltTy = VT->getElementType();
872 llvm::SmallVector<APValue, 4> Elements;
873
John McCalla7d6c222010-06-11 17:54:15 +0000874 // If a vector is initialized with a single element, that value
875 // becomes every element of the vector, not just the first.
876 // This is the behavior described in the IBM AltiVec documentation.
877 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000878
879 // Handle the case where the vector is initialized by a another
880 // vector (OpenCL 6.1.6).
881 if (E->getInit(0)->getType()->isVectorType())
882 return this->Visit(const_cast<Expr*>(E->getInit(0)));
883
John McCalla7d6c222010-06-11 17:54:15 +0000884 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000885 if (EltTy->isIntegerType()) {
886 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000887 if (!EvaluateInteger(E->getInit(0), sInt, Info))
888 return APValue();
889 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000890 } else {
891 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000892 if (!EvaluateFloat(E->getInit(0), f, Info))
893 return APValue();
894 InitValue = APValue(f);
895 }
896 for (unsigned i = 0; i < NumElements; i++) {
897 Elements.push_back(InitValue);
898 }
899 } else {
900 for (unsigned i = 0; i < NumElements; i++) {
901 if (EltTy->isIntegerType()) {
902 llvm::APSInt sInt(32);
903 if (i < NumInits) {
904 if (!EvaluateInteger(E->getInit(i), sInt, Info))
905 return APValue();
906 } else {
907 sInt = Info.Ctx.MakeIntValue(0, EltTy);
908 }
909 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000910 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000911 llvm::APFloat f(0.0);
912 if (i < NumInits) {
913 if (!EvaluateFloat(E->getInit(i), f, Info))
914 return APValue();
915 } else {
916 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
917 }
918 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000919 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000920 }
921 }
922 return APValue(&Elements[0], Elements.size());
923}
924
Mike Stump1eb44332009-09-09 15:08:12 +0000925APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000926VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000927 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000928 QualType EltTy = VT->getElementType();
929 APValue ZeroElement;
930 if (EltTy->isIntegerType())
931 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
932 else
933 ZeroElement =
934 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
935
936 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
937 return APValue(&Elements[0], Elements.size());
938}
939
Eli Friedman91110ee2009-02-23 04:23:56 +0000940APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
941 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
942 Info.EvalResult.HasSideEffects = true;
943 return GetZeroVector(E->getType());
944}
945
Nate Begeman59b5da62009-01-18 03:20:47 +0000946//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000947// Integer Evaluation
948//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000949
950namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000951class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000952 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000953 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000954public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000955 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000956 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000957
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000958 bool Success(const llvm::APSInt &SI, const Expr *E) {
959 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000960 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000961 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000962 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000963 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000964 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000965 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000966 return true;
967 }
968
Daniel Dunbar131eb432009-02-19 09:06:44 +0000969 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000970 assert(E->getType()->isIntegralOrEnumerationType() &&
971 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000972 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000973 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000974 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +0000975 Result.getInt().setIsUnsigned(
976 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000977 return true;
978 }
979
980 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000981 assert(E->getType()->isIntegralOrEnumerationType() &&
982 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000983 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000984 return true;
985 }
986
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000987 bool Success(CharUnits Size, const Expr *E) {
988 return Success(Size.getQuantity(), E);
989 }
990
991
Anders Carlsson82206e22008-11-30 18:14:57 +0000992 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000993 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000994 if (Info.EvalResult.Diag == 0) {
995 Info.EvalResult.DiagLoc = L;
996 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000997 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000998 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000999 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00001000 }
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001002 bool Success(const APValue &V, const Expr *E) {
1003 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00001004 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001005 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001006 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00001007 }
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001009 //===--------------------------------------------------------------------===//
1010 // Visitor Methods
1011 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001012
Chris Lattner4c4867e2008-07-12 00:38:25 +00001013 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001014 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001015 }
1016 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001017 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001018 }
Eli Friedman04309752009-11-24 05:28:59 +00001019
1020 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1021 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001022 if (CheckReferencedDecl(E, E->getDecl()))
1023 return true;
1024
1025 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001026 }
1027 bool VisitMemberExpr(const MemberExpr *E) {
1028 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1029 // Conservatively assume a MemberExpr will have side-effects
1030 Info.EvalResult.HasSideEffects = true;
1031 return true;
1032 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001033
1034 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001035 }
1036
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001037 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001038 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001039 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001040 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001041
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001042 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001043 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001044
Anders Carlsson3068d112008-11-16 19:01:22 +00001045 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001046 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001047 }
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Anders Carlsson3f704562008-12-21 22:39:40 +00001049 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001050 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001051 }
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Douglas Gregored8abf12010-07-08 06:14:04 +00001053 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001054 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001055 }
1056
Eli Friedman664a1042009-02-27 04:45:43 +00001057 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1058 return Success(0, E);
1059 }
1060
Sebastian Redl64b45f72009-01-05 20:52:13 +00001061 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001062 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001063 }
1064
Francois Pichet6ad6f282010-12-07 00:08:36 +00001065 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1066 return Success(E->getValue(), E);
1067 }
1068
John Wiegley21ff2e52011-04-28 00:16:57 +00001069 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1070 return Success(E->getValue(), E);
1071 }
1072
John Wiegley55262202011-04-25 06:54:41 +00001073 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1074 return Success(E->getValue(), E);
1075 }
1076
Eli Friedman722c7172009-02-28 03:59:05 +00001077 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001078 bool VisitUnaryImag(const UnaryOperator *E);
1079
Sebastian Redl295995c2010-09-10 20:55:47 +00001080 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001081 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1082
Chris Lattnerfcee0012008-07-11 21:24:13 +00001083private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001084 CharUnits GetAlignOfExpr(const Expr *E);
1085 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001086 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001087 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001088 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001089};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001090} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001091
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001092static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001093 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001094 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001095}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001096
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001097static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001098 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001099
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001100 APValue Val;
1101 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1102 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001103 Result = Val.getInt();
1104 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001105}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001106
Eli Friedman04309752009-11-24 05:28:59 +00001107bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001108 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001109 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001110 // Check for signedness/width mismatches between E type and ECD value.
1111 bool SameSign = (ECD->getInitVal().isSigned()
1112 == E->getType()->isSignedIntegerOrEnumerationType());
1113 bool SameWidth = (ECD->getInitVal().getBitWidth()
1114 == Info.Ctx.getIntWidth(E->getType()));
1115 if (SameSign && SameWidth)
1116 return Success(ECD->getInitVal(), E);
1117 else {
1118 // Get rid of mismatch (otherwise Success assertions will fail)
1119 // by computing a new value matching the type of E.
1120 llvm::APSInt Val = ECD->getInitVal();
1121 if (!SameSign)
1122 Val.setIsSigned(!ECD->getInitVal().isSigned());
1123 if (!SameWidth)
1124 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1125 return Success(Val, E);
1126 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001127 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001128
1129 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001130 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001131 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1132 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001133
1134 if (isa<ParmVarDecl>(D))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001135 return false;
Anders Carlssonf6b60252010-02-03 21:58:41 +00001136
Eli Friedman04309752009-11-24 05:28:59 +00001137 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001138 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001139 if (APValue *V = VD->getEvaluatedValue()) {
1140 if (V->isInt())
1141 return Success(V->getInt(), E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001142 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001143 }
1144
1145 if (VD->isEvaluatingValue())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001146 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001147
1148 VD->setEvaluatingValue();
1149
Eli Friedmana7dedf72010-09-06 00:10:32 +00001150 Expr::EvalResult EResult;
1151 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1152 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001153 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001154 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001155 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001156 return true;
1157 }
1158
Eli Friedmanc0131182009-12-03 20:31:57 +00001159 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001160 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001161 }
1162 }
1163
Chris Lattner4c4867e2008-07-12 00:38:25 +00001164 // Otherwise, random variable references are not constants.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001165 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001166}
1167
Chris Lattnera4d55d82008-10-06 06:40:35 +00001168/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1169/// as GCC.
1170static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1171 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001172 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001173 enum gcc_type_class {
1174 no_type_class = -1,
1175 void_type_class, integer_type_class, char_type_class,
1176 enumeral_type_class, boolean_type_class,
1177 pointer_type_class, reference_type_class, offset_type_class,
1178 real_type_class, complex_type_class,
1179 function_type_class, method_type_class,
1180 record_type_class, union_type_class,
1181 array_type_class, string_type_class,
1182 lang_type_class
1183 };
Mike Stump1eb44332009-09-09 15:08:12 +00001184
1185 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001186 // ideal, however it is what gcc does.
1187 if (E->getNumArgs() == 0)
1188 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Chris Lattnera4d55d82008-10-06 06:40:35 +00001190 QualType ArgTy = E->getArg(0)->getType();
1191 if (ArgTy->isVoidType())
1192 return void_type_class;
1193 else if (ArgTy->isEnumeralType())
1194 return enumeral_type_class;
1195 else if (ArgTy->isBooleanType())
1196 return boolean_type_class;
1197 else if (ArgTy->isCharType())
1198 return string_type_class; // gcc doesn't appear to use char_type_class
1199 else if (ArgTy->isIntegerType())
1200 return integer_type_class;
1201 else if (ArgTy->isPointerType())
1202 return pointer_type_class;
1203 else if (ArgTy->isReferenceType())
1204 return reference_type_class;
1205 else if (ArgTy->isRealType())
1206 return real_type_class;
1207 else if (ArgTy->isComplexType())
1208 return complex_type_class;
1209 else if (ArgTy->isFunctionType())
1210 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001211 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001212 return record_type_class;
1213 else if (ArgTy->isUnionType())
1214 return union_type_class;
1215 else if (ArgTy->isArrayType())
1216 return array_type_class;
1217 else if (ArgTy->isUnionType())
1218 return union_type_class;
1219 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1220 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1221 return -1;
1222}
1223
John McCall42c8f872010-05-10 23:27:23 +00001224/// Retrieves the "underlying object type" of the given expression,
1225/// as used by __builtin_object_size.
1226QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1227 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1228 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1229 return VD->getType();
1230 } else if (isa<CompoundLiteralExpr>(E)) {
1231 return E->getType();
1232 }
1233
1234 return QualType();
1235}
1236
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001237bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001238 // TODO: Perhaps we should let LLVM lower this?
1239 LValue Base;
1240 if (!EvaluatePointer(E->getArg(0), Base, Info))
1241 return false;
1242
1243 // If we can prove the base is null, lower to zero now.
1244 const Expr *LVBase = Base.getLValueBase();
1245 if (!LVBase) return Success(0, E);
1246
1247 QualType T = GetObjectType(LVBase);
1248 if (T.isNull() ||
1249 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001250 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001251 T->isVariablyModifiedType() ||
1252 T->isDependentType())
1253 return false;
1254
1255 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1256 CharUnits Offset = Base.getLValueOffset();
1257
1258 if (!Offset.isNegative() && Offset <= Size)
1259 Size -= Offset;
1260 else
1261 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001262 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001263}
1264
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001265bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001266 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001267 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001268 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001269
1270 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001271 if (TryEvaluateBuiltinObjectSize(E))
1272 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001273
Eric Christopherb2aaf512010-01-19 22:58:35 +00001274 // If evaluating the argument has side-effects we can't determine
1275 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001276 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001277 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001278 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001279 return Success(0, E);
1280 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001281
Mike Stump64eda9e2009-10-26 18:35:08 +00001282 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1283 }
1284
Chris Lattner019f4e82008-10-06 05:28:25 +00001285 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001286 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001288 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001289 // __builtin_constant_p always has one operand: it returns true if that
1290 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001291 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001292
1293 case Builtin::BI__builtin_eh_return_data_regno: {
1294 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1295 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1296 return Success(Operand, E);
1297 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001298
1299 case Builtin::BI__builtin_expect:
1300 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001301
1302 case Builtin::BIstrlen:
1303 case Builtin::BI__builtin_strlen:
1304 // As an extension, we support strlen() and __builtin_strlen() as constant
1305 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001306 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001307 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1308 // The string literal may have embedded null characters. Find the first
1309 // one and truncate there.
1310 llvm::StringRef Str = S->getString();
1311 llvm::StringRef::size_type Pos = Str.find(0);
1312 if (Pos != llvm::StringRef::npos)
1313 Str = Str.substr(0, Pos);
1314
1315 return Success(Str.size(), E);
1316 }
1317
1318 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001319 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001320}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001321
Chris Lattnerb542afe2008-07-11 19:10:17 +00001322bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001323 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001324 if (!Visit(E->getRHS()))
1325 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001326
Eli Friedman33ef1452009-02-26 10:19:36 +00001327 // If we can't evaluate the LHS, it might have side effects;
1328 // conservatively mark it.
1329 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1330 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001331
Anders Carlsson027f62e2008-12-01 02:07:06 +00001332 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001333 }
1334
1335 if (E->isLogicalOp()) {
1336 // These need to be handled specially because the operands aren't
1337 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001338 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001340 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001341 // We were able to evaluate the LHS, see if we can get away with not
1342 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001343 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001344 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001345
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001346 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001347 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001348 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001349 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001350 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001351 }
1352 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001353 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001354 // We can't evaluate the LHS; however, sometimes the result
1355 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001356 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1357 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001358 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001359 // must have had side effects.
1360 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001361
1362 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001363 }
1364 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001365 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001366
Eli Friedmana6afa762008-11-13 06:09:17 +00001367 return false;
1368 }
1369
Anders Carlsson286f85e2008-11-16 07:17:21 +00001370 QualType LHSTy = E->getLHS()->getType();
1371 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001372
1373 if (LHSTy->isAnyComplexType()) {
1374 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001375 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001376
1377 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1378 return false;
1379
1380 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1381 return false;
1382
1383 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001384 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001385 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001386 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001387 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1388
John McCall2de56d12010-08-25 11:45:40 +00001389 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001390 return Success((CR_r == APFloat::cmpEqual &&
1391 CR_i == APFloat::cmpEqual), E);
1392 else {
John McCall2de56d12010-08-25 11:45:40 +00001393 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001394 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001395 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001396 CR_r == APFloat::cmpLessThan ||
1397 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001398 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001399 CR_i == APFloat::cmpLessThan ||
1400 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001401 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001402 } else {
John McCall2de56d12010-08-25 11:45:40 +00001403 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001404 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1405 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1406 else {
John McCall2de56d12010-08-25 11:45:40 +00001407 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001408 "Invalid compex comparison.");
1409 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1410 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1411 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001412 }
1413 }
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Anders Carlsson286f85e2008-11-16 07:17:21 +00001415 if (LHSTy->isRealFloatingType() &&
1416 RHSTy->isRealFloatingType()) {
1417 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Anders Carlsson286f85e2008-11-16 07:17:21 +00001419 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1420 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Anders Carlsson286f85e2008-11-16 07:17:21 +00001422 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1423 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Anders Carlsson286f85e2008-11-16 07:17:21 +00001425 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001426
Anders Carlsson286f85e2008-11-16 07:17:21 +00001427 switch (E->getOpcode()) {
1428 default:
1429 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001430 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001431 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001432 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001433 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001434 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001435 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001436 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001437 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001438 E);
John McCall2de56d12010-08-25 11:45:40 +00001439 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001440 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001441 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001442 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001443 || CR == APFloat::cmpLessThan
1444 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001445 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001448 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001449 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001450 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001451 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1452 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001453
John McCallefdb83e2010-05-07 21:00:08 +00001454 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001455 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1456 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001457
Eli Friedman5bc86102009-06-14 02:17:33 +00001458 // Reject any bases from the normal codepath; we special-case comparisons
1459 // to null.
1460 if (LHSValue.getLValueBase()) {
1461 if (!E->isEqualityOp())
1462 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001463 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001464 return false;
1465 bool bres;
1466 if (!EvalPointerValueAsBool(LHSValue, bres))
1467 return false;
John McCall2de56d12010-08-25 11:45:40 +00001468 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001469 } else if (RHSValue.getLValueBase()) {
1470 if (!E->isEqualityOp())
1471 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001472 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001473 return false;
1474 bool bres;
1475 if (!EvalPointerValueAsBool(RHSValue, bres))
1476 return false;
John McCall2de56d12010-08-25 11:45:40 +00001477 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001478 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001479
John McCall2de56d12010-08-25 11:45:40 +00001480 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001481 QualType Type = E->getLHS()->getType();
1482 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001483
Ken Dycka7305832010-01-15 12:37:54 +00001484 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001485 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001486 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001487
Ken Dycka7305832010-01-15 12:37:54 +00001488 CharUnits Diff = LHSValue.getLValueOffset() -
1489 RHSValue.getLValueOffset();
1490 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001491 }
1492 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001493 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001494 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001495 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001496 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1497 }
1498 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001499 }
1500 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001501 if (!LHSTy->isIntegralOrEnumerationType() ||
1502 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001503 // We can't continue from here for non-integral types, and they
1504 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001505 return false;
1506 }
1507
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001508 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001509 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001510 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001511
Eli Friedman42edd0d2009-03-24 01:14:50 +00001512 APValue RHSVal;
1513 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001514 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001515
1516 // Handle cases like (unsigned long)&a + 4.
1517 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001518 CharUnits Offset = Result.getLValueOffset();
1519 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1520 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001521 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001522 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001523 else
Ken Dycka7305832010-01-15 12:37:54 +00001524 Offset -= AdditionalOffset;
1525 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001526 return true;
1527 }
1528
1529 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001530 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001531 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001532 CharUnits Offset = RHSVal.getLValueOffset();
1533 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1534 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001535 return true;
1536 }
1537
1538 // All the following cases expect both operands to be an integer
1539 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001540 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001541
Eli Friedman42edd0d2009-03-24 01:14:50 +00001542 APSInt& RHS = RHSVal.getInt();
1543
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001544 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001545 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001546 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001547 case BO_Mul: return Success(Result.getInt() * RHS, E);
1548 case BO_Add: return Success(Result.getInt() + RHS, E);
1549 case BO_Sub: return Success(Result.getInt() - RHS, E);
1550 case BO_And: return Success(Result.getInt() & RHS, E);
1551 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1552 case BO_Or: return Success(Result.getInt() | RHS, E);
1553 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001554 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001555 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001556 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001557 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001558 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001559 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001560 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001561 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001562 // During constant-folding, a negative shift is an opposite shift.
1563 if (RHS.isSigned() && RHS.isNegative()) {
1564 RHS = -RHS;
1565 goto shift_right;
1566 }
1567
1568 shift_left:
1569 unsigned SA
1570 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001571 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001572 }
John McCall2de56d12010-08-25 11:45:40 +00001573 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001574 // During constant-folding, a negative shift is an opposite shift.
1575 if (RHS.isSigned() && RHS.isNegative()) {
1576 RHS = -RHS;
1577 goto shift_left;
1578 }
1579
1580 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001581 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001582 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1583 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
John McCall2de56d12010-08-25 11:45:40 +00001586 case BO_LT: return Success(Result.getInt() < RHS, E);
1587 case BO_GT: return Success(Result.getInt() > RHS, E);
1588 case BO_LE: return Success(Result.getInt() <= RHS, E);
1589 case BO_GE: return Success(Result.getInt() >= RHS, E);
1590 case BO_EQ: return Success(Result.getInt() == RHS, E);
1591 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001592 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001593}
1594
Ken Dyck8b752f12010-01-27 17:10:57 +00001595CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001596 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1597 // the result is the size of the referenced type."
1598 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1599 // result shall be the alignment of the referenced type."
1600 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1601 T = Ref->getPointeeType();
1602
Eli Friedman2be58612009-05-30 21:09:44 +00001603 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001604 return Info.Ctx.toCharUnitsFromBits(
1605 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001606}
1607
Ken Dyck8b752f12010-01-27 17:10:57 +00001608CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001609 E = E->IgnoreParens();
1610
1611 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001612 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001613 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001614 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1615 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001616
Chris Lattneraf707ab2009-01-24 21:53:27 +00001617 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001618 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1619 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001620
Chris Lattnere9feb472009-01-24 21:09:06 +00001621 return GetAlignOfType(E->getType());
1622}
1623
1624
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001625/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1626/// a result as the expression's type.
1627bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1628 const UnaryExprOrTypeTraitExpr *E) {
1629 switch(E->getKind()) {
1630 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001631 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001632 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001633 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001634 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001635 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001636
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001637 case UETT_VecStep: {
1638 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001639
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001640 if (Ty->isVectorType()) {
1641 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001642
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001643 // The vec_step built-in functions that take a 3-component
1644 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1645 if (n == 3)
1646 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001647
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001648 return Success(n, E);
1649 } else
1650 return Success(1, E);
1651 }
1652
1653 case UETT_SizeOf: {
1654 QualType SrcTy = E->getTypeOfArgument();
1655 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1656 // the result is the size of the referenced type."
1657 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1658 // result shall be the alignment of the referenced type."
1659 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1660 SrcTy = Ref->getPointeeType();
1661
1662 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1663 // extension.
1664 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1665 return Success(1, E);
1666
1667 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1668 if (!SrcTy->isConstantSizeType())
1669 return false;
1670
1671 // Get information about the size.
1672 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1673 }
1674 }
1675
1676 llvm_unreachable("unknown expr/type trait");
1677 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001678}
1679
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001680bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001681 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001682 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001683 if (n == 0)
1684 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001685 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001686 for (unsigned i = 0; i != n; ++i) {
1687 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1688 switch (ON.getKind()) {
1689 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001690 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001691 APSInt IdxResult;
1692 if (!EvaluateInteger(Idx, IdxResult, Info))
1693 return false;
1694 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1695 if (!AT)
1696 return false;
1697 CurrentType = AT->getElementType();
1698 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1699 Result += IdxResult.getSExtValue() * ElementSize;
1700 break;
1701 }
1702
1703 case OffsetOfExpr::OffsetOfNode::Field: {
1704 FieldDecl *MemberDecl = ON.getField();
1705 const RecordType *RT = CurrentType->getAs<RecordType>();
1706 if (!RT)
1707 return false;
1708 RecordDecl *RD = RT->getDecl();
1709 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001710 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001711 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001712 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001713 CurrentType = MemberDecl->getType().getNonReferenceType();
1714 break;
1715 }
1716
1717 case OffsetOfExpr::OffsetOfNode::Identifier:
1718 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001719 return false;
1720
1721 case OffsetOfExpr::OffsetOfNode::Base: {
1722 CXXBaseSpecifier *BaseSpec = ON.getBase();
1723 if (BaseSpec->isVirtual())
1724 return false;
1725
1726 // Find the layout of the class whose base we are looking into.
1727 const RecordType *RT = CurrentType->getAs<RecordType>();
1728 if (!RT)
1729 return false;
1730 RecordDecl *RD = RT->getDecl();
1731 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1732
1733 // Find the base class itself.
1734 CurrentType = BaseSpec->getType();
1735 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1736 if (!BaseRT)
1737 return false;
1738
1739 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001740 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001741 break;
1742 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001743 }
1744 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001745 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001746}
1747
Chris Lattnerb542afe2008-07-11 19:10:17 +00001748bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001749 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001750 // LNot's operand isn't necessarily an integer, so we handle it specially.
1751 bool bres;
1752 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1753 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001754 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001755 }
1756
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001757 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001758 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001759 return false;
1760
Chris Lattner87eae5e2008-07-11 22:52:41 +00001761 // Get the operand value into 'Result'.
1762 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001763 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001764
Chris Lattner75a48812008-07-11 22:15:16 +00001765 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001766 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001767 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1768 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001769 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001770 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001771 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1772 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001773 return true;
John McCall2de56d12010-08-25 11:45:40 +00001774 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001775 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001776 return true;
John McCall2de56d12010-08-25 11:45:40 +00001777 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001778 if (!Result.isInt()) return false;
1779 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001780 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001781 if (!Result.isInt()) return false;
1782 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001783 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001784}
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Chris Lattner732b2232008-07-12 01:15:53 +00001786/// HandleCast - This is used to evaluate implicit or explicit casts where the
1787/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001788bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1789 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001790 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001791 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001792
Eli Friedman46a52322011-03-25 00:43:55 +00001793 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001794 case CK_BaseToDerived:
1795 case CK_DerivedToBase:
1796 case CK_UncheckedDerivedToBase:
1797 case CK_Dynamic:
1798 case CK_ToUnion:
1799 case CK_ArrayToPointerDecay:
1800 case CK_FunctionToPointerDecay:
1801 case CK_NullToPointer:
1802 case CK_NullToMemberPointer:
1803 case CK_BaseToDerivedMemberPointer:
1804 case CK_DerivedToBaseMemberPointer:
1805 case CK_ConstructorConversion:
1806 case CK_IntegralToPointer:
1807 case CK_ToVoid:
1808 case CK_VectorSplat:
1809 case CK_IntegralToFloating:
1810 case CK_FloatingCast:
1811 case CK_AnyPointerToObjCPointerCast:
1812 case CK_AnyPointerToBlockPointerCast:
1813 case CK_ObjCObjectLValueCast:
1814 case CK_FloatingRealToComplex:
1815 case CK_FloatingComplexToReal:
1816 case CK_FloatingComplexCast:
1817 case CK_FloatingComplexToIntegralComplex:
1818 case CK_IntegralRealToComplex:
1819 case CK_IntegralComplexCast:
1820 case CK_IntegralComplexToFloatingComplex:
1821 llvm_unreachable("invalid cast kind for integral value");
1822
Eli Friedmane50c2972011-03-25 19:07:11 +00001823 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001824 case CK_Dependent:
1825 case CK_GetObjCProperty:
1826 case CK_LValueBitCast:
1827 case CK_UserDefinedConversion:
John McCallf85e1932011-06-15 23:02:42 +00001828 case CK_ObjCProduceObject:
1829 case CK_ObjCConsumeObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001830 return false;
1831
1832 case CK_LValueToRValue:
1833 case CK_NoOp:
1834 return Visit(E->getSubExpr());
1835
1836 case CK_MemberPointerToBoolean:
1837 case CK_PointerToBoolean:
1838 case CK_IntegralToBoolean:
1839 case CK_FloatingToBoolean:
1840 case CK_FloatingComplexToBoolean:
1841 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001842 bool BoolResult;
1843 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1844 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001845 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001846 }
1847
Eli Friedman46a52322011-03-25 00:43:55 +00001848 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001849 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001850 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001851
Eli Friedmanbe265702009-02-20 01:15:07 +00001852 if (!Result.isInt()) {
1853 // Only allow casts of lvalues if they are lossless.
1854 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1855 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001856
Daniel Dunbardd211642009-02-19 22:24:01 +00001857 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001858 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Eli Friedman46a52322011-03-25 00:43:55 +00001861 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001862 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001863 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001864 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001865
Daniel Dunbardd211642009-02-19 22:24:01 +00001866 if (LV.getLValueBase()) {
1867 // Only allow based lvalue casts if they are lossless.
1868 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1869 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001870
John McCallefdb83e2010-05-07 21:00:08 +00001871 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001872 return true;
1873 }
1874
Ken Dycka7305832010-01-15 12:37:54 +00001875 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1876 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001877 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001878 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001879
Eli Friedman46a52322011-03-25 00:43:55 +00001880 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001881 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001882 if (!EvaluateComplex(SubExpr, C, Info))
1883 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001884 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001885 }
Eli Friedman2217c872009-02-22 11:46:18 +00001886
Eli Friedman46a52322011-03-25 00:43:55 +00001887 case CK_FloatingToIntegral: {
1888 APFloat F(0.0);
1889 if (!EvaluateFloat(SubExpr, F, Info))
1890 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001891
Eli Friedman46a52322011-03-25 00:43:55 +00001892 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1893 }
1894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Eli Friedman46a52322011-03-25 00:43:55 +00001896 llvm_unreachable("unknown cast resulting in integral value");
1897 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001898}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001899
Eli Friedman722c7172009-02-28 03:59:05 +00001900bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1901 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001902 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001903 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1904 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1905 return Success(LV.getComplexIntReal(), E);
1906 }
1907
1908 return Visit(E->getSubExpr());
1909}
1910
Eli Friedman664a1042009-02-27 04:45:43 +00001911bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001912 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001913 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001914 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1915 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1916 return Success(LV.getComplexIntImag(), E);
1917 }
1918
Eli Friedman664a1042009-02-27 04:45:43 +00001919 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1920 Info.EvalResult.HasSideEffects = true;
1921 return Success(0, E);
1922}
1923
Douglas Gregoree8aff02011-01-04 17:33:58 +00001924bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1925 return Success(E->getPackLength(), E);
1926}
1927
Sebastian Redl295995c2010-09-10 20:55:47 +00001928bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1929 return Success(E->getValue(), E);
1930}
1931
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001932//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001933// Float Evaluation
1934//===----------------------------------------------------------------------===//
1935
1936namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001937class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001938 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001939 APFloat &Result;
1940public:
1941 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001942 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001943
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001944 bool Success(const APValue &V, const Expr *e) {
1945 Result = V.getFloat();
1946 return true;
1947 }
1948 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001949 return false;
1950 }
1951
Chris Lattner019f4e82008-10-06 05:28:25 +00001952 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001953
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001954 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001955 bool VisitBinaryOperator(const BinaryOperator *E);
1956 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001957 bool VisitCastExpr(const CastExpr *E);
1958 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001959
John McCallabd3a852010-05-07 22:08:54 +00001960 bool VisitUnaryReal(const UnaryOperator *E);
1961 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001962
John McCall189d6ef2010-10-09 01:34:31 +00001963 bool VisitDeclRefExpr(const DeclRefExpr *E);
1964
John McCallabd3a852010-05-07 22:08:54 +00001965 // FIXME: Missing: array subscript of vector, member of vector,
1966 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001967};
1968} // end anonymous namespace
1969
1970static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001971 assert(E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001972 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001973}
1974
Jay Foad4ba2a172011-01-12 09:06:06 +00001975static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001976 QualType ResultTy,
1977 const Expr *Arg,
1978 bool SNaN,
1979 llvm::APFloat &Result) {
1980 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1981 if (!S) return false;
1982
1983 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1984
1985 llvm::APInt fill;
1986
1987 // Treat empty strings as if they were zero.
1988 if (S->getString().empty())
1989 fill = llvm::APInt(32, 0);
1990 else if (S->getString().getAsInteger(0, fill))
1991 return false;
1992
1993 if (SNaN)
1994 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1995 else
1996 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1997 return true;
1998}
1999
Chris Lattner019f4e82008-10-06 05:28:25 +00002000bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002001 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002002 default:
2003 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2004
Chris Lattner019f4e82008-10-06 05:28:25 +00002005 case Builtin::BI__builtin_huge_val:
2006 case Builtin::BI__builtin_huge_valf:
2007 case Builtin::BI__builtin_huge_vall:
2008 case Builtin::BI__builtin_inf:
2009 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002010 case Builtin::BI__builtin_infl: {
2011 const llvm::fltSemantics &Sem =
2012 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002013 Result = llvm::APFloat::getInf(Sem);
2014 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
John McCalldb7b72a2010-02-28 13:00:19 +00002017 case Builtin::BI__builtin_nans:
2018 case Builtin::BI__builtin_nansf:
2019 case Builtin::BI__builtin_nansl:
2020 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2021 true, Result);
2022
Chris Lattner9e621712008-10-06 06:31:58 +00002023 case Builtin::BI__builtin_nan:
2024 case Builtin::BI__builtin_nanf:
2025 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002026 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002027 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002028 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2029 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002030
2031 case Builtin::BI__builtin_fabs:
2032 case Builtin::BI__builtin_fabsf:
2033 case Builtin::BI__builtin_fabsl:
2034 if (!EvaluateFloat(E->getArg(0), Result, Info))
2035 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002037 if (Result.isNegative())
2038 Result.changeSign();
2039 return true;
2040
Mike Stump1eb44332009-09-09 15:08:12 +00002041 case Builtin::BI__builtin_copysign:
2042 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002043 case Builtin::BI__builtin_copysignl: {
2044 APFloat RHS(0.);
2045 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2046 !EvaluateFloat(E->getArg(1), RHS, Info))
2047 return false;
2048 Result.copySign(RHS);
2049 return true;
2050 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002051 }
2052}
2053
John McCall189d6ef2010-10-09 01:34:31 +00002054bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002055 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2056 return true;
2057
John McCall189d6ef2010-10-09 01:34:31 +00002058 const Decl *D = E->getDecl();
2059 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2060 const VarDecl *VD = cast<VarDecl>(D);
2061
2062 // Require the qualifiers to be const and not volatile.
2063 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2064 if (!T.isConstQualified() || T.isVolatileQualified())
2065 return false;
2066
2067 const Expr *Init = VD->getAnyInitializer();
2068 if (!Init) return false;
2069
2070 if (APValue *V = VD->getEvaluatedValue()) {
2071 if (V->isFloat()) {
2072 Result = V->getFloat();
2073 return true;
2074 }
2075 return false;
2076 }
2077
2078 if (VD->isEvaluatingValue())
2079 return false;
2080
2081 VD->setEvaluatingValue();
2082
2083 Expr::EvalResult InitResult;
2084 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2085 InitResult.Val.isFloat()) {
2086 // Cache the evaluated value in the variable declaration.
2087 Result = InitResult.Val.getFloat();
2088 VD->setEvaluatedValue(InitResult.Val);
2089 return true;
2090 }
2091
2092 VD->setEvaluatedValue(APValue());
2093 return false;
2094}
2095
John McCallabd3a852010-05-07 22:08:54 +00002096bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002097 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2098 ComplexValue CV;
2099 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2100 return false;
2101 Result = CV.FloatReal;
2102 return true;
2103 }
2104
2105 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002106}
2107
2108bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002109 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2110 ComplexValue CV;
2111 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2112 return false;
2113 Result = CV.FloatImag;
2114 return true;
2115 }
2116
2117 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2118 Info.EvalResult.HasSideEffects = true;
2119 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2120 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002121 return true;
2122}
2123
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002124bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002125 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002126 return false;
2127
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002128 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2129 return false;
2130
2131 switch (E->getOpcode()) {
2132 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002133 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002134 return true;
John McCall2de56d12010-08-25 11:45:40 +00002135 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002136 Result.changeSign();
2137 return true;
2138 }
2139}
Chris Lattner019f4e82008-10-06 05:28:25 +00002140
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002141bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002142 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002143 if (!EvaluateFloat(E->getRHS(), Result, Info))
2144 return false;
2145
2146 // If we can't evaluate the LHS, it might have side effects;
2147 // conservatively mark it.
2148 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2149 Info.EvalResult.HasSideEffects = true;
2150
2151 return true;
2152 }
2153
Anders Carlsson96e93662010-10-31 01:21:47 +00002154 // We can't evaluate pointer-to-member operations.
2155 if (E->isPtrMemOp())
2156 return false;
2157
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002158 // FIXME: Diagnostics? I really don't understand how the warnings
2159 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002160 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002161 if (!EvaluateFloat(E->getLHS(), Result, Info))
2162 return false;
2163 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2164 return false;
2165
2166 switch (E->getOpcode()) {
2167 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002168 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002169 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2170 return true;
John McCall2de56d12010-08-25 11:45:40 +00002171 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002172 Result.add(RHS, APFloat::rmNearestTiesToEven);
2173 return true;
John McCall2de56d12010-08-25 11:45:40 +00002174 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002175 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2176 return true;
John McCall2de56d12010-08-25 11:45:40 +00002177 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002178 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2179 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002180 }
2181}
2182
2183bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2184 Result = E->getValue();
2185 return true;
2186}
2187
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002188bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2189 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Eli Friedman2a523ee2011-03-25 00:54:52 +00002191 switch (E->getCastKind()) {
2192 default:
2193 return false;
2194
2195 case CK_LValueToRValue:
2196 case CK_NoOp:
2197 return Visit(SubExpr);
2198
2199 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002200 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002201 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002202 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002203 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002204 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002205 return true;
2206 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002207
2208 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002209 if (!Visit(SubExpr))
2210 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002211 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2212 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002213 return true;
2214 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002215
Eli Friedman2a523ee2011-03-25 00:54:52 +00002216 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002217 ComplexValue V;
2218 if (!EvaluateComplex(SubExpr, V, Info))
2219 return false;
2220 Result = V.getComplexFloatReal();
2221 return true;
2222 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002223 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002224
2225 return false;
2226}
2227
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002228bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002229 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2230 return true;
2231}
2232
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002233//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002234// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002235//===----------------------------------------------------------------------===//
2236
2237namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002238class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002239 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002240 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002242public:
John McCallf4cf1a12010-05-07 17:22:02 +00002243 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002244 : ExprEvaluatorBaseTy(info), Result(Result) {}
2245
2246 bool Success(const APValue &V, const Expr *e) {
2247 Result.setFrom(V);
2248 return true;
2249 }
2250 bool Error(const Expr *E) {
2251 return false;
2252 }
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002254 //===--------------------------------------------------------------------===//
2255 // Visitor Methods
2256 //===--------------------------------------------------------------------===//
2257
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002258 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002260 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002261
John McCallf4cf1a12010-05-07 17:22:02 +00002262 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002263 bool VisitUnaryOperator(const UnaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002264 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002265};
2266} // end anonymous namespace
2267
John McCallf4cf1a12010-05-07 17:22:02 +00002268static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2269 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002270 assert(E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002271 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002272}
2273
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002274bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2275 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002276
2277 if (SubExpr->getType()->isRealFloatingType()) {
2278 Result.makeComplexFloat();
2279 APFloat &Imag = Result.FloatImag;
2280 if (!EvaluateFloat(SubExpr, Imag, Info))
2281 return false;
2282
2283 Result.FloatReal = APFloat(Imag.getSemantics());
2284 return true;
2285 } else {
2286 assert(SubExpr->getType()->isIntegerType() &&
2287 "Unexpected imaginary literal.");
2288
2289 Result.makeComplexInt();
2290 APSInt &Imag = Result.IntImag;
2291 if (!EvaluateInteger(SubExpr, Imag, Info))
2292 return false;
2293
2294 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2295 return true;
2296 }
2297}
2298
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002299bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002300
John McCall8786da72010-12-14 17:51:41 +00002301 switch (E->getCastKind()) {
2302 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002303 case CK_BaseToDerived:
2304 case CK_DerivedToBase:
2305 case CK_UncheckedDerivedToBase:
2306 case CK_Dynamic:
2307 case CK_ToUnion:
2308 case CK_ArrayToPointerDecay:
2309 case CK_FunctionToPointerDecay:
2310 case CK_NullToPointer:
2311 case CK_NullToMemberPointer:
2312 case CK_BaseToDerivedMemberPointer:
2313 case CK_DerivedToBaseMemberPointer:
2314 case CK_MemberPointerToBoolean:
2315 case CK_ConstructorConversion:
2316 case CK_IntegralToPointer:
2317 case CK_PointerToIntegral:
2318 case CK_PointerToBoolean:
2319 case CK_ToVoid:
2320 case CK_VectorSplat:
2321 case CK_IntegralCast:
2322 case CK_IntegralToBoolean:
2323 case CK_IntegralToFloating:
2324 case CK_FloatingToIntegral:
2325 case CK_FloatingToBoolean:
2326 case CK_FloatingCast:
2327 case CK_AnyPointerToObjCPointerCast:
2328 case CK_AnyPointerToBlockPointerCast:
2329 case CK_ObjCObjectLValueCast:
2330 case CK_FloatingComplexToReal:
2331 case CK_FloatingComplexToBoolean:
2332 case CK_IntegralComplexToReal:
2333 case CK_IntegralComplexToBoolean:
John McCallf85e1932011-06-15 23:02:42 +00002334 case CK_ObjCProduceObject:
2335 case CK_ObjCConsumeObject:
John McCall8786da72010-12-14 17:51:41 +00002336 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002337
John McCall8786da72010-12-14 17:51:41 +00002338 case CK_LValueToRValue:
2339 case CK_NoOp:
2340 return Visit(E->getSubExpr());
2341
2342 case CK_Dependent:
2343 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002344 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002345 case CK_UserDefinedConversion:
2346 return false;
2347
2348 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002349 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002350 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002351 return false;
2352
John McCall8786da72010-12-14 17:51:41 +00002353 Result.makeComplexFloat();
2354 Result.FloatImag = APFloat(Real.getSemantics());
2355 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002356 }
2357
John McCall8786da72010-12-14 17:51:41 +00002358 case CK_FloatingComplexCast: {
2359 if (!Visit(E->getSubExpr()))
2360 return false;
2361
2362 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2363 QualType From
2364 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2365
2366 Result.FloatReal
2367 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2368 Result.FloatImag
2369 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2370 return true;
2371 }
2372
2373 case CK_FloatingComplexToIntegralComplex: {
2374 if (!Visit(E->getSubExpr()))
2375 return false;
2376
2377 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2378 QualType From
2379 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2380 Result.makeComplexInt();
2381 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2382 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2383 return true;
2384 }
2385
2386 case CK_IntegralRealToComplex: {
2387 APSInt &Real = Result.IntReal;
2388 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2389 return false;
2390
2391 Result.makeComplexInt();
2392 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2393 return true;
2394 }
2395
2396 case CK_IntegralComplexCast: {
2397 if (!Visit(E->getSubExpr()))
2398 return false;
2399
2400 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2401 QualType From
2402 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2403
2404 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2405 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2406 return true;
2407 }
2408
2409 case CK_IntegralComplexToFloatingComplex: {
2410 if (!Visit(E->getSubExpr()))
2411 return false;
2412
2413 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2414 QualType From
2415 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2416 Result.makeComplexFloat();
2417 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2418 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2419 return true;
2420 }
2421 }
2422
2423 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002424 return false;
2425}
2426
John McCallf4cf1a12010-05-07 17:22:02 +00002427bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002428 if (E->getOpcode() == BO_Comma) {
2429 if (!Visit(E->getRHS()))
2430 return false;
2431
2432 // If we can't evaluate the LHS, it might have side effects;
2433 // conservatively mark it.
2434 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2435 Info.EvalResult.HasSideEffects = true;
2436
2437 return true;
2438 }
John McCallf4cf1a12010-05-07 17:22:02 +00002439 if (!Visit(E->getLHS()))
2440 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002441
John McCallf4cf1a12010-05-07 17:22:02 +00002442 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002443 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002444 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002445
Daniel Dunbar3f279872009-01-29 01:32:56 +00002446 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2447 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002448 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002449 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002450 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002451 if (Result.isComplexFloat()) {
2452 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2453 APFloat::rmNearestTiesToEven);
2454 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2455 APFloat::rmNearestTiesToEven);
2456 } else {
2457 Result.getComplexIntReal() += RHS.getComplexIntReal();
2458 Result.getComplexIntImag() += RHS.getComplexIntImag();
2459 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002460 break;
John McCall2de56d12010-08-25 11:45:40 +00002461 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002462 if (Result.isComplexFloat()) {
2463 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2464 APFloat::rmNearestTiesToEven);
2465 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2466 APFloat::rmNearestTiesToEven);
2467 } else {
2468 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2469 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2470 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002471 break;
John McCall2de56d12010-08-25 11:45:40 +00002472 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002473 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002474 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002475 APFloat &LHS_r = LHS.getComplexFloatReal();
2476 APFloat &LHS_i = LHS.getComplexFloatImag();
2477 APFloat &RHS_r = RHS.getComplexFloatReal();
2478 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002479
Daniel Dunbar3f279872009-01-29 01:32:56 +00002480 APFloat Tmp = LHS_r;
2481 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2482 Result.getComplexFloatReal() = Tmp;
2483 Tmp = LHS_i;
2484 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2485 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2486
2487 Tmp = LHS_r;
2488 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2489 Result.getComplexFloatImag() = Tmp;
2490 Tmp = LHS_i;
2491 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2492 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2493 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002494 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002495 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002496 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2497 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002498 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002499 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2500 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2501 }
2502 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002503 case BO_Div:
2504 if (Result.isComplexFloat()) {
2505 ComplexValue LHS = Result;
2506 APFloat &LHS_r = LHS.getComplexFloatReal();
2507 APFloat &LHS_i = LHS.getComplexFloatImag();
2508 APFloat &RHS_r = RHS.getComplexFloatReal();
2509 APFloat &RHS_i = RHS.getComplexFloatImag();
2510 APFloat &Res_r = Result.getComplexFloatReal();
2511 APFloat &Res_i = Result.getComplexFloatImag();
2512
2513 APFloat Den = RHS_r;
2514 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2515 APFloat Tmp = RHS_i;
2516 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2517 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2518
2519 Res_r = LHS_r;
2520 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2521 Tmp = LHS_i;
2522 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2523 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2524 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2525
2526 Res_i = LHS_i;
2527 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2528 Tmp = LHS_r;
2529 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2530 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2531 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2532 } else {
2533 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2534 // FIXME: what about diagnostics?
2535 return false;
2536 }
2537 ComplexValue LHS = Result;
2538 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2539 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2540 Result.getComplexIntReal() =
2541 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2542 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2543 Result.getComplexIntImag() =
2544 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2545 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2546 }
2547 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002548 }
2549
John McCallf4cf1a12010-05-07 17:22:02 +00002550 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002551}
2552
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002553bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2554 // Get the operand value into 'Result'.
2555 if (!Visit(E->getSubExpr()))
2556 return false;
2557
2558 switch (E->getOpcode()) {
2559 default:
2560 // FIXME: what about diagnostics?
2561 return false;
2562 case UO_Extension:
2563 return true;
2564 case UO_Plus:
2565 // The result is always just the subexpr.
2566 return true;
2567 case UO_Minus:
2568 if (Result.isComplexFloat()) {
2569 Result.getComplexFloatReal().changeSign();
2570 Result.getComplexFloatImag().changeSign();
2571 }
2572 else {
2573 Result.getComplexIntReal() = -Result.getComplexIntReal();
2574 Result.getComplexIntImag() = -Result.getComplexIntImag();
2575 }
2576 return true;
2577 case UO_Not:
2578 if (Result.isComplexFloat())
2579 Result.getComplexFloatImag().changeSign();
2580 else
2581 Result.getComplexIntImag() = -Result.getComplexIntImag();
2582 return true;
2583 }
2584}
2585
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002586//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002587// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002588//===----------------------------------------------------------------------===//
2589
John McCall56ca35d2011-02-17 10:25:35 +00002590static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002591 if (E->getType()->isVectorType()) {
2592 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002593 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002594 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002595 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002596 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002597 if (Info.EvalResult.Val.isLValue() &&
2598 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002599 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002600 } else if (E->getType()->hasPointerRepresentation()) {
2601 LValue LV;
2602 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002603 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002604 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002605 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002606 LV.moveInto(Info.EvalResult.Val);
2607 } else if (E->getType()->isRealFloatingType()) {
2608 llvm::APFloat F(0.0);
2609 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002610 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002611
John McCallefdb83e2010-05-07 21:00:08 +00002612 Info.EvalResult.Val = APValue(F);
2613 } else if (E->getType()->isAnyComplexType()) {
2614 ComplexValue C;
2615 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002616 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002617 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002618 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002619 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002620
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002621 return true;
2622}
2623
John McCall56ca35d2011-02-17 10:25:35 +00002624/// Evaluate - Return true if this is a constant which we can fold using
2625/// any crazy technique (that has nothing to do with language standards) that
2626/// we want to. If this function returns true, it returns the folded constant
2627/// in Result.
2628bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2629 EvalInfo Info(Ctx, Result);
2630 return ::Evaluate(Info, this);
2631}
2632
Jay Foad4ba2a172011-01-12 09:06:06 +00002633bool Expr::EvaluateAsBooleanCondition(bool &Result,
2634 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002635 EvalResult Scratch;
2636 EvalInfo Info(Ctx, Scratch);
2637
2638 return HandleConversionToBool(this, Result, Info);
2639}
2640
Jay Foad4ba2a172011-01-12 09:06:06 +00002641bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002642 EvalInfo Info(Ctx, Result);
2643
John McCallefdb83e2010-05-07 21:00:08 +00002644 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002645 if (EvaluateLValue(this, LV, Info) &&
2646 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002647 IsGlobalLValue(LV.Base)) {
2648 LV.moveInto(Result.Val);
2649 return true;
2650 }
2651 return false;
2652}
2653
Jay Foad4ba2a172011-01-12 09:06:06 +00002654bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2655 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002656 EvalInfo Info(Ctx, Result);
2657
2658 LValue LV;
2659 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002660 LV.moveInto(Result.Val);
2661 return true;
2662 }
2663 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002664}
2665
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002666/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002667/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002668bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002669 EvalResult Result;
2670 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002671}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002672
Jay Foad4ba2a172011-01-12 09:06:06 +00002673bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002674 Expr::EvalResult Result;
2675 EvalInfo Info(Ctx, Result);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002676 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002677}
2678
Jay Foad4ba2a172011-01-12 09:06:06 +00002679APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002680 EvalResult EvalResult;
2681 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002682 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002683 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002684 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002685
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002686 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002687}
John McCalld905f5a2010-05-07 05:32:02 +00002688
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002689 bool Expr::EvalResult::isGlobalLValue() const {
2690 assert(Val.isLValue());
2691 return IsGlobalLValue(Val.getLValueBase());
2692 }
2693
2694
John McCalld905f5a2010-05-07 05:32:02 +00002695/// isIntegerConstantExpr - this recursive routine will test if an expression is
2696/// an integer constant expression.
2697
2698/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2699/// comma, etc
2700///
2701/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2702/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2703/// cast+dereference.
2704
2705// CheckICE - This function does the fundamental ICE checking: the returned
2706// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2707// Note that to reduce code duplication, this helper does no evaluation
2708// itself; the caller checks whether the expression is evaluatable, and
2709// in the rare cases where CheckICE actually cares about the evaluated
2710// value, it calls into Evalute.
2711//
2712// Meanings of Val:
2713// 0: This expression is an ICE if it can be evaluated by Evaluate.
2714// 1: This expression is not an ICE, but if it isn't evaluated, it's
2715// a legal subexpression for an ICE. This return value is used to handle
2716// the comma operator in C99 mode.
2717// 2: This expression is not an ICE, and is not a legal subexpression for one.
2718
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002719namespace {
2720
John McCalld905f5a2010-05-07 05:32:02 +00002721struct ICEDiag {
2722 unsigned Val;
2723 SourceLocation Loc;
2724
2725 public:
2726 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2727 ICEDiag() : Val(0) {}
2728};
2729
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002730}
2731
2732static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002733
2734static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2735 Expr::EvalResult EVResult;
2736 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2737 !EVResult.Val.isInt()) {
2738 return ICEDiag(2, E->getLocStart());
2739 }
2740 return NoDiag();
2741}
2742
2743static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2744 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002745 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002746 return ICEDiag(2, E->getLocStart());
2747 }
2748
2749 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002750#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002751#define STMT(Node, Base) case Expr::Node##Class:
2752#define EXPR(Node, Base)
2753#include "clang/AST/StmtNodes.inc"
2754 case Expr::PredefinedExprClass:
2755 case Expr::FloatingLiteralClass:
2756 case Expr::ImaginaryLiteralClass:
2757 case Expr::StringLiteralClass:
2758 case Expr::ArraySubscriptExprClass:
2759 case Expr::MemberExprClass:
2760 case Expr::CompoundAssignOperatorClass:
2761 case Expr::CompoundLiteralExprClass:
2762 case Expr::ExtVectorElementExprClass:
2763 case Expr::InitListExprClass:
2764 case Expr::DesignatedInitExprClass:
2765 case Expr::ImplicitValueInitExprClass:
2766 case Expr::ParenListExprClass:
2767 case Expr::VAArgExprClass:
2768 case Expr::AddrLabelExprClass:
2769 case Expr::StmtExprClass:
2770 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002771 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002772 case Expr::CXXDynamicCastExprClass:
2773 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002774 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002775 case Expr::CXXNullPtrLiteralExprClass:
2776 case Expr::CXXThisExprClass:
2777 case Expr::CXXThrowExprClass:
2778 case Expr::CXXNewExprClass:
2779 case Expr::CXXDeleteExprClass:
2780 case Expr::CXXPseudoDestructorExprClass:
2781 case Expr::UnresolvedLookupExprClass:
2782 case Expr::DependentScopeDeclRefExprClass:
2783 case Expr::CXXConstructExprClass:
2784 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002785 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002786 case Expr::CXXTemporaryObjectExprClass:
2787 case Expr::CXXUnresolvedConstructExprClass:
2788 case Expr::CXXDependentScopeMemberExprClass:
2789 case Expr::UnresolvedMemberExprClass:
2790 case Expr::ObjCStringLiteralClass:
2791 case Expr::ObjCEncodeExprClass:
2792 case Expr::ObjCMessageExprClass:
2793 case Expr::ObjCSelectorExprClass:
2794 case Expr::ObjCProtocolExprClass:
2795 case Expr::ObjCIvarRefExprClass:
2796 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002797 case Expr::ObjCIsaExprClass:
2798 case Expr::ShuffleVectorExprClass:
2799 case Expr::BlockExprClass:
2800 case Expr::BlockDeclRefExprClass:
2801 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002802 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002803 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002804 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002805 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002806 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002807 case Expr::MaterializeTemporaryExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002808 return ICEDiag(2, E->getLocStart());
2809
Douglas Gregoree8aff02011-01-04 17:33:58 +00002810 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002811 case Expr::GNUNullExprClass:
2812 // GCC considers the GNU __null value to be an integral constant expression.
2813 return NoDiag();
2814
2815 case Expr::ParenExprClass:
2816 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002817 case Expr::GenericSelectionExprClass:
2818 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002819 case Expr::IntegerLiteralClass:
2820 case Expr::CharacterLiteralClass:
2821 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002822 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002823 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002824 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002825 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002826 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002827 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002828 return NoDiag();
2829 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002830 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002831 const CallExpr *CE = cast<CallExpr>(E);
2832 if (CE->isBuiltinCall(Ctx))
2833 return CheckEvalInICE(E, Ctx);
2834 return ICEDiag(2, E->getLocStart());
2835 }
2836 case Expr::DeclRefExprClass:
2837 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2838 return NoDiag();
2839 if (Ctx.getLangOptions().CPlusPlus &&
2840 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2841 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2842
2843 // Parameter variables are never constants. Without this check,
2844 // getAnyInitializer() can find a default argument, which leads
2845 // to chaos.
2846 if (isa<ParmVarDecl>(D))
2847 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2848
2849 // C++ 7.1.5.1p2
2850 // A variable of non-volatile const-qualified integral or enumeration
2851 // type initialized by an ICE can be used in ICEs.
2852 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2853 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2854 if (Quals.hasVolatile() || !Quals.hasConst())
2855 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2856
2857 // Look for a declaration of this variable that has an initializer.
2858 const VarDecl *ID = 0;
2859 const Expr *Init = Dcl->getAnyInitializer(ID);
2860 if (Init) {
2861 if (ID->isInitKnownICE()) {
2862 // We have already checked whether this subexpression is an
2863 // integral constant expression.
2864 if (ID->isInitICE())
2865 return NoDiag();
2866 else
2867 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2868 }
2869
2870 // It's an ICE whether or not the definition we found is
2871 // out-of-line. See DR 721 and the discussion in Clang PR
2872 // 6206 for details.
2873
2874 if (Dcl->isCheckingICE()) {
2875 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2876 }
2877
2878 Dcl->setCheckingICE();
2879 ICEDiag Result = CheckICE(Init, Ctx);
2880 // Cache the result of the ICE test.
2881 Dcl->setInitKnownICE(Result.Val == 0);
2882 return Result;
2883 }
2884 }
2885 }
2886 return ICEDiag(2, E->getLocStart());
2887 case Expr::UnaryOperatorClass: {
2888 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2889 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002890 case UO_PostInc:
2891 case UO_PostDec:
2892 case UO_PreInc:
2893 case UO_PreDec:
2894 case UO_AddrOf:
2895 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002896 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002897 case UO_Extension:
2898 case UO_LNot:
2899 case UO_Plus:
2900 case UO_Minus:
2901 case UO_Not:
2902 case UO_Real:
2903 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002904 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002905 }
2906
2907 // OffsetOf falls through here.
2908 }
2909 case Expr::OffsetOfExprClass: {
2910 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2911 // Evaluate matches the proposed gcc behavior for cases like
2912 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2913 // compliance: we should warn earlier for offsetof expressions with
2914 // array subscripts that aren't ICEs, and if the array subscripts
2915 // are ICEs, the value of the offsetof must be an integer constant.
2916 return CheckEvalInICE(E, Ctx);
2917 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002918 case Expr::UnaryExprOrTypeTraitExprClass: {
2919 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2920 if ((Exp->getKind() == UETT_SizeOf) &&
2921 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002922 return ICEDiag(2, E->getLocStart());
2923 return NoDiag();
2924 }
2925 case Expr::BinaryOperatorClass: {
2926 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2927 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002928 case BO_PtrMemD:
2929 case BO_PtrMemI:
2930 case BO_Assign:
2931 case BO_MulAssign:
2932 case BO_DivAssign:
2933 case BO_RemAssign:
2934 case BO_AddAssign:
2935 case BO_SubAssign:
2936 case BO_ShlAssign:
2937 case BO_ShrAssign:
2938 case BO_AndAssign:
2939 case BO_XorAssign:
2940 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002941 return ICEDiag(2, E->getLocStart());
2942
John McCall2de56d12010-08-25 11:45:40 +00002943 case BO_Mul:
2944 case BO_Div:
2945 case BO_Rem:
2946 case BO_Add:
2947 case BO_Sub:
2948 case BO_Shl:
2949 case BO_Shr:
2950 case BO_LT:
2951 case BO_GT:
2952 case BO_LE:
2953 case BO_GE:
2954 case BO_EQ:
2955 case BO_NE:
2956 case BO_And:
2957 case BO_Xor:
2958 case BO_Or:
2959 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002960 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2961 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002962 if (Exp->getOpcode() == BO_Div ||
2963 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002964 // Evaluate gives an error for undefined Div/Rem, so make sure
2965 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00002966 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00002967 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2968 if (REval == 0)
2969 return ICEDiag(1, E->getLocStart());
2970 if (REval.isSigned() && REval.isAllOnesValue()) {
2971 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2972 if (LEval.isMinSignedValue())
2973 return ICEDiag(1, E->getLocStart());
2974 }
2975 }
2976 }
John McCall2de56d12010-08-25 11:45:40 +00002977 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002978 if (Ctx.getLangOptions().C99) {
2979 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2980 // if it isn't evaluated.
2981 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2982 return ICEDiag(1, E->getLocStart());
2983 } else {
2984 // In both C89 and C++, commas in ICEs are illegal.
2985 return ICEDiag(2, E->getLocStart());
2986 }
2987 }
2988 if (LHSResult.Val >= RHSResult.Val)
2989 return LHSResult;
2990 return RHSResult;
2991 }
John McCall2de56d12010-08-25 11:45:40 +00002992 case BO_LAnd:
2993 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002994 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00002995
2996 // C++0x [expr.const]p2:
2997 // [...] subexpressions of logical AND (5.14), logical OR
2998 // (5.15), and condi- tional (5.16) operations that are not
2999 // evaluated are not considered.
3000 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3001 if (Exp->getOpcode() == BO_LAnd &&
3002 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
3003 return LHSResult;
3004
3005 if (Exp->getOpcode() == BO_LOr &&
3006 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
3007 return LHSResult;
3008 }
3009
John McCalld905f5a2010-05-07 05:32:02 +00003010 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3011 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3012 // Rare case where the RHS has a comma "side-effect"; we need
3013 // to actually check the condition to see whether the side
3014 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003015 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003016 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3017 return RHSResult;
3018 return NoDiag();
3019 }
3020
3021 if (LHSResult.Val >= RHSResult.Val)
3022 return LHSResult;
3023 return RHSResult;
3024 }
3025 }
3026 }
3027 case Expr::ImplicitCastExprClass:
3028 case Expr::CStyleCastExprClass:
3029 case Expr::CXXFunctionalCastExprClass:
3030 case Expr::CXXStaticCastExprClass:
3031 case Expr::CXXReinterpretCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003032 case Expr::CXXConstCastExprClass:
3033 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003034 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003035 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003036 return CheckICE(SubExpr, Ctx);
3037 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3038 return NoDiag();
3039 return ICEDiag(2, E->getLocStart());
3040 }
John McCall56ca35d2011-02-17 10:25:35 +00003041 case Expr::BinaryConditionalOperatorClass: {
3042 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3043 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3044 if (CommonResult.Val == 2) return CommonResult;
3045 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3046 if (FalseResult.Val == 2) return FalseResult;
3047 if (CommonResult.Val == 1) return CommonResult;
3048 if (FalseResult.Val == 1 &&
3049 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3050 return FalseResult;
3051 }
John McCalld905f5a2010-05-07 05:32:02 +00003052 case Expr::ConditionalOperatorClass: {
3053 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3054 // If the condition (ignoring parens) is a __builtin_constant_p call,
3055 // then only the true side is actually considered in an integer constant
3056 // expression, and it is fully evaluated. This is an important GNU
3057 // extension. See GCC PR38377 for discussion.
3058 if (const CallExpr *CallCE
3059 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3060 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3061 Expr::EvalResult EVResult;
3062 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3063 !EVResult.Val.isInt()) {
3064 return ICEDiag(2, E->getLocStart());
3065 }
3066 return NoDiag();
3067 }
3068 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003069 if (CondResult.Val == 2)
3070 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003071
3072 // C++0x [expr.const]p2:
3073 // subexpressions of [...] conditional (5.16) operations that
3074 // are not evaluated are not considered
3075 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3076 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3077 : false;
3078 ICEDiag TrueResult = NoDiag();
3079 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3080 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3081 ICEDiag FalseResult = NoDiag();
3082 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3083 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3084
John McCalld905f5a2010-05-07 05:32:02 +00003085 if (TrueResult.Val == 2)
3086 return TrueResult;
3087 if (FalseResult.Val == 2)
3088 return FalseResult;
3089 if (CondResult.Val == 1)
3090 return CondResult;
3091 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3092 return NoDiag();
3093 // Rare case where the diagnostics depend on which side is evaluated
3094 // Note that if we get here, CondResult is 0, and at least one of
3095 // TrueResult and FalseResult is non-zero.
3096 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3097 return FalseResult;
3098 }
3099 return TrueResult;
3100 }
3101 case Expr::CXXDefaultArgExprClass:
3102 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3103 case Expr::ChooseExprClass: {
3104 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3105 }
3106 }
3107
3108 // Silence a GCC warning
3109 return ICEDiag(2, E->getLocStart());
3110}
3111
3112bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3113 SourceLocation *Loc, bool isEvaluated) const {
3114 ICEDiag d = CheckICE(this, Ctx);
3115 if (d.Val != 0) {
3116 if (Loc) *Loc = d.Loc;
3117 return false;
3118 }
3119 EvalResult EvalResult;
3120 if (!Evaluate(EvalResult, Ctx))
3121 llvm_unreachable("ICE cannot be evaluated!");
3122 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3123 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3124 Result = EvalResult.Val.getInt();
3125 return true;
3126}