ExprConstant.cpp revision 35873c49adad211ff466e34342a52665742794f5
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
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"
16#include "clang/AST/RecordLayout.h"
17#include "clang/AST/StmtVisitor.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/TargetInfo.h"
20#include "llvm/Support/Compiler.h"
21using namespace clang;
22using llvm::APSInt;
23using llvm::APFloat;
24
25/// 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
46  /// 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.
53  ///
54  /// 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.
59  unsigned ICEDiag;
60  SourceLocation DiagLoc;
61
62  EvalInfo(ASTContext &ctx) : Ctx(ctx), isEvaluated(true), ICEDiag(0) {}
63};
64
65
66static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
67static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
68static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
69static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
70static bool EvaluateComplexFloat(const Expr *E, APValue &Result,
71                                 EvalInfo &Info);
72
73//===----------------------------------------------------------------------===//
74// Misc utilities
75//===----------------------------------------------------------------------===//
76
77static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
78  if (E->getType()->isIntegralType()) {
79    APSInt IntResult;
80    if (!EvaluateInteger(E, IntResult, Info))
81      return false;
82    Result = IntResult != 0;
83    return true;
84  } else if (E->getType()->isRealFloatingType()) {
85    APFloat FloatResult(0.0);
86    if (!EvaluateFloat(E, FloatResult, Info))
87      return false;
88    Result = !FloatResult.isZero();
89    return true;
90  } else if (E->getType()->isPointerType()) {
91    APValue PointerResult;
92    if (!EvaluatePointer(E, PointerResult, Info))
93      return false;
94    // FIXME: Is this accurate for all kinds of bases?  If not, what would
95    // the check look like?
96    Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
97    return true;
98  }
99
100  return false;
101}
102
103//===----------------------------------------------------------------------===//
104// LValue Evaluation
105//===----------------------------------------------------------------------===//
106namespace {
107class VISIBILITY_HIDDEN LValueExprEvaluator
108  : public StmtVisitor<LValueExprEvaluator, APValue> {
109  EvalInfo &Info;
110public:
111
112  LValueExprEvaluator(EvalInfo &info) : Info(info) {}
113
114  APValue VisitStmt(Stmt *S) {
115#if 0
116    // FIXME: Remove this when we support more expressions.
117    printf("Unhandled pointer statement\n");
118    S->dump();
119#endif
120    return APValue();
121  }
122
123  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
124  APValue VisitDeclRefExpr(DeclRefExpr *E);
125  APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
126  APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
127  APValue VisitMemberExpr(MemberExpr *E);
128  APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
129  APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
130};
131} // end anonymous namespace
132
133static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
134  Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
135  return Result.isLValue();
136}
137
138APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
139{
140  if (!E->hasGlobalStorage())
141    return APValue();
142
143  return APValue(E, 0);
144}
145
146APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
147  if (E->isFileScope())
148    return APValue(E, 0);
149  return APValue();
150}
151
152APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
153  APValue result;
154  QualType Ty;
155  if (E->isArrow()) {
156    if (!EvaluatePointer(E->getBase(), result, Info))
157      return APValue();
158    Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
159  } else {
160    result = Visit(E->getBase());
161    if (result.isUninit())
162      return APValue();
163    Ty = E->getBase()->getType();
164  }
165
166  RecordDecl *RD = Ty->getAsRecordType()->getDecl();
167  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
168  FieldDecl *FD = E->getMemberDecl();
169
170  // FIXME: This is linear time.
171  unsigned i = 0, e = 0;
172  for (i = 0, e = RD->getNumMembers(); i != e; i++) {
173    if (RD->getMember(i) == FD)
174      break;
175  }
176
177  result.setLValue(result.getLValueBase(),
178                   result.getLValueOffset() + RL.getFieldOffset(i) / 8);
179
180  return result;
181}
182
183APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
184{
185  APValue Result;
186
187  if (!EvaluatePointer(E->getBase(), Result, Info))
188    return APValue();
189
190  APSInt Index;
191  if (!EvaluateInteger(E->getIdx(), Index, Info))
192    return APValue();
193
194  uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
195
196  uint64_t Offset = Index.getSExtValue() * ElementSize;
197  Result.setLValue(Result.getLValueBase(),
198                   Result.getLValueOffset() + Offset);
199  return Result;
200}
201
202//===----------------------------------------------------------------------===//
203// Pointer Evaluation
204//===----------------------------------------------------------------------===//
205
206namespace {
207class VISIBILITY_HIDDEN PointerExprEvaluator
208  : public StmtVisitor<PointerExprEvaluator, APValue> {
209  EvalInfo &Info;
210public:
211
212  PointerExprEvaluator(EvalInfo &info) : Info(info) {}
213
214  APValue VisitStmt(Stmt *S) {
215    return APValue();
216  }
217
218  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
219
220  APValue VisitBinaryOperator(const BinaryOperator *E);
221  APValue VisitCastExpr(const CastExpr* E);
222  APValue VisitUnaryOperator(const UnaryOperator *E);
223  APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
224      { return APValue(E, 0); }
225  APValue VisitConditionalOperator(ConditionalOperator *E);
226};
227} // end anonymous namespace
228
229static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
230  if (!E->getType()->isPointerType())
231    return false;
232  Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
233  return Result.isLValue();
234}
235
236APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
237  if (E->getOpcode() != BinaryOperator::Add &&
238      E->getOpcode() != BinaryOperator::Sub)
239    return APValue();
240
241  const Expr *PExp = E->getLHS();
242  const Expr *IExp = E->getRHS();
243  if (IExp->getType()->isPointerType())
244    std::swap(PExp, IExp);
245
246  APValue ResultLValue;
247  if (!EvaluatePointer(PExp, ResultLValue, Info))
248    return APValue();
249
250  llvm::APSInt AdditionalOffset(32);
251  if (!EvaluateInteger(IExp, AdditionalOffset, Info))
252    return APValue();
253
254  QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
255  uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
256
257  uint64_t Offset = ResultLValue.getLValueOffset();
258
259  if (E->getOpcode() == BinaryOperator::Add)
260    Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
261  else
262    Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
263
264  return APValue(ResultLValue.getLValueBase(), Offset);
265}
266
267APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
268  if (E->getOpcode() == UnaryOperator::Extension) {
269    // FIXME: Deal with warnings?
270    return Visit(E->getSubExpr());
271  }
272
273  if (E->getOpcode() == UnaryOperator::AddrOf) {
274    APValue result;
275    if (EvaluateLValue(E->getSubExpr(), result, Info))
276      return result;
277  }
278
279  return APValue();
280}
281
282
283APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
284  const Expr* SubExpr = E->getSubExpr();
285
286   // Check for pointer->pointer cast
287  if (SubExpr->getType()->isPointerType()) {
288    APValue Result;
289    if (EvaluatePointer(SubExpr, Result, Info))
290      return Result;
291    return APValue();
292  }
293
294  if (SubExpr->getType()->isIntegralType()) {
295    llvm::APSInt Result(32);
296    if (EvaluateInteger(SubExpr, Result, Info)) {
297      Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
298      return APValue(0, Result.getZExtValue());
299    }
300  }
301
302  if (SubExpr->getType()->isFunctionType() ||
303      SubExpr->getType()->isArrayType()) {
304    APValue Result;
305    if (EvaluateLValue(SubExpr, Result, Info))
306      return Result;
307    return APValue();
308  }
309
310  //assert(0 && "Unhandled cast");
311  return APValue();
312}
313
314APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
315  bool BoolResult;
316  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
317    return APValue();
318
319  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
320
321  APValue Result;
322  if (EvaluatePointer(EvalExpr, Result, Info))
323    return Result;
324  return APValue();
325}
326
327//===----------------------------------------------------------------------===//
328// Integer Evaluation
329//===----------------------------------------------------------------------===//
330
331namespace {
332class VISIBILITY_HIDDEN IntExprEvaluator
333  : public StmtVisitor<IntExprEvaluator, bool> {
334  EvalInfo &Info;
335  APSInt &Result;
336public:
337  IntExprEvaluator(EvalInfo &info, APSInt &result)
338    : Info(info), Result(result) {}
339
340  unsigned getIntTypeSizeInBits(QualType T) const {
341    return (unsigned)Info.Ctx.getIntWidth(T);
342  }
343
344  bool Extension(SourceLocation L, diag::kind D) {
345    Info.DiagLoc = L;
346    Info.ICEDiag = D;
347    return true;  // still a constant.
348  }
349
350  bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
351    // If this is in an unevaluated portion of the subexpression, ignore the
352    // error.
353    if (!Info.isEvaluated) {
354      // If error is ignored because the value isn't evaluated, get the real
355      // type at least to prevent errors downstream.
356      Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
357      Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
358      return true;
359    }
360
361    // Take the first error.
362    if (Info.ICEDiag == 0) {
363      Info.DiagLoc = L;
364      Info.ICEDiag = D;
365    }
366    return false;
367  }
368
369  //===--------------------------------------------------------------------===//
370  //                            Visitor Methods
371  //===--------------------------------------------------------------------===//
372
373  bool VisitStmt(Stmt *) {
374    assert(0 && "This should be called on integers, stmts are not integers");
375    return false;
376  }
377
378  bool VisitExpr(Expr *E) {
379    return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
380  }
381
382  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
383
384  bool VisitIntegerLiteral(const IntegerLiteral *E) {
385    Result = E->getValue();
386    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
387    return true;
388  }
389  bool VisitCharacterLiteral(const CharacterLiteral *E) {
390    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
391    Result = E->getValue();
392    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
393    return true;
394  }
395  bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
396    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
397    // Per gcc docs "this built-in function ignores top level
398    // qualifiers".  We need to use the canonical version to properly
399    // be able to strip CRV qualifiers from the type.
400    QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
401    QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
402    Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
403                                         T1.getUnqualifiedType());
404    return true;
405  }
406  bool VisitDeclRefExpr(const DeclRefExpr *E);
407  bool VisitCallExpr(const CallExpr *E);
408  bool VisitBinaryOperator(const BinaryOperator *E);
409  bool VisitUnaryOperator(const UnaryOperator *E);
410  bool VisitConditionalOperator(const ConditionalOperator *E);
411
412  bool VisitCastExpr(CastExpr* E) {
413    return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
414  }
415  bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
416
417  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
418    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
419    Result = E->getValue();
420    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
421    return true;
422  }
423
424  bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
425    Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
426    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
427    return true;
428  }
429
430private:
431  bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
432};
433} // end anonymous namespace
434
435static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
436  return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
437}
438
439bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
440  // Enums are integer constant exprs.
441  if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
442    Result = D->getInitVal();
443    return true;
444  }
445
446  // Otherwise, random variable references are not constants.
447  return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
448}
449
450/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
451/// as GCC.
452static int EvaluateBuiltinClassifyType(const CallExpr *E) {
453  // The following enum mimics the values returned by GCC.
454  enum gcc_type_class {
455    no_type_class = -1,
456    void_type_class, integer_type_class, char_type_class,
457    enumeral_type_class, boolean_type_class,
458    pointer_type_class, reference_type_class, offset_type_class,
459    real_type_class, complex_type_class,
460    function_type_class, method_type_class,
461    record_type_class, union_type_class,
462    array_type_class, string_type_class,
463    lang_type_class
464  };
465
466  // If no argument was supplied, default to "no_type_class". This isn't
467  // ideal, however it is what gcc does.
468  if (E->getNumArgs() == 0)
469    return no_type_class;
470
471  QualType ArgTy = E->getArg(0)->getType();
472  if (ArgTy->isVoidType())
473    return void_type_class;
474  else if (ArgTy->isEnumeralType())
475    return enumeral_type_class;
476  else if (ArgTy->isBooleanType())
477    return boolean_type_class;
478  else if (ArgTy->isCharType())
479    return string_type_class; // gcc doesn't appear to use char_type_class
480  else if (ArgTy->isIntegerType())
481    return integer_type_class;
482  else if (ArgTy->isPointerType())
483    return pointer_type_class;
484  else if (ArgTy->isReferenceType())
485    return reference_type_class;
486  else if (ArgTy->isRealType())
487    return real_type_class;
488  else if (ArgTy->isComplexType())
489    return complex_type_class;
490  else if (ArgTy->isFunctionType())
491    return function_type_class;
492  else if (ArgTy->isStructureType())
493    return record_type_class;
494  else if (ArgTy->isUnionType())
495    return union_type_class;
496  else if (ArgTy->isArrayType())
497    return array_type_class;
498  else if (ArgTy->isUnionType())
499    return union_type_class;
500  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
501    assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
502  return -1;
503}
504
505bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
506  Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
507
508  switch (E->isBuiltinCall()) {
509  default:
510    return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
511  case Builtin::BI__builtin_classify_type:
512    Result.setIsSigned(true);
513    Result = EvaluateBuiltinClassifyType(E);
514    return true;
515
516  case Builtin::BI__builtin_constant_p:
517    // __builtin_constant_p always has one operand: it returns true if that
518    // operand can be folded, false otherwise.
519    Result = E->getArg(0)->isEvaluatable(Info.Ctx);
520    return true;
521  }
522}
523
524bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
525  if (E->getOpcode() == BinaryOperator::Comma) {
526    // Evaluate the side that actually matters; this needs to be
527    // handled specially because calling Visit() on the LHS can
528    // have strange results when it doesn't have an integral type.
529    if (Visit(E->getRHS()))
530      return true;
531
532    // Check for isEvaluated; the idea is that this might eventually
533    // be useful for isICE and other similar uses that care about
534    // whether a comma is evaluated.  This isn't really used yet, though,
535    // and I'm not sure it really works as intended.
536    if (!Info.isEvaluated)
537      return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
538
539    return false;
540  }
541
542  if (E->isLogicalOp()) {
543    // These need to be handled specially because the operands aren't
544    // necessarily integral
545    bool bres;
546
547    if (HandleConversionToBool(E->getLHS(), bres, Info)) {
548      // We were able to evaluate the LHS, see if we can get away with not
549      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
550      if (bres == (E->getOpcode() == BinaryOperator::LOr) ||
551          !bres == (E->getOpcode() == BinaryOperator::LAnd)) {
552        Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
553        Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
554        Result = bres;
555
556        return true;
557      }
558
559      bool bres2;
560      if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
561        Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
562        Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
563        if (E->getOpcode() == BinaryOperator::LOr)
564          Result = bres || bres2;
565        else
566          Result = bres && bres2;
567        return true;
568      }
569    } else {
570      if (HandleConversionToBool(E->getRHS(), bres, Info)) {
571        // We can't evaluate the LHS; however, sometimes the result
572        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
573        if (bres == (E->getOpcode() == BinaryOperator::LOr) ||
574            !bres == (E->getOpcode() == BinaryOperator::LAnd)) {
575          Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
576          Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
577          Result = bres;
578          Info.isEvaluated = false;
579
580          return true;
581        }
582      }
583    }
584
585    return false;
586  }
587
588  QualType LHSTy = E->getLHS()->getType();
589  QualType RHSTy = E->getRHS()->getType();
590
591  if (LHSTy->isRealFloatingType() &&
592      RHSTy->isRealFloatingType()) {
593    APFloat RHS(0.0), LHS(0.0);
594
595    if (!EvaluateFloat(E->getRHS(), RHS, Info))
596      return false;
597
598    if (!EvaluateFloat(E->getLHS(), LHS, Info))
599      return false;
600
601    APFloat::cmpResult CR = LHS.compare(RHS);
602
603    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
604
605    switch (E->getOpcode()) {
606    default:
607      assert(0 && "Invalid binary operator!");
608    case BinaryOperator::LT:
609      Result = CR == APFloat::cmpLessThan;
610      break;
611    case BinaryOperator::GT:
612      Result = CR == APFloat::cmpGreaterThan;
613      break;
614    case BinaryOperator::LE:
615      Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
616      break;
617    case BinaryOperator::GE:
618      Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
619      break;
620    case BinaryOperator::EQ:
621      Result = CR == APFloat::cmpEqual;
622      break;
623    case BinaryOperator::NE:
624      Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
625      break;
626    }
627
628    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
629    return true;
630  }
631
632  if (E->getOpcode() == BinaryOperator::Sub) {
633    if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
634      APValue LHSValue;
635      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
636        return false;
637
638      APValue RHSValue;
639      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
640        return false;
641
642      // FIXME: Is this correct? What if only one of the operands has a base?
643      if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
644        return false;
645
646      const QualType Type = E->getLHS()->getType();
647      const QualType ElementType = Type->getAsPointerType()->getPointeeType();
648
649      uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
650      D /= Info.Ctx.getTypeSize(ElementType) / 8;
651
652      Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
653      Result = D;
654      Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
655
656      return true;
657    }
658  }
659  if (!LHSTy->isIntegralType() ||
660      !RHSTy->isIntegralType()) {
661    // We can't continue from here for non-integral types, and they
662    // could potentially confuse the following operations.
663    // FIXME: Deal with EQ and friends.
664    return false;
665  }
666
667  // The LHS of a constant expr is always evaluated and needed.
668  llvm::APSInt RHS(32);
669  if (!Visit(E->getLHS())) {
670    return false; // error in subexpression.
671  }
672
673
674  // FIXME Maybe we want to succeed even where we can't evaluate the
675  // right side of LAnd/LOr?
676  // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
677  if (!EvaluateInteger(E->getRHS(), RHS, Info))
678    return false;
679
680  switch (E->getOpcode()) {
681  default:
682    return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
683  case BinaryOperator::Mul: Result *= RHS; return true;
684  case BinaryOperator::Add: Result += RHS; return true;
685  case BinaryOperator::Sub: Result -= RHS; return true;
686  case BinaryOperator::And: Result &= RHS; return true;
687  case BinaryOperator::Xor: Result ^= RHS; return true;
688  case BinaryOperator::Or:  Result |= RHS; return true;
689  case BinaryOperator::Div:
690    if (RHS == 0)
691      return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
692                   E->getType());
693    Result /= RHS;
694    break;
695  case BinaryOperator::Rem:
696    if (RHS == 0)
697      return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
698                   E->getType());
699    Result %= RHS;
700    break;
701  case BinaryOperator::Shl:
702    // FIXME: Warn about out of range shift amounts!
703    Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
704    break;
705  case BinaryOperator::Shr:
706    Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
707    break;
708
709  case BinaryOperator::LT:
710    Result = Result < RHS;
711    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
712    break;
713  case BinaryOperator::GT:
714    Result = Result > RHS;
715    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
716    break;
717  case BinaryOperator::LE:
718    Result = Result <= RHS;
719    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
720    break;
721  case BinaryOperator::GE:
722    Result = Result >= RHS;
723    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
724    break;
725  case BinaryOperator::EQ:
726    Result = Result == RHS;
727    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
728    break;
729  case BinaryOperator::NE:
730    Result = Result != RHS;
731    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
732    break;
733  case BinaryOperator::LAnd:
734    Result = Result != 0 && RHS != 0;
735    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
736    break;
737  case BinaryOperator::LOr:
738    Result = Result != 0 || RHS != 0;
739    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
740    break;
741  }
742
743  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
744  return true;
745}
746
747bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
748  bool Cond;
749  if (!HandleConversionToBool(E->getCond(), Cond, Info))
750    return false;
751
752  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
753}
754
755/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
756/// expression's type.
757bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
758  QualType DstTy = E->getType();
759  // Return the result in the right width.
760  Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
761  Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
762
763  QualType SrcTy = E->getTypeOfArgument();
764
765  // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
766  if (SrcTy->isVoidType()) {
767    Result = 1;
768    return true;
769  }
770
771  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
772  // FIXME: But alignof(vla) is!
773  if (!SrcTy->isConstantSizeType()) {
774    // FIXME: Should we attempt to evaluate this?
775    return false;
776  }
777
778  bool isSizeOf = E->isSizeOf();
779
780  // GCC extension: sizeof(function) = 1.
781  if (SrcTy->isFunctionType()) {
782    // FIXME: AlignOf shouldn't be unconditionally 4!
783    Result = isSizeOf ? 1 : 4;
784    return true;
785  }
786
787  // Get information about the size or align.
788  unsigned CharSize = Info.Ctx.Target.getCharWidth();
789  if (isSizeOf)
790    Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
791  else
792    Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
793  return true;
794}
795
796bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
797  // Special case unary operators that do not need their subexpression
798  // evaluated.  offsetof/sizeof/alignof are all special.
799  if (E->isOffsetOfOp()) {
800    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
801    Result = E->evaluateOffsetOf(Info.Ctx);
802    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
803    return true;
804  }
805
806  if (E->getOpcode() == UnaryOperator::LNot) {
807    // LNot's operand isn't necessarily an integer, so we handle it specially.
808    bool bres;
809    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
810      return false;
811    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
812    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
813    Result = !bres;
814    return true;
815  }
816
817  // Get the operand value into 'Result'.
818  if (!Visit(E->getSubExpr()))
819    return false;
820
821  switch (E->getOpcode()) {
822  default:
823    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
824    // See C99 6.6p3.
825    return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
826                 E->getType());
827  case UnaryOperator::Extension:
828    // FIXME: Should extension allow i-c-e extension expressions in its scope?
829    // If so, we could clear the diagnostic ID.
830  case UnaryOperator::Plus:
831    // The result is always just the subexpr.
832    break;
833  case UnaryOperator::Minus:
834    Result = -Result;
835    break;
836  case UnaryOperator::Not:
837    Result = ~Result;
838    break;
839  }
840
841  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
842  return true;
843}
844
845/// HandleCast - This is used to evaluate implicit or explicit casts where the
846/// result type is integer.
847bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
848                                  Expr *SubExpr, QualType DestType) {
849  unsigned DestWidth = getIntTypeSizeInBits(DestType);
850
851  if (DestType->isBooleanType()) {
852    bool BoolResult;
853    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
854      return false;
855    Result.zextOrTrunc(DestWidth);
856    Result.setIsUnsigned(DestType->isUnsignedIntegerType());
857    Result = BoolResult;
858    return true;
859  }
860
861  // Handle simple integer->integer casts.
862  if (SubExpr->getType()->isIntegralType()) {
863    if (!Visit(SubExpr))
864      return false;
865
866    // Figure out if this is a truncate, extend or noop cast.
867    // If the input is signed, do a sign extend, noop, or truncate.
868    Result.extOrTrunc(DestWidth);
869    Result.setIsUnsigned(DestType->isUnsignedIntegerType());
870    return true;
871  }
872
873  // FIXME: Clean this up!
874  if (SubExpr->getType()->isPointerType()) {
875    APValue LV;
876    if (!EvaluatePointer(SubExpr, LV, Info))
877      return false;
878
879    if (LV.getLValueBase())
880      return false;
881
882    Result.extOrTrunc(DestWidth);
883    Result = LV.getLValueOffset();
884    Result.setIsUnsigned(DestType->isUnsignedIntegerType());
885    return true;
886  }
887
888  if (!SubExpr->getType()->isRealFloatingType())
889    return Error(CastLoc, diag::err_expr_not_constant, DestType);
890
891  APFloat F(0.0);
892  if (!EvaluateFloat(SubExpr, F, Info))
893    return Error(CastLoc, diag::err_expr_not_constant, DestType);
894
895  // Determine whether we are converting to unsigned or signed.
896  bool DestSigned = DestType->isSignedIntegerType();
897
898  // FIXME: Warning for overflow.
899  uint64_t Space[4];
900  bool ignored;
901  (void)F.convertToInteger(Space, DestWidth, DestSigned,
902                           llvm::APFloat::rmTowardZero, &ignored);
903  Result = llvm::APInt(DestWidth, 4, Space);
904  Result.setIsUnsigned(!DestSigned);
905  return true;
906}
907
908//===----------------------------------------------------------------------===//
909// Float Evaluation
910//===----------------------------------------------------------------------===//
911
912namespace {
913class VISIBILITY_HIDDEN FloatExprEvaluator
914  : public StmtVisitor<FloatExprEvaluator, bool> {
915  EvalInfo &Info;
916  APFloat &Result;
917public:
918  FloatExprEvaluator(EvalInfo &info, APFloat &result)
919    : Info(info), Result(result) {}
920
921  bool VisitStmt(Stmt *S) {
922    return false;
923  }
924
925  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
926  bool VisitCallExpr(const CallExpr *E);
927
928  bool VisitUnaryOperator(const UnaryOperator *E);
929  bool VisitBinaryOperator(const BinaryOperator *E);
930  bool VisitFloatingLiteral(const FloatingLiteral *E);
931  bool VisitCastExpr(CastExpr *E);
932  bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
933};
934} // end anonymous namespace
935
936static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
937  return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
938}
939
940bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
941  switch (E->isBuiltinCall()) {
942  default: return false;
943  case Builtin::BI__builtin_huge_val:
944  case Builtin::BI__builtin_huge_valf:
945  case Builtin::BI__builtin_huge_vall:
946  case Builtin::BI__builtin_inf:
947  case Builtin::BI__builtin_inff:
948  case Builtin::BI__builtin_infl: {
949    const llvm::fltSemantics &Sem =
950      Info.Ctx.getFloatTypeSemantics(E->getType());
951    Result = llvm::APFloat::getInf(Sem);
952    return true;
953  }
954
955  case Builtin::BI__builtin_nan:
956  case Builtin::BI__builtin_nanf:
957  case Builtin::BI__builtin_nanl:
958    // If this is __builtin_nan("") turn this into a simple nan, otherwise we
959    // can't constant fold it.
960    if (const StringLiteral *S =
961        dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
962      if (!S->isWide() && S->getByteLength() == 0) { // empty string.
963        const llvm::fltSemantics &Sem =
964          Info.Ctx.getFloatTypeSemantics(E->getType());
965        Result = llvm::APFloat::getNaN(Sem);
966        return true;
967      }
968    }
969    return false;
970
971  case Builtin::BI__builtin_fabs:
972  case Builtin::BI__builtin_fabsf:
973  case Builtin::BI__builtin_fabsl:
974    if (!EvaluateFloat(E->getArg(0), Result, Info))
975      return false;
976
977    if (Result.isNegative())
978      Result.changeSign();
979    return true;
980
981  case Builtin::BI__builtin_copysign:
982  case Builtin::BI__builtin_copysignf:
983  case Builtin::BI__builtin_copysignl: {
984    APFloat RHS(0.);
985    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
986        !EvaluateFloat(E->getArg(1), RHS, Info))
987      return false;
988    Result.copySign(RHS);
989    return true;
990  }
991  }
992}
993
994bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
995  if (E->getOpcode() == UnaryOperator::Deref)
996    return false;
997
998  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
999    return false;
1000
1001  switch (E->getOpcode()) {
1002  default: return false;
1003  case UnaryOperator::Plus:
1004    return true;
1005  case UnaryOperator::Minus:
1006    Result.changeSign();
1007    return true;
1008  }
1009}
1010
1011bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1012  // FIXME: Diagnostics?  I really don't understand how the warnings
1013  // and errors are supposed to work.
1014  APFloat RHS(0.0);
1015  if (!EvaluateFloat(E->getLHS(), Result, Info))
1016    return false;
1017  if (!EvaluateFloat(E->getRHS(), RHS, Info))
1018    return false;
1019
1020  switch (E->getOpcode()) {
1021  default: return false;
1022  case BinaryOperator::Mul:
1023    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1024    return true;
1025  case BinaryOperator::Add:
1026    Result.add(RHS, APFloat::rmNearestTiesToEven);
1027    return true;
1028  case BinaryOperator::Sub:
1029    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1030    return true;
1031  case BinaryOperator::Div:
1032    Result.divide(RHS, APFloat::rmNearestTiesToEven);
1033    return true;
1034  case BinaryOperator::Rem:
1035    Result.mod(RHS, APFloat::rmNearestTiesToEven);
1036    return true;
1037  }
1038}
1039
1040bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1041  Result = E->getValue();
1042  return true;
1043}
1044
1045bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1046  Expr* SubExpr = E->getSubExpr();
1047  const llvm::fltSemantics& destSemantics =
1048      Info.Ctx.getFloatTypeSemantics(E->getType());
1049  if (SubExpr->getType()->isIntegralType()) {
1050    APSInt IntResult;
1051    if (!EvaluateInteger(E, IntResult, Info))
1052      return false;
1053    Result = APFloat(destSemantics, 1);
1054    Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1055                            APFloat::rmNearestTiesToEven);
1056    return true;
1057  }
1058  if (SubExpr->getType()->isRealFloatingType()) {
1059    if (!Visit(SubExpr))
1060      return false;
1061    bool ignored;
1062    Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1063    return true;
1064  }
1065
1066  return false;
1067}
1068
1069bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1070  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1071  return true;
1072}
1073
1074//===----------------------------------------------------------------------===//
1075// Complex Float Evaluation
1076//===----------------------------------------------------------------------===//
1077
1078namespace {
1079class VISIBILITY_HIDDEN ComplexFloatExprEvaluator
1080  : public StmtVisitor<ComplexFloatExprEvaluator, APValue> {
1081  EvalInfo &Info;
1082
1083public:
1084  ComplexFloatExprEvaluator(EvalInfo &info) : Info(info) {}
1085
1086  //===--------------------------------------------------------------------===//
1087  //                            Visitor Methods
1088  //===--------------------------------------------------------------------===//
1089
1090  APValue VisitStmt(Stmt *S) {
1091    assert(0 && "This should be called on complex floats");
1092    return APValue();
1093  }
1094
1095  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1096
1097  APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1098    APFloat Result(0.0);
1099    if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1100      return APValue();
1101
1102    return APValue(APFloat(0.0), Result);
1103  }
1104
1105  APValue VisitCastExpr(CastExpr *E) {
1106    Expr* SubExpr = E->getSubExpr();
1107
1108    if (SubExpr->getType()->isRealFloatingType()) {
1109      APFloat Result(0.0);
1110
1111      if (!EvaluateFloat(SubExpr, Result, Info))
1112        return APValue();
1113
1114      return APValue(Result, APFloat(0.0));
1115    }
1116
1117    // FIXME: Handle more casts.
1118    return APValue();
1119  }
1120
1121  APValue VisitBinaryOperator(const BinaryOperator *E);
1122
1123};
1124} // end anonymous namespace
1125
1126static bool EvaluateComplexFloat(const Expr *E, APValue &Result, EvalInfo &Info)
1127{
1128  Result = ComplexFloatExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1129  return Result.isComplexFloat();
1130}
1131
1132APValue ComplexFloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1133{
1134  APValue Result, RHS;
1135
1136  if (!EvaluateComplexFloat(E->getLHS(), Result, Info))
1137    return APValue();
1138
1139  if (!EvaluateComplexFloat(E->getRHS(), RHS, Info))
1140    return APValue();
1141
1142  switch (E->getOpcode()) {
1143  default: return APValue();
1144  case BinaryOperator::Add:
1145    Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1146                                     APFloat::rmNearestTiesToEven);
1147    Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1148                                     APFloat::rmNearestTiesToEven);
1149  case BinaryOperator::Sub:
1150    Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1151                                          APFloat::rmNearestTiesToEven);
1152    Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1153                                          APFloat::rmNearestTiesToEven);
1154  }
1155
1156  return Result;
1157}
1158
1159//===----------------------------------------------------------------------===//
1160// Top level Expr::Evaluate method.
1161//===----------------------------------------------------------------------===//
1162
1163/// Evaluate - Return true if this is a constant which we can fold using
1164/// any crazy technique (that has nothing to do with language standards) that
1165/// we want to.  If this function returns true, it returns the folded constant
1166/// in Result.
1167bool Expr::Evaluate(APValue &Result, ASTContext &Ctx, bool *isEvaluated) const {
1168  EvalInfo Info(Ctx);
1169  if (getType()->isIntegerType()) {
1170    llvm::APSInt sInt(32);
1171    if (!EvaluateInteger(this, sInt, Info))
1172      return false;
1173
1174    Result = APValue(sInt);
1175  } else if (getType()->isPointerType()) {
1176    if (!EvaluatePointer(this, Result, Info))
1177      return false;
1178  } else if (getType()->isRealFloatingType()) {
1179    llvm::APFloat f(0.0);
1180    if (!EvaluateFloat(this, f, Info))
1181      return false;
1182
1183    Result = APValue(f);
1184  } else if (getType()->isComplexType()) {
1185    if (!EvaluateComplexFloat(this, Result, Info))
1186      return false;
1187  }  else
1188    return false;
1189
1190  if (isEvaluated)
1191    *isEvaluated = Info.isEvaluated;
1192  return true;
1193}
1194
1195/// isEvaluatable - Call Evaluate to see if this expression can be constant
1196/// folded, but discard the result.
1197bool Expr::isEvaluatable(ASTContext &Ctx) const {
1198  APValue V;
1199  return Evaluate(V, Ctx);
1200}
1201
1202APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1203  APValue V;
1204  bool Result = Evaluate(V, Ctx);
1205  assert(Result && "Could not evaluate expression");
1206  assert(V.isInt() && "Expression did not evaluate to integer");
1207
1208  return V.getInt();
1209}
1210