blob: 5bc4170e70a69c2d6320a998d7f5fef718258f05 [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"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000016#include "clang/AST/StmtVisitor.h"
Chris Lattner54176fd2008-07-12 00:14:42 +000017#include "clang/Basic/Diagnostic.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonc754aa62008-07-08 05:13:58 +000019#include "llvm/Support/Compiler.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000020using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000021using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000022using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000023
Chris Lattner87eae5e2008-07-11 22:52:41 +000024/// EvalInfo - This is a private struct used by the evaluator to capture
25/// information about a subexpression as it is folded. It retains information
26/// about the AST context, but also maintains information about the folded
27/// expression.
28///
29/// If an expression could be evaluated, it is still possible it is not a C
30/// "integer constant expression" or constant expression. If not, this struct
31/// captures information about how and why not.
32///
33/// One bit of information passed *into* the request for constant folding
34/// indicates whether the subexpression is "evaluated" or not according to C
35/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
36/// evaluate the expression regardless of what the RHS is, but C only allows
37/// certain things in certain situations.
38struct EvalInfo {
39 ASTContext &Ctx;
40
41 /// isEvaluated - True if the subexpression is required to be evaluated, false
42 /// if it is short-circuited (according to C rules).
43 bool isEvaluated;
44
Chris Lattner54176fd2008-07-12 00:14:42 +000045 /// ICEDiag - If the expression is unfoldable, then ICEDiag contains the
46 /// error diagnostic indicating why it is not foldable and DiagLoc indicates a
47 /// caret position for the error. If it is foldable, but the expression is
48 /// not an integer constant expression, ICEDiag contains the extension
49 /// diagnostic to emit which describes why it isn't an integer constant
50 /// expression. If this expression *is* an integer-constant-expr, then
51 /// ICEDiag is zero.
Chris Lattner87eae5e2008-07-11 22:52:41 +000052 ///
Chris Lattner54176fd2008-07-12 00:14:42 +000053 /// The caller can choose to emit this diagnostic or not, depending on whether
54 /// they require an i-c-e or a constant or not. DiagLoc indicates the caret
55 /// position for the report.
56 ///
57 /// If ICEDiag is zero, then this expression is an i-c-e.
Chris Lattner87eae5e2008-07-11 22:52:41 +000058 unsigned ICEDiag;
59 SourceLocation DiagLoc;
60
61 EvalInfo(ASTContext &ctx) : Ctx(ctx), isEvaluated(true), ICEDiag(0) {}
62};
63
64
65static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
66static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000067static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +000068
69//===----------------------------------------------------------------------===//
70// Pointer Evaluation
71//===----------------------------------------------------------------------===//
72
Anders Carlssonc754aa62008-07-08 05:13:58 +000073namespace {
Anders Carlsson2bad1682008-07-08 14:30:00 +000074class VISIBILITY_HIDDEN PointerExprEvaluator
75 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +000076 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +000077public:
Anders Carlsson2bad1682008-07-08 14:30:00 +000078
Chris Lattner87eae5e2008-07-11 22:52:41 +000079 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +000080
Anders Carlsson2bad1682008-07-08 14:30:00 +000081 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +000082 return APValue();
83 }
84
85 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
86
Anders Carlsson650c92f2008-07-08 15:34:11 +000087 APValue VisitBinaryOperator(const BinaryOperator *E);
88 APValue VisitCastExpr(const CastExpr* E);
Anders Carlsson650c92f2008-07-08 15:34:11 +000089};
Chris Lattnerf5eeb052008-07-11 18:11:29 +000090} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +000091
Chris Lattner87eae5e2008-07-11 22:52:41 +000092static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +000093 if (!E->getType()->isPointerType())
94 return false;
Chris Lattner87eae5e2008-07-11 22:52:41 +000095 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +000096 return Result.isLValue();
97}
98
99APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
100 if (E->getOpcode() != BinaryOperator::Add &&
101 E->getOpcode() != BinaryOperator::Sub)
102 return APValue();
103
104 const Expr *PExp = E->getLHS();
105 const Expr *IExp = E->getRHS();
106 if (IExp->getType()->isPointerType())
107 std::swap(PExp, IExp);
108
109 APValue ResultLValue;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000110 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000111 return APValue();
112
113 llvm::APSInt AdditionalOffset(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000114 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000115 return APValue();
116
117 uint64_t Offset = ResultLValue.getLValueOffset();
118 if (E->getOpcode() == BinaryOperator::Add)
119 Offset += AdditionalOffset.getZExtValue();
120 else
121 Offset -= AdditionalOffset.getZExtValue();
122
123 return APValue(ResultLValue.getLValueBase(), Offset);
124}
125
126
Chris Lattnerb542afe2008-07-11 19:10:17 +0000127APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000128 const Expr* SubExpr = E->getSubExpr();
129
130 // Check for pointer->pointer cast
131 if (SubExpr->getType()->isPointerType()) {
132 APValue Result;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000133 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000134 return Result;
135 return APValue();
136 }
137
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000138 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000139 llvm::APSInt Result(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000140 if (EvaluateInteger(SubExpr, Result, Info)) {
141 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000142 return APValue(0, Result.getZExtValue());
143 }
144 }
145
146 assert(0 && "Unhandled cast");
147 return APValue();
148}
149
150
151//===----------------------------------------------------------------------===//
152// Integer Evaluation
153//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000154
155namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000156class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000157 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000158 EvalInfo &Info;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000159 APSInt &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000160public:
Chris Lattner87eae5e2008-07-11 22:52:41 +0000161 IntExprEvaluator(EvalInfo &info, APSInt &result)
162 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000163
Chris Lattner7a767782008-07-11 19:24:49 +0000164 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner54176fd2008-07-12 00:14:42 +0000165 return (unsigned)Info.Ctx.getIntWidth(T);
166 }
167
168 bool Extension(SourceLocation L, diag::kind D) {
169 Info.DiagLoc = L;
170 Info.ICEDiag = D;
171 return true; // still a constant.
172 }
173
174 bool Error(SourceLocation L, diag::kind D) {
175 // If this is in an unevaluated portion of the subexpression, ignore the
176 // error.
177 if (!Info.isEvaluated)
178 return true;
179
180 Info.DiagLoc = L;
181 Info.ICEDiag = D;
182 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000183 }
184
Anders Carlssonc754aa62008-07-08 05:13:58 +0000185 //===--------------------------------------------------------------------===//
186 // Visitor Methods
187 //===--------------------------------------------------------------------===//
Chris Lattner7a767782008-07-11 19:24:49 +0000188
Chris Lattnerb542afe2008-07-11 19:10:17 +0000189 bool VisitStmt(Stmt *S) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000190 return Error(S->getLocStart(), diag::err_expr_not_constant);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000191 }
192
Chris Lattnerb542afe2008-07-11 19:10:17 +0000193 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000194
Chris Lattner4c4867e2008-07-12 00:38:25 +0000195 bool VisitIntegerLiteral(const IntegerLiteral *E) {
196 Result = E->getValue();
197 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
198 return true;
199 }
200 bool VisitCharacterLiteral(const CharacterLiteral *E) {
201 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
202 Result = E->getValue();
203 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
204 return true;
205 }
206 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
207 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
208 Result = Info.Ctx.typesAreCompatible(E->getArgType1(), E->getArgType2());
209 return true;
210 }
211 bool VisitDeclRefExpr(const DeclRefExpr *E);
212 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000213 bool VisitBinaryOperator(const BinaryOperator *E);
214 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000215
Chris Lattner732b2232008-07-12 01:15:53 +0000216 bool VisitCastExpr(CastExpr* E) {
Chris Lattner732b2232008-07-12 01:15:53 +0000217 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlsson650c92f2008-07-08 15:34:11 +0000218 }
Chris Lattnerfcee0012008-07-11 21:24:13 +0000219 bool VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000220 return EvaluateSizeAlignOf(E->isSizeOf(), E->getArgumentType(),
221 E->getType());
Chris Lattnerfcee0012008-07-11 21:24:13 +0000222 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000223
Chris Lattnerfcee0012008-07-11 21:24:13 +0000224private:
Chris Lattner732b2232008-07-12 01:15:53 +0000225 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Chris Lattnerfcee0012008-07-11 21:24:13 +0000226 bool EvaluateSizeAlignOf(bool isSizeOf, QualType SrcTy, QualType DstTy);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000227};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000228} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000229
Chris Lattner87eae5e2008-07-11 22:52:41 +0000230static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
231 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson650c92f2008-07-08 15:34:11 +0000232}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000233
Chris Lattner4c4867e2008-07-12 00:38:25 +0000234bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
235 // Enums are integer constant exprs.
236 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
237 Result = D->getInitVal();
238 return true;
239 }
240
241 // Otherwise, random variable references are not constants.
242 return Error(E->getLocStart(), diag::err_expr_not_constant);
243}
244
Chris Lattnera4d55d82008-10-06 06:40:35 +0000245/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
246/// as GCC.
247static int EvaluateBuiltinClassifyType(const CallExpr *E) {
248 // The following enum mimics the values returned by GCC.
249 enum gcc_type_class {
250 no_type_class = -1,
251 void_type_class, integer_type_class, char_type_class,
252 enumeral_type_class, boolean_type_class,
253 pointer_type_class, reference_type_class, offset_type_class,
254 real_type_class, complex_type_class,
255 function_type_class, method_type_class,
256 record_type_class, union_type_class,
257 array_type_class, string_type_class,
258 lang_type_class
259 };
260
261 // If no argument was supplied, default to "no_type_class". This isn't
262 // ideal, however it is what gcc does.
263 if (E->getNumArgs() == 0)
264 return no_type_class;
265
266 QualType ArgTy = E->getArg(0)->getType();
267 if (ArgTy->isVoidType())
268 return void_type_class;
269 else if (ArgTy->isEnumeralType())
270 return enumeral_type_class;
271 else if (ArgTy->isBooleanType())
272 return boolean_type_class;
273 else if (ArgTy->isCharType())
274 return string_type_class; // gcc doesn't appear to use char_type_class
275 else if (ArgTy->isIntegerType())
276 return integer_type_class;
277 else if (ArgTy->isPointerType())
278 return pointer_type_class;
279 else if (ArgTy->isReferenceType())
280 return reference_type_class;
281 else if (ArgTy->isRealType())
282 return real_type_class;
283 else if (ArgTy->isComplexType())
284 return complex_type_class;
285 else if (ArgTy->isFunctionType())
286 return function_type_class;
287 else if (ArgTy->isStructureType())
288 return record_type_class;
289 else if (ArgTy->isUnionType())
290 return union_type_class;
291 else if (ArgTy->isArrayType())
292 return array_type_class;
293 else if (ArgTy->isUnionType())
294 return union_type_class;
295 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
296 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
297 return -1;
298}
299
Chris Lattner4c4867e2008-07-12 00:38:25 +0000300bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
301 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner4c4867e2008-07-12 00:38:25 +0000302
Chris Lattner019f4e82008-10-06 05:28:25 +0000303 switch (E->isBuiltinCall()) {
304 default:
305 return Error(E->getLocStart(), diag::err_expr_not_constant);
306 case Builtin::BI__builtin_classify_type:
Chris Lattnera4d55d82008-10-06 06:40:35 +0000307 Result.setIsSigned(true);
308 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000309 return true;
310
311 case Builtin::BI__builtin_constant_p: {
312 // __builtin_constant_p always has one operand: it returns true if that
313 // operand can be folded, false otherwise.
314 APValue Res;
315 Result = E->getArg(0)->tryEvaluate(Res, Info.Ctx);
316 return true;
317 }
318 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000319}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000320
Chris Lattnerb542afe2008-07-11 19:10:17 +0000321bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000322 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000323 llvm::APSInt RHS(32);
Chris Lattner54176fd2008-07-12 00:14:42 +0000324 if (!Visit(E->getLHS()))
325 return false; // error in subexpression.
326
327 bool OldEval = Info.isEvaluated;
328
329 // The short-circuiting &&/|| operators don't necessarily evaluate their
330 // RHS. Make sure to pass isEvaluated down correctly.
331 if ((E->getOpcode() == BinaryOperator::LAnd && Result == 0) ||
332 (E->getOpcode() == BinaryOperator::LOr && Result != 0))
333 Info.isEvaluated = false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000334
335 // FIXME: Handle pointer subtraction
336
337 // FIXME Maybe we want to succeed even where we can't evaluate the
338 // right side of LAnd/LOr?
339 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000340 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000341 return false;
Chris Lattner54176fd2008-07-12 00:14:42 +0000342 Info.isEvaluated = OldEval;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000343
344 switch (E->getOpcode()) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000345 default: return Error(E->getOperatorLoc(), diag::err_expr_not_constant);
346 case BinaryOperator::Mul: Result *= RHS; return true;
347 case BinaryOperator::Add: Result += RHS; return true;
348 case BinaryOperator::Sub: Result -= RHS; return true;
349 case BinaryOperator::And: Result &= RHS; return true;
350 case BinaryOperator::Xor: Result ^= RHS; return true;
351 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000352 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000353 if (RHS == 0)
354 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero);
Chris Lattner75a48812008-07-11 22:15:16 +0000355 Result /= RHS;
Chris Lattner54176fd2008-07-12 00:14:42 +0000356 return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000357 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000358 if (RHS == 0)
359 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero);
Chris Lattner75a48812008-07-11 22:15:16 +0000360 Result %= RHS;
Chris Lattner54176fd2008-07-12 00:14:42 +0000361 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000362 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000363 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000364 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000365 break;
366 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000367 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000368 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000369
Chris Lattnerac7cb602008-07-11 19:29:32 +0000370 case BinaryOperator::LT:
371 Result = Result < RHS;
372 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
373 break;
374 case BinaryOperator::GT:
375 Result = Result > RHS;
376 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
377 break;
378 case BinaryOperator::LE:
379 Result = Result <= RHS;
380 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
381 break;
382 case BinaryOperator::GE:
383 Result = Result >= RHS;
384 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
385 break;
386 case BinaryOperator::EQ:
387 Result = Result == RHS;
388 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
389 break;
390 case BinaryOperator::NE:
391 Result = Result != RHS;
392 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
393 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000394 case BinaryOperator::LAnd:
395 Result = Result != 0 && RHS != 0;
396 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
397 break;
398 case BinaryOperator::LOr:
399 Result = Result != 0 || RHS != 0;
400 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
401 break;
402
Anders Carlsson06a36752008-07-08 05:49:43 +0000403
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000404 case BinaryOperator::Comma:
Chris Lattner54176fd2008-07-12 00:14:42 +0000405 // Result of the comma is just the result of the RHS.
406 Result = RHS;
407
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000408 // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
409 // *except* when they are contained within a subexpression that is not
410 // evaluated". Note that Assignment can never happen due to constraints
411 // on the LHS subexpr, so we don't need to check it here.
Chris Lattner54176fd2008-07-12 00:14:42 +0000412 if (!Info.isEvaluated)
413 return true;
414
415 // If the value is evaluated, we can accept it as an extension.
416 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000417 }
418
419 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000420 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000421}
422
Chris Lattnerfcee0012008-07-11 21:24:13 +0000423/// EvaluateSizeAlignOf - Evaluate sizeof(SrcTy) or alignof(SrcTy) with a result
424/// as a DstTy type.
425bool IntExprEvaluator::EvaluateSizeAlignOf(bool isSizeOf, QualType SrcTy,
426 QualType DstTy) {
427 // Return the result in the right width.
428 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
429 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
430
431 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
432 if (SrcTy->isVoidType())
433 Result = 1;
434
435 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
436 if (!SrcTy->isConstantSizeType()) {
437 // FIXME: Should we attempt to evaluate this?
438 return false;
439 }
440
441 // GCC extension: sizeof(function) = 1.
442 if (SrcTy->isFunctionType()) {
443 // FIXME: AlignOf shouldn't be unconditionally 4!
444 Result = isSizeOf ? 1 : 4;
445 return true;
446 }
447
448 // Get information about the size or align.
Chris Lattner87eae5e2008-07-11 22:52:41 +0000449 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000450 if (isSizeOf)
451 Result = getIntTypeSizeInBits(SrcTy) / CharSize;
452 else
Chris Lattner87eae5e2008-07-11 22:52:41 +0000453 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000454 return true;
455}
456
Chris Lattnerb542afe2008-07-11 19:10:17 +0000457bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000458 // Special case unary operators that do not need their subexpression
459 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +0000460 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000461 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +0000462 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +0000463 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
464 return true;
465 }
466
467 if (E->isSizeOfAlignOfOp())
Chris Lattnerfcee0012008-07-11 21:24:13 +0000468 return EvaluateSizeAlignOf(E->getOpcode() == UnaryOperator::SizeOf,
469 E->getSubExpr()->getType(), E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000470
Chris Lattner87eae5e2008-07-11 22:52:41 +0000471 // Get the operand value into 'Result'.
472 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +0000473 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000474
Chris Lattner75a48812008-07-11 22:15:16 +0000475 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000476 default:
Chris Lattner75a48812008-07-11 22:15:16 +0000477 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
478 // See C99 6.6p3.
Chris Lattner4c4867e2008-07-12 00:38:25 +0000479 return Error(E->getOperatorLoc(), diag::err_expr_not_constant);
Chris Lattner75a48812008-07-11 22:15:16 +0000480 case UnaryOperator::LNot: {
481 bool Val = Result == 0;
482 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
483 Result = Val;
484 break;
485 }
486 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000487 // FIXME: Should extension allow i-c-e extension expressions in its scope?
488 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +0000489 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000490 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +0000491 break;
492 case UnaryOperator::Minus:
493 Result = -Result;
494 break;
495 case UnaryOperator::Not:
496 Result = ~Result;
497 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000498 }
499
500 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000501 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000502}
503
Chris Lattner732b2232008-07-12 01:15:53 +0000504/// HandleCast - This is used to evaluate implicit or explicit casts where the
505/// result type is integer.
506bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
507 Expr *SubExpr, QualType DestType) {
Chris Lattner7a767782008-07-11 19:24:49 +0000508 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000509
510 // Handle simple integer->integer casts.
511 if (SubExpr->getType()->isIntegerType()) {
Chris Lattner732b2232008-07-12 01:15:53 +0000512 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000513 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000514
515 // Figure out if this is a truncate, extend or noop cast.
516 // If the input is signed, do a sign extend, noop, or truncate.
517 if (DestType->isBooleanType()) {
518 // Conversion to bool compares against zero.
519 Result = Result != 0;
520 Result.zextOrTrunc(DestWidth);
Chris Lattner7a767782008-07-11 19:24:49 +0000521 } else
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000522 Result.extOrTrunc(DestWidth);
Chris Lattner732b2232008-07-12 01:15:53 +0000523 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
524 return true;
525 }
526
527 // FIXME: Clean this up!
528 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000529 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000530 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000531 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000532 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +0000533 return false;
Anders Carlsson06a36752008-07-08 05:49:43 +0000534
Anders Carlsson559e56b2008-07-08 16:49:00 +0000535 Result.extOrTrunc(DestWidth);
536 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +0000537 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
538 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000539 }
540
Chris Lattner732b2232008-07-12 01:15:53 +0000541 if (!SubExpr->getType()->isRealFloatingType())
542 return Error(CastLoc, diag::err_expr_not_constant);
543
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000544 APFloat F(0.0);
545 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner732b2232008-07-12 01:15:53 +0000546 return Error(CastLoc, diag::err_expr_not_constant);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000547
Chris Lattner732b2232008-07-12 01:15:53 +0000548 // If the destination is boolean, compare against zero.
549 if (DestType->isBooleanType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000550 Result = !F.isZero();
Chris Lattner732b2232008-07-12 01:15:53 +0000551 Result.zextOrTrunc(DestWidth);
552 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
553 return true;
554 }
555
556 // Determine whether we are converting to unsigned or signed.
557 bool DestSigned = DestType->isSignedIntegerType();
558
559 // FIXME: Warning for overflow.
Dale Johannesenee5a7002008-10-09 23:02:32 +0000560 uint64_t Space[4];
561 bool ignored;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000562 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesenee5a7002008-10-09 23:02:32 +0000563 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattner732b2232008-07-12 01:15:53 +0000564 Result = llvm::APInt(DestWidth, 4, Space);
565 Result.setIsUnsigned(!DestSigned);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000566 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000567}
Anders Carlsson2bad1682008-07-08 14:30:00 +0000568
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000569//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000570// Float Evaluation
571//===----------------------------------------------------------------------===//
572
573namespace {
574class VISIBILITY_HIDDEN FloatExprEvaluator
575 : public StmtVisitor<FloatExprEvaluator, bool> {
576 EvalInfo &Info;
577 APFloat &Result;
578public:
579 FloatExprEvaluator(EvalInfo &info, APFloat &result)
580 : Info(info), Result(result) {}
581
582 bool VisitStmt(Stmt *S) {
583 return false;
584 }
585
586 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +0000587 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000588
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000589 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000590 bool VisitBinaryOperator(const BinaryOperator *E);
591 bool VisitFloatingLiteral(const FloatingLiteral *E);
592};
593} // end anonymous namespace
594
595static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
596 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
597}
598
Chris Lattner019f4e82008-10-06 05:28:25 +0000599bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000600 switch (E->isBuiltinCall()) {
Chris Lattner34a74ab2008-10-06 05:53:16 +0000601 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +0000602 case Builtin::BI__builtin_huge_val:
603 case Builtin::BI__builtin_huge_valf:
604 case Builtin::BI__builtin_huge_vall:
605 case Builtin::BI__builtin_inf:
606 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000607 case Builtin::BI__builtin_infl: {
608 const llvm::fltSemantics &Sem =
609 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +0000610 Result = llvm::APFloat::getInf(Sem);
611 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000612 }
Chris Lattner9e621712008-10-06 06:31:58 +0000613
614 case Builtin::BI__builtin_nan:
615 case Builtin::BI__builtin_nanf:
616 case Builtin::BI__builtin_nanl:
617 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
618 // can't constant fold it.
619 if (const StringLiteral *S =
620 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
621 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000622 const llvm::fltSemantics &Sem =
623 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +0000624 Result = llvm::APFloat::getNaN(Sem);
625 return true;
626 }
627 }
628 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000629
630 case Builtin::BI__builtin_fabs:
631 case Builtin::BI__builtin_fabsf:
632 case Builtin::BI__builtin_fabsl:
633 if (!EvaluateFloat(E->getArg(0), Result, Info))
634 return false;
635
636 if (Result.isNegative())
637 Result.changeSign();
638 return true;
639
640 case Builtin::BI__builtin_copysign:
641 case Builtin::BI__builtin_copysignf:
642 case Builtin::BI__builtin_copysignl: {
643 APFloat RHS(0.);
644 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
645 !EvaluateFloat(E->getArg(1), RHS, Info))
646 return false;
647 Result.copySign(RHS);
648 return true;
649 }
Chris Lattner019f4e82008-10-06 05:28:25 +0000650 }
651}
652
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000653bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
654 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
655 return false;
656
657 switch (E->getOpcode()) {
658 default: return false;
659 case UnaryOperator::Plus:
660 return true;
661 case UnaryOperator::Minus:
662 Result.changeSign();
663 return true;
664 }
665}
Chris Lattner019f4e82008-10-06 05:28:25 +0000666
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000667bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
668 // FIXME: Diagnostics? I really don't understand how the warnings
669 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000670 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000671 if (!EvaluateFloat(E->getLHS(), Result, Info))
672 return false;
673 if (!EvaluateFloat(E->getRHS(), RHS, Info))
674 return false;
675
676 switch (E->getOpcode()) {
677 default: return false;
678 case BinaryOperator::Mul:
679 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
680 return true;
681 case BinaryOperator::Add:
682 Result.add(RHS, APFloat::rmNearestTiesToEven);
683 return true;
684 case BinaryOperator::Sub:
685 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
686 return true;
687 case BinaryOperator::Div:
688 Result.divide(RHS, APFloat::rmNearestTiesToEven);
689 return true;
690 case BinaryOperator::Rem:
691 Result.mod(RHS, APFloat::rmNearestTiesToEven);
692 return true;
693 }
694}
695
696bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
697 Result = E->getValue();
698 return true;
699}
700
701//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000702// Top level TryEvaluate.
703//===----------------------------------------------------------------------===//
704
Chris Lattner019f4e82008-10-06 05:28:25 +0000705/// tryEvaluate - Return true if this is a constant which we can fold using
706/// any crazy technique (that has nothing to do with language standards) that
707/// we want to. If this function returns true, it returns the folded constant
708/// in Result.
Chris Lattnerb542afe2008-07-11 19:10:17 +0000709bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000710 EvalInfo Info(Ctx);
Anders Carlsson06a36752008-07-08 05:49:43 +0000711 if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000712 llvm::APSInt sInt(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000713 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlsson06a36752008-07-08 05:49:43 +0000714 Result = APValue(sInt);
715 return true;
716 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000717 } else if (getType()->isPointerType()) {
718 if (EvaluatePointer(this, Result, Info)) {
719 return true;
720 }
721 } else if (getType()->isRealFloatingType()) {
722 llvm::APFloat f(0.0);
723 if (EvaluateFloat(this, f, Info)) {
724 Result = APValue(f);
725 return true;
726 }
727 }
Anders Carlsson165a70f2008-08-10 17:03:01 +0000728
Anders Carlssonc44eec62008-07-03 04:20:39 +0000729 return false;
730}
Chris Lattner45b6b9d2008-10-06 06:49:02 +0000731
732/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
733/// folded, but discard the result.
734bool Expr::isEvaluatable(ASTContext &Ctx) const {
735 APValue V;
736 return tryEvaluate(V, Ctx);
737}