blob: 98400a450d689df7b1df44452b6a780317da282e [file] [log] [blame]
Chris Lattnera42f09a2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc7436af2008-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"
Eli Friedman7888b932008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeonefddb9c2008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner82437da2008-07-12 00:14:42 +000018#include "clang/Basic/Diagnostic.h"
Anders Carlssonc0328012008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssoncad17b52008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnera823ccf2008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedman2f445492008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc7436af2008-07-03 04:20:39 +000024
Chris Lattner422373c2008-07-11 22:52:41 +000025/// EvalInfo - This is a private struct used by the evaluator to capture
26/// information about a subexpression as it is folded. It retains information
27/// about the AST context, but also maintains information about the folded
28/// expression.
29///
30/// If an expression could be evaluated, it is still possible it is not a C
31/// "integer constant expression" or constant expression. If not, this struct
32/// captures information about how and why not.
33///
34/// One bit of information passed *into* the request for constant folding
35/// indicates whether the subexpression is "evaluated" or not according to C
36/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
37/// evaluate the expression regardless of what the RHS is, but C only allows
38/// certain things in certain situations.
39struct EvalInfo {
40 ASTContext &Ctx;
41
42 /// isEvaluated - True if the subexpression is required to be evaluated, false
43 /// if it is short-circuited (according to C rules).
44 bool isEvaluated;
45
Chris Lattner82437da2008-07-12 00:14:42 +000046 /// ICEDiag - If the expression is unfoldable, then ICEDiag contains the
47 /// error diagnostic indicating why it is not foldable and DiagLoc indicates a
48 /// caret position for the error. If it is foldable, but the expression is
49 /// not an integer constant expression, ICEDiag contains the extension
50 /// diagnostic to emit which describes why it isn't an integer constant
51 /// expression. If this expression *is* an integer-constant-expr, then
52 /// ICEDiag is zero.
Chris Lattner422373c2008-07-11 22:52:41 +000053 ///
Chris Lattner82437da2008-07-12 00:14:42 +000054 /// The caller can choose to emit this diagnostic or not, depending on whether
55 /// they require an i-c-e or a constant or not. DiagLoc indicates the caret
56 /// position for the report.
57 ///
58 /// If ICEDiag is zero, then this expression is an i-c-e.
Chris Lattner422373c2008-07-11 22:52:41 +000059 unsigned ICEDiag;
60 SourceLocation DiagLoc;
61
62 EvalInfo(ASTContext &ctx) : Ctx(ctx), isEvaluated(true), ICEDiag(0) {}
63};
64
65
Eli Friedman7888b932008-11-12 09:44:48 +000066static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner422373c2008-07-11 22:52:41 +000067static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
68static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Eli Friedman2f445492008-08-22 00:06:13 +000069static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000070
71//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-11-12 09:44:48 +000072// Misc utilities
73//===----------------------------------------------------------------------===//
74
75static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
76 if (E->getType()->isIntegralType()) {
77 APSInt IntResult;
78 if (!EvaluateInteger(E, IntResult, Info))
79 return false;
80 Result = IntResult != 0;
81 return true;
82 } else if (E->getType()->isRealFloatingType()) {
83 APFloat FloatResult(0.0);
84 if (!EvaluateFloat(E, FloatResult, Info))
85 return false;
86 Result = !FloatResult.isZero();
87 return true;
88 } else if (E->getType()->isPointerType()) {
89 APValue PointerResult;
90 if (!EvaluatePointer(E, PointerResult, Info))
91 return false;
92 // FIXME: Is this accurate for all kinds of bases? If not, what would
93 // the check look like?
94 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
95 return true;
96 }
97
98 return false;
99}
100
101//===----------------------------------------------------------------------===//
102// LValue Evaluation
103//===----------------------------------------------------------------------===//
104namespace {
105class VISIBILITY_HIDDEN LValueExprEvaluator
106 : public StmtVisitor<LValueExprEvaluator, APValue> {
107 EvalInfo &Info;
108public:
109
110 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
111
112 APValue VisitStmt(Stmt *S) {
113 // FIXME: Remove this when we support more expressions.
114 printf("Unhandled pointer statement\n");
115 S->dump();
116 return APValue();
117 }
118
119 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
120 APValue VisitDeclRefExpr(DeclRefExpr *E) { return APValue(E, 0); }
121 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
122 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
123 APValue VisitMemberExpr(MemberExpr *E);
124 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
125};
126} // end anonymous namespace
127
128static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
129 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
130 return Result.isLValue();
131}
132
133APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
134 if (E->isFileScope())
135 return APValue(E, 0);
136 return APValue();
137}
138
139APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
140 APValue result;
141 QualType Ty;
142 if (E->isArrow()) {
143 if (!EvaluatePointer(E->getBase(), result, Info))
144 return APValue();
145 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
146 } else {
147 result = Visit(E->getBase());
148 if (result.isUninit())
149 return APValue();
150 Ty = E->getBase()->getType();
151 }
152
153 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
154 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
155 FieldDecl *FD = E->getMemberDecl();
156
157 // FIXME: This is linear time.
158 unsigned i = 0, e = 0;
159 for (i = 0, e = RD->getNumMembers(); i != e; i++) {
160 if (RD->getMember(i) == FD)
161 break;
162 }
163
164 result.setLValue(result.getLValueBase(),
165 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
166
167 return result;
168}
169
170
171//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000172// Pointer Evaluation
173//===----------------------------------------------------------------------===//
174
Anders Carlssoncad17b52008-07-08 05:13:58 +0000175namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000176class VISIBILITY_HIDDEN PointerExprEvaluator
177 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000178 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000179public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000180
Chris Lattner422373c2008-07-11 22:52:41 +0000181 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000182
Anders Carlsson02a34c32008-07-08 14:30:00 +0000183 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000184 return APValue();
185 }
186
187 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
188
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000189 APValue VisitBinaryOperator(const BinaryOperator *E);
190 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000191 APValue VisitUnaryOperator(const UnaryOperator *E);
192 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
193 { return APValue(E, 0); }
194 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000195};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000196} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000197
Chris Lattner422373c2008-07-11 22:52:41 +0000198static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000199 if (!E->getType()->isPointerType())
200 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000201 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000202 return Result.isLValue();
203}
204
205APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
206 if (E->getOpcode() != BinaryOperator::Add &&
207 E->getOpcode() != BinaryOperator::Sub)
208 return APValue();
209
210 const Expr *PExp = E->getLHS();
211 const Expr *IExp = E->getRHS();
212 if (IExp->getType()->isPointerType())
213 std::swap(PExp, IExp);
214
215 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000216 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000217 return APValue();
218
219 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000220 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000221 return APValue();
222
Eli Friedman7888b932008-11-12 09:44:48 +0000223 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
224 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
225
Chris Lattnera823ccf2008-07-11 18:11:29 +0000226 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000227
Chris Lattnera823ccf2008-07-11 18:11:29 +0000228 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000229 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000230 else
Eli Friedman7888b932008-11-12 09:44:48 +0000231 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
232
Chris Lattnera823ccf2008-07-11 18:11:29 +0000233 return APValue(ResultLValue.getLValueBase(), Offset);
234}
Eli Friedman7888b932008-11-12 09:44:48 +0000235
236APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
237 if (E->getOpcode() == UnaryOperator::Extension) {
238 // FIXME: Deal with warnings?
239 return Visit(E->getSubExpr());
240 }
241
242 if (E->getOpcode() == UnaryOperator::AddrOf) {
243 APValue result;
244 if (EvaluateLValue(E->getSubExpr(), result, Info))
245 return result;
246 }
247
248 return APValue();
249}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000250
251
Chris Lattnera42f09a2008-07-11 19:10:17 +0000252APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000253 const Expr* SubExpr = E->getSubExpr();
254
255 // Check for pointer->pointer cast
256 if (SubExpr->getType()->isPointerType()) {
257 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000258 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000259 return Result;
260 return APValue();
261 }
262
Eli Friedman3e64dd72008-07-27 05:46:18 +0000263 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000264 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000265 if (EvaluateInteger(SubExpr, Result, Info)) {
266 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000267 return APValue(0, Result.getZExtValue());
268 }
269 }
Eli Friedman7888b932008-11-12 09:44:48 +0000270
271 if (SubExpr->getType()->isFunctionType() ||
272 SubExpr->getType()->isArrayType()) {
273 APValue Result;
274 if (EvaluateLValue(SubExpr, Result, Info))
275 return Result;
276 return APValue();
277 }
278
279 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000280 return APValue();
281}
282
Eli Friedman7888b932008-11-12 09:44:48 +0000283APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
284 bool BoolResult;
285 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
286 return APValue();
287
288 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
289
290 APValue Result;
291 if (EvaluatePointer(EvalExpr, Result, Info))
292 return Result;
293 return APValue();
294}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000295
296//===----------------------------------------------------------------------===//
297// Integer Evaluation
298//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000299
300namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000301class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000302 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000303 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000304 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000305public:
Chris Lattner422373c2008-07-11 22:52:41 +0000306 IntExprEvaluator(EvalInfo &info, APSInt &result)
307 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000308
Chris Lattner2c99c712008-07-11 19:24:49 +0000309 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-07-12 00:14:42 +0000310 return (unsigned)Info.Ctx.getIntWidth(T);
311 }
312
313 bool Extension(SourceLocation L, diag::kind D) {
314 Info.DiagLoc = L;
315 Info.ICEDiag = D;
316 return true; // still a constant.
317 }
318
Chris Lattner438f3b12008-11-12 07:43:42 +0000319 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner82437da2008-07-12 00:14:42 +0000320 // If this is in an unevaluated portion of the subexpression, ignore the
321 // error.
Chris Lattner438f3b12008-11-12 07:43:42 +0000322 if (!Info.isEvaluated) {
323 // If error is ignored because the value isn't evaluated, get the real
324 // type at least to prevent errors downstream.
325 Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
326 Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
Chris Lattner82437da2008-07-12 00:14:42 +0000327 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000328 }
Chris Lattner82437da2008-07-12 00:14:42 +0000329
Chris Lattner438f3b12008-11-12 07:43:42 +0000330 // Take the first error.
331 if (Info.ICEDiag == 0) {
332 Info.DiagLoc = L;
333 Info.ICEDiag = D;
334 }
Chris Lattner82437da2008-07-12 00:14:42 +0000335 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000336 }
337
Anders Carlssoncad17b52008-07-08 05:13:58 +0000338 //===--------------------------------------------------------------------===//
339 // Visitor Methods
340 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000341
342 bool VisitStmt(Stmt *) {
343 assert(0 && "This should be called on integers, stmts are not integers");
344 return false;
345 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000346
Chris Lattner438f3b12008-11-12 07:43:42 +0000347 bool VisitExpr(Expr *E) {
348 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssoncad17b52008-07-08 05:13:58 +0000349 }
350
Chris Lattnera42f09a2008-07-11 19:10:17 +0000351 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000352
Chris Lattner15e59112008-07-12 00:38:25 +0000353 bool VisitIntegerLiteral(const IntegerLiteral *E) {
354 Result = E->getValue();
355 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
356 return true;
357 }
358 bool VisitCharacterLiteral(const CharacterLiteral *E) {
359 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
360 Result = E->getValue();
361 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
362 return true;
363 }
364 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
365 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000366 // Per gcc docs "this built-in function ignores top level
367 // qualifiers". We need to use the canonical version to properly
368 // be able to strip CRV qualifiers from the type.
369 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
370 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
371 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
372 T1.getUnqualifiedType());
Chris Lattner15e59112008-07-12 00:38:25 +0000373 return true;
374 }
375 bool VisitDeclRefExpr(const DeclRefExpr *E);
376 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000377 bool VisitBinaryOperator(const BinaryOperator *E);
378 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000379
Chris Lattnerff579ff2008-07-12 01:15:53 +0000380 bool VisitCastExpr(CastExpr* E) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000381 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000382 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000383 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
384
Chris Lattner265a0892008-07-11 21:24:13 +0000385private:
Chris Lattnerff579ff2008-07-12 01:15:53 +0000386 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000387};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000388} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000389
Chris Lattner422373c2008-07-11 22:52:41 +0000390static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
391 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000392}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000393
Chris Lattner15e59112008-07-12 00:38:25 +0000394bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
395 // Enums are integer constant exprs.
396 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
397 Result = D->getInitVal();
398 return true;
399 }
400
401 // Otherwise, random variable references are not constants.
Chris Lattner438f3b12008-11-12 07:43:42 +0000402 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner15e59112008-07-12 00:38:25 +0000403}
404
Chris Lattner1eee9402008-10-06 06:40:35 +0000405/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
406/// as GCC.
407static int EvaluateBuiltinClassifyType(const CallExpr *E) {
408 // The following enum mimics the values returned by GCC.
409 enum gcc_type_class {
410 no_type_class = -1,
411 void_type_class, integer_type_class, char_type_class,
412 enumeral_type_class, boolean_type_class,
413 pointer_type_class, reference_type_class, offset_type_class,
414 real_type_class, complex_type_class,
415 function_type_class, method_type_class,
416 record_type_class, union_type_class,
417 array_type_class, string_type_class,
418 lang_type_class
419 };
420
421 // If no argument was supplied, default to "no_type_class". This isn't
422 // ideal, however it is what gcc does.
423 if (E->getNumArgs() == 0)
424 return no_type_class;
425
426 QualType ArgTy = E->getArg(0)->getType();
427 if (ArgTy->isVoidType())
428 return void_type_class;
429 else if (ArgTy->isEnumeralType())
430 return enumeral_type_class;
431 else if (ArgTy->isBooleanType())
432 return boolean_type_class;
433 else if (ArgTy->isCharType())
434 return string_type_class; // gcc doesn't appear to use char_type_class
435 else if (ArgTy->isIntegerType())
436 return integer_type_class;
437 else if (ArgTy->isPointerType())
438 return pointer_type_class;
439 else if (ArgTy->isReferenceType())
440 return reference_type_class;
441 else if (ArgTy->isRealType())
442 return real_type_class;
443 else if (ArgTy->isComplexType())
444 return complex_type_class;
445 else if (ArgTy->isFunctionType())
446 return function_type_class;
447 else if (ArgTy->isStructureType())
448 return record_type_class;
449 else if (ArgTy->isUnionType())
450 return union_type_class;
451 else if (ArgTy->isArrayType())
452 return array_type_class;
453 else if (ArgTy->isUnionType())
454 return union_type_class;
455 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
456 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
457 return -1;
458}
459
Chris Lattner15e59112008-07-12 00:38:25 +0000460bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
461 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000462
Chris Lattner87293782008-10-06 05:28:25 +0000463 switch (E->isBuiltinCall()) {
464 default:
Chris Lattner438f3b12008-11-12 07:43:42 +0000465 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner87293782008-10-06 05:28:25 +0000466 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000467 Result.setIsSigned(true);
468 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000469 return true;
470
471 case Builtin::BI__builtin_constant_p: {
472 // __builtin_constant_p always has one operand: it returns true if that
473 // operand can be folded, false otherwise.
474 APValue Res;
475 Result = E->getArg(0)->tryEvaluate(Res, Info.Ctx);
476 return true;
477 }
478 }
Chris Lattner15e59112008-07-12 00:38:25 +0000479}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000480
Chris Lattnera42f09a2008-07-11 19:10:17 +0000481bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000482 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000483 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000484 if (!Visit(E->getLHS())) {
485 // If the LHS is unfoldable, we generally can't fold this. However, if this
486 // is a logical operator like &&/||, and if we know that the RHS determines
487 // the outcome of the result (e.g. X && 0), return the outcome.
488 if (!E->isLogicalOp())
489 return false;
490
491 // If this is a logical op, see if the RHS determines the outcome.
492 EvalInfo Info2(Info.Ctx);
493 if (!EvaluateInteger(E->getRHS(), RHS, Info2))
494 return false;
495
496 // X && 0 -> 0, X || 1 -> 1.
Eli Friedman7888b932008-11-12 09:44:48 +0000497 if ((E->getOpcode() == BinaryOperator::LAnd && RHS == 0) ||
498 (E->getOpcode() == BinaryOperator::LOr && RHS != 0)) {
Chris Lattner40d2ae82008-11-12 07:04:29 +0000499 Result = RHS != 0;
500 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner438f3b12008-11-12 07:43:42 +0000501 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner40d2ae82008-11-12 07:04:29 +0000502 return true;
503 }
504
Chris Lattner82437da2008-07-12 00:14:42 +0000505 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000506 }
Chris Lattner82437da2008-07-12 00:14:42 +0000507
508 bool OldEval = Info.isEvaluated;
509
510 // The short-circuiting &&/|| operators don't necessarily evaluate their
511 // RHS. Make sure to pass isEvaluated down correctly.
512 if ((E->getOpcode() == BinaryOperator::LAnd && Result == 0) ||
513 (E->getOpcode() == BinaryOperator::LOr && Result != 0))
514 Info.isEvaluated = false;
Eli Friedman3e64dd72008-07-27 05:46:18 +0000515
516 // FIXME: Handle pointer subtraction
517
518 // FIXME Maybe we want to succeed even where we can't evaluate the
519 // right side of LAnd/LOr?
520 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000521 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000522 return false;
Chris Lattner82437da2008-07-12 00:14:42 +0000523 Info.isEvaluated = OldEval;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000524
525 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000526 default:
527 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner82437da2008-07-12 00:14:42 +0000528 case BinaryOperator::Mul: Result *= RHS; return true;
529 case BinaryOperator::Add: Result += RHS; return true;
530 case BinaryOperator::Sub: Result -= RHS; return true;
531 case BinaryOperator::And: Result &= RHS; return true;
532 case BinaryOperator::Xor: Result ^= RHS; return true;
533 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000534 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000535 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000536 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
537 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000538 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000539 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000540 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000541 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000542 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
543 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000544 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000545 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000546 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000547 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000548 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000549 break;
550 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000551 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000552 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000553
Chris Lattner045502c2008-07-11 19:29:32 +0000554 case BinaryOperator::LT:
555 Result = Result < RHS;
556 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
557 break;
558 case BinaryOperator::GT:
559 Result = Result > RHS;
560 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
561 break;
562 case BinaryOperator::LE:
563 Result = Result <= RHS;
564 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
565 break;
566 case BinaryOperator::GE:
567 Result = Result >= RHS;
568 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
569 break;
570 case BinaryOperator::EQ:
571 Result = Result == RHS;
572 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
573 break;
574 case BinaryOperator::NE:
575 Result = Result != RHS;
576 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
577 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000578 case BinaryOperator::LAnd:
579 Result = Result != 0 && RHS != 0;
580 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
581 break;
582 case BinaryOperator::LOr:
583 Result = Result != 0 || RHS != 0;
584 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
585 break;
586
Anders Carlssonc0328012008-07-08 05:49:43 +0000587
Anders Carlssond1aa5812008-07-08 14:35:21 +0000588 case BinaryOperator::Comma:
Chris Lattner82437da2008-07-12 00:14:42 +0000589 // Result of the comma is just the result of the RHS.
590 Result = RHS;
591
Anders Carlssond1aa5812008-07-08 14:35:21 +0000592 // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
593 // *except* when they are contained within a subexpression that is not
594 // evaluated". Note that Assignment can never happen due to constraints
595 // on the LHS subexpr, so we don't need to check it here.
Chris Lattner82437da2008-07-12 00:14:42 +0000596 if (!Info.isEvaluated)
597 return true;
598
599 // If the value is evaluated, we can accept it as an extension.
600 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000601 }
602
603 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000604 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000605}
606
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000607/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
608/// expression's type.
609bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
610 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000611 // Return the result in the right width.
612 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
613 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
614
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000615 QualType SrcTy = E->getTypeOfArgument();
616
Chris Lattner265a0892008-07-11 21:24:13 +0000617 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000618 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000619 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000620 return true;
621 }
Chris Lattner265a0892008-07-11 21:24:13 +0000622
623 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000624 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000625 if (!SrcTy->isConstantSizeType()) {
626 // FIXME: Should we attempt to evaluate this?
627 return false;
628 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000629
630 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000631
632 // GCC extension: sizeof(function) = 1.
633 if (SrcTy->isFunctionType()) {
634 // FIXME: AlignOf shouldn't be unconditionally 4!
635 Result = isSizeOf ? 1 : 4;
636 return true;
637 }
638
639 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000640 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000641 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000642 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000643 else
Chris Lattner422373c2008-07-11 22:52:41 +0000644 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000645 return true;
646}
647
Chris Lattnera42f09a2008-07-11 19:10:17 +0000648bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000649 // Special case unary operators that do not need their subexpression
650 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000651 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000652 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000653 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000654 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
655 return true;
656 }
657
Chris Lattner422373c2008-07-11 22:52:41 +0000658 // Get the operand value into 'Result'.
659 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000660 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000661
Chris Lattner400d7402008-07-11 22:15:16 +0000662 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000663 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000664 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
665 // See C99 6.6p3.
Chris Lattner438f3b12008-11-12 07:43:42 +0000666 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
667 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000668 case UnaryOperator::LNot: {
669 bool Val = Result == 0;
670 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
671 Result = Val;
672 break;
673 }
674 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000675 // FIXME: Should extension allow i-c-e extension expressions in its scope?
676 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000677 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000678 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000679 break;
680 case UnaryOperator::Minus:
681 Result = -Result;
682 break;
683 case UnaryOperator::Not:
684 Result = ~Result;
685 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000686 }
687
688 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000689 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000690}
691
Chris Lattnerff579ff2008-07-12 01:15:53 +0000692/// HandleCast - This is used to evaluate implicit or explicit casts where the
693/// result type is integer.
694bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
695 Expr *SubExpr, QualType DestType) {
Chris Lattner2c99c712008-07-11 19:24:49 +0000696 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000697
Eli Friedman7888b932008-11-12 09:44:48 +0000698 if (DestType->isBooleanType()) {
699 bool BoolResult;
700 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
701 return false;
702 Result.zextOrTrunc(DestWidth);
703 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
704 Result = BoolResult;
705 return true;
706 }
707
Anders Carlssond1aa5812008-07-08 14:35:21 +0000708 // Handle simple integer->integer casts.
709 if (SubExpr->getType()->isIntegerType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000710 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000711 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000712
713 // Figure out if this is a truncate, extend or noop cast.
714 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000715 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000716 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
717 return true;
718 }
719
720 // FIXME: Clean this up!
721 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000722 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000723 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000724 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000725
Anders Carlssond1aa5812008-07-08 14:35:21 +0000726 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000727 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000728
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000729 Result.extOrTrunc(DestWidth);
730 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000731 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
732 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000733 }
Eli Friedman7888b932008-11-12 09:44:48 +0000734
Chris Lattnerff579ff2008-07-12 01:15:53 +0000735 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner438f3b12008-11-12 07:43:42 +0000736 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000737
Eli Friedman2f445492008-08-22 00:06:13 +0000738 APFloat F(0.0);
739 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner438f3b12008-11-12 07:43:42 +0000740 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000741
742 // Determine whether we are converting to unsigned or signed.
743 bool DestSigned = DestType->isSignedIntegerType();
744
745 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000746 uint64_t Space[4];
747 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000748 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000749 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000750 Result = llvm::APInt(DestWidth, 4, Space);
751 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000752 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000753}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000754
Chris Lattnera823ccf2008-07-11 18:11:29 +0000755//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000756// Float Evaluation
757//===----------------------------------------------------------------------===//
758
759namespace {
760class VISIBILITY_HIDDEN FloatExprEvaluator
761 : public StmtVisitor<FloatExprEvaluator, bool> {
762 EvalInfo &Info;
763 APFloat &Result;
764public:
765 FloatExprEvaluator(EvalInfo &info, APFloat &result)
766 : Info(info), Result(result) {}
767
768 bool VisitStmt(Stmt *S) {
769 return false;
770 }
771
772 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000773 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000774
Daniel Dunbar804ead02008-10-16 03:51:50 +0000775 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000776 bool VisitBinaryOperator(const BinaryOperator *E);
777 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000778 bool VisitCastExpr(CastExpr *E);
779 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000780};
781} // end anonymous namespace
782
783static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
784 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
785}
786
Chris Lattner87293782008-10-06 05:28:25 +0000787bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000788 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000789 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000790 case Builtin::BI__builtin_huge_val:
791 case Builtin::BI__builtin_huge_valf:
792 case Builtin::BI__builtin_huge_vall:
793 case Builtin::BI__builtin_inf:
794 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000795 case Builtin::BI__builtin_infl: {
796 const llvm::fltSemantics &Sem =
797 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000798 Result = llvm::APFloat::getInf(Sem);
799 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000800 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000801
802 case Builtin::BI__builtin_nan:
803 case Builtin::BI__builtin_nanf:
804 case Builtin::BI__builtin_nanl:
805 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
806 // can't constant fold it.
807 if (const StringLiteral *S =
808 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
809 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000810 const llvm::fltSemantics &Sem =
811 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000812 Result = llvm::APFloat::getNaN(Sem);
813 return true;
814 }
815 }
816 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000817
818 case Builtin::BI__builtin_fabs:
819 case Builtin::BI__builtin_fabsf:
820 case Builtin::BI__builtin_fabsl:
821 if (!EvaluateFloat(E->getArg(0), Result, Info))
822 return false;
823
824 if (Result.isNegative())
825 Result.changeSign();
826 return true;
827
828 case Builtin::BI__builtin_copysign:
829 case Builtin::BI__builtin_copysignf:
830 case Builtin::BI__builtin_copysignl: {
831 APFloat RHS(0.);
832 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
833 !EvaluateFloat(E->getArg(1), RHS, Info))
834 return false;
835 Result.copySign(RHS);
836 return true;
837 }
Chris Lattner87293782008-10-06 05:28:25 +0000838 }
839}
840
Daniel Dunbar804ead02008-10-16 03:51:50 +0000841bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
842 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
843 return false;
844
845 switch (E->getOpcode()) {
846 default: return false;
847 case UnaryOperator::Plus:
848 return true;
849 case UnaryOperator::Minus:
850 Result.changeSign();
851 return true;
852 }
853}
Chris Lattner87293782008-10-06 05:28:25 +0000854
Eli Friedman2f445492008-08-22 00:06:13 +0000855bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
856 // FIXME: Diagnostics? I really don't understand how the warnings
857 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +0000858 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +0000859 if (!EvaluateFloat(E->getLHS(), Result, Info))
860 return false;
861 if (!EvaluateFloat(E->getRHS(), RHS, Info))
862 return false;
863
864 switch (E->getOpcode()) {
865 default: return false;
866 case BinaryOperator::Mul:
867 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
868 return true;
869 case BinaryOperator::Add:
870 Result.add(RHS, APFloat::rmNearestTiesToEven);
871 return true;
872 case BinaryOperator::Sub:
873 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
874 return true;
875 case BinaryOperator::Div:
876 Result.divide(RHS, APFloat::rmNearestTiesToEven);
877 return true;
878 case BinaryOperator::Rem:
879 Result.mod(RHS, APFloat::rmNearestTiesToEven);
880 return true;
881 }
882}
883
884bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
885 Result = E->getValue();
886 return true;
887}
888
Eli Friedman7888b932008-11-12 09:44:48 +0000889bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
890 Expr* SubExpr = E->getSubExpr();
891 const llvm::fltSemantics& destSemantics =
892 Info.Ctx.getFloatTypeSemantics(E->getType());
893 if (SubExpr->getType()->isIntegralType()) {
894 APSInt IntResult;
895 if (!EvaluateInteger(E, IntResult, Info))
896 return false;
897 Result = APFloat(destSemantics, 1);
898 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
899 APFloat::rmNearestTiesToEven);
900 return true;
901 }
902 if (SubExpr->getType()->isRealFloatingType()) {
903 if (!Visit(SubExpr))
904 return false;
905 bool ignored;
906 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
907 return true;
908 }
909
910 return false;
911}
912
913bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
914 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
915 return true;
916}
917
Eli Friedman2f445492008-08-22 00:06:13 +0000918//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000919// Top level TryEvaluate.
920//===----------------------------------------------------------------------===//
921
Chris Lattner87293782008-10-06 05:28:25 +0000922/// tryEvaluate - Return true if this is a constant which we can fold using
923/// any crazy technique (that has nothing to do with language standards) that
924/// we want to. If this function returns true, it returns the folded constant
925/// in Result.
Chris Lattnera42f09a2008-07-11 19:10:17 +0000926bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner422373c2008-07-11 22:52:41 +0000927 EvalInfo Info(Ctx);
Anders Carlssonc0328012008-07-08 05:49:43 +0000928 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +0000929 llvm::APSInt sInt(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000930 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlssonc0328012008-07-08 05:49:43 +0000931 Result = APValue(sInt);
932 return true;
933 }
Eli Friedman2f445492008-08-22 00:06:13 +0000934 } else if (getType()->isPointerType()) {
935 if (EvaluatePointer(this, Result, Info)) {
936 return true;
937 }
938 } else if (getType()->isRealFloatingType()) {
939 llvm::APFloat f(0.0);
940 if (EvaluateFloat(this, f, Info)) {
941 Result = APValue(f);
942 return true;
943 }
944 }
Anders Carlsson47968a92008-08-10 17:03:01 +0000945
Anders Carlssonc7436af2008-07-03 04:20:39 +0000946 return false;
947}
Chris Lattner2d9a3f62008-10-06 06:49:02 +0000948
949/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
950/// folded, but discard the result.
951bool Expr::isEvaluatable(ASTContext &Ctx) const {
952 APValue V;
953 return tryEvaluate(V, Ctx);
954}