blob: cc8c50198cbdba3aef30f8ef85ce6eea51cfd9ac [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 Friedman82905742011-07-07 01:54:01 +0000539 unsigned i = FD->getFieldIndex();
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000540 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000541 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000542}
543
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000544bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000545 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000546 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Anders Carlsson3068d112008-11-16 19:01:22 +0000548 APSInt Index;
549 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000550 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000551
Ken Dyck199c3d62010-01-11 17:06:35 +0000552 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000553 Result.Offset += Index.getSExtValue() * ElementSize;
554 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000555}
Eli Friedman4efaa272008-11-12 09:44:48 +0000556
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000557bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000558 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000559}
560
Eli Friedman4efaa272008-11-12 09:44:48 +0000561//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000562// Pointer Evaluation
563//===----------------------------------------------------------------------===//
564
Anders Carlssonc754aa62008-07-08 05:13:58 +0000565namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000566class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000567 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000568 LValue &Result;
569
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000570 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000571 Result.Base = E;
572 Result.Offset = CharUnits::Zero();
573 return true;
574 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000575public:
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCallefdb83e2010-05-07 21:00:08 +0000577 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000578 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000579
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000580 bool Success(const APValue &V, const Expr *E) {
581 Result.setFrom(V);
582 return true;
583 }
584 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000585 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000586 }
587
John McCallefdb83e2010-05-07 21:00:08 +0000588 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000589 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000590 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000591 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000592 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000593 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000594 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000595 bool VisitCallExpr(const CallExpr *E);
596 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000597 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000598 return Success(E);
599 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000600 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000601 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000602 { return Success((Expr*)0); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000603 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000604 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000605
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000606 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000607};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000608} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000609
John McCallefdb83e2010-05-07 21:00:08 +0000610static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000611 assert(E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000612 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000613}
614
John McCallefdb83e2010-05-07 21:00:08 +0000615bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000616 if (E->getOpcode() != BO_Add &&
617 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000618 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000620 const Expr *PExp = E->getLHS();
621 const Expr *IExp = E->getRHS();
622 if (IExp->getType()->isPointerType())
623 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000624
John McCallefdb83e2010-05-07 21:00:08 +0000625 if (!EvaluatePointer(PExp, Result, Info))
626 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000627
John McCallefdb83e2010-05-07 21:00:08 +0000628 llvm::APSInt Offset;
629 if (!EvaluateInteger(IExp, Offset, Info))
630 return false;
631 int64_t AdditionalOffset
632 = Offset.isSigned() ? Offset.getSExtValue()
633 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000634
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000635 // Compute the new offset in the appropriate width.
636
637 QualType PointeeType =
638 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000639 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000641 // Explicitly handle GNU void* and function pointer arithmetic extensions.
642 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000643 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000644 else
John McCallefdb83e2010-05-07 21:00:08 +0000645 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000646
John McCall2de56d12010-08-25 11:45:40 +0000647 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000648 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000649 else
John McCallefdb83e2010-05-07 21:00:08 +0000650 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000651
John McCallefdb83e2010-05-07 21:00:08 +0000652 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000653}
Eli Friedman4efaa272008-11-12 09:44:48 +0000654
John McCallefdb83e2010-05-07 21:00:08 +0000655bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
656 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000657}
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000659
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000660bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
661 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000662
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000663 switch (E->getCastKind()) {
664 default:
665 break;
666
John McCall2de56d12010-08-25 11:45:40 +0000667 case CK_NoOp:
668 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000669 case CK_AnyPointerToObjCPointerCast:
670 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000671 return Visit(SubExpr);
672
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000673 case CK_DerivedToBase:
674 case CK_UncheckedDerivedToBase: {
675 LValue BaseLV;
676 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
677 return false;
678
679 // Now figure out the necessary offset to add to the baseLV to get from
680 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000681 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000682
683 QualType Ty = E->getSubExpr()->getType();
684 const CXXRecordDecl *DerivedDecl =
685 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
686
687 for (CastExpr::path_const_iterator PathI = E->path_begin(),
688 PathE = E->path_end(); PathI != PathE; ++PathI) {
689 const CXXBaseSpecifier *Base = *PathI;
690
691 // FIXME: If the base is virtual, we'd need to determine the type of the
692 // most derived class and we don't support that right now.
693 if (Base->isVirtual())
694 return false;
695
696 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
697 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
698
Ken Dyck7c7f8202011-01-26 02:17:08 +0000699 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000700 DerivedDecl = BaseDecl;
701 }
702
703 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000704 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000705 return true;
706 }
707
John McCall404cd162010-11-13 01:35:44 +0000708 case CK_NullToPointer: {
709 Result.Base = 0;
710 Result.Offset = CharUnits::Zero();
711 return true;
712 }
713
John McCall2de56d12010-08-25 11:45:40 +0000714 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000715 APValue Value;
716 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000717 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000718
John McCallefdb83e2010-05-07 21:00:08 +0000719 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000720 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000721 Result.Base = 0;
722 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
723 return true;
724 } else {
725 // Cast is of an lvalue, no need to change value.
726 Result.Base = Value.getLValueBase();
727 Result.Offset = Value.getLValueOffset();
728 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000729 }
730 }
John McCall2de56d12010-08-25 11:45:40 +0000731 case CK_ArrayToPointerDecay:
732 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000733 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000734 }
735
John McCallefdb83e2010-05-07 21:00:08 +0000736 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000737}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000738
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000739bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000740 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000741 Builtin::BI__builtin___CFStringMakeConstantString ||
742 E->isBuiltinCall(Info.Ctx) ==
743 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000744 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000745
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000746 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000747}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000748
749//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000750// Vector Evaluation
751//===----------------------------------------------------------------------===//
752
753namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000754 class VectorExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000755 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman91110ee2009-02-23 04:23:56 +0000756 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000757 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000759 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000761 APValue Success(const APValue &V, const Expr *E) { return V; }
762 APValue Error(const Expr *E) { return APValue(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Eli Friedman91110ee2009-02-23 04:23:56 +0000764 APValue VisitUnaryReal(const UnaryOperator *E)
765 { return Visit(E->getSubExpr()); }
766 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
767 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000768 APValue VisitCastExpr(const CastExpr* E);
769 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
770 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000771 APValue VisitUnaryImag(const UnaryOperator *E);
772 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000773 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000774 // shufflevector, ExtVectorElementExpr
775 // (Note that these require implementing conversions
776 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000777 };
778} // end anonymous namespace
779
780static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
781 if (!E->getType()->isVectorType())
782 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000783 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000784 return !Result.isUninit();
785}
786
787APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000788 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000789 QualType EltTy = VTy->getElementType();
790 unsigned NElts = VTy->getNumElements();
791 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Nate Begeman59b5da62009-01-18 03:20:47 +0000793 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000794 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000795
Eli Friedman46a52322011-03-25 00:43:55 +0000796 switch (E->getCastKind()) {
797 case CK_VectorSplat: {
798 APValue Result = APValue();
799 if (SETy->isIntegerType()) {
800 APSInt IntResult;
801 if (!EvaluateInteger(SE, IntResult, Info))
802 return APValue();
803 Result = APValue(IntResult);
804 } else if (SETy->isRealFloatingType()) {
805 APFloat F(0.0);
806 if (!EvaluateFloat(SE, F, Info))
807 return APValue();
808 Result = APValue(F);
809 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000810 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000811 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000812
813 // Splat and create vector APValue.
814 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
815 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000816 }
Eli Friedman46a52322011-03-25 00:43:55 +0000817 case CK_BitCast: {
818 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000819 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000820
Eli Friedman46a52322011-03-25 00:43:55 +0000821 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000822 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Eli Friedman46a52322011-03-25 00:43:55 +0000824 APSInt Init;
825 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000826 return APValue();
827
Eli Friedman46a52322011-03-25 00:43:55 +0000828 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
829 "Vectors must be composed of ints or floats");
830
831 llvm::SmallVector<APValue, 4> Elts;
832 for (unsigned i = 0; i != NElts; ++i) {
833 APSInt Tmp = Init.extOrTrunc(EltWidth);
834
835 if (EltTy->isIntegerType())
836 Elts.push_back(APValue(Tmp));
837 else
838 Elts.push_back(APValue(APFloat(Tmp)));
839
840 Init >>= EltWidth;
841 }
842 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000843 }
Eli Friedman46a52322011-03-25 00:43:55 +0000844 case CK_LValueToRValue:
845 case CK_NoOp:
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000846 return Visit(SE);
Eli Friedman46a52322011-03-25 00:43:55 +0000847 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000848 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000849 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000850}
851
Mike Stump1eb44332009-09-09 15:08:12 +0000852APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000853VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000854 return this->Visit(E->getInitializer());
Nate Begeman59b5da62009-01-18 03:20:47 +0000855}
856
Mike Stump1eb44332009-09-09 15:08:12 +0000857APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000858VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000859 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000860 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000861 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Nate Begeman59b5da62009-01-18 03:20:47 +0000863 QualType EltTy = VT->getElementType();
864 llvm::SmallVector<APValue, 4> Elements;
865
John McCalla7d6c222010-06-11 17:54:15 +0000866 // If a vector is initialized with a single element, that value
867 // becomes every element of the vector, not just the first.
868 // This is the behavior described in the IBM AltiVec documentation.
869 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000870
871 // Handle the case where the vector is initialized by a another
872 // vector (OpenCL 6.1.6).
873 if (E->getInit(0)->getType()->isVectorType())
874 return this->Visit(const_cast<Expr*>(E->getInit(0)));
875
John McCalla7d6c222010-06-11 17:54:15 +0000876 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000877 if (EltTy->isIntegerType()) {
878 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000879 if (!EvaluateInteger(E->getInit(0), sInt, Info))
880 return APValue();
881 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000882 } else {
883 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000884 if (!EvaluateFloat(E->getInit(0), f, Info))
885 return APValue();
886 InitValue = APValue(f);
887 }
888 for (unsigned i = 0; i < NumElements; i++) {
889 Elements.push_back(InitValue);
890 }
891 } else {
892 for (unsigned i = 0; i < NumElements; i++) {
893 if (EltTy->isIntegerType()) {
894 llvm::APSInt sInt(32);
895 if (i < NumInits) {
896 if (!EvaluateInteger(E->getInit(i), sInt, Info))
897 return APValue();
898 } else {
899 sInt = Info.Ctx.MakeIntValue(0, EltTy);
900 }
901 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000902 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000903 llvm::APFloat f(0.0);
904 if (i < NumInits) {
905 if (!EvaluateFloat(E->getInit(i), f, Info))
906 return APValue();
907 } else {
908 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
909 }
910 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000911 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000912 }
913 }
914 return APValue(&Elements[0], Elements.size());
915}
916
Mike Stump1eb44332009-09-09 15:08:12 +0000917APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000918VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000919 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000920 QualType EltTy = VT->getElementType();
921 APValue ZeroElement;
922 if (EltTy->isIntegerType())
923 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
924 else
925 ZeroElement =
926 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
927
928 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
929 return APValue(&Elements[0], Elements.size());
930}
931
Eli Friedman91110ee2009-02-23 04:23:56 +0000932APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
933 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
934 Info.EvalResult.HasSideEffects = true;
935 return GetZeroVector(E->getType());
936}
937
Nate Begeman59b5da62009-01-18 03:20:47 +0000938//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000939// Integer Evaluation
940//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000941
942namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000943class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000944 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000945 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000946public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000947 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000948 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000949
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000950 bool Success(const llvm::APSInt &SI, const Expr *E) {
951 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000952 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000953 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000954 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000955 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000956 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000957 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000958 return true;
959 }
960
Daniel Dunbar131eb432009-02-19 09:06:44 +0000961 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000962 assert(E->getType()->isIntegralOrEnumerationType() &&
963 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000964 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000965 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000966 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +0000967 Result.getInt().setIsUnsigned(
968 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000969 return true;
970 }
971
972 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000973 assert(E->getType()->isIntegralOrEnumerationType() &&
974 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000975 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000976 return true;
977 }
978
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000979 bool Success(CharUnits Size, const Expr *E) {
980 return Success(Size.getQuantity(), E);
981 }
982
983
Anders Carlsson82206e22008-11-30 18:14:57 +0000984 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000985 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000986 if (Info.EvalResult.Diag == 0) {
987 Info.EvalResult.DiagLoc = L;
988 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000989 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000990 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000991 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000994 bool Success(const APValue &V, const Expr *E) {
995 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +0000996 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000997 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000998 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000999 }
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001001 //===--------------------------------------------------------------------===//
1002 // Visitor Methods
1003 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001004
Chris Lattner4c4867e2008-07-12 00:38:25 +00001005 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001006 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001007 }
1008 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001009 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001010 }
Eli Friedman04309752009-11-24 05:28:59 +00001011
1012 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1013 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001014 if (CheckReferencedDecl(E, E->getDecl()))
1015 return true;
1016
1017 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001018 }
1019 bool VisitMemberExpr(const MemberExpr *E) {
1020 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1021 // Conservatively assume a MemberExpr will have side-effects
1022 Info.EvalResult.HasSideEffects = true;
1023 return true;
1024 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001025
1026 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001027 }
1028
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001029 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001030 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001031 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001032 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001033
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001034 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001035 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001036
Anders Carlsson3068d112008-11-16 19:01:22 +00001037 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001038 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001039 }
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Anders Carlsson3f704562008-12-21 22:39:40 +00001041 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001042 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001043 }
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Douglas Gregored8abf12010-07-08 06:14:04 +00001045 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001046 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001047 }
1048
Eli Friedman664a1042009-02-27 04:45:43 +00001049 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1050 return Success(0, E);
1051 }
1052
Sebastian Redl64b45f72009-01-05 20:52:13 +00001053 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001054 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001055 }
1056
Francois Pichet6ad6f282010-12-07 00:08:36 +00001057 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1058 return Success(E->getValue(), E);
1059 }
1060
John Wiegley21ff2e52011-04-28 00:16:57 +00001061 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1062 return Success(E->getValue(), E);
1063 }
1064
John Wiegley55262202011-04-25 06:54:41 +00001065 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1066 return Success(E->getValue(), E);
1067 }
1068
Eli Friedman722c7172009-02-28 03:59:05 +00001069 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001070 bool VisitUnaryImag(const UnaryOperator *E);
1071
Sebastian Redl295995c2010-09-10 20:55:47 +00001072 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001073 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1074
Chris Lattnerfcee0012008-07-11 21:24:13 +00001075private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001076 CharUnits GetAlignOfExpr(const Expr *E);
1077 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001078 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001079 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001080 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001081};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001082} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001083
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001084static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001085 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001086 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001087}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001088
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001089static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001090 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001091
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001092 APValue Val;
1093 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1094 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001095 Result = Val.getInt();
1096 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001097}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001098
Eli Friedman04309752009-11-24 05:28:59 +00001099bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001100 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001101 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001102 // Check for signedness/width mismatches between E type and ECD value.
1103 bool SameSign = (ECD->getInitVal().isSigned()
1104 == E->getType()->isSignedIntegerOrEnumerationType());
1105 bool SameWidth = (ECD->getInitVal().getBitWidth()
1106 == Info.Ctx.getIntWidth(E->getType()));
1107 if (SameSign && SameWidth)
1108 return Success(ECD->getInitVal(), E);
1109 else {
1110 // Get rid of mismatch (otherwise Success assertions will fail)
1111 // by computing a new value matching the type of E.
1112 llvm::APSInt Val = ECD->getInitVal();
1113 if (!SameSign)
1114 Val.setIsSigned(!ECD->getInitVal().isSigned());
1115 if (!SameWidth)
1116 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1117 return Success(Val, E);
1118 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001119 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001120
1121 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001122 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001123 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1124 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001125
1126 if (isa<ParmVarDecl>(D))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001127 return false;
Anders Carlssonf6b60252010-02-03 21:58:41 +00001128
Eli Friedman04309752009-11-24 05:28:59 +00001129 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001130 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001131 if (APValue *V = VD->getEvaluatedValue()) {
1132 if (V->isInt())
1133 return Success(V->getInt(), E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001134 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001135 }
1136
1137 if (VD->isEvaluatingValue())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001138 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001139
1140 VD->setEvaluatingValue();
1141
Eli Friedmana7dedf72010-09-06 00:10:32 +00001142 Expr::EvalResult EResult;
1143 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1144 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001145 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001146 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001147 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001148 return true;
1149 }
1150
Eli Friedmanc0131182009-12-03 20:31:57 +00001151 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001152 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001153 }
1154 }
1155
Chris Lattner4c4867e2008-07-12 00:38:25 +00001156 // Otherwise, random variable references are not constants.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001157 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001158}
1159
Chris Lattnera4d55d82008-10-06 06:40:35 +00001160/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1161/// as GCC.
1162static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1163 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001164 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001165 enum gcc_type_class {
1166 no_type_class = -1,
1167 void_type_class, integer_type_class, char_type_class,
1168 enumeral_type_class, boolean_type_class,
1169 pointer_type_class, reference_type_class, offset_type_class,
1170 real_type_class, complex_type_class,
1171 function_type_class, method_type_class,
1172 record_type_class, union_type_class,
1173 array_type_class, string_type_class,
1174 lang_type_class
1175 };
Mike Stump1eb44332009-09-09 15:08:12 +00001176
1177 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001178 // ideal, however it is what gcc does.
1179 if (E->getNumArgs() == 0)
1180 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Chris Lattnera4d55d82008-10-06 06:40:35 +00001182 QualType ArgTy = E->getArg(0)->getType();
1183 if (ArgTy->isVoidType())
1184 return void_type_class;
1185 else if (ArgTy->isEnumeralType())
1186 return enumeral_type_class;
1187 else if (ArgTy->isBooleanType())
1188 return boolean_type_class;
1189 else if (ArgTy->isCharType())
1190 return string_type_class; // gcc doesn't appear to use char_type_class
1191 else if (ArgTy->isIntegerType())
1192 return integer_type_class;
1193 else if (ArgTy->isPointerType())
1194 return pointer_type_class;
1195 else if (ArgTy->isReferenceType())
1196 return reference_type_class;
1197 else if (ArgTy->isRealType())
1198 return real_type_class;
1199 else if (ArgTy->isComplexType())
1200 return complex_type_class;
1201 else if (ArgTy->isFunctionType())
1202 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001203 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001204 return record_type_class;
1205 else if (ArgTy->isUnionType())
1206 return union_type_class;
1207 else if (ArgTy->isArrayType())
1208 return array_type_class;
1209 else if (ArgTy->isUnionType())
1210 return union_type_class;
1211 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1212 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1213 return -1;
1214}
1215
John McCall42c8f872010-05-10 23:27:23 +00001216/// Retrieves the "underlying object type" of the given expression,
1217/// as used by __builtin_object_size.
1218QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1219 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1220 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1221 return VD->getType();
1222 } else if (isa<CompoundLiteralExpr>(E)) {
1223 return E->getType();
1224 }
1225
1226 return QualType();
1227}
1228
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001229bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001230 // TODO: Perhaps we should let LLVM lower this?
1231 LValue Base;
1232 if (!EvaluatePointer(E->getArg(0), Base, Info))
1233 return false;
1234
1235 // If we can prove the base is null, lower to zero now.
1236 const Expr *LVBase = Base.getLValueBase();
1237 if (!LVBase) return Success(0, E);
1238
1239 QualType T = GetObjectType(LVBase);
1240 if (T.isNull() ||
1241 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001242 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001243 T->isVariablyModifiedType() ||
1244 T->isDependentType())
1245 return false;
1246
1247 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1248 CharUnits Offset = Base.getLValueOffset();
1249
1250 if (!Offset.isNegative() && Offset <= Size)
1251 Size -= Offset;
1252 else
1253 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001254 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001255}
1256
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001257bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001258 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001259 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001260 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001261
1262 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001263 if (TryEvaluateBuiltinObjectSize(E))
1264 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001265
Eric Christopherb2aaf512010-01-19 22:58:35 +00001266 // If evaluating the argument has side-effects we can't determine
1267 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001268 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001269 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001270 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001271 return Success(0, E);
1272 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001273
Mike Stump64eda9e2009-10-26 18:35:08 +00001274 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1275 }
1276
Chris Lattner019f4e82008-10-06 05:28:25 +00001277 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001278 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001280 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001281 // __builtin_constant_p always has one operand: it returns true if that
1282 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001283 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001284
1285 case Builtin::BI__builtin_eh_return_data_regno: {
1286 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1287 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1288 return Success(Operand, E);
1289 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001290
1291 case Builtin::BI__builtin_expect:
1292 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001293
1294 case Builtin::BIstrlen:
1295 case Builtin::BI__builtin_strlen:
1296 // As an extension, we support strlen() and __builtin_strlen() as constant
1297 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001298 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001299 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1300 // The string literal may have embedded null characters. Find the first
1301 // one and truncate there.
1302 llvm::StringRef Str = S->getString();
1303 llvm::StringRef::size_type Pos = Str.find(0);
1304 if (Pos != llvm::StringRef::npos)
1305 Str = Str.substr(0, Pos);
1306
1307 return Success(Str.size(), E);
1308 }
1309
1310 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001311 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001312}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001313
Chris Lattnerb542afe2008-07-11 19:10:17 +00001314bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001315 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001316 if (!Visit(E->getRHS()))
1317 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001318
Eli Friedman33ef1452009-02-26 10:19:36 +00001319 // If we can't evaluate the LHS, it might have side effects;
1320 // conservatively mark it.
1321 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1322 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001323
Anders Carlsson027f62e2008-12-01 02:07:06 +00001324 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001325 }
1326
1327 if (E->isLogicalOp()) {
1328 // These need to be handled specially because the operands aren't
1329 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001330 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001332 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001333 // We were able to evaluate the LHS, see if we can get away with not
1334 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001335 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001336 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001337
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001338 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001339 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001340 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001341 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001342 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001343 }
1344 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001345 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001346 // We can't evaluate the LHS; however, sometimes the result
1347 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001348 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1349 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001350 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001351 // must have had side effects.
1352 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001353
1354 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001355 }
1356 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001357 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001358
Eli Friedmana6afa762008-11-13 06:09:17 +00001359 return false;
1360 }
1361
Anders Carlsson286f85e2008-11-16 07:17:21 +00001362 QualType LHSTy = E->getLHS()->getType();
1363 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001364
1365 if (LHSTy->isAnyComplexType()) {
1366 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001367 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001368
1369 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1370 return false;
1371
1372 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1373 return false;
1374
1375 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001376 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001377 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001378 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001379 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1380
John McCall2de56d12010-08-25 11:45:40 +00001381 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001382 return Success((CR_r == APFloat::cmpEqual &&
1383 CR_i == APFloat::cmpEqual), E);
1384 else {
John McCall2de56d12010-08-25 11:45:40 +00001385 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001386 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001387 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001388 CR_r == APFloat::cmpLessThan ||
1389 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001390 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001391 CR_i == APFloat::cmpLessThan ||
1392 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001393 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001394 } else {
John McCall2de56d12010-08-25 11:45:40 +00001395 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001396 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1397 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1398 else {
John McCall2de56d12010-08-25 11:45:40 +00001399 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001400 "Invalid compex comparison.");
1401 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1402 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1403 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001404 }
1405 }
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Anders Carlsson286f85e2008-11-16 07:17:21 +00001407 if (LHSTy->isRealFloatingType() &&
1408 RHSTy->isRealFloatingType()) {
1409 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Anders Carlsson286f85e2008-11-16 07:17:21 +00001411 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1412 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Anders Carlsson286f85e2008-11-16 07:17:21 +00001414 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1415 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Anders Carlsson286f85e2008-11-16 07:17:21 +00001417 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001418
Anders Carlsson286f85e2008-11-16 07:17:21 +00001419 switch (E->getOpcode()) {
1420 default:
1421 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001422 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001423 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001424 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001425 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001426 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001427 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001428 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001429 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001430 E);
John McCall2de56d12010-08-25 11:45:40 +00001431 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001432 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001433 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001434 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001435 || CR == APFloat::cmpLessThan
1436 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001437 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001440 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001441 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001442 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001443 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1444 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001445
John McCallefdb83e2010-05-07 21:00:08 +00001446 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001447 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1448 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001449
Eli Friedman5bc86102009-06-14 02:17:33 +00001450 // Reject any bases from the normal codepath; we special-case comparisons
1451 // to null.
1452 if (LHSValue.getLValueBase()) {
1453 if (!E->isEqualityOp())
1454 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001455 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001456 return false;
1457 bool bres;
1458 if (!EvalPointerValueAsBool(LHSValue, bres))
1459 return false;
John McCall2de56d12010-08-25 11:45:40 +00001460 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001461 } else if (RHSValue.getLValueBase()) {
1462 if (!E->isEqualityOp())
1463 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001464 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001465 return false;
1466 bool bres;
1467 if (!EvalPointerValueAsBool(RHSValue, bres))
1468 return false;
John McCall2de56d12010-08-25 11:45:40 +00001469 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001470 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001471
John McCall2de56d12010-08-25 11:45:40 +00001472 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001473 QualType Type = E->getLHS()->getType();
1474 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001475
Ken Dycka7305832010-01-15 12:37:54 +00001476 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001477 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001478 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001479
Ken Dycka7305832010-01-15 12:37:54 +00001480 CharUnits Diff = LHSValue.getLValueOffset() -
1481 RHSValue.getLValueOffset();
1482 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001483 }
1484 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001485 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001486 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001487 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001488 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1489 }
1490 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001491 }
1492 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001493 if (!LHSTy->isIntegralOrEnumerationType() ||
1494 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001495 // We can't continue from here for non-integral types, and they
1496 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001497 return false;
1498 }
1499
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001500 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001501 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001502 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001503
Eli Friedman42edd0d2009-03-24 01:14:50 +00001504 APValue RHSVal;
1505 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001506 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001507
1508 // Handle cases like (unsigned long)&a + 4.
1509 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001510 CharUnits Offset = Result.getLValueOffset();
1511 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1512 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001513 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001514 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001515 else
Ken Dycka7305832010-01-15 12:37:54 +00001516 Offset -= AdditionalOffset;
1517 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001518 return true;
1519 }
1520
1521 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001522 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001523 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001524 CharUnits Offset = RHSVal.getLValueOffset();
1525 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1526 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001527 return true;
1528 }
1529
1530 // All the following cases expect both operands to be an integer
1531 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001532 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001533
Eli Friedman42edd0d2009-03-24 01:14:50 +00001534 APSInt& RHS = RHSVal.getInt();
1535
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001536 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001537 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001538 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001539 case BO_Mul: return Success(Result.getInt() * RHS, E);
1540 case BO_Add: return Success(Result.getInt() + RHS, E);
1541 case BO_Sub: return Success(Result.getInt() - RHS, E);
1542 case BO_And: return Success(Result.getInt() & RHS, E);
1543 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1544 case BO_Or: return Success(Result.getInt() | RHS, E);
1545 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001546 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001547 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001548 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001549 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001550 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001551 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001552 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001553 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001554 // During constant-folding, a negative shift is an opposite shift.
1555 if (RHS.isSigned() && RHS.isNegative()) {
1556 RHS = -RHS;
1557 goto shift_right;
1558 }
1559
1560 shift_left:
1561 unsigned SA
1562 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001563 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001564 }
John McCall2de56d12010-08-25 11:45:40 +00001565 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001566 // During constant-folding, a negative shift is an opposite shift.
1567 if (RHS.isSigned() && RHS.isNegative()) {
1568 RHS = -RHS;
1569 goto shift_left;
1570 }
1571
1572 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001573 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001574 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1575 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
John McCall2de56d12010-08-25 11:45:40 +00001578 case BO_LT: return Success(Result.getInt() < RHS, E);
1579 case BO_GT: return Success(Result.getInt() > RHS, E);
1580 case BO_LE: return Success(Result.getInt() <= RHS, E);
1581 case BO_GE: return Success(Result.getInt() >= RHS, E);
1582 case BO_EQ: return Success(Result.getInt() == RHS, E);
1583 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001584 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001585}
1586
Ken Dyck8b752f12010-01-27 17:10:57 +00001587CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001588 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1589 // the result is the size of the referenced type."
1590 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1591 // result shall be the alignment of the referenced type."
1592 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1593 T = Ref->getPointeeType();
1594
Eli Friedman2be58612009-05-30 21:09:44 +00001595 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001596 return Info.Ctx.toCharUnitsFromBits(
1597 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001598}
1599
Ken Dyck8b752f12010-01-27 17:10:57 +00001600CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001601 E = E->IgnoreParens();
1602
1603 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001604 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001605 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001606 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1607 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001608
Chris Lattneraf707ab2009-01-24 21:53:27 +00001609 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001610 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1611 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001612
Chris Lattnere9feb472009-01-24 21:09:06 +00001613 return GetAlignOfType(E->getType());
1614}
1615
1616
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001617/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1618/// a result as the expression's type.
1619bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1620 const UnaryExprOrTypeTraitExpr *E) {
1621 switch(E->getKind()) {
1622 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001623 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001624 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001625 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001626 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001627 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001628
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001629 case UETT_VecStep: {
1630 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001631
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001632 if (Ty->isVectorType()) {
1633 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001634
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001635 // The vec_step built-in functions that take a 3-component
1636 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1637 if (n == 3)
1638 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001639
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001640 return Success(n, E);
1641 } else
1642 return Success(1, E);
1643 }
1644
1645 case UETT_SizeOf: {
1646 QualType SrcTy = E->getTypeOfArgument();
1647 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1648 // the result is the size of the referenced type."
1649 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1650 // result shall be the alignment of the referenced type."
1651 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1652 SrcTy = Ref->getPointeeType();
1653
1654 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1655 // extension.
1656 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1657 return Success(1, E);
1658
1659 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1660 if (!SrcTy->isConstantSizeType())
1661 return false;
1662
1663 // Get information about the size.
1664 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1665 }
1666 }
1667
1668 llvm_unreachable("unknown expr/type trait");
1669 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001670}
1671
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001672bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001673 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001674 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001675 if (n == 0)
1676 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001677 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001678 for (unsigned i = 0; i != n; ++i) {
1679 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1680 switch (ON.getKind()) {
1681 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001682 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001683 APSInt IdxResult;
1684 if (!EvaluateInteger(Idx, IdxResult, Info))
1685 return false;
1686 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1687 if (!AT)
1688 return false;
1689 CurrentType = AT->getElementType();
1690 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1691 Result += IdxResult.getSExtValue() * ElementSize;
1692 break;
1693 }
1694
1695 case OffsetOfExpr::OffsetOfNode::Field: {
1696 FieldDecl *MemberDecl = ON.getField();
1697 const RecordType *RT = CurrentType->getAs<RecordType>();
1698 if (!RT)
1699 return false;
1700 RecordDecl *RD = RT->getDecl();
1701 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001702 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001703 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001704 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001705 CurrentType = MemberDecl->getType().getNonReferenceType();
1706 break;
1707 }
1708
1709 case OffsetOfExpr::OffsetOfNode::Identifier:
1710 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001711 return false;
1712
1713 case OffsetOfExpr::OffsetOfNode::Base: {
1714 CXXBaseSpecifier *BaseSpec = ON.getBase();
1715 if (BaseSpec->isVirtual())
1716 return false;
1717
1718 // Find the layout of the class whose base we are looking into.
1719 const RecordType *RT = CurrentType->getAs<RecordType>();
1720 if (!RT)
1721 return false;
1722 RecordDecl *RD = RT->getDecl();
1723 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1724
1725 // Find the base class itself.
1726 CurrentType = BaseSpec->getType();
1727 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1728 if (!BaseRT)
1729 return false;
1730
1731 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001732 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001733 break;
1734 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001735 }
1736 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001737 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001738}
1739
Chris Lattnerb542afe2008-07-11 19:10:17 +00001740bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001741 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001742 // LNot's operand isn't necessarily an integer, so we handle it specially.
1743 bool bres;
1744 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1745 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001746 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001747 }
1748
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001749 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001750 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001751 return false;
1752
Chris Lattner87eae5e2008-07-11 22:52:41 +00001753 // Get the operand value into 'Result'.
1754 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001755 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001756
Chris Lattner75a48812008-07-11 22:15:16 +00001757 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001758 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001759 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1760 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001761 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001762 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001763 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1764 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001765 return true;
John McCall2de56d12010-08-25 11:45:40 +00001766 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001767 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001768 return true;
John McCall2de56d12010-08-25 11:45:40 +00001769 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001770 if (!Result.isInt()) return false;
1771 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001772 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001773 if (!Result.isInt()) return false;
1774 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001775 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001776}
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Chris Lattner732b2232008-07-12 01:15:53 +00001778/// HandleCast - This is used to evaluate implicit or explicit casts where the
1779/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001780bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1781 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001782 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001783 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001784
Eli Friedman46a52322011-03-25 00:43:55 +00001785 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001786 case CK_BaseToDerived:
1787 case CK_DerivedToBase:
1788 case CK_UncheckedDerivedToBase:
1789 case CK_Dynamic:
1790 case CK_ToUnion:
1791 case CK_ArrayToPointerDecay:
1792 case CK_FunctionToPointerDecay:
1793 case CK_NullToPointer:
1794 case CK_NullToMemberPointer:
1795 case CK_BaseToDerivedMemberPointer:
1796 case CK_DerivedToBaseMemberPointer:
1797 case CK_ConstructorConversion:
1798 case CK_IntegralToPointer:
1799 case CK_ToVoid:
1800 case CK_VectorSplat:
1801 case CK_IntegralToFloating:
1802 case CK_FloatingCast:
1803 case CK_AnyPointerToObjCPointerCast:
1804 case CK_AnyPointerToBlockPointerCast:
1805 case CK_ObjCObjectLValueCast:
1806 case CK_FloatingRealToComplex:
1807 case CK_FloatingComplexToReal:
1808 case CK_FloatingComplexCast:
1809 case CK_FloatingComplexToIntegralComplex:
1810 case CK_IntegralRealToComplex:
1811 case CK_IntegralComplexCast:
1812 case CK_IntegralComplexToFloatingComplex:
1813 llvm_unreachable("invalid cast kind for integral value");
1814
Eli Friedmane50c2972011-03-25 19:07:11 +00001815 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001816 case CK_Dependent:
1817 case CK_GetObjCProperty:
1818 case CK_LValueBitCast:
1819 case CK_UserDefinedConversion:
John McCallf85e1932011-06-15 23:02:42 +00001820 case CK_ObjCProduceObject:
1821 case CK_ObjCConsumeObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001822 return false;
1823
1824 case CK_LValueToRValue:
1825 case CK_NoOp:
1826 return Visit(E->getSubExpr());
1827
1828 case CK_MemberPointerToBoolean:
1829 case CK_PointerToBoolean:
1830 case CK_IntegralToBoolean:
1831 case CK_FloatingToBoolean:
1832 case CK_FloatingComplexToBoolean:
1833 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001834 bool BoolResult;
1835 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1836 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001837 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001838 }
1839
Eli Friedman46a52322011-03-25 00:43:55 +00001840 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001841 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001842 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001843
Eli Friedmanbe265702009-02-20 01:15:07 +00001844 if (!Result.isInt()) {
1845 // Only allow casts of lvalues if they are lossless.
1846 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1847 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001848
Daniel Dunbardd211642009-02-19 22:24:01 +00001849 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001850 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001851 }
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Eli Friedman46a52322011-03-25 00:43:55 +00001853 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001854 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001855 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001856 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001857
Daniel Dunbardd211642009-02-19 22:24:01 +00001858 if (LV.getLValueBase()) {
1859 // Only allow based lvalue casts if they are lossless.
1860 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1861 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001862
John McCallefdb83e2010-05-07 21:00:08 +00001863 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001864 return true;
1865 }
1866
Ken Dycka7305832010-01-15 12:37:54 +00001867 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1868 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001869 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001870 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001871
Eli Friedman46a52322011-03-25 00:43:55 +00001872 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001873 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001874 if (!EvaluateComplex(SubExpr, C, Info))
1875 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001876 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001877 }
Eli Friedman2217c872009-02-22 11:46:18 +00001878
Eli Friedman46a52322011-03-25 00:43:55 +00001879 case CK_FloatingToIntegral: {
1880 APFloat F(0.0);
1881 if (!EvaluateFloat(SubExpr, F, Info))
1882 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001883
Eli Friedman46a52322011-03-25 00:43:55 +00001884 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1885 }
1886 }
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Eli Friedman46a52322011-03-25 00:43:55 +00001888 llvm_unreachable("unknown cast resulting in integral value");
1889 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001890}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001891
Eli Friedman722c7172009-02-28 03:59:05 +00001892bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1893 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001894 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001895 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1896 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1897 return Success(LV.getComplexIntReal(), E);
1898 }
1899
1900 return Visit(E->getSubExpr());
1901}
1902
Eli Friedman664a1042009-02-27 04:45:43 +00001903bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001904 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001905 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001906 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1907 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1908 return Success(LV.getComplexIntImag(), E);
1909 }
1910
Eli Friedman664a1042009-02-27 04:45:43 +00001911 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1912 Info.EvalResult.HasSideEffects = true;
1913 return Success(0, E);
1914}
1915
Douglas Gregoree8aff02011-01-04 17:33:58 +00001916bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1917 return Success(E->getPackLength(), E);
1918}
1919
Sebastian Redl295995c2010-09-10 20:55:47 +00001920bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1921 return Success(E->getValue(), E);
1922}
1923
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001924//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001925// Float Evaluation
1926//===----------------------------------------------------------------------===//
1927
1928namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001929class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001930 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001931 APFloat &Result;
1932public:
1933 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001934 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001935
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001936 bool Success(const APValue &V, const Expr *e) {
1937 Result = V.getFloat();
1938 return true;
1939 }
1940 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001941 return false;
1942 }
1943
Chris Lattner019f4e82008-10-06 05:28:25 +00001944 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001945
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001946 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001947 bool VisitBinaryOperator(const BinaryOperator *E);
1948 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001949 bool VisitCastExpr(const CastExpr *E);
1950 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001951
John McCallabd3a852010-05-07 22:08:54 +00001952 bool VisitUnaryReal(const UnaryOperator *E);
1953 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001954
John McCall189d6ef2010-10-09 01:34:31 +00001955 bool VisitDeclRefExpr(const DeclRefExpr *E);
1956
John McCallabd3a852010-05-07 22:08:54 +00001957 // FIXME: Missing: array subscript of vector, member of vector,
1958 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001959};
1960} // end anonymous namespace
1961
1962static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001963 assert(E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001964 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001965}
1966
Jay Foad4ba2a172011-01-12 09:06:06 +00001967static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001968 QualType ResultTy,
1969 const Expr *Arg,
1970 bool SNaN,
1971 llvm::APFloat &Result) {
1972 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1973 if (!S) return false;
1974
1975 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1976
1977 llvm::APInt fill;
1978
1979 // Treat empty strings as if they were zero.
1980 if (S->getString().empty())
1981 fill = llvm::APInt(32, 0);
1982 else if (S->getString().getAsInteger(0, fill))
1983 return false;
1984
1985 if (SNaN)
1986 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1987 else
1988 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1989 return true;
1990}
1991
Chris Lattner019f4e82008-10-06 05:28:25 +00001992bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001993 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001994 default:
1995 return ExprEvaluatorBaseTy::VisitCallExpr(E);
1996
Chris Lattner019f4e82008-10-06 05:28:25 +00001997 case Builtin::BI__builtin_huge_val:
1998 case Builtin::BI__builtin_huge_valf:
1999 case Builtin::BI__builtin_huge_vall:
2000 case Builtin::BI__builtin_inf:
2001 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002002 case Builtin::BI__builtin_infl: {
2003 const llvm::fltSemantics &Sem =
2004 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002005 Result = llvm::APFloat::getInf(Sem);
2006 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002007 }
Mike Stump1eb44332009-09-09 15:08:12 +00002008
John McCalldb7b72a2010-02-28 13:00:19 +00002009 case Builtin::BI__builtin_nans:
2010 case Builtin::BI__builtin_nansf:
2011 case Builtin::BI__builtin_nansl:
2012 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2013 true, Result);
2014
Chris Lattner9e621712008-10-06 06:31:58 +00002015 case Builtin::BI__builtin_nan:
2016 case Builtin::BI__builtin_nanf:
2017 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002018 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002019 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002020 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2021 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002022
2023 case Builtin::BI__builtin_fabs:
2024 case Builtin::BI__builtin_fabsf:
2025 case Builtin::BI__builtin_fabsl:
2026 if (!EvaluateFloat(E->getArg(0), Result, Info))
2027 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002029 if (Result.isNegative())
2030 Result.changeSign();
2031 return true;
2032
Mike Stump1eb44332009-09-09 15:08:12 +00002033 case Builtin::BI__builtin_copysign:
2034 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002035 case Builtin::BI__builtin_copysignl: {
2036 APFloat RHS(0.);
2037 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2038 !EvaluateFloat(E->getArg(1), RHS, Info))
2039 return false;
2040 Result.copySign(RHS);
2041 return true;
2042 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002043 }
2044}
2045
John McCall189d6ef2010-10-09 01:34:31 +00002046bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002047 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2048 return true;
2049
John McCall189d6ef2010-10-09 01:34:31 +00002050 const Decl *D = E->getDecl();
2051 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2052 const VarDecl *VD = cast<VarDecl>(D);
2053
2054 // Require the qualifiers to be const and not volatile.
2055 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2056 if (!T.isConstQualified() || T.isVolatileQualified())
2057 return false;
2058
2059 const Expr *Init = VD->getAnyInitializer();
2060 if (!Init) return false;
2061
2062 if (APValue *V = VD->getEvaluatedValue()) {
2063 if (V->isFloat()) {
2064 Result = V->getFloat();
2065 return true;
2066 }
2067 return false;
2068 }
2069
2070 if (VD->isEvaluatingValue())
2071 return false;
2072
2073 VD->setEvaluatingValue();
2074
2075 Expr::EvalResult InitResult;
2076 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2077 InitResult.Val.isFloat()) {
2078 // Cache the evaluated value in the variable declaration.
2079 Result = InitResult.Val.getFloat();
2080 VD->setEvaluatedValue(InitResult.Val);
2081 return true;
2082 }
2083
2084 VD->setEvaluatedValue(APValue());
2085 return false;
2086}
2087
John McCallabd3a852010-05-07 22:08:54 +00002088bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002089 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2090 ComplexValue CV;
2091 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2092 return false;
2093 Result = CV.FloatReal;
2094 return true;
2095 }
2096
2097 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002098}
2099
2100bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002101 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2102 ComplexValue CV;
2103 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2104 return false;
2105 Result = CV.FloatImag;
2106 return true;
2107 }
2108
2109 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2110 Info.EvalResult.HasSideEffects = true;
2111 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2112 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002113 return true;
2114}
2115
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002116bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002117 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002118 return false;
2119
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002120 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2121 return false;
2122
2123 switch (E->getOpcode()) {
2124 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002125 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002126 return true;
John McCall2de56d12010-08-25 11:45:40 +00002127 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002128 Result.changeSign();
2129 return true;
2130 }
2131}
Chris Lattner019f4e82008-10-06 05:28:25 +00002132
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002133bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002134 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002135 if (!EvaluateFloat(E->getRHS(), Result, Info))
2136 return false;
2137
2138 // If we can't evaluate the LHS, it might have side effects;
2139 // conservatively mark it.
2140 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2141 Info.EvalResult.HasSideEffects = true;
2142
2143 return true;
2144 }
2145
Anders Carlsson96e93662010-10-31 01:21:47 +00002146 // We can't evaluate pointer-to-member operations.
2147 if (E->isPtrMemOp())
2148 return false;
2149
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002150 // FIXME: Diagnostics? I really don't understand how the warnings
2151 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002152 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002153 if (!EvaluateFloat(E->getLHS(), Result, Info))
2154 return false;
2155 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2156 return false;
2157
2158 switch (E->getOpcode()) {
2159 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002160 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002161 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2162 return true;
John McCall2de56d12010-08-25 11:45:40 +00002163 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002164 Result.add(RHS, APFloat::rmNearestTiesToEven);
2165 return true;
John McCall2de56d12010-08-25 11:45:40 +00002166 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002167 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2168 return true;
John McCall2de56d12010-08-25 11:45:40 +00002169 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002170 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2171 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002172 }
2173}
2174
2175bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2176 Result = E->getValue();
2177 return true;
2178}
2179
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002180bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2181 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Eli Friedman2a523ee2011-03-25 00:54:52 +00002183 switch (E->getCastKind()) {
2184 default:
2185 return false;
2186
2187 case CK_LValueToRValue:
2188 case CK_NoOp:
2189 return Visit(SubExpr);
2190
2191 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002192 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002193 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002194 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002195 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002196 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002197 return true;
2198 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002199
2200 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002201 if (!Visit(SubExpr))
2202 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002203 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2204 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002205 return true;
2206 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002207
Eli Friedman2a523ee2011-03-25 00:54:52 +00002208 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002209 ComplexValue V;
2210 if (!EvaluateComplex(SubExpr, V, Info))
2211 return false;
2212 Result = V.getComplexFloatReal();
2213 return true;
2214 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002215 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002216
2217 return false;
2218}
2219
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002220bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002221 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2222 return true;
2223}
2224
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002225//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002226// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002227//===----------------------------------------------------------------------===//
2228
2229namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002230class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002231 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002232 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002234public:
John McCallf4cf1a12010-05-07 17:22:02 +00002235 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002236 : ExprEvaluatorBaseTy(info), Result(Result) {}
2237
2238 bool Success(const APValue &V, const Expr *e) {
2239 Result.setFrom(V);
2240 return true;
2241 }
2242 bool Error(const Expr *E) {
2243 return false;
2244 }
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002246 //===--------------------------------------------------------------------===//
2247 // Visitor Methods
2248 //===--------------------------------------------------------------------===//
2249
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002250 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002252 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002253
John McCallf4cf1a12010-05-07 17:22:02 +00002254 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002255 bool VisitUnaryOperator(const UnaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002256 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002257};
2258} // end anonymous namespace
2259
John McCallf4cf1a12010-05-07 17:22:02 +00002260static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2261 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002262 assert(E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002263 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002264}
2265
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002266bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2267 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002268
2269 if (SubExpr->getType()->isRealFloatingType()) {
2270 Result.makeComplexFloat();
2271 APFloat &Imag = Result.FloatImag;
2272 if (!EvaluateFloat(SubExpr, Imag, Info))
2273 return false;
2274
2275 Result.FloatReal = APFloat(Imag.getSemantics());
2276 return true;
2277 } else {
2278 assert(SubExpr->getType()->isIntegerType() &&
2279 "Unexpected imaginary literal.");
2280
2281 Result.makeComplexInt();
2282 APSInt &Imag = Result.IntImag;
2283 if (!EvaluateInteger(SubExpr, Imag, Info))
2284 return false;
2285
2286 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2287 return true;
2288 }
2289}
2290
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002291bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002292
John McCall8786da72010-12-14 17:51:41 +00002293 switch (E->getCastKind()) {
2294 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002295 case CK_BaseToDerived:
2296 case CK_DerivedToBase:
2297 case CK_UncheckedDerivedToBase:
2298 case CK_Dynamic:
2299 case CK_ToUnion:
2300 case CK_ArrayToPointerDecay:
2301 case CK_FunctionToPointerDecay:
2302 case CK_NullToPointer:
2303 case CK_NullToMemberPointer:
2304 case CK_BaseToDerivedMemberPointer:
2305 case CK_DerivedToBaseMemberPointer:
2306 case CK_MemberPointerToBoolean:
2307 case CK_ConstructorConversion:
2308 case CK_IntegralToPointer:
2309 case CK_PointerToIntegral:
2310 case CK_PointerToBoolean:
2311 case CK_ToVoid:
2312 case CK_VectorSplat:
2313 case CK_IntegralCast:
2314 case CK_IntegralToBoolean:
2315 case CK_IntegralToFloating:
2316 case CK_FloatingToIntegral:
2317 case CK_FloatingToBoolean:
2318 case CK_FloatingCast:
2319 case CK_AnyPointerToObjCPointerCast:
2320 case CK_AnyPointerToBlockPointerCast:
2321 case CK_ObjCObjectLValueCast:
2322 case CK_FloatingComplexToReal:
2323 case CK_FloatingComplexToBoolean:
2324 case CK_IntegralComplexToReal:
2325 case CK_IntegralComplexToBoolean:
John McCallf85e1932011-06-15 23:02:42 +00002326 case CK_ObjCProduceObject:
2327 case CK_ObjCConsumeObject:
John McCall8786da72010-12-14 17:51:41 +00002328 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002329
John McCall8786da72010-12-14 17:51:41 +00002330 case CK_LValueToRValue:
2331 case CK_NoOp:
2332 return Visit(E->getSubExpr());
2333
2334 case CK_Dependent:
2335 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002336 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002337 case CK_UserDefinedConversion:
2338 return false;
2339
2340 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002341 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002342 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002343 return false;
2344
John McCall8786da72010-12-14 17:51:41 +00002345 Result.makeComplexFloat();
2346 Result.FloatImag = APFloat(Real.getSemantics());
2347 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002348 }
2349
John McCall8786da72010-12-14 17:51:41 +00002350 case CK_FloatingComplexCast: {
2351 if (!Visit(E->getSubExpr()))
2352 return false;
2353
2354 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2355 QualType From
2356 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2357
2358 Result.FloatReal
2359 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2360 Result.FloatImag
2361 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2362 return true;
2363 }
2364
2365 case CK_FloatingComplexToIntegralComplex: {
2366 if (!Visit(E->getSubExpr()))
2367 return false;
2368
2369 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2370 QualType From
2371 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2372 Result.makeComplexInt();
2373 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2374 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2375 return true;
2376 }
2377
2378 case CK_IntegralRealToComplex: {
2379 APSInt &Real = Result.IntReal;
2380 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2381 return false;
2382
2383 Result.makeComplexInt();
2384 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2385 return true;
2386 }
2387
2388 case CK_IntegralComplexCast: {
2389 if (!Visit(E->getSubExpr()))
2390 return false;
2391
2392 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2393 QualType From
2394 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2395
2396 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2397 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2398 return true;
2399 }
2400
2401 case CK_IntegralComplexToFloatingComplex: {
2402 if (!Visit(E->getSubExpr()))
2403 return false;
2404
2405 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2406 QualType From
2407 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2408 Result.makeComplexFloat();
2409 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2410 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2411 return true;
2412 }
2413 }
2414
2415 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002416 return false;
2417}
2418
John McCallf4cf1a12010-05-07 17:22:02 +00002419bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002420 if (E->getOpcode() == BO_Comma) {
2421 if (!Visit(E->getRHS()))
2422 return false;
2423
2424 // If we can't evaluate the LHS, it might have side effects;
2425 // conservatively mark it.
2426 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2427 Info.EvalResult.HasSideEffects = true;
2428
2429 return true;
2430 }
John McCallf4cf1a12010-05-07 17:22:02 +00002431 if (!Visit(E->getLHS()))
2432 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002433
John McCallf4cf1a12010-05-07 17:22:02 +00002434 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002435 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002436 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002437
Daniel Dunbar3f279872009-01-29 01:32:56 +00002438 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2439 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002440 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002441 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002442 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002443 if (Result.isComplexFloat()) {
2444 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2445 APFloat::rmNearestTiesToEven);
2446 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2447 APFloat::rmNearestTiesToEven);
2448 } else {
2449 Result.getComplexIntReal() += RHS.getComplexIntReal();
2450 Result.getComplexIntImag() += RHS.getComplexIntImag();
2451 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002452 break;
John McCall2de56d12010-08-25 11:45:40 +00002453 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002454 if (Result.isComplexFloat()) {
2455 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2456 APFloat::rmNearestTiesToEven);
2457 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2458 APFloat::rmNearestTiesToEven);
2459 } else {
2460 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2461 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2462 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002463 break;
John McCall2de56d12010-08-25 11:45:40 +00002464 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002465 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002466 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002467 APFloat &LHS_r = LHS.getComplexFloatReal();
2468 APFloat &LHS_i = LHS.getComplexFloatImag();
2469 APFloat &RHS_r = RHS.getComplexFloatReal();
2470 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002471
Daniel Dunbar3f279872009-01-29 01:32:56 +00002472 APFloat Tmp = LHS_r;
2473 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2474 Result.getComplexFloatReal() = Tmp;
2475 Tmp = LHS_i;
2476 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2477 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2478
2479 Tmp = LHS_r;
2480 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2481 Result.getComplexFloatImag() = Tmp;
2482 Tmp = LHS_i;
2483 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2484 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2485 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002486 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002487 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002488 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2489 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002490 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002491 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2492 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2493 }
2494 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002495 case BO_Div:
2496 if (Result.isComplexFloat()) {
2497 ComplexValue LHS = Result;
2498 APFloat &LHS_r = LHS.getComplexFloatReal();
2499 APFloat &LHS_i = LHS.getComplexFloatImag();
2500 APFloat &RHS_r = RHS.getComplexFloatReal();
2501 APFloat &RHS_i = RHS.getComplexFloatImag();
2502 APFloat &Res_r = Result.getComplexFloatReal();
2503 APFloat &Res_i = Result.getComplexFloatImag();
2504
2505 APFloat Den = RHS_r;
2506 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2507 APFloat Tmp = RHS_i;
2508 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2509 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2510
2511 Res_r = LHS_r;
2512 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2513 Tmp = LHS_i;
2514 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2515 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2516 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2517
2518 Res_i = LHS_i;
2519 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2520 Tmp = LHS_r;
2521 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2522 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2523 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2524 } else {
2525 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2526 // FIXME: what about diagnostics?
2527 return false;
2528 }
2529 ComplexValue LHS = Result;
2530 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2531 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2532 Result.getComplexIntReal() =
2533 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2534 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2535 Result.getComplexIntImag() =
2536 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2537 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2538 }
2539 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002540 }
2541
John McCallf4cf1a12010-05-07 17:22:02 +00002542 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002543}
2544
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002545bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2546 // Get the operand value into 'Result'.
2547 if (!Visit(E->getSubExpr()))
2548 return false;
2549
2550 switch (E->getOpcode()) {
2551 default:
2552 // FIXME: what about diagnostics?
2553 return false;
2554 case UO_Extension:
2555 return true;
2556 case UO_Plus:
2557 // The result is always just the subexpr.
2558 return true;
2559 case UO_Minus:
2560 if (Result.isComplexFloat()) {
2561 Result.getComplexFloatReal().changeSign();
2562 Result.getComplexFloatImag().changeSign();
2563 }
2564 else {
2565 Result.getComplexIntReal() = -Result.getComplexIntReal();
2566 Result.getComplexIntImag() = -Result.getComplexIntImag();
2567 }
2568 return true;
2569 case UO_Not:
2570 if (Result.isComplexFloat())
2571 Result.getComplexFloatImag().changeSign();
2572 else
2573 Result.getComplexIntImag() = -Result.getComplexIntImag();
2574 return true;
2575 }
2576}
2577
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002578//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002579// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002580//===----------------------------------------------------------------------===//
2581
John McCall56ca35d2011-02-17 10:25:35 +00002582static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002583 if (E->getType()->isVectorType()) {
2584 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002585 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002586 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002587 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002588 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002589 if (Info.EvalResult.Val.isLValue() &&
2590 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002591 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002592 } else if (E->getType()->hasPointerRepresentation()) {
2593 LValue LV;
2594 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002595 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002596 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002597 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002598 LV.moveInto(Info.EvalResult.Val);
2599 } else if (E->getType()->isRealFloatingType()) {
2600 llvm::APFloat F(0.0);
2601 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002602 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002603
John McCallefdb83e2010-05-07 21:00:08 +00002604 Info.EvalResult.Val = APValue(F);
2605 } else if (E->getType()->isAnyComplexType()) {
2606 ComplexValue C;
2607 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002608 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002609 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002610 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002611 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002612
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002613 return true;
2614}
2615
John McCall56ca35d2011-02-17 10:25:35 +00002616/// Evaluate - Return true if this is a constant which we can fold using
2617/// any crazy technique (that has nothing to do with language standards) that
2618/// we want to. If this function returns true, it returns the folded constant
2619/// in Result.
2620bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2621 EvalInfo Info(Ctx, Result);
2622 return ::Evaluate(Info, this);
2623}
2624
Jay Foad4ba2a172011-01-12 09:06:06 +00002625bool Expr::EvaluateAsBooleanCondition(bool &Result,
2626 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002627 EvalResult Scratch;
2628 EvalInfo Info(Ctx, Scratch);
2629
2630 return HandleConversionToBool(this, Result, Info);
2631}
2632
Jay Foad4ba2a172011-01-12 09:06:06 +00002633bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002634 EvalInfo Info(Ctx, Result);
2635
John McCallefdb83e2010-05-07 21:00:08 +00002636 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002637 if (EvaluateLValue(this, LV, Info) &&
2638 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002639 IsGlobalLValue(LV.Base)) {
2640 LV.moveInto(Result.Val);
2641 return true;
2642 }
2643 return false;
2644}
2645
Jay Foad4ba2a172011-01-12 09:06:06 +00002646bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2647 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002648 EvalInfo Info(Ctx, Result);
2649
2650 LValue LV;
2651 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002652 LV.moveInto(Result.Val);
2653 return true;
2654 }
2655 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002656}
2657
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002658/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002659/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002660bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002661 EvalResult Result;
2662 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002663}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002664
Jay Foad4ba2a172011-01-12 09:06:06 +00002665bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002666 Expr::EvalResult Result;
2667 EvalInfo Info(Ctx, Result);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002668 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002669}
2670
Jay Foad4ba2a172011-01-12 09:06:06 +00002671APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002672 EvalResult EvalResult;
2673 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002674 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002675 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002676 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002677
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002678 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002679}
John McCalld905f5a2010-05-07 05:32:02 +00002680
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002681 bool Expr::EvalResult::isGlobalLValue() const {
2682 assert(Val.isLValue());
2683 return IsGlobalLValue(Val.getLValueBase());
2684 }
2685
2686
John McCalld905f5a2010-05-07 05:32:02 +00002687/// isIntegerConstantExpr - this recursive routine will test if an expression is
2688/// an integer constant expression.
2689
2690/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2691/// comma, etc
2692///
2693/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2694/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2695/// cast+dereference.
2696
2697// CheckICE - This function does the fundamental ICE checking: the returned
2698// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2699// Note that to reduce code duplication, this helper does no evaluation
2700// itself; the caller checks whether the expression is evaluatable, and
2701// in the rare cases where CheckICE actually cares about the evaluated
2702// value, it calls into Evalute.
2703//
2704// Meanings of Val:
2705// 0: This expression is an ICE if it can be evaluated by Evaluate.
2706// 1: This expression is not an ICE, but if it isn't evaluated, it's
2707// a legal subexpression for an ICE. This return value is used to handle
2708// the comma operator in C99 mode.
2709// 2: This expression is not an ICE, and is not a legal subexpression for one.
2710
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002711namespace {
2712
John McCalld905f5a2010-05-07 05:32:02 +00002713struct ICEDiag {
2714 unsigned Val;
2715 SourceLocation Loc;
2716
2717 public:
2718 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2719 ICEDiag() : Val(0) {}
2720};
2721
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002722}
2723
2724static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002725
2726static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2727 Expr::EvalResult EVResult;
2728 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2729 !EVResult.Val.isInt()) {
2730 return ICEDiag(2, E->getLocStart());
2731 }
2732 return NoDiag();
2733}
2734
2735static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2736 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002737 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002738 return ICEDiag(2, E->getLocStart());
2739 }
2740
2741 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002742#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002743#define STMT(Node, Base) case Expr::Node##Class:
2744#define EXPR(Node, Base)
2745#include "clang/AST/StmtNodes.inc"
2746 case Expr::PredefinedExprClass:
2747 case Expr::FloatingLiteralClass:
2748 case Expr::ImaginaryLiteralClass:
2749 case Expr::StringLiteralClass:
2750 case Expr::ArraySubscriptExprClass:
2751 case Expr::MemberExprClass:
2752 case Expr::CompoundAssignOperatorClass:
2753 case Expr::CompoundLiteralExprClass:
2754 case Expr::ExtVectorElementExprClass:
2755 case Expr::InitListExprClass:
2756 case Expr::DesignatedInitExprClass:
2757 case Expr::ImplicitValueInitExprClass:
2758 case Expr::ParenListExprClass:
2759 case Expr::VAArgExprClass:
2760 case Expr::AddrLabelExprClass:
2761 case Expr::StmtExprClass:
2762 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002763 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002764 case Expr::CXXDynamicCastExprClass:
2765 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002766 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002767 case Expr::CXXNullPtrLiteralExprClass:
2768 case Expr::CXXThisExprClass:
2769 case Expr::CXXThrowExprClass:
2770 case Expr::CXXNewExprClass:
2771 case Expr::CXXDeleteExprClass:
2772 case Expr::CXXPseudoDestructorExprClass:
2773 case Expr::UnresolvedLookupExprClass:
2774 case Expr::DependentScopeDeclRefExprClass:
2775 case Expr::CXXConstructExprClass:
2776 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002777 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002778 case Expr::CXXTemporaryObjectExprClass:
2779 case Expr::CXXUnresolvedConstructExprClass:
2780 case Expr::CXXDependentScopeMemberExprClass:
2781 case Expr::UnresolvedMemberExprClass:
2782 case Expr::ObjCStringLiteralClass:
2783 case Expr::ObjCEncodeExprClass:
2784 case Expr::ObjCMessageExprClass:
2785 case Expr::ObjCSelectorExprClass:
2786 case Expr::ObjCProtocolExprClass:
2787 case Expr::ObjCIvarRefExprClass:
2788 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002789 case Expr::ObjCIsaExprClass:
2790 case Expr::ShuffleVectorExprClass:
2791 case Expr::BlockExprClass:
2792 case Expr::BlockDeclRefExprClass:
2793 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002794 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002795 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002796 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002797 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002798 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002799 case Expr::MaterializeTemporaryExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002800 return ICEDiag(2, E->getLocStart());
2801
Douglas Gregoree8aff02011-01-04 17:33:58 +00002802 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002803 case Expr::GNUNullExprClass:
2804 // GCC considers the GNU __null value to be an integral constant expression.
2805 return NoDiag();
2806
2807 case Expr::ParenExprClass:
2808 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002809 case Expr::GenericSelectionExprClass:
2810 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002811 case Expr::IntegerLiteralClass:
2812 case Expr::CharacterLiteralClass:
2813 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002814 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002815 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002816 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002817 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002818 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002819 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002820 return NoDiag();
2821 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002822 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002823 const CallExpr *CE = cast<CallExpr>(E);
2824 if (CE->isBuiltinCall(Ctx))
2825 return CheckEvalInICE(E, Ctx);
2826 return ICEDiag(2, E->getLocStart());
2827 }
2828 case Expr::DeclRefExprClass:
2829 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2830 return NoDiag();
2831 if (Ctx.getLangOptions().CPlusPlus &&
2832 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2833 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2834
2835 // Parameter variables are never constants. Without this check,
2836 // getAnyInitializer() can find a default argument, which leads
2837 // to chaos.
2838 if (isa<ParmVarDecl>(D))
2839 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2840
2841 // C++ 7.1.5.1p2
2842 // A variable of non-volatile const-qualified integral or enumeration
2843 // type initialized by an ICE can be used in ICEs.
2844 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2845 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2846 if (Quals.hasVolatile() || !Quals.hasConst())
2847 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2848
2849 // Look for a declaration of this variable that has an initializer.
2850 const VarDecl *ID = 0;
2851 const Expr *Init = Dcl->getAnyInitializer(ID);
2852 if (Init) {
2853 if (ID->isInitKnownICE()) {
2854 // We have already checked whether this subexpression is an
2855 // integral constant expression.
2856 if (ID->isInitICE())
2857 return NoDiag();
2858 else
2859 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2860 }
2861
2862 // It's an ICE whether or not the definition we found is
2863 // out-of-line. See DR 721 and the discussion in Clang PR
2864 // 6206 for details.
2865
2866 if (Dcl->isCheckingICE()) {
2867 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2868 }
2869
2870 Dcl->setCheckingICE();
2871 ICEDiag Result = CheckICE(Init, Ctx);
2872 // Cache the result of the ICE test.
2873 Dcl->setInitKnownICE(Result.Val == 0);
2874 return Result;
2875 }
2876 }
2877 }
2878 return ICEDiag(2, E->getLocStart());
2879 case Expr::UnaryOperatorClass: {
2880 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2881 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002882 case UO_PostInc:
2883 case UO_PostDec:
2884 case UO_PreInc:
2885 case UO_PreDec:
2886 case UO_AddrOf:
2887 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002888 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002889 case UO_Extension:
2890 case UO_LNot:
2891 case UO_Plus:
2892 case UO_Minus:
2893 case UO_Not:
2894 case UO_Real:
2895 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002896 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002897 }
2898
2899 // OffsetOf falls through here.
2900 }
2901 case Expr::OffsetOfExprClass: {
2902 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2903 // Evaluate matches the proposed gcc behavior for cases like
2904 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2905 // compliance: we should warn earlier for offsetof expressions with
2906 // array subscripts that aren't ICEs, and if the array subscripts
2907 // are ICEs, the value of the offsetof must be an integer constant.
2908 return CheckEvalInICE(E, Ctx);
2909 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002910 case Expr::UnaryExprOrTypeTraitExprClass: {
2911 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2912 if ((Exp->getKind() == UETT_SizeOf) &&
2913 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002914 return ICEDiag(2, E->getLocStart());
2915 return NoDiag();
2916 }
2917 case Expr::BinaryOperatorClass: {
2918 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2919 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002920 case BO_PtrMemD:
2921 case BO_PtrMemI:
2922 case BO_Assign:
2923 case BO_MulAssign:
2924 case BO_DivAssign:
2925 case BO_RemAssign:
2926 case BO_AddAssign:
2927 case BO_SubAssign:
2928 case BO_ShlAssign:
2929 case BO_ShrAssign:
2930 case BO_AndAssign:
2931 case BO_XorAssign:
2932 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002933 return ICEDiag(2, E->getLocStart());
2934
John McCall2de56d12010-08-25 11:45:40 +00002935 case BO_Mul:
2936 case BO_Div:
2937 case BO_Rem:
2938 case BO_Add:
2939 case BO_Sub:
2940 case BO_Shl:
2941 case BO_Shr:
2942 case BO_LT:
2943 case BO_GT:
2944 case BO_LE:
2945 case BO_GE:
2946 case BO_EQ:
2947 case BO_NE:
2948 case BO_And:
2949 case BO_Xor:
2950 case BO_Or:
2951 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002952 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2953 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002954 if (Exp->getOpcode() == BO_Div ||
2955 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002956 // Evaluate gives an error for undefined Div/Rem, so make sure
2957 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00002958 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00002959 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2960 if (REval == 0)
2961 return ICEDiag(1, E->getLocStart());
2962 if (REval.isSigned() && REval.isAllOnesValue()) {
2963 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2964 if (LEval.isMinSignedValue())
2965 return ICEDiag(1, E->getLocStart());
2966 }
2967 }
2968 }
John McCall2de56d12010-08-25 11:45:40 +00002969 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002970 if (Ctx.getLangOptions().C99) {
2971 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2972 // if it isn't evaluated.
2973 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2974 return ICEDiag(1, E->getLocStart());
2975 } else {
2976 // In both C89 and C++, commas in ICEs are illegal.
2977 return ICEDiag(2, E->getLocStart());
2978 }
2979 }
2980 if (LHSResult.Val >= RHSResult.Val)
2981 return LHSResult;
2982 return RHSResult;
2983 }
John McCall2de56d12010-08-25 11:45:40 +00002984 case BO_LAnd:
2985 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002986 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00002987
2988 // C++0x [expr.const]p2:
2989 // [...] subexpressions of logical AND (5.14), logical OR
2990 // (5.15), and condi- tional (5.16) operations that are not
2991 // evaluated are not considered.
2992 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
2993 if (Exp->getOpcode() == BO_LAnd &&
2994 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
2995 return LHSResult;
2996
2997 if (Exp->getOpcode() == BO_LOr &&
2998 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
2999 return LHSResult;
3000 }
3001
John McCalld905f5a2010-05-07 05:32:02 +00003002 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3003 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3004 // Rare case where the RHS has a comma "side-effect"; we need
3005 // to actually check the condition to see whether the side
3006 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003007 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003008 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3009 return RHSResult;
3010 return NoDiag();
3011 }
3012
3013 if (LHSResult.Val >= RHSResult.Val)
3014 return LHSResult;
3015 return RHSResult;
3016 }
3017 }
3018 }
3019 case Expr::ImplicitCastExprClass:
3020 case Expr::CStyleCastExprClass:
3021 case Expr::CXXFunctionalCastExprClass:
3022 case Expr::CXXStaticCastExprClass:
3023 case Expr::CXXReinterpretCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003024 case Expr::CXXConstCastExprClass:
3025 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003026 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003027 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003028 return CheckICE(SubExpr, Ctx);
3029 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3030 return NoDiag();
3031 return ICEDiag(2, E->getLocStart());
3032 }
John McCall56ca35d2011-02-17 10:25:35 +00003033 case Expr::BinaryConditionalOperatorClass: {
3034 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3035 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3036 if (CommonResult.Val == 2) return CommonResult;
3037 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3038 if (FalseResult.Val == 2) return FalseResult;
3039 if (CommonResult.Val == 1) return CommonResult;
3040 if (FalseResult.Val == 1 &&
3041 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3042 return FalseResult;
3043 }
John McCalld905f5a2010-05-07 05:32:02 +00003044 case Expr::ConditionalOperatorClass: {
3045 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3046 // If the condition (ignoring parens) is a __builtin_constant_p call,
3047 // then only the true side is actually considered in an integer constant
3048 // expression, and it is fully evaluated. This is an important GNU
3049 // extension. See GCC PR38377 for discussion.
3050 if (const CallExpr *CallCE
3051 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3052 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3053 Expr::EvalResult EVResult;
3054 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3055 !EVResult.Val.isInt()) {
3056 return ICEDiag(2, E->getLocStart());
3057 }
3058 return NoDiag();
3059 }
3060 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003061 if (CondResult.Val == 2)
3062 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003063
3064 // C++0x [expr.const]p2:
3065 // subexpressions of [...] conditional (5.16) operations that
3066 // are not evaluated are not considered
3067 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3068 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3069 : false;
3070 ICEDiag TrueResult = NoDiag();
3071 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3072 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3073 ICEDiag FalseResult = NoDiag();
3074 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3075 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3076
John McCalld905f5a2010-05-07 05:32:02 +00003077 if (TrueResult.Val == 2)
3078 return TrueResult;
3079 if (FalseResult.Val == 2)
3080 return FalseResult;
3081 if (CondResult.Val == 1)
3082 return CondResult;
3083 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3084 return NoDiag();
3085 // Rare case where the diagnostics depend on which side is evaluated
3086 // Note that if we get here, CondResult is 0, and at least one of
3087 // TrueResult and FalseResult is non-zero.
3088 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3089 return FalseResult;
3090 }
3091 return TrueResult;
3092 }
3093 case Expr::CXXDefaultArgExprClass:
3094 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3095 case Expr::ChooseExprClass: {
3096 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3097 }
3098 }
3099
3100 // Silence a GCC warning
3101 return ICEDiag(2, E->getLocStart());
3102}
3103
3104bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3105 SourceLocation *Loc, bool isEvaluated) const {
3106 ICEDiag d = CheckICE(this, Ctx);
3107 if (d.Val != 0) {
3108 if (Loc) *Loc = d.Loc;
3109 return false;
3110 }
3111 EvalResult EvalResult;
3112 if (!Evaluate(EvalResult, Ctx))
3113 llvm_unreachable("ICE cannot be evaluated!");
3114 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3115 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3116 Result = EvalResult.Val.getInt();
3117 return true;
3118}