blob: 7d2ea13d0a74c066765a9089b3b56b10eb499164 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Benjamin Kramerc54061a2011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCallf4cf1a12010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCall56ca35d2011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCall56ca35d2011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCallf4cf1a12010-05-07 17:22:02 +0000102 };
John McCallefdb83e2010-05-07 21:00:08 +0000103
104 struct LValue {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000105 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCallefdb83e2010-05-07 21:00:08 +0000109 CharUnits getLValueOffset() { return Offset; }
110
John McCall56ca35d2011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCall56ca35d2011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCallefdb83e2010-05-07 21:00:08 +0000119 };
John McCallf4cf1a12010-05-07 17:22:02 +0000120}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000121
John McCall56ca35d2011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCallefdb83e2010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000154
John McCall35542832010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000161
John McCall42c8f872010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000164
John McCall35542832010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCall35542832010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCall35542832010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman5bc86102009-06-14 02:17:33 +0000181 return true;
182}
183
John McCallcd7a4452010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
227 uint64_t Space[4];
228 bool ignored;
229 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
230 llvm::APFloat::rmTowardZero, &ignored);
231 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
232}
233
Mike Stump1eb44332009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump1eb44332009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000245 unsigned DestWidth = Ctx.getIntWidth(DestType);
246 APSInt Result = Value;
247 // Figure out if this is a truncate, extend or noop cast.
248 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000251 return Result;
252}
253
Mike Stump1eb44332009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000256
257 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
258 Result.convertFromAPInt(Value, Value.isSigned(),
259 APFloat::rmNearestTiesToEven);
260 return Result;
261}
262
Mike Stumpc4c90452009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000264class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000265 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stumpc4c90452009-10-27 22:09:17 +0000266 EvalInfo &Info;
267public:
268
269 HasSideEffect(EvalInfo &info) : Info(info) {}
270
271 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000272 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000273 return true;
274 }
275
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000276 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
277 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000278 return Visit(E->getResultExpr());
279 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000280 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
John McCallf85e1932011-06-15 23:02:42 +0000285 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
286 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
287 return true;
288 return false;
289 }
290 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
291 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
292 return true;
293 return false;
294 }
295
Mike Stumpc4c90452009-10-27 22:09:17 +0000296 // We don't want to evaluate BlockExprs multiple times, as they generate
297 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000298 bool VisitBlockExpr(const BlockExpr *E) { return true; }
299 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
300 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000301 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000302 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
303 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
304 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
305 bool VisitStringLiteral(const StringLiteral *E) { return false; }
306 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
307 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000308 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000309 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000310 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000311 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000312 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000313 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
314 bool VisitBinAssign(const BinaryOperator *E) { return true; }
315 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
316 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +0000317 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000318 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
319 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
321 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
322 bool VisitUnaryDeref(const UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000323 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000324 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000325 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000326 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000327 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000328
329 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000330 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +0000331 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
332 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000333 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000334 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000335 return false;
336 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000337
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000338 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000339};
340
John McCall56ca35d2011-02-17 10:25:35 +0000341class OpaqueValueEvaluation {
342 EvalInfo &info;
343 OpaqueValueExpr *opaqueValue;
344
345public:
346 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
347 Expr *value)
348 : info(info), opaqueValue(opaqueValue) {
349
350 // If evaluation fails, fail immediately.
351 if (!Evaluate(info, value)) {
352 this->opaqueValue = 0;
353 return;
354 }
355 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
356 }
357
358 bool hasError() const { return opaqueValue == 0; }
359
360 ~OpaqueValueEvaluation() {
361 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
362 }
363};
364
Mike Stumpc4c90452009-10-27 22:09:17 +0000365} // end anonymous namespace
366
Eli Friedman4efaa272008-11-12 09:44:48 +0000367//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000368// Generic Evaluation
369//===----------------------------------------------------------------------===//
370namespace {
371
372template <class Derived, typename RetTy=void>
373class ExprEvaluatorBase
374 : public ConstStmtVisitor<Derived, RetTy> {
375private:
376 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
377 return static_cast<Derived*>(this)->Success(V, E);
378 }
379 RetTy DerivedError(const Expr *E) {
380 return static_cast<Derived*>(this)->Error(E);
381 }
382
383protected:
384 EvalInfo &Info;
385 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
386 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
387
388public:
389 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
390
391 RetTy VisitStmt(const Stmt *) {
392 assert(0 && "Expression evaluator should not be called on stmts");
393 return DerivedError(0);
394 }
395 RetTy VisitExpr(const Expr *E) {
396 return DerivedError(E);
397 }
398
399 RetTy VisitParenExpr(const ParenExpr *E)
400 { return StmtVisitorTy::Visit(E->getSubExpr()); }
401 RetTy VisitUnaryExtension(const UnaryOperator *E)
402 { return StmtVisitorTy::Visit(E->getSubExpr()); }
403 RetTy VisitUnaryPlus(const UnaryOperator *E)
404 { return StmtVisitorTy::Visit(E->getSubExpr()); }
405 RetTy VisitChooseExpr(const ChooseExpr *E)
406 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
407 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
408 { return StmtVisitorTy::Visit(E->getResultExpr()); }
409
410 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
411 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
412 if (opaque.hasError())
413 return DerivedError(E);
414
415 bool cond;
416 if (!HandleConversionToBool(E->getCond(), cond, Info))
417 return DerivedError(E);
418
419 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
420 }
421
422 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
423 bool BoolResult;
424 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
425 return DerivedError(E);
426
427 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
428 return StmtVisitorTy::Visit(EvalExpr);
429 }
430
431 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
432 const APValue *value = Info.getOpaqueValue(E);
433 if (!value)
434 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
435 : DerivedError(E));
436 return DerivedSuccess(*value, E);
437 }
438};
439
440}
441
442//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000443// LValue Evaluation
444//===----------------------------------------------------------------------===//
445namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000446class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000447 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000448 LValue &Result;
449
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000450 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000451 Result.Base = E;
452 Result.Offset = CharUnits::Zero();
453 return true;
454 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000455public:
Mike Stump1eb44332009-09-09 15:08:12 +0000456
John McCallefdb83e2010-05-07 21:00:08 +0000457 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000458 ExprEvaluatorBaseTy(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000459
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000460 bool Success(const APValue &V, const Expr *E) {
461 Result.setFrom(V);
462 return true;
463 }
464 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000465 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000466 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000467
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000468 bool VisitDeclRefExpr(const DeclRefExpr *E);
469 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
470 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
471 bool VisitMemberExpr(const MemberExpr *E);
472 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
473 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
474 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
475 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000476
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000477 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000478 switch (E->getCastKind()) {
479 default:
John McCallefdb83e2010-05-07 21:00:08 +0000480 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000481
John McCall2de56d12010-08-25 11:45:40 +0000482 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000483 return Visit(E->getSubExpr());
484 }
485 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000486 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000487
Eli Friedman4efaa272008-11-12 09:44:48 +0000488};
489} // end anonymous namespace
490
John McCallefdb83e2010-05-07 21:00:08 +0000491static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000492 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000493}
494
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000495bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000496 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000497 return Success(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000498 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000499 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000500 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000501 // Reference parameters can refer to anything even if they have an
502 // "initializer" in the form of a default argument.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000503 if (!isa<ParmVarDecl>(VD))
504 // FIXME: Check whether VD might be overridden!
505 if (const Expr *Init = VD->getAnyInitializer())
506 return Visit(Init);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000507 }
508
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000509 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlsson35873c42008-11-24 04:41:22 +0000510}
511
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000512bool
513LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000514 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000515}
516
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000517bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000518 QualType Ty;
519 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000520 if (!EvaluatePointer(E->getBase(), Result, Info))
521 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000522 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000523 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000524 if (!Visit(E->getBase()))
525 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000526 Ty = E->getBase()->getType();
527 }
528
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000529 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000530 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000531
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000532 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +0000533 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000534 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000535
536 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000537 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000538
Eli Friedman4efaa272008-11-12 09:44:48 +0000539 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000540 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000541 for (RecordDecl::field_iterator Field = RD->field_begin(),
542 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000543 Field != FieldEnd; (void)++Field, ++i) {
544 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000545 break;
546 }
547
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000548 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000549 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000550}
551
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000552bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000553 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000554 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Anders Carlsson3068d112008-11-16 19:01:22 +0000556 APSInt Index;
557 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000558 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000559
Ken Dyck199c3d62010-01-11 17:06:35 +0000560 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000561 Result.Offset += Index.getSExtValue() * ElementSize;
562 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000563}
Eli Friedman4efaa272008-11-12 09:44:48 +0000564
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000565bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000566 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000567}
568
Eli Friedman4efaa272008-11-12 09:44:48 +0000569//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000570// Pointer Evaluation
571//===----------------------------------------------------------------------===//
572
Anders Carlssonc754aa62008-07-08 05:13:58 +0000573namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000574class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000575 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000576 LValue &Result;
577
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000578 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000579 Result.Base = E;
580 Result.Offset = CharUnits::Zero();
581 return true;
582 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000583public:
Mike Stump1eb44332009-09-09 15:08:12 +0000584
John McCallefdb83e2010-05-07 21:00:08 +0000585 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000586 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000587
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000588 bool Success(const APValue &V, const Expr *E) {
589 Result.setFrom(V);
590 return true;
591 }
592 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000593 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000594 }
595
John McCallefdb83e2010-05-07 21:00:08 +0000596 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000597 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000598 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000599 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000600 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000601 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000602 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000603 bool VisitCallExpr(const CallExpr *E);
604 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000605 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000606 return Success(E);
607 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000608 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000609 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000610 { return Success((Expr*)0); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000611 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000612 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000613
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000614 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000615};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000616} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000617
John McCallefdb83e2010-05-07 21:00:08 +0000618static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000619 assert(E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000620 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000621}
622
John McCallefdb83e2010-05-07 21:00:08 +0000623bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000624 if (E->getOpcode() != BO_Add &&
625 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000626 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000628 const Expr *PExp = E->getLHS();
629 const Expr *IExp = E->getRHS();
630 if (IExp->getType()->isPointerType())
631 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000632
John McCallefdb83e2010-05-07 21:00:08 +0000633 if (!EvaluatePointer(PExp, Result, Info))
634 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000635
John McCallefdb83e2010-05-07 21:00:08 +0000636 llvm::APSInt Offset;
637 if (!EvaluateInteger(IExp, Offset, Info))
638 return false;
639 int64_t AdditionalOffset
640 = Offset.isSigned() ? Offset.getSExtValue()
641 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000642
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000643 // Compute the new offset in the appropriate width.
644
645 QualType PointeeType =
646 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000647 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000649 // Explicitly handle GNU void* and function pointer arithmetic extensions.
650 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000651 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000652 else
John McCallefdb83e2010-05-07 21:00:08 +0000653 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000654
John McCall2de56d12010-08-25 11:45:40 +0000655 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000656 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000657 else
John McCallefdb83e2010-05-07 21:00:08 +0000658 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000659
John McCallefdb83e2010-05-07 21:00:08 +0000660 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000661}
Eli Friedman4efaa272008-11-12 09:44:48 +0000662
John McCallefdb83e2010-05-07 21:00:08 +0000663bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
664 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000665}
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000667
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000668bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
669 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000670
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000671 switch (E->getCastKind()) {
672 default:
673 break;
674
John McCall2de56d12010-08-25 11:45:40 +0000675 case CK_NoOp:
676 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000677 case CK_AnyPointerToObjCPointerCast:
678 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000679 return Visit(SubExpr);
680
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000681 case CK_DerivedToBase:
682 case CK_UncheckedDerivedToBase: {
683 LValue BaseLV;
684 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
685 return false;
686
687 // Now figure out the necessary offset to add to the baseLV to get from
688 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000689 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000690
691 QualType Ty = E->getSubExpr()->getType();
692 const CXXRecordDecl *DerivedDecl =
693 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
694
695 for (CastExpr::path_const_iterator PathI = E->path_begin(),
696 PathE = E->path_end(); PathI != PathE; ++PathI) {
697 const CXXBaseSpecifier *Base = *PathI;
698
699 // FIXME: If the base is virtual, we'd need to determine the type of the
700 // most derived class and we don't support that right now.
701 if (Base->isVirtual())
702 return false;
703
704 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
705 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
706
Ken Dyck7c7f8202011-01-26 02:17:08 +0000707 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000708 DerivedDecl = BaseDecl;
709 }
710
711 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000712 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000713 return true;
714 }
715
John McCall404cd162010-11-13 01:35:44 +0000716 case CK_NullToPointer: {
717 Result.Base = 0;
718 Result.Offset = CharUnits::Zero();
719 return true;
720 }
721
John McCall2de56d12010-08-25 11:45:40 +0000722 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000723 APValue Value;
724 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000725 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000726
John McCallefdb83e2010-05-07 21:00:08 +0000727 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000728 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000729 Result.Base = 0;
730 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
731 return true;
732 } else {
733 // Cast is of an lvalue, no need to change value.
734 Result.Base = Value.getLValueBase();
735 Result.Offset = Value.getLValueOffset();
736 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000737 }
738 }
John McCall2de56d12010-08-25 11:45:40 +0000739 case CK_ArrayToPointerDecay:
740 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000741 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000742 }
743
John McCallefdb83e2010-05-07 21:00:08 +0000744 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000745}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000746
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000747bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000748 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000749 Builtin::BI__builtin___CFStringMakeConstantString ||
750 E->isBuiltinCall(Info.Ctx) ==
751 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000752 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000753
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000754 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000755}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000756
757//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000758// Vector Evaluation
759//===----------------------------------------------------------------------===//
760
761namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000762 class VectorExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000763 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman91110ee2009-02-23 04:23:56 +0000764 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000765 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000767 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000769 APValue Success(const APValue &V, const Expr *E) { return V; }
770 APValue Error(const Expr *E) { return APValue(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Eli Friedman91110ee2009-02-23 04:23:56 +0000772 APValue VisitUnaryReal(const UnaryOperator *E)
773 { return Visit(E->getSubExpr()); }
774 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
775 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000776 APValue VisitCastExpr(const CastExpr* E);
777 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
778 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000779 APValue VisitUnaryImag(const UnaryOperator *E);
780 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000781 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000782 // shufflevector, ExtVectorElementExpr
783 // (Note that these require implementing conversions
784 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000785 };
786} // end anonymous namespace
787
788static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
789 if (!E->getType()->isVectorType())
790 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000791 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000792 return !Result.isUninit();
793}
794
795APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000796 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000797 QualType EltTy = VTy->getElementType();
798 unsigned NElts = VTy->getNumElements();
799 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Nate Begeman59b5da62009-01-18 03:20:47 +0000801 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000802 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000803
Eli Friedman46a52322011-03-25 00:43:55 +0000804 switch (E->getCastKind()) {
805 case CK_VectorSplat: {
806 APValue Result = APValue();
807 if (SETy->isIntegerType()) {
808 APSInt IntResult;
809 if (!EvaluateInteger(SE, IntResult, Info))
810 return APValue();
811 Result = APValue(IntResult);
812 } else if (SETy->isRealFloatingType()) {
813 APFloat F(0.0);
814 if (!EvaluateFloat(SE, F, Info))
815 return APValue();
816 Result = APValue(F);
817 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000818 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000819 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000820
821 // Splat and create vector APValue.
822 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
823 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000824 }
Eli Friedman46a52322011-03-25 00:43:55 +0000825 case CK_BitCast: {
826 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000827 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000828
Eli Friedman46a52322011-03-25 00:43:55 +0000829 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000830 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Eli Friedman46a52322011-03-25 00:43:55 +0000832 APSInt Init;
833 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000834 return APValue();
835
Eli Friedman46a52322011-03-25 00:43:55 +0000836 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
837 "Vectors must be composed of ints or floats");
838
839 llvm::SmallVector<APValue, 4> Elts;
840 for (unsigned i = 0; i != NElts; ++i) {
841 APSInt Tmp = Init.extOrTrunc(EltWidth);
842
843 if (EltTy->isIntegerType())
844 Elts.push_back(APValue(Tmp));
845 else
846 Elts.push_back(APValue(APFloat(Tmp)));
847
848 Init >>= EltWidth;
849 }
850 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000851 }
Eli Friedman46a52322011-03-25 00:43:55 +0000852 case CK_LValueToRValue:
853 case CK_NoOp:
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000854 return Visit(SE);
Eli Friedman46a52322011-03-25 00:43:55 +0000855 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000856 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000857 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000858}
859
Mike Stump1eb44332009-09-09 15:08:12 +0000860APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000861VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000862 return this->Visit(E->getInitializer());
Nate Begeman59b5da62009-01-18 03:20:47 +0000863}
864
Mike Stump1eb44332009-09-09 15:08:12 +0000865APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000866VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000867 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000868 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000869 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Nate Begeman59b5da62009-01-18 03:20:47 +0000871 QualType EltTy = VT->getElementType();
872 llvm::SmallVector<APValue, 4> Elements;
873
John McCalla7d6c222010-06-11 17:54:15 +0000874 // If a vector is initialized with a single element, that value
875 // becomes every element of the vector, not just the first.
876 // This is the behavior described in the IBM AltiVec documentation.
877 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000878
879 // Handle the case where the vector is initialized by a another
880 // vector (OpenCL 6.1.6).
881 if (E->getInit(0)->getType()->isVectorType())
882 return this->Visit(const_cast<Expr*>(E->getInit(0)));
883
John McCalla7d6c222010-06-11 17:54:15 +0000884 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000885 if (EltTy->isIntegerType()) {
886 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000887 if (!EvaluateInteger(E->getInit(0), sInt, Info))
888 return APValue();
889 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000890 } else {
891 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000892 if (!EvaluateFloat(E->getInit(0), f, Info))
893 return APValue();
894 InitValue = APValue(f);
895 }
896 for (unsigned i = 0; i < NumElements; i++) {
897 Elements.push_back(InitValue);
898 }
899 } else {
900 for (unsigned i = 0; i < NumElements; i++) {
901 if (EltTy->isIntegerType()) {
902 llvm::APSInt sInt(32);
903 if (i < NumInits) {
904 if (!EvaluateInteger(E->getInit(i), sInt, Info))
905 return APValue();
906 } else {
907 sInt = Info.Ctx.MakeIntValue(0, EltTy);
908 }
909 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000910 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000911 llvm::APFloat f(0.0);
912 if (i < NumInits) {
913 if (!EvaluateFloat(E->getInit(i), f, Info))
914 return APValue();
915 } else {
916 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
917 }
918 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000919 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000920 }
921 }
922 return APValue(&Elements[0], Elements.size());
923}
924
Mike Stump1eb44332009-09-09 15:08:12 +0000925APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000926VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000927 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000928 QualType EltTy = VT->getElementType();
929 APValue ZeroElement;
930 if (EltTy->isIntegerType())
931 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
932 else
933 ZeroElement =
934 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
935
936 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
937 return APValue(&Elements[0], Elements.size());
938}
939
Eli Friedman91110ee2009-02-23 04:23:56 +0000940APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
941 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
942 Info.EvalResult.HasSideEffects = true;
943 return GetZeroVector(E->getType());
944}
945
Nate Begeman59b5da62009-01-18 03:20:47 +0000946//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000947// Integer Evaluation
948//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000949
950namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000951class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000952 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000953 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000954public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000955 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000956 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000957
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000958 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000959 assert(E->getType()->isIntegralOrEnumerationType() &&
960 "Invalid evaluation result.");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000961 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000962 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000963 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000964 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000965 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000966 return true;
967 }
968
Daniel Dunbar131eb432009-02-19 09:06:44 +0000969 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000970 assert(E->getType()->isIntegralOrEnumerationType() &&
971 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000972 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000973 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000974 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +0000975 Result.getInt().setIsUnsigned(
976 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000977 return true;
978 }
979
980 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000981 assert(E->getType()->isIntegralOrEnumerationType() &&
982 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000983 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000984 return true;
985 }
986
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000987 bool Success(CharUnits Size, const Expr *E) {
988 return Success(Size.getQuantity(), E);
989 }
990
991
Anders Carlsson82206e22008-11-30 18:14:57 +0000992 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000993 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000994 if (Info.EvalResult.Diag == 0) {
995 Info.EvalResult.DiagLoc = L;
996 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000997 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000998 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000999 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00001000 }
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001002 bool Success(const APValue &V, const Expr *E) {
1003 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00001004 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001005 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001006 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00001007 }
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001009 //===--------------------------------------------------------------------===//
1010 // Visitor Methods
1011 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001012
Chris Lattner4c4867e2008-07-12 00:38:25 +00001013 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001014 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001015 }
1016 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001017 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001018 }
Eli Friedman04309752009-11-24 05:28:59 +00001019
1020 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1021 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001022 if (CheckReferencedDecl(E, E->getDecl()))
1023 return true;
1024
1025 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001026 }
1027 bool VisitMemberExpr(const MemberExpr *E) {
1028 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1029 // Conservatively assume a MemberExpr will have side-effects
1030 Info.EvalResult.HasSideEffects = true;
1031 return true;
1032 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001033
1034 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001035 }
1036
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001037 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001038 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001039 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001040 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001041
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001042 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001043 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001044
Anders Carlsson3068d112008-11-16 19:01:22 +00001045 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001046 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001047 }
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Anders Carlsson3f704562008-12-21 22:39:40 +00001049 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001050 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001051 }
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Douglas Gregored8abf12010-07-08 06:14:04 +00001053 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001054 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001055 }
1056
Eli Friedman664a1042009-02-27 04:45:43 +00001057 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1058 return Success(0, E);
1059 }
1060
Sebastian Redl64b45f72009-01-05 20:52:13 +00001061 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001062 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001063 }
1064
Francois Pichet6ad6f282010-12-07 00:08:36 +00001065 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1066 return Success(E->getValue(), E);
1067 }
1068
John Wiegley21ff2e52011-04-28 00:16:57 +00001069 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1070 return Success(E->getValue(), E);
1071 }
1072
John Wiegley55262202011-04-25 06:54:41 +00001073 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1074 return Success(E->getValue(), E);
1075 }
1076
Eli Friedman722c7172009-02-28 03:59:05 +00001077 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001078 bool VisitUnaryImag(const UnaryOperator *E);
1079
Sebastian Redl295995c2010-09-10 20:55:47 +00001080 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001081 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1082
Chris Lattnerfcee0012008-07-11 21:24:13 +00001083private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001084 CharUnits GetAlignOfExpr(const Expr *E);
1085 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001086 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001087 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001088 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001089};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001090} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001091
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001092static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001093 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001094 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001095}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001096
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001097static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001098 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001099
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001100 APValue Val;
1101 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1102 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001103 Result = Val.getInt();
1104 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001105}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001106
Eli Friedman04309752009-11-24 05:28:59 +00001107bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001108 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001109 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1110 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001111
1112 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001113 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001114 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1115 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001116
1117 if (isa<ParmVarDecl>(D))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001118 return false;
Anders Carlssonf6b60252010-02-03 21:58:41 +00001119
Eli Friedman04309752009-11-24 05:28:59 +00001120 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001121 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001122 if (APValue *V = VD->getEvaluatedValue()) {
1123 if (V->isInt())
1124 return Success(V->getInt(), E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001125 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001126 }
1127
1128 if (VD->isEvaluatingValue())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001129 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001130
1131 VD->setEvaluatingValue();
1132
Eli Friedmana7dedf72010-09-06 00:10:32 +00001133 Expr::EvalResult EResult;
1134 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1135 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001136 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001137 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001138 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001139 return true;
1140 }
1141
Eli Friedmanc0131182009-12-03 20:31:57 +00001142 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001143 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001144 }
1145 }
1146
Chris Lattner4c4867e2008-07-12 00:38:25 +00001147 // Otherwise, random variable references are not constants.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001148 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001149}
1150
Chris Lattnera4d55d82008-10-06 06:40:35 +00001151/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1152/// as GCC.
1153static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1154 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001155 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001156 enum gcc_type_class {
1157 no_type_class = -1,
1158 void_type_class, integer_type_class, char_type_class,
1159 enumeral_type_class, boolean_type_class,
1160 pointer_type_class, reference_type_class, offset_type_class,
1161 real_type_class, complex_type_class,
1162 function_type_class, method_type_class,
1163 record_type_class, union_type_class,
1164 array_type_class, string_type_class,
1165 lang_type_class
1166 };
Mike Stump1eb44332009-09-09 15:08:12 +00001167
1168 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001169 // ideal, however it is what gcc does.
1170 if (E->getNumArgs() == 0)
1171 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Chris Lattnera4d55d82008-10-06 06:40:35 +00001173 QualType ArgTy = E->getArg(0)->getType();
1174 if (ArgTy->isVoidType())
1175 return void_type_class;
1176 else if (ArgTy->isEnumeralType())
1177 return enumeral_type_class;
1178 else if (ArgTy->isBooleanType())
1179 return boolean_type_class;
1180 else if (ArgTy->isCharType())
1181 return string_type_class; // gcc doesn't appear to use char_type_class
1182 else if (ArgTy->isIntegerType())
1183 return integer_type_class;
1184 else if (ArgTy->isPointerType())
1185 return pointer_type_class;
1186 else if (ArgTy->isReferenceType())
1187 return reference_type_class;
1188 else if (ArgTy->isRealType())
1189 return real_type_class;
1190 else if (ArgTy->isComplexType())
1191 return complex_type_class;
1192 else if (ArgTy->isFunctionType())
1193 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001194 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001195 return record_type_class;
1196 else if (ArgTy->isUnionType())
1197 return union_type_class;
1198 else if (ArgTy->isArrayType())
1199 return array_type_class;
1200 else if (ArgTy->isUnionType())
1201 return union_type_class;
1202 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1203 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1204 return -1;
1205}
1206
John McCall42c8f872010-05-10 23:27:23 +00001207/// Retrieves the "underlying object type" of the given expression,
1208/// as used by __builtin_object_size.
1209QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1210 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1211 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1212 return VD->getType();
1213 } else if (isa<CompoundLiteralExpr>(E)) {
1214 return E->getType();
1215 }
1216
1217 return QualType();
1218}
1219
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001220bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001221 // TODO: Perhaps we should let LLVM lower this?
1222 LValue Base;
1223 if (!EvaluatePointer(E->getArg(0), Base, Info))
1224 return false;
1225
1226 // If we can prove the base is null, lower to zero now.
1227 const Expr *LVBase = Base.getLValueBase();
1228 if (!LVBase) return Success(0, E);
1229
1230 QualType T = GetObjectType(LVBase);
1231 if (T.isNull() ||
1232 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001233 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001234 T->isVariablyModifiedType() ||
1235 T->isDependentType())
1236 return false;
1237
1238 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1239 CharUnits Offset = Base.getLValueOffset();
1240
1241 if (!Offset.isNegative() && Offset <= Size)
1242 Size -= Offset;
1243 else
1244 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001245 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001246}
1247
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001248bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001249 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001250 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001251 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001252
1253 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001254 if (TryEvaluateBuiltinObjectSize(E))
1255 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001256
Eric Christopherb2aaf512010-01-19 22:58:35 +00001257 // If evaluating the argument has side-effects we can't determine
1258 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001259 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001260 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001261 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001262 return Success(0, E);
1263 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001264
Mike Stump64eda9e2009-10-26 18:35:08 +00001265 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1266 }
1267
Chris Lattner019f4e82008-10-06 05:28:25 +00001268 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001269 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001271 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001272 // __builtin_constant_p always has one operand: it returns true if that
1273 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001274 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001275
1276 case Builtin::BI__builtin_eh_return_data_regno: {
1277 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1278 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1279 return Success(Operand, E);
1280 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001281
1282 case Builtin::BI__builtin_expect:
1283 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001284
1285 case Builtin::BIstrlen:
1286 case Builtin::BI__builtin_strlen:
1287 // As an extension, we support strlen() and __builtin_strlen() as constant
1288 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001289 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001290 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1291 // The string literal may have embedded null characters. Find the first
1292 // one and truncate there.
1293 llvm::StringRef Str = S->getString();
1294 llvm::StringRef::size_type Pos = Str.find(0);
1295 if (Pos != llvm::StringRef::npos)
1296 Str = Str.substr(0, Pos);
1297
1298 return Success(Str.size(), E);
1299 }
1300
1301 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001302 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001303}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001304
Chris Lattnerb542afe2008-07-11 19:10:17 +00001305bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001306 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001307 if (!Visit(E->getRHS()))
1308 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001309
Eli Friedman33ef1452009-02-26 10:19:36 +00001310 // If we can't evaluate the LHS, it might have side effects;
1311 // conservatively mark it.
1312 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1313 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001314
Anders Carlsson027f62e2008-12-01 02:07:06 +00001315 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001316 }
1317
1318 if (E->isLogicalOp()) {
1319 // These need to be handled specially because the operands aren't
1320 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001321 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001323 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001324 // We were able to evaluate the LHS, see if we can get away with not
1325 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001326 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001327 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001328
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001329 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001330 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001331 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001332 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001333 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001334 }
1335 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001336 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001337 // We can't evaluate the LHS; however, sometimes the result
1338 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001339 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1340 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001341 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001342 // must have had side effects.
1343 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001344
1345 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001346 }
1347 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001348 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001349
Eli Friedmana6afa762008-11-13 06:09:17 +00001350 return false;
1351 }
1352
Anders Carlsson286f85e2008-11-16 07:17:21 +00001353 QualType LHSTy = E->getLHS()->getType();
1354 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001355
1356 if (LHSTy->isAnyComplexType()) {
1357 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001358 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001359
1360 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1361 return false;
1362
1363 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1364 return false;
1365
1366 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001367 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001368 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001369 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001370 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1371
John McCall2de56d12010-08-25 11:45:40 +00001372 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001373 return Success((CR_r == APFloat::cmpEqual &&
1374 CR_i == APFloat::cmpEqual), E);
1375 else {
John McCall2de56d12010-08-25 11:45:40 +00001376 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001377 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001378 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001379 CR_r == APFloat::cmpLessThan ||
1380 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001381 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001382 CR_i == APFloat::cmpLessThan ||
1383 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001384 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001385 } else {
John McCall2de56d12010-08-25 11:45:40 +00001386 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001387 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1388 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1389 else {
John McCall2de56d12010-08-25 11:45:40 +00001390 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001391 "Invalid compex comparison.");
1392 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1393 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1394 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001395 }
1396 }
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Anders Carlsson286f85e2008-11-16 07:17:21 +00001398 if (LHSTy->isRealFloatingType() &&
1399 RHSTy->isRealFloatingType()) {
1400 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Anders Carlsson286f85e2008-11-16 07:17:21 +00001402 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1403 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Anders Carlsson286f85e2008-11-16 07:17:21 +00001405 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1406 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Anders Carlsson286f85e2008-11-16 07:17:21 +00001408 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001409
Anders Carlsson286f85e2008-11-16 07:17:21 +00001410 switch (E->getOpcode()) {
1411 default:
1412 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001413 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001414 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001415 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001416 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001417 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001418 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001419 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001420 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001421 E);
John McCall2de56d12010-08-25 11:45:40 +00001422 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001423 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001424 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001425 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001426 || CR == APFloat::cmpLessThan
1427 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001428 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001429 }
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001431 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001432 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001433 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001434 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1435 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001436
John McCallefdb83e2010-05-07 21:00:08 +00001437 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001438 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1439 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001440
Eli Friedman5bc86102009-06-14 02:17:33 +00001441 // Reject any bases from the normal codepath; we special-case comparisons
1442 // to null.
1443 if (LHSValue.getLValueBase()) {
1444 if (!E->isEqualityOp())
1445 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001446 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001447 return false;
1448 bool bres;
1449 if (!EvalPointerValueAsBool(LHSValue, bres))
1450 return false;
John McCall2de56d12010-08-25 11:45:40 +00001451 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001452 } else if (RHSValue.getLValueBase()) {
1453 if (!E->isEqualityOp())
1454 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001455 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001456 return false;
1457 bool bres;
1458 if (!EvalPointerValueAsBool(RHSValue, 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 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001462
John McCall2de56d12010-08-25 11:45:40 +00001463 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001464 QualType Type = E->getLHS()->getType();
1465 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001466
Ken Dycka7305832010-01-15 12:37:54 +00001467 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001468 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001469 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001470
Ken Dycka7305832010-01-15 12:37:54 +00001471 CharUnits Diff = LHSValue.getLValueOffset() -
1472 RHSValue.getLValueOffset();
1473 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001474 }
1475 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001476 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001477 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001478 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001479 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1480 }
1481 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001482 }
1483 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001484 if (!LHSTy->isIntegralOrEnumerationType() ||
1485 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001486 // We can't continue from here for non-integral types, and they
1487 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001488 return false;
1489 }
1490
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001491 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001492 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001493 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001494
Eli Friedman42edd0d2009-03-24 01:14:50 +00001495 APValue RHSVal;
1496 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001497 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001498
1499 // Handle cases like (unsigned long)&a + 4.
1500 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001501 CharUnits Offset = Result.getLValueOffset();
1502 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1503 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001504 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001505 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001506 else
Ken Dycka7305832010-01-15 12:37:54 +00001507 Offset -= AdditionalOffset;
1508 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001509 return true;
1510 }
1511
1512 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001513 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001514 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001515 CharUnits Offset = RHSVal.getLValueOffset();
1516 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1517 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001518 return true;
1519 }
1520
1521 // All the following cases expect both operands to be an integer
1522 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001523 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001524
Eli Friedman42edd0d2009-03-24 01:14:50 +00001525 APSInt& RHS = RHSVal.getInt();
1526
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001527 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001528 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001529 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001530 case BO_Mul: return Success(Result.getInt() * RHS, E);
1531 case BO_Add: return Success(Result.getInt() + RHS, E);
1532 case BO_Sub: return Success(Result.getInt() - RHS, E);
1533 case BO_And: return Success(Result.getInt() & RHS, E);
1534 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1535 case BO_Or: return Success(Result.getInt() | RHS, E);
1536 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001537 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001538 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001539 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001540 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001541 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001542 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001543 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001544 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001545 // During constant-folding, a negative shift is an opposite shift.
1546 if (RHS.isSigned() && RHS.isNegative()) {
1547 RHS = -RHS;
1548 goto shift_right;
1549 }
1550
1551 shift_left:
1552 unsigned SA
1553 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001554 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001555 }
John McCall2de56d12010-08-25 11:45:40 +00001556 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001557 // During constant-folding, a negative shift is an opposite shift.
1558 if (RHS.isSigned() && RHS.isNegative()) {
1559 RHS = -RHS;
1560 goto shift_left;
1561 }
1562
1563 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001564 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001565 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1566 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
John McCall2de56d12010-08-25 11:45:40 +00001569 case BO_LT: return Success(Result.getInt() < RHS, E);
1570 case BO_GT: return Success(Result.getInt() > RHS, E);
1571 case BO_LE: return Success(Result.getInt() <= RHS, E);
1572 case BO_GE: return Success(Result.getInt() >= RHS, E);
1573 case BO_EQ: return Success(Result.getInt() == RHS, E);
1574 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001575 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001576}
1577
Ken Dyck8b752f12010-01-27 17:10:57 +00001578CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001579 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1580 // the result is the size of the referenced type."
1581 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1582 // result shall be the alignment of the referenced type."
1583 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1584 T = Ref->getPointeeType();
1585
Eli Friedman2be58612009-05-30 21:09:44 +00001586 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001587 return Info.Ctx.toCharUnitsFromBits(
1588 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001589}
1590
Ken Dyck8b752f12010-01-27 17:10:57 +00001591CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001592 E = E->IgnoreParens();
1593
1594 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001595 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001596 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001597 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1598 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001599
Chris Lattneraf707ab2009-01-24 21:53:27 +00001600 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001601 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1602 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001603
Chris Lattnere9feb472009-01-24 21:09:06 +00001604 return GetAlignOfType(E->getType());
1605}
1606
1607
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001608/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1609/// a result as the expression's type.
1610bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1611 const UnaryExprOrTypeTraitExpr *E) {
1612 switch(E->getKind()) {
1613 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001614 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001615 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001616 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001617 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001618 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001619
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001620 case UETT_VecStep: {
1621 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001622
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001623 if (Ty->isVectorType()) {
1624 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001625
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001626 // The vec_step built-in functions that take a 3-component
1627 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1628 if (n == 3)
1629 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001630
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001631 return Success(n, E);
1632 } else
1633 return Success(1, E);
1634 }
1635
1636 case UETT_SizeOf: {
1637 QualType SrcTy = E->getTypeOfArgument();
1638 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1639 // the result is the size of the referenced type."
1640 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1641 // result shall be the alignment of the referenced type."
1642 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1643 SrcTy = Ref->getPointeeType();
1644
1645 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1646 // extension.
1647 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1648 return Success(1, E);
1649
1650 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1651 if (!SrcTy->isConstantSizeType())
1652 return false;
1653
1654 // Get information about the size.
1655 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1656 }
1657 }
1658
1659 llvm_unreachable("unknown expr/type trait");
1660 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001661}
1662
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001663bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001664 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001665 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001666 if (n == 0)
1667 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001668 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001669 for (unsigned i = 0; i != n; ++i) {
1670 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1671 switch (ON.getKind()) {
1672 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001673 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001674 APSInt IdxResult;
1675 if (!EvaluateInteger(Idx, IdxResult, Info))
1676 return false;
1677 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1678 if (!AT)
1679 return false;
1680 CurrentType = AT->getElementType();
1681 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1682 Result += IdxResult.getSExtValue() * ElementSize;
1683 break;
1684 }
1685
1686 case OffsetOfExpr::OffsetOfNode::Field: {
1687 FieldDecl *MemberDecl = ON.getField();
1688 const RecordType *RT = CurrentType->getAs<RecordType>();
1689 if (!RT)
1690 return false;
1691 RecordDecl *RD = RT->getDecl();
1692 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001693 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001694 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001695 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001696 CurrentType = MemberDecl->getType().getNonReferenceType();
1697 break;
1698 }
1699
1700 case OffsetOfExpr::OffsetOfNode::Identifier:
1701 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001702 return false;
1703
1704 case OffsetOfExpr::OffsetOfNode::Base: {
1705 CXXBaseSpecifier *BaseSpec = ON.getBase();
1706 if (BaseSpec->isVirtual())
1707 return false;
1708
1709 // Find the layout of the class whose base we are looking into.
1710 const RecordType *RT = CurrentType->getAs<RecordType>();
1711 if (!RT)
1712 return false;
1713 RecordDecl *RD = RT->getDecl();
1714 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1715
1716 // Find the base class itself.
1717 CurrentType = BaseSpec->getType();
1718 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1719 if (!BaseRT)
1720 return false;
1721
1722 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001723 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001724 break;
1725 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001726 }
1727 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001728 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001729}
1730
Chris Lattnerb542afe2008-07-11 19:10:17 +00001731bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001732 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001733 // LNot's operand isn't necessarily an integer, so we handle it specially.
1734 bool bres;
1735 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1736 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001737 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001738 }
1739
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001740 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001741 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001742 return false;
1743
Chris Lattner87eae5e2008-07-11 22:52:41 +00001744 // Get the operand value into 'Result'.
1745 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001746 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001747
Chris Lattner75a48812008-07-11 22:15:16 +00001748 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001749 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001750 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1751 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001752 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001753 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001754 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1755 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001756 return true;
John McCall2de56d12010-08-25 11:45:40 +00001757 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001758 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001759 return true;
John McCall2de56d12010-08-25 11:45:40 +00001760 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001761 if (!Result.isInt()) return false;
1762 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001763 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001764 if (!Result.isInt()) return false;
1765 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001766 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001767}
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Chris Lattner732b2232008-07-12 01:15:53 +00001769/// HandleCast - This is used to evaluate implicit or explicit casts where the
1770/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001771bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1772 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001773 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001774 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001775
Eli Friedman46a52322011-03-25 00:43:55 +00001776 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001777 case CK_BaseToDerived:
1778 case CK_DerivedToBase:
1779 case CK_UncheckedDerivedToBase:
1780 case CK_Dynamic:
1781 case CK_ToUnion:
1782 case CK_ArrayToPointerDecay:
1783 case CK_FunctionToPointerDecay:
1784 case CK_NullToPointer:
1785 case CK_NullToMemberPointer:
1786 case CK_BaseToDerivedMemberPointer:
1787 case CK_DerivedToBaseMemberPointer:
1788 case CK_ConstructorConversion:
1789 case CK_IntegralToPointer:
1790 case CK_ToVoid:
1791 case CK_VectorSplat:
1792 case CK_IntegralToFloating:
1793 case CK_FloatingCast:
1794 case CK_AnyPointerToObjCPointerCast:
1795 case CK_AnyPointerToBlockPointerCast:
1796 case CK_ObjCObjectLValueCast:
1797 case CK_FloatingRealToComplex:
1798 case CK_FloatingComplexToReal:
1799 case CK_FloatingComplexCast:
1800 case CK_FloatingComplexToIntegralComplex:
1801 case CK_IntegralRealToComplex:
1802 case CK_IntegralComplexCast:
1803 case CK_IntegralComplexToFloatingComplex:
1804 llvm_unreachable("invalid cast kind for integral value");
1805
Eli Friedmane50c2972011-03-25 19:07:11 +00001806 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001807 case CK_Dependent:
1808 case CK_GetObjCProperty:
1809 case CK_LValueBitCast:
1810 case CK_UserDefinedConversion:
John McCallf85e1932011-06-15 23:02:42 +00001811 case CK_ObjCProduceObject:
1812 case CK_ObjCConsumeObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001813 return false;
1814
1815 case CK_LValueToRValue:
1816 case CK_NoOp:
1817 return Visit(E->getSubExpr());
1818
1819 case CK_MemberPointerToBoolean:
1820 case CK_PointerToBoolean:
1821 case CK_IntegralToBoolean:
1822 case CK_FloatingToBoolean:
1823 case CK_FloatingComplexToBoolean:
1824 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001825 bool BoolResult;
1826 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1827 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001828 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001829 }
1830
Eli Friedman46a52322011-03-25 00:43:55 +00001831 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001832 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001833 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001834
Eli Friedmanbe265702009-02-20 01:15:07 +00001835 if (!Result.isInt()) {
1836 // Only allow casts of lvalues if they are lossless.
1837 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1838 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001839
Daniel Dunbardd211642009-02-19 22:24:01 +00001840 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001841 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001842 }
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Eli Friedman46a52322011-03-25 00:43:55 +00001844 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001845 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001846 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001847 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001848
Daniel Dunbardd211642009-02-19 22:24:01 +00001849 if (LV.getLValueBase()) {
1850 // Only allow based lvalue casts if they are lossless.
1851 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1852 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001853
John McCallefdb83e2010-05-07 21:00:08 +00001854 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001855 return true;
1856 }
1857
Ken Dycka7305832010-01-15 12:37:54 +00001858 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1859 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001860 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001861 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001862
Eli Friedman46a52322011-03-25 00:43:55 +00001863 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001864 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001865 if (!EvaluateComplex(SubExpr, C, Info))
1866 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001867 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001868 }
Eli Friedman2217c872009-02-22 11:46:18 +00001869
Eli Friedman46a52322011-03-25 00:43:55 +00001870 case CK_FloatingToIntegral: {
1871 APFloat F(0.0);
1872 if (!EvaluateFloat(SubExpr, F, Info))
1873 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001874
Eli Friedman46a52322011-03-25 00:43:55 +00001875 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1876 }
1877 }
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Eli Friedman46a52322011-03-25 00:43:55 +00001879 llvm_unreachable("unknown cast resulting in integral value");
1880 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001881}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001882
Eli Friedman722c7172009-02-28 03:59:05 +00001883bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1884 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001885 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001886 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1887 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1888 return Success(LV.getComplexIntReal(), E);
1889 }
1890
1891 return Visit(E->getSubExpr());
1892}
1893
Eli Friedman664a1042009-02-27 04:45:43 +00001894bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001895 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001896 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001897 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1898 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1899 return Success(LV.getComplexIntImag(), E);
1900 }
1901
Eli Friedman664a1042009-02-27 04:45:43 +00001902 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1903 Info.EvalResult.HasSideEffects = true;
1904 return Success(0, E);
1905}
1906
Douglas Gregoree8aff02011-01-04 17:33:58 +00001907bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1908 return Success(E->getPackLength(), E);
1909}
1910
Sebastian Redl295995c2010-09-10 20:55:47 +00001911bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1912 return Success(E->getValue(), E);
1913}
1914
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001915//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001916// Float Evaluation
1917//===----------------------------------------------------------------------===//
1918
1919namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001920class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001921 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001922 APFloat &Result;
1923public:
1924 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001925 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001926
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001927 bool Success(const APValue &V, const Expr *e) {
1928 Result = V.getFloat();
1929 return true;
1930 }
1931 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001932 return false;
1933 }
1934
Chris Lattner019f4e82008-10-06 05:28:25 +00001935 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001936
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001937 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001938 bool VisitBinaryOperator(const BinaryOperator *E);
1939 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001940 bool VisitCastExpr(const CastExpr *E);
1941 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001942
John McCallabd3a852010-05-07 22:08:54 +00001943 bool VisitUnaryReal(const UnaryOperator *E);
1944 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001945
John McCall189d6ef2010-10-09 01:34:31 +00001946 bool VisitDeclRefExpr(const DeclRefExpr *E);
1947
John McCallabd3a852010-05-07 22:08:54 +00001948 // FIXME: Missing: array subscript of vector, member of vector,
1949 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001950};
1951} // end anonymous namespace
1952
1953static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001954 assert(E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001955 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001956}
1957
Jay Foad4ba2a172011-01-12 09:06:06 +00001958static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001959 QualType ResultTy,
1960 const Expr *Arg,
1961 bool SNaN,
1962 llvm::APFloat &Result) {
1963 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1964 if (!S) return false;
1965
1966 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1967
1968 llvm::APInt fill;
1969
1970 // Treat empty strings as if they were zero.
1971 if (S->getString().empty())
1972 fill = llvm::APInt(32, 0);
1973 else if (S->getString().getAsInteger(0, fill))
1974 return false;
1975
1976 if (SNaN)
1977 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1978 else
1979 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1980 return true;
1981}
1982
Chris Lattner019f4e82008-10-06 05:28:25 +00001983bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001984 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001985 default:
1986 return ExprEvaluatorBaseTy::VisitCallExpr(E);
1987
Chris Lattner019f4e82008-10-06 05:28:25 +00001988 case Builtin::BI__builtin_huge_val:
1989 case Builtin::BI__builtin_huge_valf:
1990 case Builtin::BI__builtin_huge_vall:
1991 case Builtin::BI__builtin_inf:
1992 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001993 case Builtin::BI__builtin_infl: {
1994 const llvm::fltSemantics &Sem =
1995 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001996 Result = llvm::APFloat::getInf(Sem);
1997 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001998 }
Mike Stump1eb44332009-09-09 15:08:12 +00001999
John McCalldb7b72a2010-02-28 13:00:19 +00002000 case Builtin::BI__builtin_nans:
2001 case Builtin::BI__builtin_nansf:
2002 case Builtin::BI__builtin_nansl:
2003 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2004 true, Result);
2005
Chris Lattner9e621712008-10-06 06:31:58 +00002006 case Builtin::BI__builtin_nan:
2007 case Builtin::BI__builtin_nanf:
2008 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002009 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002010 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002011 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2012 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002013
2014 case Builtin::BI__builtin_fabs:
2015 case Builtin::BI__builtin_fabsf:
2016 case Builtin::BI__builtin_fabsl:
2017 if (!EvaluateFloat(E->getArg(0), Result, Info))
2018 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002020 if (Result.isNegative())
2021 Result.changeSign();
2022 return true;
2023
Mike Stump1eb44332009-09-09 15:08:12 +00002024 case Builtin::BI__builtin_copysign:
2025 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002026 case Builtin::BI__builtin_copysignl: {
2027 APFloat RHS(0.);
2028 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2029 !EvaluateFloat(E->getArg(1), RHS, Info))
2030 return false;
2031 Result.copySign(RHS);
2032 return true;
2033 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002034 }
2035}
2036
John McCall189d6ef2010-10-09 01:34:31 +00002037bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002038 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2039 return true;
2040
John McCall189d6ef2010-10-09 01:34:31 +00002041 const Decl *D = E->getDecl();
2042 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2043 const VarDecl *VD = cast<VarDecl>(D);
2044
2045 // Require the qualifiers to be const and not volatile.
2046 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2047 if (!T.isConstQualified() || T.isVolatileQualified())
2048 return false;
2049
2050 const Expr *Init = VD->getAnyInitializer();
2051 if (!Init) return false;
2052
2053 if (APValue *V = VD->getEvaluatedValue()) {
2054 if (V->isFloat()) {
2055 Result = V->getFloat();
2056 return true;
2057 }
2058 return false;
2059 }
2060
2061 if (VD->isEvaluatingValue())
2062 return false;
2063
2064 VD->setEvaluatingValue();
2065
2066 Expr::EvalResult InitResult;
2067 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2068 InitResult.Val.isFloat()) {
2069 // Cache the evaluated value in the variable declaration.
2070 Result = InitResult.Val.getFloat();
2071 VD->setEvaluatedValue(InitResult.Val);
2072 return true;
2073 }
2074
2075 VD->setEvaluatedValue(APValue());
2076 return false;
2077}
2078
John McCallabd3a852010-05-07 22:08:54 +00002079bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002080 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2081 ComplexValue CV;
2082 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2083 return false;
2084 Result = CV.FloatReal;
2085 return true;
2086 }
2087
2088 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002089}
2090
2091bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002092 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2093 ComplexValue CV;
2094 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2095 return false;
2096 Result = CV.FloatImag;
2097 return true;
2098 }
2099
2100 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2101 Info.EvalResult.HasSideEffects = true;
2102 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2103 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002104 return true;
2105}
2106
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002107bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002108 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002109 return false;
2110
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002111 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2112 return false;
2113
2114 switch (E->getOpcode()) {
2115 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002116 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002117 return true;
John McCall2de56d12010-08-25 11:45:40 +00002118 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002119 Result.changeSign();
2120 return true;
2121 }
2122}
Chris Lattner019f4e82008-10-06 05:28:25 +00002123
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002124bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002125 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002126 if (!EvaluateFloat(E->getRHS(), Result, Info))
2127 return false;
2128
2129 // If we can't evaluate the LHS, it might have side effects;
2130 // conservatively mark it.
2131 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2132 Info.EvalResult.HasSideEffects = true;
2133
2134 return true;
2135 }
2136
Anders Carlsson96e93662010-10-31 01:21:47 +00002137 // We can't evaluate pointer-to-member operations.
2138 if (E->isPtrMemOp())
2139 return false;
2140
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002141 // FIXME: Diagnostics? I really don't understand how the warnings
2142 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002143 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002144 if (!EvaluateFloat(E->getLHS(), Result, Info))
2145 return false;
2146 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2147 return false;
2148
2149 switch (E->getOpcode()) {
2150 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002151 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002152 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2153 return true;
John McCall2de56d12010-08-25 11:45:40 +00002154 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002155 Result.add(RHS, APFloat::rmNearestTiesToEven);
2156 return true;
John McCall2de56d12010-08-25 11:45:40 +00002157 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002158 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2159 return true;
John McCall2de56d12010-08-25 11:45:40 +00002160 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002161 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2162 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002163 }
2164}
2165
2166bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2167 Result = E->getValue();
2168 return true;
2169}
2170
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002171bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2172 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Eli Friedman2a523ee2011-03-25 00:54:52 +00002174 switch (E->getCastKind()) {
2175 default:
2176 return false;
2177
2178 case CK_LValueToRValue:
2179 case CK_NoOp:
2180 return Visit(SubExpr);
2181
2182 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002183 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002184 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002185 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002186 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002187 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002188 return true;
2189 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002190
2191 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002192 if (!Visit(SubExpr))
2193 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002194 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2195 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002196 return true;
2197 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002198
Eli Friedman2a523ee2011-03-25 00:54:52 +00002199 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002200 ComplexValue V;
2201 if (!EvaluateComplex(SubExpr, V, Info))
2202 return false;
2203 Result = V.getComplexFloatReal();
2204 return true;
2205 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002206 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002207
2208 return false;
2209}
2210
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002211bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002212 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2213 return true;
2214}
2215
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002216//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002217// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002218//===----------------------------------------------------------------------===//
2219
2220namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002221class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002222 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002223 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002225public:
John McCallf4cf1a12010-05-07 17:22:02 +00002226 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002227 : ExprEvaluatorBaseTy(info), Result(Result) {}
2228
2229 bool Success(const APValue &V, const Expr *e) {
2230 Result.setFrom(V);
2231 return true;
2232 }
2233 bool Error(const Expr *E) {
2234 return false;
2235 }
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002237 //===--------------------------------------------------------------------===//
2238 // Visitor Methods
2239 //===--------------------------------------------------------------------===//
2240
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002241 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002243 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002244
John McCallf4cf1a12010-05-07 17:22:02 +00002245 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002246 bool VisitUnaryOperator(const UnaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002247 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002248};
2249} // end anonymous namespace
2250
John McCallf4cf1a12010-05-07 17:22:02 +00002251static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2252 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002253 assert(E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002254 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002255}
2256
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002257bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2258 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002259
2260 if (SubExpr->getType()->isRealFloatingType()) {
2261 Result.makeComplexFloat();
2262 APFloat &Imag = Result.FloatImag;
2263 if (!EvaluateFloat(SubExpr, Imag, Info))
2264 return false;
2265
2266 Result.FloatReal = APFloat(Imag.getSemantics());
2267 return true;
2268 } else {
2269 assert(SubExpr->getType()->isIntegerType() &&
2270 "Unexpected imaginary literal.");
2271
2272 Result.makeComplexInt();
2273 APSInt &Imag = Result.IntImag;
2274 if (!EvaluateInteger(SubExpr, Imag, Info))
2275 return false;
2276
2277 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2278 return true;
2279 }
2280}
2281
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002282bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002283
John McCall8786da72010-12-14 17:51:41 +00002284 switch (E->getCastKind()) {
2285 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002286 case CK_BaseToDerived:
2287 case CK_DerivedToBase:
2288 case CK_UncheckedDerivedToBase:
2289 case CK_Dynamic:
2290 case CK_ToUnion:
2291 case CK_ArrayToPointerDecay:
2292 case CK_FunctionToPointerDecay:
2293 case CK_NullToPointer:
2294 case CK_NullToMemberPointer:
2295 case CK_BaseToDerivedMemberPointer:
2296 case CK_DerivedToBaseMemberPointer:
2297 case CK_MemberPointerToBoolean:
2298 case CK_ConstructorConversion:
2299 case CK_IntegralToPointer:
2300 case CK_PointerToIntegral:
2301 case CK_PointerToBoolean:
2302 case CK_ToVoid:
2303 case CK_VectorSplat:
2304 case CK_IntegralCast:
2305 case CK_IntegralToBoolean:
2306 case CK_IntegralToFloating:
2307 case CK_FloatingToIntegral:
2308 case CK_FloatingToBoolean:
2309 case CK_FloatingCast:
2310 case CK_AnyPointerToObjCPointerCast:
2311 case CK_AnyPointerToBlockPointerCast:
2312 case CK_ObjCObjectLValueCast:
2313 case CK_FloatingComplexToReal:
2314 case CK_FloatingComplexToBoolean:
2315 case CK_IntegralComplexToReal:
2316 case CK_IntegralComplexToBoolean:
John McCallf85e1932011-06-15 23:02:42 +00002317 case CK_ObjCProduceObject:
2318 case CK_ObjCConsumeObject:
John McCall8786da72010-12-14 17:51:41 +00002319 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002320
John McCall8786da72010-12-14 17:51:41 +00002321 case CK_LValueToRValue:
2322 case CK_NoOp:
2323 return Visit(E->getSubExpr());
2324
2325 case CK_Dependent:
2326 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002327 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002328 case CK_UserDefinedConversion:
2329 return false;
2330
2331 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002332 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002333 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002334 return false;
2335
John McCall8786da72010-12-14 17:51:41 +00002336 Result.makeComplexFloat();
2337 Result.FloatImag = APFloat(Real.getSemantics());
2338 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002339 }
2340
John McCall8786da72010-12-14 17:51:41 +00002341 case CK_FloatingComplexCast: {
2342 if (!Visit(E->getSubExpr()))
2343 return false;
2344
2345 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2346 QualType From
2347 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2348
2349 Result.FloatReal
2350 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2351 Result.FloatImag
2352 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2353 return true;
2354 }
2355
2356 case CK_FloatingComplexToIntegralComplex: {
2357 if (!Visit(E->getSubExpr()))
2358 return false;
2359
2360 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2361 QualType From
2362 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2363 Result.makeComplexInt();
2364 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2365 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2366 return true;
2367 }
2368
2369 case CK_IntegralRealToComplex: {
2370 APSInt &Real = Result.IntReal;
2371 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2372 return false;
2373
2374 Result.makeComplexInt();
2375 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2376 return true;
2377 }
2378
2379 case CK_IntegralComplexCast: {
2380 if (!Visit(E->getSubExpr()))
2381 return false;
2382
2383 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2384 QualType From
2385 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2386
2387 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2388 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2389 return true;
2390 }
2391
2392 case CK_IntegralComplexToFloatingComplex: {
2393 if (!Visit(E->getSubExpr()))
2394 return false;
2395
2396 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2397 QualType From
2398 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2399 Result.makeComplexFloat();
2400 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2401 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2402 return true;
2403 }
2404 }
2405
2406 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002407 return false;
2408}
2409
John McCallf4cf1a12010-05-07 17:22:02 +00002410bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002411 if (E->getOpcode() == BO_Comma) {
2412 if (!Visit(E->getRHS()))
2413 return false;
2414
2415 // If we can't evaluate the LHS, it might have side effects;
2416 // conservatively mark it.
2417 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2418 Info.EvalResult.HasSideEffects = true;
2419
2420 return true;
2421 }
John McCallf4cf1a12010-05-07 17:22:02 +00002422 if (!Visit(E->getLHS()))
2423 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002424
John McCallf4cf1a12010-05-07 17:22:02 +00002425 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002426 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002427 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002428
Daniel Dunbar3f279872009-01-29 01:32:56 +00002429 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2430 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002431 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002432 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002433 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002434 if (Result.isComplexFloat()) {
2435 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2436 APFloat::rmNearestTiesToEven);
2437 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2438 APFloat::rmNearestTiesToEven);
2439 } else {
2440 Result.getComplexIntReal() += RHS.getComplexIntReal();
2441 Result.getComplexIntImag() += RHS.getComplexIntImag();
2442 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002443 break;
John McCall2de56d12010-08-25 11:45:40 +00002444 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002445 if (Result.isComplexFloat()) {
2446 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2447 APFloat::rmNearestTiesToEven);
2448 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2449 APFloat::rmNearestTiesToEven);
2450 } else {
2451 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2452 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2453 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002454 break;
John McCall2de56d12010-08-25 11:45:40 +00002455 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002456 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002457 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002458 APFloat &LHS_r = LHS.getComplexFloatReal();
2459 APFloat &LHS_i = LHS.getComplexFloatImag();
2460 APFloat &RHS_r = RHS.getComplexFloatReal();
2461 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002462
Daniel Dunbar3f279872009-01-29 01:32:56 +00002463 APFloat Tmp = LHS_r;
2464 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2465 Result.getComplexFloatReal() = Tmp;
2466 Tmp = LHS_i;
2467 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2468 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2469
2470 Tmp = LHS_r;
2471 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2472 Result.getComplexFloatImag() = Tmp;
2473 Tmp = LHS_i;
2474 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2475 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2476 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002477 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002478 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002479 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2480 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002481 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002482 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2483 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2484 }
2485 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002486 case BO_Div:
2487 if (Result.isComplexFloat()) {
2488 ComplexValue LHS = Result;
2489 APFloat &LHS_r = LHS.getComplexFloatReal();
2490 APFloat &LHS_i = LHS.getComplexFloatImag();
2491 APFloat &RHS_r = RHS.getComplexFloatReal();
2492 APFloat &RHS_i = RHS.getComplexFloatImag();
2493 APFloat &Res_r = Result.getComplexFloatReal();
2494 APFloat &Res_i = Result.getComplexFloatImag();
2495
2496 APFloat Den = RHS_r;
2497 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2498 APFloat Tmp = RHS_i;
2499 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2500 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2501
2502 Res_r = LHS_r;
2503 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2504 Tmp = LHS_i;
2505 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2506 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2507 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2508
2509 Res_i = LHS_i;
2510 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2511 Tmp = LHS_r;
2512 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2513 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2514 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2515 } else {
2516 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2517 // FIXME: what about diagnostics?
2518 return false;
2519 }
2520 ComplexValue LHS = Result;
2521 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2522 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2523 Result.getComplexIntReal() =
2524 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2525 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2526 Result.getComplexIntImag() =
2527 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2528 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2529 }
2530 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002531 }
2532
John McCallf4cf1a12010-05-07 17:22:02 +00002533 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002534}
2535
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002536bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2537 // Get the operand value into 'Result'.
2538 if (!Visit(E->getSubExpr()))
2539 return false;
2540
2541 switch (E->getOpcode()) {
2542 default:
2543 // FIXME: what about diagnostics?
2544 return false;
2545 case UO_Extension:
2546 return true;
2547 case UO_Plus:
2548 // The result is always just the subexpr.
2549 return true;
2550 case UO_Minus:
2551 if (Result.isComplexFloat()) {
2552 Result.getComplexFloatReal().changeSign();
2553 Result.getComplexFloatImag().changeSign();
2554 }
2555 else {
2556 Result.getComplexIntReal() = -Result.getComplexIntReal();
2557 Result.getComplexIntImag() = -Result.getComplexIntImag();
2558 }
2559 return true;
2560 case UO_Not:
2561 if (Result.isComplexFloat())
2562 Result.getComplexFloatImag().changeSign();
2563 else
2564 Result.getComplexIntImag() = -Result.getComplexIntImag();
2565 return true;
2566 }
2567}
2568
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002569//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002570// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002571//===----------------------------------------------------------------------===//
2572
John McCall56ca35d2011-02-17 10:25:35 +00002573static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002574 if (E->getType()->isVectorType()) {
2575 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002576 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002577 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002578 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002579 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002580 if (Info.EvalResult.Val.isLValue() &&
2581 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002582 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002583 } else if (E->getType()->hasPointerRepresentation()) {
2584 LValue LV;
2585 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002586 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002587 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002588 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002589 LV.moveInto(Info.EvalResult.Val);
2590 } else if (E->getType()->isRealFloatingType()) {
2591 llvm::APFloat F(0.0);
2592 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002593 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002594
John McCallefdb83e2010-05-07 21:00:08 +00002595 Info.EvalResult.Val = APValue(F);
2596 } else if (E->getType()->isAnyComplexType()) {
2597 ComplexValue C;
2598 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002599 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002600 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002601 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002602 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002603
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002604 return true;
2605}
2606
John McCall56ca35d2011-02-17 10:25:35 +00002607/// Evaluate - Return true if this is a constant which we can fold using
2608/// any crazy technique (that has nothing to do with language standards) that
2609/// we want to. If this function returns true, it returns the folded constant
2610/// in Result.
2611bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2612 EvalInfo Info(Ctx, Result);
2613 return ::Evaluate(Info, this);
2614}
2615
Jay Foad4ba2a172011-01-12 09:06:06 +00002616bool Expr::EvaluateAsBooleanCondition(bool &Result,
2617 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002618 EvalResult Scratch;
2619 EvalInfo Info(Ctx, Scratch);
2620
2621 return HandleConversionToBool(this, Result, Info);
2622}
2623
Jay Foad4ba2a172011-01-12 09:06:06 +00002624bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002625 EvalInfo Info(Ctx, Result);
2626
John McCallefdb83e2010-05-07 21:00:08 +00002627 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002628 if (EvaluateLValue(this, LV, Info) &&
2629 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002630 IsGlobalLValue(LV.Base)) {
2631 LV.moveInto(Result.Val);
2632 return true;
2633 }
2634 return false;
2635}
2636
Jay Foad4ba2a172011-01-12 09:06:06 +00002637bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2638 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002639 EvalInfo Info(Ctx, Result);
2640
2641 LValue LV;
2642 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002643 LV.moveInto(Result.Val);
2644 return true;
2645 }
2646 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002647}
2648
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002649/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002650/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002651bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002652 EvalResult Result;
2653 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002654}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002655
Jay Foad4ba2a172011-01-12 09:06:06 +00002656bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002657 Expr::EvalResult Result;
2658 EvalInfo Info(Ctx, Result);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002659 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002660}
2661
Jay Foad4ba2a172011-01-12 09:06:06 +00002662APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002663 EvalResult EvalResult;
2664 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002665 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002666 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002667 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002668
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002669 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002670}
John McCalld905f5a2010-05-07 05:32:02 +00002671
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002672 bool Expr::EvalResult::isGlobalLValue() const {
2673 assert(Val.isLValue());
2674 return IsGlobalLValue(Val.getLValueBase());
2675 }
2676
2677
John McCalld905f5a2010-05-07 05:32:02 +00002678/// isIntegerConstantExpr - this recursive routine will test if an expression is
2679/// an integer constant expression.
2680
2681/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2682/// comma, etc
2683///
2684/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2685/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2686/// cast+dereference.
2687
2688// CheckICE - This function does the fundamental ICE checking: the returned
2689// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2690// Note that to reduce code duplication, this helper does no evaluation
2691// itself; the caller checks whether the expression is evaluatable, and
2692// in the rare cases where CheckICE actually cares about the evaluated
2693// value, it calls into Evalute.
2694//
2695// Meanings of Val:
2696// 0: This expression is an ICE if it can be evaluated by Evaluate.
2697// 1: This expression is not an ICE, but if it isn't evaluated, it's
2698// a legal subexpression for an ICE. This return value is used to handle
2699// the comma operator in C99 mode.
2700// 2: This expression is not an ICE, and is not a legal subexpression for one.
2701
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002702namespace {
2703
John McCalld905f5a2010-05-07 05:32:02 +00002704struct ICEDiag {
2705 unsigned Val;
2706 SourceLocation Loc;
2707
2708 public:
2709 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2710 ICEDiag() : Val(0) {}
2711};
2712
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002713}
2714
2715static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002716
2717static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2718 Expr::EvalResult EVResult;
2719 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2720 !EVResult.Val.isInt()) {
2721 return ICEDiag(2, E->getLocStart());
2722 }
2723 return NoDiag();
2724}
2725
2726static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2727 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002728 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002729 return ICEDiag(2, E->getLocStart());
2730 }
2731
2732 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002733#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002734#define STMT(Node, Base) case Expr::Node##Class:
2735#define EXPR(Node, Base)
2736#include "clang/AST/StmtNodes.inc"
2737 case Expr::PredefinedExprClass:
2738 case Expr::FloatingLiteralClass:
2739 case Expr::ImaginaryLiteralClass:
2740 case Expr::StringLiteralClass:
2741 case Expr::ArraySubscriptExprClass:
2742 case Expr::MemberExprClass:
2743 case Expr::CompoundAssignOperatorClass:
2744 case Expr::CompoundLiteralExprClass:
2745 case Expr::ExtVectorElementExprClass:
2746 case Expr::InitListExprClass:
2747 case Expr::DesignatedInitExprClass:
2748 case Expr::ImplicitValueInitExprClass:
2749 case Expr::ParenListExprClass:
2750 case Expr::VAArgExprClass:
2751 case Expr::AddrLabelExprClass:
2752 case Expr::StmtExprClass:
2753 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002754 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002755 case Expr::CXXDynamicCastExprClass:
2756 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002757 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002758 case Expr::CXXNullPtrLiteralExprClass:
2759 case Expr::CXXThisExprClass:
2760 case Expr::CXXThrowExprClass:
2761 case Expr::CXXNewExprClass:
2762 case Expr::CXXDeleteExprClass:
2763 case Expr::CXXPseudoDestructorExprClass:
2764 case Expr::UnresolvedLookupExprClass:
2765 case Expr::DependentScopeDeclRefExprClass:
2766 case Expr::CXXConstructExprClass:
2767 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002768 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002769 case Expr::CXXTemporaryObjectExprClass:
2770 case Expr::CXXUnresolvedConstructExprClass:
2771 case Expr::CXXDependentScopeMemberExprClass:
2772 case Expr::UnresolvedMemberExprClass:
2773 case Expr::ObjCStringLiteralClass:
2774 case Expr::ObjCEncodeExprClass:
2775 case Expr::ObjCMessageExprClass:
2776 case Expr::ObjCSelectorExprClass:
2777 case Expr::ObjCProtocolExprClass:
2778 case Expr::ObjCIvarRefExprClass:
2779 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002780 case Expr::ObjCIsaExprClass:
2781 case Expr::ShuffleVectorExprClass:
2782 case Expr::BlockExprClass:
2783 case Expr::BlockDeclRefExprClass:
2784 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002785 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002786 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002787 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002788 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002789 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002790 case Expr::MaterializeTemporaryExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002791 return ICEDiag(2, E->getLocStart());
2792
Douglas Gregoree8aff02011-01-04 17:33:58 +00002793 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002794 case Expr::GNUNullExprClass:
2795 // GCC considers the GNU __null value to be an integral constant expression.
2796 return NoDiag();
2797
2798 case Expr::ParenExprClass:
2799 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002800 case Expr::GenericSelectionExprClass:
2801 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002802 case Expr::IntegerLiteralClass:
2803 case Expr::CharacterLiteralClass:
2804 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002805 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002806 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002807 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002808 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002809 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002810 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002811 return NoDiag();
2812 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002813 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002814 const CallExpr *CE = cast<CallExpr>(E);
2815 if (CE->isBuiltinCall(Ctx))
2816 return CheckEvalInICE(E, Ctx);
2817 return ICEDiag(2, E->getLocStart());
2818 }
2819 case Expr::DeclRefExprClass:
2820 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2821 return NoDiag();
2822 if (Ctx.getLangOptions().CPlusPlus &&
2823 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2824 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2825
2826 // Parameter variables are never constants. Without this check,
2827 // getAnyInitializer() can find a default argument, which leads
2828 // to chaos.
2829 if (isa<ParmVarDecl>(D))
2830 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2831
2832 // C++ 7.1.5.1p2
2833 // A variable of non-volatile const-qualified integral or enumeration
2834 // type initialized by an ICE can be used in ICEs.
2835 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2836 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2837 if (Quals.hasVolatile() || !Quals.hasConst())
2838 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2839
2840 // Look for a declaration of this variable that has an initializer.
2841 const VarDecl *ID = 0;
2842 const Expr *Init = Dcl->getAnyInitializer(ID);
2843 if (Init) {
2844 if (ID->isInitKnownICE()) {
2845 // We have already checked whether this subexpression is an
2846 // integral constant expression.
2847 if (ID->isInitICE())
2848 return NoDiag();
2849 else
2850 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2851 }
2852
2853 // It's an ICE whether or not the definition we found is
2854 // out-of-line. See DR 721 and the discussion in Clang PR
2855 // 6206 for details.
2856
2857 if (Dcl->isCheckingICE()) {
2858 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2859 }
2860
2861 Dcl->setCheckingICE();
2862 ICEDiag Result = CheckICE(Init, Ctx);
2863 // Cache the result of the ICE test.
2864 Dcl->setInitKnownICE(Result.Val == 0);
2865 return Result;
2866 }
2867 }
2868 }
2869 return ICEDiag(2, E->getLocStart());
2870 case Expr::UnaryOperatorClass: {
2871 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2872 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002873 case UO_PostInc:
2874 case UO_PostDec:
2875 case UO_PreInc:
2876 case UO_PreDec:
2877 case UO_AddrOf:
2878 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002879 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002880 case UO_Extension:
2881 case UO_LNot:
2882 case UO_Plus:
2883 case UO_Minus:
2884 case UO_Not:
2885 case UO_Real:
2886 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002887 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002888 }
2889
2890 // OffsetOf falls through here.
2891 }
2892 case Expr::OffsetOfExprClass: {
2893 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2894 // Evaluate matches the proposed gcc behavior for cases like
2895 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2896 // compliance: we should warn earlier for offsetof expressions with
2897 // array subscripts that aren't ICEs, and if the array subscripts
2898 // are ICEs, the value of the offsetof must be an integer constant.
2899 return CheckEvalInICE(E, Ctx);
2900 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002901 case Expr::UnaryExprOrTypeTraitExprClass: {
2902 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2903 if ((Exp->getKind() == UETT_SizeOf) &&
2904 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002905 return ICEDiag(2, E->getLocStart());
2906 return NoDiag();
2907 }
2908 case Expr::BinaryOperatorClass: {
2909 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2910 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002911 case BO_PtrMemD:
2912 case BO_PtrMemI:
2913 case BO_Assign:
2914 case BO_MulAssign:
2915 case BO_DivAssign:
2916 case BO_RemAssign:
2917 case BO_AddAssign:
2918 case BO_SubAssign:
2919 case BO_ShlAssign:
2920 case BO_ShrAssign:
2921 case BO_AndAssign:
2922 case BO_XorAssign:
2923 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002924 return ICEDiag(2, E->getLocStart());
2925
John McCall2de56d12010-08-25 11:45:40 +00002926 case BO_Mul:
2927 case BO_Div:
2928 case BO_Rem:
2929 case BO_Add:
2930 case BO_Sub:
2931 case BO_Shl:
2932 case BO_Shr:
2933 case BO_LT:
2934 case BO_GT:
2935 case BO_LE:
2936 case BO_GE:
2937 case BO_EQ:
2938 case BO_NE:
2939 case BO_And:
2940 case BO_Xor:
2941 case BO_Or:
2942 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002943 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2944 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002945 if (Exp->getOpcode() == BO_Div ||
2946 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002947 // Evaluate gives an error for undefined Div/Rem, so make sure
2948 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00002949 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00002950 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2951 if (REval == 0)
2952 return ICEDiag(1, E->getLocStart());
2953 if (REval.isSigned() && REval.isAllOnesValue()) {
2954 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2955 if (LEval.isMinSignedValue())
2956 return ICEDiag(1, E->getLocStart());
2957 }
2958 }
2959 }
John McCall2de56d12010-08-25 11:45:40 +00002960 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002961 if (Ctx.getLangOptions().C99) {
2962 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2963 // if it isn't evaluated.
2964 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2965 return ICEDiag(1, E->getLocStart());
2966 } else {
2967 // In both C89 and C++, commas in ICEs are illegal.
2968 return ICEDiag(2, E->getLocStart());
2969 }
2970 }
2971 if (LHSResult.Val >= RHSResult.Val)
2972 return LHSResult;
2973 return RHSResult;
2974 }
John McCall2de56d12010-08-25 11:45:40 +00002975 case BO_LAnd:
2976 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002977 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00002978
2979 // C++0x [expr.const]p2:
2980 // [...] subexpressions of logical AND (5.14), logical OR
2981 // (5.15), and condi- tional (5.16) operations that are not
2982 // evaluated are not considered.
2983 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
2984 if (Exp->getOpcode() == BO_LAnd &&
2985 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
2986 return LHSResult;
2987
2988 if (Exp->getOpcode() == BO_LOr &&
2989 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
2990 return LHSResult;
2991 }
2992
John McCalld905f5a2010-05-07 05:32:02 +00002993 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2994 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2995 // Rare case where the RHS has a comma "side-effect"; we need
2996 // to actually check the condition to see whether the side
2997 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00002998 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00002999 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3000 return RHSResult;
3001 return NoDiag();
3002 }
3003
3004 if (LHSResult.Val >= RHSResult.Val)
3005 return LHSResult;
3006 return RHSResult;
3007 }
3008 }
3009 }
3010 case Expr::ImplicitCastExprClass:
3011 case Expr::CStyleCastExprClass:
3012 case Expr::CXXFunctionalCastExprClass:
3013 case Expr::CXXStaticCastExprClass:
3014 case Expr::CXXReinterpretCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003015 case Expr::CXXConstCastExprClass:
3016 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003017 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003018 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003019 return CheckICE(SubExpr, Ctx);
3020 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3021 return NoDiag();
3022 return ICEDiag(2, E->getLocStart());
3023 }
John McCall56ca35d2011-02-17 10:25:35 +00003024 case Expr::BinaryConditionalOperatorClass: {
3025 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3026 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3027 if (CommonResult.Val == 2) return CommonResult;
3028 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3029 if (FalseResult.Val == 2) return FalseResult;
3030 if (CommonResult.Val == 1) return CommonResult;
3031 if (FalseResult.Val == 1 &&
3032 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3033 return FalseResult;
3034 }
John McCalld905f5a2010-05-07 05:32:02 +00003035 case Expr::ConditionalOperatorClass: {
3036 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3037 // If the condition (ignoring parens) is a __builtin_constant_p call,
3038 // then only the true side is actually considered in an integer constant
3039 // expression, and it is fully evaluated. This is an important GNU
3040 // extension. See GCC PR38377 for discussion.
3041 if (const CallExpr *CallCE
3042 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3043 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3044 Expr::EvalResult EVResult;
3045 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3046 !EVResult.Val.isInt()) {
3047 return ICEDiag(2, E->getLocStart());
3048 }
3049 return NoDiag();
3050 }
3051 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003052 if (CondResult.Val == 2)
3053 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003054
3055 // C++0x [expr.const]p2:
3056 // subexpressions of [...] conditional (5.16) operations that
3057 // are not evaluated are not considered
3058 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3059 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3060 : false;
3061 ICEDiag TrueResult = NoDiag();
3062 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3063 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3064 ICEDiag FalseResult = NoDiag();
3065 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3066 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3067
John McCalld905f5a2010-05-07 05:32:02 +00003068 if (TrueResult.Val == 2)
3069 return TrueResult;
3070 if (FalseResult.Val == 2)
3071 return FalseResult;
3072 if (CondResult.Val == 1)
3073 return CondResult;
3074 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3075 return NoDiag();
3076 // Rare case where the diagnostics depend on which side is evaluated
3077 // Note that if we get here, CondResult is 0, and at least one of
3078 // TrueResult and FalseResult is non-zero.
3079 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3080 return FalseResult;
3081 }
3082 return TrueResult;
3083 }
3084 case Expr::CXXDefaultArgExprClass:
3085 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3086 case Expr::ChooseExprClass: {
3087 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3088 }
3089 }
3090
3091 // Silence a GCC warning
3092 return ICEDiag(2, E->getLocStart());
3093}
3094
3095bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3096 SourceLocation *Loc, bool isEvaluated) const {
3097 ICEDiag d = CheckICE(this, Ctx);
3098 if (d.Val != 0) {
3099 if (Loc) *Loc = d.Loc;
3100 return false;
3101 }
3102 EvalResult EvalResult;
3103 if (!Evaluate(EvalResult, Ctx))
3104 llvm_unreachable("ICE cannot be evaluated!");
3105 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3106 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3107 Result = EvalResult.Val.getInt();
3108 return true;
3109}