ExprConstant.cpp revision 363ff23cfddb51abe4ee4212a6dd3c9b534fcc8b
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/CharUnits.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/AST/ASTDiagnostic.h"
20#include "clang/Basic/Builtins.h"
21#include "clang/Basic/TargetInfo.h"
22#include "llvm/ADT/SmallString.h"
23#include <cstring>
24
25using namespace clang;
26using llvm::APSInt;
27using llvm::APFloat;
28
29/// EvalInfo - This is a private struct used by the evaluator to capture
30/// information about a subexpression as it is folded.  It retains information
31/// about the AST context, but also maintains information about the folded
32/// expression.
33///
34/// If an expression could be evaluated, it is still possible it is not a C
35/// "integer constant expression" or constant expression.  If not, this struct
36/// captures information about how and why not.
37///
38/// One bit of information passed *into* the request for constant folding
39/// indicates whether the subexpression is "evaluated" or not according to C
40/// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
41/// evaluate the expression regardless of what the RHS is, but C only allows
42/// certain things in certain situations.
43struct EvalInfo {
44  ASTContext &Ctx;
45
46  /// EvalResult - Contains information about the evaluation.
47  Expr::EvalResult &EvalResult;
48
49  /// AnyLValue - Stack based LValue results are not discarded.
50  bool AnyLValue;
51
52  EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult,
53           bool anylvalue = false)
54    : Ctx(ctx), EvalResult(evalresult), AnyLValue(anylvalue) {}
55};
56
57
58static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
59static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
60static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
61static bool EvaluateIntegerOrLValue(const Expr *E, APValue  &Result,
62                                    EvalInfo &Info);
63static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
64static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
65
66//===----------------------------------------------------------------------===//
67// Misc utilities
68//===----------------------------------------------------------------------===//
69
70static bool EvalPointerValueAsBool(APValue& Value, bool& Result) {
71  // FIXME: Is this accurate for all kinds of bases?  If not, what would
72  // the check look like?
73  Result = Value.getLValueBase() || !Value.getLValueOffset().isZero();
74  return true;
75}
76
77static bool HandleConversionToBool(const Expr* E, bool& Result,
78                                   EvalInfo &Info) {
79  if (E->getType()->isIntegralType()) {
80    APSInt IntResult;
81    if (!EvaluateInteger(E, IntResult, Info))
82      return false;
83    Result = IntResult != 0;
84    return true;
85  } else if (E->getType()->isRealFloatingType()) {
86    APFloat FloatResult(0.0);
87    if (!EvaluateFloat(E, FloatResult, Info))
88      return false;
89    Result = !FloatResult.isZero();
90    return true;
91  } else if (E->getType()->hasPointerRepresentation()) {
92    APValue PointerResult;
93    if (!EvaluatePointer(E, PointerResult, Info))
94      return false;
95    return EvalPointerValueAsBool(PointerResult, Result);
96  } else if (E->getType()->isAnyComplexType()) {
97    APValue ComplexResult;
98    if (!EvaluateComplex(E, ComplexResult, Info))
99      return false;
100    if (ComplexResult.isComplexFloat()) {
101      Result = !ComplexResult.getComplexFloatReal().isZero() ||
102               !ComplexResult.getComplexFloatImag().isZero();
103    } else {
104      Result = ComplexResult.getComplexIntReal().getBoolValue() ||
105               ComplexResult.getComplexIntImag().getBoolValue();
106    }
107    return true;
108  }
109
110  return false;
111}
112
113static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
114                                   APFloat &Value, ASTContext &Ctx) {
115  unsigned DestWidth = Ctx.getIntWidth(DestType);
116  // Determine whether we are converting to unsigned or signed.
117  bool DestSigned = DestType->isSignedIntegerType();
118
119  // FIXME: Warning for overflow.
120  uint64_t Space[4];
121  bool ignored;
122  (void)Value.convertToInteger(Space, DestWidth, DestSigned,
123                               llvm::APFloat::rmTowardZero, &ignored);
124  return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
125}
126
127static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
128                                      APFloat &Value, ASTContext &Ctx) {
129  bool ignored;
130  APFloat Result = Value;
131  Result.convert(Ctx.getFloatTypeSemantics(DestType),
132                 APFloat::rmNearestTiesToEven, &ignored);
133  return Result;
134}
135
136static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
137                                 APSInt &Value, ASTContext &Ctx) {
138  unsigned DestWidth = Ctx.getIntWidth(DestType);
139  APSInt Result = Value;
140  // Figure out if this is a truncate, extend or noop cast.
141  // If the input is signed, do a sign extend, noop, or truncate.
142  Result.extOrTrunc(DestWidth);
143  Result.setIsUnsigned(DestType->isUnsignedIntegerType());
144  return Result;
145}
146
147static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
148                                    APSInt &Value, ASTContext &Ctx) {
149
150  APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
151  Result.convertFromAPInt(Value, Value.isSigned(),
152                          APFloat::rmNearestTiesToEven);
153  return Result;
154}
155
156namespace {
157class HasSideEffect
158  : public StmtVisitor<HasSideEffect, bool> {
159  EvalInfo &Info;
160public:
161
162  HasSideEffect(EvalInfo &info) : Info(info) {}
163
164  // Unhandled nodes conservatively default to having side effects.
165  bool VisitStmt(Stmt *S) {
166    return true;
167  }
168
169  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
170  bool VisitDeclRefExpr(DeclRefExpr *E) {
171    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
172      return true;
173    return false;
174  }
175  // We don't want to evaluate BlockExprs multiple times, as they generate
176  // a ton of code.
177  bool VisitBlockExpr(BlockExpr *E) { return true; }
178  bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
179  bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
180    { return Visit(E->getInitializer()); }
181  bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
182  bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
183  bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
184  bool VisitStringLiteral(StringLiteral *E) { return false; }
185  bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
186  bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
187  bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
188    { return Visit(E->getLHS()) || Visit(E->getRHS()); }
189  bool VisitChooseExpr(ChooseExpr *E)
190    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
191  bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
192  bool VisitBinAssign(BinaryOperator *E) { return true; }
193  bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
194  bool VisitBinaryOperator(BinaryOperator *E)
195  { return Visit(E->getLHS()) || Visit(E->getRHS()); }
196  bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
197  bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
198  bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
199  bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
200  bool VisitUnaryDeref(UnaryOperator *E) {
201    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
202      return true;
203    return Visit(E->getSubExpr());
204  }
205  bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
206
207  // Has side effects if any element does.
208  bool VisitInitListExpr(InitListExpr *E) {
209    for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
210      if (Visit(E->getInit(i))) return true;
211    return false;
212  }
213};
214
215} // end anonymous namespace
216
217//===----------------------------------------------------------------------===//
218// LValue Evaluation
219//===----------------------------------------------------------------------===//
220namespace {
221class LValueExprEvaluator
222  : public StmtVisitor<LValueExprEvaluator, APValue> {
223  EvalInfo &Info;
224public:
225
226  LValueExprEvaluator(EvalInfo &info) : Info(info) {}
227
228  APValue VisitStmt(Stmt *S) {
229    return APValue();
230  }
231
232  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
233  APValue VisitDeclRefExpr(DeclRefExpr *E);
234  APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E); }
235  APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
236  APValue VisitMemberExpr(MemberExpr *E);
237  APValue VisitStringLiteral(StringLiteral *E) { return APValue(E); }
238  APValue VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return APValue(E); }
239  APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
240  APValue VisitUnaryDeref(UnaryOperator *E);
241  APValue VisitUnaryExtension(const UnaryOperator *E)
242    { return Visit(E->getSubExpr()); }
243  APValue VisitChooseExpr(const ChooseExpr *E)
244    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
245
246  APValue VisitCastExpr(CastExpr *E) {
247    switch (E->getCastKind()) {
248    default:
249      return APValue();
250
251    case CastExpr::CK_NoOp:
252      return Visit(E->getSubExpr());
253    }
254  }
255  // FIXME: Missing: __real__, __imag__
256};
257} // end anonymous namespace
258
259static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
260  Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
261  return Result.isLValue();
262}
263
264APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
265  if (isa<FunctionDecl>(E->getDecl())) {
266    return APValue(E);
267  } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
268    if (!Info.AnyLValue && !VD->hasGlobalStorage())
269      return APValue();
270    if (!VD->getType()->isReferenceType())
271      return APValue(E);
272    // FIXME: Check whether VD might be overridden!
273    if (const Expr *Init = VD->getAnyInitializer())
274      return Visit(const_cast<Expr *>(Init));
275  }
276
277  return APValue();
278}
279
280APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
281  if (!Info.AnyLValue && !E->isFileScope())
282    return APValue();
283  return APValue(E);
284}
285
286APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
287  APValue result;
288  QualType Ty;
289  if (E->isArrow()) {
290    if (!EvaluatePointer(E->getBase(), result, Info))
291      return APValue();
292    Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
293  } else {
294    result = Visit(E->getBase());
295    if (result.isUninit())
296      return APValue();
297    Ty = E->getBase()->getType();
298  }
299
300  RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
301  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
302
303  FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
304  if (!FD) // FIXME: deal with other kinds of member expressions
305    return APValue();
306
307  if (FD->getType()->isReferenceType())
308    return APValue();
309
310  // FIXME: This is linear time.
311  unsigned i = 0;
312  for (RecordDecl::field_iterator Field = RD->field_begin(),
313                               FieldEnd = RD->field_end();
314       Field != FieldEnd; (void)++Field, ++i) {
315    if (*Field == FD)
316      break;
317  }
318
319  result.setLValue(result.getLValueBase(),
320                   result.getLValueOffset() +
321                       CharUnits::fromQuantity(RL.getFieldOffset(i) / 8));
322
323  return result;
324}
325
326APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
327  APValue Result;
328
329  if (!EvaluatePointer(E->getBase(), Result, Info))
330    return APValue();
331
332  APSInt Index;
333  if (!EvaluateInteger(E->getIdx(), Index, Info))
334    return APValue();
335
336  CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
337
338  CharUnits Offset = Index.getSExtValue() * ElementSize;
339  Result.setLValue(Result.getLValueBase(),
340                   Result.getLValueOffset() + Offset);
341  return Result;
342}
343
344APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
345  APValue Result;
346  if (!EvaluatePointer(E->getSubExpr(), Result, Info))
347    return APValue();
348  return Result;
349}
350
351//===----------------------------------------------------------------------===//
352// Pointer Evaluation
353//===----------------------------------------------------------------------===//
354
355namespace {
356class PointerExprEvaluator
357  : public StmtVisitor<PointerExprEvaluator, APValue> {
358  EvalInfo &Info;
359public:
360
361  PointerExprEvaluator(EvalInfo &info) : Info(info) {}
362
363  APValue VisitStmt(Stmt *S) {
364    return APValue();
365  }
366
367  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
368
369  APValue VisitBinaryOperator(const BinaryOperator *E);
370  APValue VisitCastExpr(CastExpr* E);
371  APValue VisitUnaryExtension(const UnaryOperator *E)
372      { return Visit(E->getSubExpr()); }
373  APValue VisitUnaryAddrOf(const UnaryOperator *E);
374  APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
375      { return APValue(E); }
376  APValue VisitAddrLabelExpr(AddrLabelExpr *E)
377      { return APValue(E); }
378  APValue VisitCallExpr(CallExpr *E);
379  APValue VisitBlockExpr(BlockExpr *E) {
380    if (!E->hasBlockDeclRefExprs())
381      return APValue(E);
382    return APValue();
383  }
384  APValue VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
385      { return APValue((Expr*)0); }
386  APValue VisitConditionalOperator(ConditionalOperator *E);
387  APValue VisitChooseExpr(ChooseExpr *E)
388      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
389  APValue VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
390      { return APValue((Expr*)0); }
391  // FIXME: Missing: @protocol, @selector
392};
393} // end anonymous namespace
394
395static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
396  if (!E->getType()->hasPointerRepresentation())
397    return false;
398  Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
399  return Result.isLValue();
400}
401
402APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
403  if (E->getOpcode() != BinaryOperator::Add &&
404      E->getOpcode() != BinaryOperator::Sub)
405    return APValue();
406
407  const Expr *PExp = E->getLHS();
408  const Expr *IExp = E->getRHS();
409  if (IExp->getType()->isPointerType())
410    std::swap(PExp, IExp);
411
412  APValue ResultLValue;
413  if (!EvaluatePointer(PExp, ResultLValue, Info))
414    return APValue();
415
416  llvm::APSInt AdditionalOffset;
417  if (!EvaluateInteger(IExp, AdditionalOffset, Info))
418    return APValue();
419
420  // Compute the new offset in the appropriate width.
421
422  QualType PointeeType =
423    PExp->getType()->getAs<PointerType>()->getPointeeType();
424  llvm::APSInt SizeOfPointee(AdditionalOffset);
425
426  // Explicitly handle GNU void* and function pointer arithmetic extensions.
427  if (PointeeType->isVoidType() || PointeeType->isFunctionType())
428    SizeOfPointee = 1;
429  else
430    SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType).getQuantity();
431
432  llvm::APSInt Offset(AdditionalOffset);
433  Offset = ResultLValue.getLValueOffset().getQuantity();
434  if (E->getOpcode() == BinaryOperator::Add)
435    Offset += AdditionalOffset * SizeOfPointee;
436  else
437    Offset -= AdditionalOffset * SizeOfPointee;
438
439  // Sign extend prior to converting back to a char unit.
440  if (Offset.getBitWidth() < 64)
441    Offset.extend(64);
442  return APValue(ResultLValue.getLValueBase(),
443                 CharUnits::fromQuantity(Offset.getLimitedValue()));
444}
445
446APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
447  APValue result;
448  if (EvaluateLValue(E->getSubExpr(), result, Info))
449    return result;
450  return APValue();
451}
452
453
454APValue PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
455  Expr* SubExpr = E->getSubExpr();
456
457  switch (E->getCastKind()) {
458  default:
459    break;
460
461  case CastExpr::CK_Unknown: {
462    // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
463
464    // Check for pointer->pointer cast
465    if (SubExpr->getType()->isPointerType() ||
466        SubExpr->getType()->isObjCObjectPointerType() ||
467        SubExpr->getType()->isNullPtrType() ||
468        SubExpr->getType()->isBlockPointerType())
469      return Visit(SubExpr);
470
471    if (SubExpr->getType()->isIntegralType()) {
472      APValue Result;
473      if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
474        break;
475
476      if (Result.isInt()) {
477        Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
478        return APValue(0,
479                       CharUnits::fromQuantity(Result.getInt().getZExtValue()));
480      }
481
482      // Cast is of an lvalue, no need to change value.
483      return Result;
484    }
485    break;
486  }
487
488  case CastExpr::CK_NoOp:
489  case CastExpr::CK_BitCast:
490  case CastExpr::CK_AnyPointerToObjCPointerCast:
491  case CastExpr::CK_AnyPointerToBlockPointerCast:
492    return Visit(SubExpr);
493
494  case CastExpr::CK_IntegralToPointer: {
495    APValue Result;
496    if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
497      break;
498
499    if (Result.isInt()) {
500      Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
501      return APValue(0,
502                     CharUnits::fromQuantity(Result.getInt().getZExtValue()));
503    }
504
505    // Cast is of an lvalue, no need to change value.
506    return Result;
507  }
508  case CastExpr::CK_ArrayToPointerDecay:
509  case CastExpr::CK_FunctionToPointerDecay: {
510    APValue Result;
511    if (EvaluateLValue(SubExpr, Result, Info))
512      return Result;
513    break;
514  }
515  }
516
517  return APValue();
518}
519
520APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
521  if (E->isBuiltinCall(Info.Ctx) ==
522        Builtin::BI__builtin___CFStringMakeConstantString ||
523      E->isBuiltinCall(Info.Ctx) ==
524        Builtin::BI__builtin___NSStringMakeConstantString)
525    return APValue(E);
526  return APValue();
527}
528
529APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
530  bool BoolResult;
531  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
532    return APValue();
533
534  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
535
536  APValue Result;
537  if (EvaluatePointer(EvalExpr, Result, Info))
538    return Result;
539  return APValue();
540}
541
542//===----------------------------------------------------------------------===//
543// Vector Evaluation
544//===----------------------------------------------------------------------===//
545
546namespace {
547  class VectorExprEvaluator
548  : public StmtVisitor<VectorExprEvaluator, APValue> {
549    EvalInfo &Info;
550    APValue GetZeroVector(QualType VecType);
551  public:
552
553    VectorExprEvaluator(EvalInfo &info) : Info(info) {}
554
555    APValue VisitStmt(Stmt *S) {
556      return APValue();
557    }
558
559    APValue VisitParenExpr(ParenExpr *E)
560        { return Visit(E->getSubExpr()); }
561    APValue VisitUnaryExtension(const UnaryOperator *E)
562      { return Visit(E->getSubExpr()); }
563    APValue VisitUnaryPlus(const UnaryOperator *E)
564      { return Visit(E->getSubExpr()); }
565    APValue VisitUnaryReal(const UnaryOperator *E)
566      { return Visit(E->getSubExpr()); }
567    APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
568      { return GetZeroVector(E->getType()); }
569    APValue VisitCastExpr(const CastExpr* E);
570    APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
571    APValue VisitInitListExpr(const InitListExpr *E);
572    APValue VisitConditionalOperator(const ConditionalOperator *E);
573    APValue VisitChooseExpr(const ChooseExpr *E)
574      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
575    APValue VisitUnaryImag(const UnaryOperator *E);
576    // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
577    //                 binary comparisons, binary and/or/xor,
578    //                 shufflevector, ExtVectorElementExpr
579    //        (Note that these require implementing conversions
580    //         between vector types.)
581  };
582} // end anonymous namespace
583
584static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
585  if (!E->getType()->isVectorType())
586    return false;
587  Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
588  return !Result.isUninit();
589}
590
591APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
592  const VectorType *VTy = E->getType()->getAs<VectorType>();
593  QualType EltTy = VTy->getElementType();
594  unsigned NElts = VTy->getNumElements();
595  unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
596
597  const Expr* SE = E->getSubExpr();
598  QualType SETy = SE->getType();
599  APValue Result = APValue();
600
601  // Check for vector->vector bitcast and scalar->vector splat.
602  if (SETy->isVectorType()) {
603    return this->Visit(const_cast<Expr*>(SE));
604  } else if (SETy->isIntegerType()) {
605    APSInt IntResult;
606    if (!EvaluateInteger(SE, IntResult, Info))
607      return APValue();
608    Result = APValue(IntResult);
609  } else if (SETy->isRealFloatingType()) {
610    APFloat F(0.0);
611    if (!EvaluateFloat(SE, F, Info))
612      return APValue();
613    Result = APValue(F);
614  } else
615    return APValue();
616
617  // For casts of a scalar to ExtVector, convert the scalar to the element type
618  // and splat it to all elements.
619  if (E->getType()->isExtVectorType()) {
620    if (EltTy->isIntegerType() && Result.isInt())
621      Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
622                                          Info.Ctx));
623    else if (EltTy->isIntegerType())
624      Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
625                                            Info.Ctx));
626    else if (EltTy->isRealFloatingType() && Result.isInt())
627      Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
628                                            Info.Ctx));
629    else if (EltTy->isRealFloatingType())
630      Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
631                                              Info.Ctx));
632    else
633      return APValue();
634
635    // Splat and create vector APValue.
636    llvm::SmallVector<APValue, 4> Elts(NElts, Result);
637    return APValue(&Elts[0], Elts.size());
638  }
639
640  // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
641  // to the vector. To construct the APValue vector initializer, bitcast the
642  // initializing value to an APInt, and shift out the bits pertaining to each
643  // element.
644  APSInt Init;
645  Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
646
647  llvm::SmallVector<APValue, 4> Elts;
648  for (unsigned i = 0; i != NElts; ++i) {
649    APSInt Tmp = Init;
650    Tmp.extOrTrunc(EltWidth);
651
652    if (EltTy->isIntegerType())
653      Elts.push_back(APValue(Tmp));
654    else if (EltTy->isRealFloatingType())
655      Elts.push_back(APValue(APFloat(Tmp)));
656    else
657      return APValue();
658
659    Init >>= EltWidth;
660  }
661  return APValue(&Elts[0], Elts.size());
662}
663
664APValue
665VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
666  return this->Visit(const_cast<Expr*>(E->getInitializer()));
667}
668
669APValue
670VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
671  const VectorType *VT = E->getType()->getAs<VectorType>();
672  unsigned NumInits = E->getNumInits();
673  unsigned NumElements = VT->getNumElements();
674
675  QualType EltTy = VT->getElementType();
676  llvm::SmallVector<APValue, 4> Elements;
677
678  for (unsigned i = 0; i < NumElements; i++) {
679    if (EltTy->isIntegerType()) {
680      llvm::APSInt sInt(32);
681      if (i < NumInits) {
682        if (!EvaluateInteger(E->getInit(i), sInt, Info))
683          return APValue();
684      } else {
685        sInt = Info.Ctx.MakeIntValue(0, EltTy);
686      }
687      Elements.push_back(APValue(sInt));
688    } else {
689      llvm::APFloat f(0.0);
690      if (i < NumInits) {
691        if (!EvaluateFloat(E->getInit(i), f, Info))
692          return APValue();
693      } else {
694        f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
695      }
696      Elements.push_back(APValue(f));
697    }
698  }
699  return APValue(&Elements[0], Elements.size());
700}
701
702APValue
703VectorExprEvaluator::GetZeroVector(QualType T) {
704  const VectorType *VT = T->getAs<VectorType>();
705  QualType EltTy = VT->getElementType();
706  APValue ZeroElement;
707  if (EltTy->isIntegerType())
708    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
709  else
710    ZeroElement =
711        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
712
713  llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
714  return APValue(&Elements[0], Elements.size());
715}
716
717APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
718  bool BoolResult;
719  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
720    return APValue();
721
722  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
723
724  APValue Result;
725  if (EvaluateVector(EvalExpr, Result, Info))
726    return Result;
727  return APValue();
728}
729
730APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
731  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
732    Info.EvalResult.HasSideEffects = true;
733  return GetZeroVector(E->getType());
734}
735
736//===----------------------------------------------------------------------===//
737// Integer Evaluation
738//===----------------------------------------------------------------------===//
739
740namespace {
741class IntExprEvaluator
742  : public StmtVisitor<IntExprEvaluator, bool> {
743  EvalInfo &Info;
744  APValue &Result;
745public:
746  IntExprEvaluator(EvalInfo &info, APValue &result)
747    : Info(info), Result(result) {}
748
749  bool Success(const llvm::APSInt &SI, const Expr *E) {
750    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
751    assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
752           "Invalid evaluation result.");
753    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
754           "Invalid evaluation result.");
755    Result = APValue(SI);
756    return true;
757  }
758
759  bool Success(const llvm::APInt &I, const Expr *E) {
760    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
761    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
762           "Invalid evaluation result.");
763    Result = APValue(APSInt(I));
764    Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
765    return true;
766  }
767
768  bool Success(uint64_t Value, const Expr *E) {
769    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
770    Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
771    return true;
772  }
773
774  bool Error(SourceLocation L, diag::kind D, const Expr *E) {
775    // Take the first error.
776    if (Info.EvalResult.Diag == 0) {
777      Info.EvalResult.DiagLoc = L;
778      Info.EvalResult.Diag = D;
779      Info.EvalResult.DiagExpr = E;
780    }
781    return false;
782  }
783
784  //===--------------------------------------------------------------------===//
785  //                            Visitor Methods
786  //===--------------------------------------------------------------------===//
787
788  bool VisitStmt(Stmt *) {
789    assert(0 && "This should be called on integers, stmts are not integers");
790    return false;
791  }
792
793  bool VisitExpr(Expr *E) {
794    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
795  }
796
797  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
798
799  bool VisitIntegerLiteral(const IntegerLiteral *E) {
800    return Success(E->getValue(), E);
801  }
802  bool VisitCharacterLiteral(const CharacterLiteral *E) {
803    return Success(E->getValue(), E);
804  }
805  bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
806    // Per gcc docs "this built-in function ignores top level
807    // qualifiers".  We need to use the canonical version to properly
808    // be able to strip CRV qualifiers from the type.
809    QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
810    QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
811    return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
812                                               T1.getUnqualifiedType()),
813                   E);
814  }
815
816  bool CheckReferencedDecl(const Expr *E, const Decl *D);
817  bool VisitDeclRefExpr(const DeclRefExpr *E) {
818    return CheckReferencedDecl(E, E->getDecl());
819  }
820  bool VisitMemberExpr(const MemberExpr *E) {
821    if (CheckReferencedDecl(E, E->getMemberDecl())) {
822      // Conservatively assume a MemberExpr will have side-effects
823      Info.EvalResult.HasSideEffects = true;
824      return true;
825    }
826    return false;
827  }
828
829  bool VisitCallExpr(CallExpr *E);
830  bool VisitBinaryOperator(const BinaryOperator *E);
831  bool VisitUnaryOperator(const UnaryOperator *E);
832  bool VisitConditionalOperator(const ConditionalOperator *E);
833
834  bool VisitCastExpr(CastExpr* E);
835  bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
836
837  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
838    return Success(E->getValue(), E);
839  }
840
841  bool VisitGNUNullExpr(const GNUNullExpr *E) {
842    return Success(0, E);
843  }
844
845  bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
846    return Success(0, E);
847  }
848
849  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
850    return Success(0, E);
851  }
852
853  bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
854    return Success(E->EvaluateTrait(Info.Ctx), E);
855  }
856
857  bool VisitChooseExpr(const ChooseExpr *E) {
858    return Visit(E->getChosenSubExpr(Info.Ctx));
859  }
860
861  bool VisitUnaryReal(const UnaryOperator *E);
862  bool VisitUnaryImag(const UnaryOperator *E);
863
864private:
865  CharUnits GetAlignOfExpr(const Expr *E);
866  CharUnits GetAlignOfType(QualType T);
867  // FIXME: Missing: array subscript of vector, member of vector
868};
869} // end anonymous namespace
870
871static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
872  if (!E->getType()->isIntegralType())
873    return false;
874
875  return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
876}
877
878static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
879  APValue Val;
880  if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
881    return false;
882  Result = Val.getInt();
883  return true;
884}
885
886bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
887  // Enums are integer constant exprs.
888  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
889    return Success(ECD->getInitVal(), E);
890
891  // In C++, const, non-volatile integers initialized with ICEs are ICEs.
892  // In C, they can also be folded, although they are not ICEs.
893  if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
894                                                        == Qualifiers::Const) {
895
896    if (isa<ParmVarDecl>(D))
897      return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
898
899    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
900      if (const Expr *Init = VD->getAnyInitializer()) {
901        if (APValue *V = VD->getEvaluatedValue()) {
902          if (V->isInt())
903            return Success(V->getInt(), E);
904          return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
905        }
906
907        if (VD->isEvaluatingValue())
908          return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
909
910        VD->setEvaluatingValue();
911
912        if (Visit(const_cast<Expr*>(Init))) {
913          // Cache the evaluated value in the variable declaration.
914          VD->setEvaluatedValue(Result);
915          return true;
916        }
917
918        VD->setEvaluatedValue(APValue());
919        return false;
920      }
921    }
922  }
923
924  // Otherwise, random variable references are not constants.
925  return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
926}
927
928/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
929/// as GCC.
930static int EvaluateBuiltinClassifyType(const CallExpr *E) {
931  // The following enum mimics the values returned by GCC.
932  // FIXME: Does GCC differ between lvalue and rvalue references here?
933  enum gcc_type_class {
934    no_type_class = -1,
935    void_type_class, integer_type_class, char_type_class,
936    enumeral_type_class, boolean_type_class,
937    pointer_type_class, reference_type_class, offset_type_class,
938    real_type_class, complex_type_class,
939    function_type_class, method_type_class,
940    record_type_class, union_type_class,
941    array_type_class, string_type_class,
942    lang_type_class
943  };
944
945  // If no argument was supplied, default to "no_type_class". This isn't
946  // ideal, however it is what gcc does.
947  if (E->getNumArgs() == 0)
948    return no_type_class;
949
950  QualType ArgTy = E->getArg(0)->getType();
951  if (ArgTy->isVoidType())
952    return void_type_class;
953  else if (ArgTy->isEnumeralType())
954    return enumeral_type_class;
955  else if (ArgTy->isBooleanType())
956    return boolean_type_class;
957  else if (ArgTy->isCharType())
958    return string_type_class; // gcc doesn't appear to use char_type_class
959  else if (ArgTy->isIntegerType())
960    return integer_type_class;
961  else if (ArgTy->isPointerType())
962    return pointer_type_class;
963  else if (ArgTy->isReferenceType())
964    return reference_type_class;
965  else if (ArgTy->isRealType())
966    return real_type_class;
967  else if (ArgTy->isComplexType())
968    return complex_type_class;
969  else if (ArgTy->isFunctionType())
970    return function_type_class;
971  else if (ArgTy->isStructureType())
972    return record_type_class;
973  else if (ArgTy->isUnionType())
974    return union_type_class;
975  else if (ArgTy->isArrayType())
976    return array_type_class;
977  else if (ArgTy->isUnionType())
978    return union_type_class;
979  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
980    assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
981  return -1;
982}
983
984bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
985  switch (E->isBuiltinCall(Info.Ctx)) {
986  default:
987    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
988
989  case Builtin::BI__builtin_object_size: {
990    const Expr *Arg = E->getArg(0)->IgnoreParens();
991    Expr::EvalResult Base;
992
993    // TODO: Perhaps we should let LLVM lower this?
994    if (Arg->EvaluateAsAny(Base, Info.Ctx)
995        && Base.Val.getKind() == APValue::LValue
996        && !Base.HasSideEffects)
997      if (const Expr *LVBase = Base.Val.getLValueBase())
998        if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVBase)) {
999          if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1000            if (!VD->getType()->isIncompleteType()
1001                && VD->getType()->isObjectType()
1002                && !VD->getType()->isVariablyModifiedType()
1003                && !VD->getType()->isDependentType()) {
1004              CharUnits Size = Info.Ctx.getTypeSizeInChars(VD->getType());
1005              CharUnits Offset = Base.Val.getLValueOffset();
1006              if (!Offset.isNegative() && Offset <= Size)
1007                Size -= Offset;
1008              else
1009                Size = CharUnits::Zero();
1010              return Success(Size.getQuantity(), E);
1011            }
1012          }
1013        }
1014
1015    // If evaluating the argument has side-effects we can't determine
1016    // the size of the object and lower it to unknown now.
1017    if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
1018      if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
1019        return Success(-1ULL, E);
1020      return Success(0, E);
1021    }
1022
1023    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1024  }
1025
1026  case Builtin::BI__builtin_classify_type:
1027    return Success(EvaluateBuiltinClassifyType(E), E);
1028
1029  case Builtin::BI__builtin_constant_p:
1030    // __builtin_constant_p always has one operand: it returns true if that
1031    // operand can be folded, false otherwise.
1032    return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
1033
1034  case Builtin::BI__builtin_eh_return_data_regno: {
1035    int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1036    Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1037    return Success(Operand, E);
1038  }
1039
1040  case Builtin::BI__builtin_expect:
1041    return Visit(E->getArg(0));
1042  }
1043}
1044
1045bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1046  if (E->getOpcode() == BinaryOperator::Comma) {
1047    if (!Visit(E->getRHS()))
1048      return false;
1049
1050    // If we can't evaluate the LHS, it might have side effects;
1051    // conservatively mark it.
1052    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1053      Info.EvalResult.HasSideEffects = true;
1054
1055    return true;
1056  }
1057
1058  if (E->isLogicalOp()) {
1059    // These need to be handled specially because the operands aren't
1060    // necessarily integral
1061    bool lhsResult, rhsResult;
1062
1063    if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
1064      // We were able to evaluate the LHS, see if we can get away with not
1065      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1066      if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
1067        return Success(lhsResult, E);
1068
1069      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1070        if (E->getOpcode() == BinaryOperator::LOr)
1071          return Success(lhsResult || rhsResult, E);
1072        else
1073          return Success(lhsResult && rhsResult, E);
1074      }
1075    } else {
1076      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1077        // We can't evaluate the LHS; however, sometimes the result
1078        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1079        if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
1080            !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
1081          // Since we weren't able to evaluate the left hand side, it
1082          // must have had side effects.
1083          Info.EvalResult.HasSideEffects = true;
1084
1085          return Success(rhsResult, E);
1086        }
1087      }
1088    }
1089
1090    return false;
1091  }
1092
1093  QualType LHSTy = E->getLHS()->getType();
1094  QualType RHSTy = E->getRHS()->getType();
1095
1096  if (LHSTy->isAnyComplexType()) {
1097    assert(RHSTy->isAnyComplexType() && "Invalid comparison");
1098    APValue LHS, RHS;
1099
1100    if (!EvaluateComplex(E->getLHS(), LHS, Info))
1101      return false;
1102
1103    if (!EvaluateComplex(E->getRHS(), RHS, Info))
1104      return false;
1105
1106    if (LHS.isComplexFloat()) {
1107      APFloat::cmpResult CR_r =
1108        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
1109      APFloat::cmpResult CR_i =
1110        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1111
1112      if (E->getOpcode() == BinaryOperator::EQ)
1113        return Success((CR_r == APFloat::cmpEqual &&
1114                        CR_i == APFloat::cmpEqual), E);
1115      else {
1116        assert(E->getOpcode() == BinaryOperator::NE &&
1117               "Invalid complex comparison.");
1118        return Success(((CR_r == APFloat::cmpGreaterThan ||
1119                         CR_r == APFloat::cmpLessThan) &&
1120                        (CR_i == APFloat::cmpGreaterThan ||
1121                         CR_i == APFloat::cmpLessThan)), E);
1122      }
1123    } else {
1124      if (E->getOpcode() == BinaryOperator::EQ)
1125        return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1126                        LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1127      else {
1128        assert(E->getOpcode() == BinaryOperator::NE &&
1129               "Invalid compex comparison.");
1130        return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1131                        LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1132      }
1133    }
1134  }
1135
1136  if (LHSTy->isRealFloatingType() &&
1137      RHSTy->isRealFloatingType()) {
1138    APFloat RHS(0.0), LHS(0.0);
1139
1140    if (!EvaluateFloat(E->getRHS(), RHS, Info))
1141      return false;
1142
1143    if (!EvaluateFloat(E->getLHS(), LHS, Info))
1144      return false;
1145
1146    APFloat::cmpResult CR = LHS.compare(RHS);
1147
1148    switch (E->getOpcode()) {
1149    default:
1150      assert(0 && "Invalid binary operator!");
1151    case BinaryOperator::LT:
1152      return Success(CR == APFloat::cmpLessThan, E);
1153    case BinaryOperator::GT:
1154      return Success(CR == APFloat::cmpGreaterThan, E);
1155    case BinaryOperator::LE:
1156      return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
1157    case BinaryOperator::GE:
1158      return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
1159                     E);
1160    case BinaryOperator::EQ:
1161      return Success(CR == APFloat::cmpEqual, E);
1162    case BinaryOperator::NE:
1163      return Success(CR == APFloat::cmpGreaterThan
1164                     || CR == APFloat::cmpLessThan, E);
1165    }
1166  }
1167
1168  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1169    if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
1170      APValue LHSValue;
1171      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1172        return false;
1173
1174      APValue RHSValue;
1175      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1176        return false;
1177
1178      // Reject any bases from the normal codepath; we special-case comparisons
1179      // to null.
1180      if (LHSValue.getLValueBase()) {
1181        if (!E->isEqualityOp())
1182          return false;
1183        if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
1184          return false;
1185        bool bres;
1186        if (!EvalPointerValueAsBool(LHSValue, bres))
1187          return false;
1188        return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1189      } else if (RHSValue.getLValueBase()) {
1190        if (!E->isEqualityOp())
1191          return false;
1192        if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
1193          return false;
1194        bool bres;
1195        if (!EvalPointerValueAsBool(RHSValue, bres))
1196          return false;
1197        return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1198      }
1199
1200      if (E->getOpcode() == BinaryOperator::Sub) {
1201        const QualType Type = E->getLHS()->getType();
1202        const QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
1203
1204        CharUnits ElementSize = CharUnits::One();
1205        if (!ElementType->isVoidType() && !ElementType->isFunctionType())
1206          ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
1207
1208        CharUnits Diff = LHSValue.getLValueOffset() -
1209                             RHSValue.getLValueOffset();
1210        return Success(Diff / ElementSize, E);
1211      }
1212      bool Result;
1213      if (E->getOpcode() == BinaryOperator::EQ) {
1214        Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
1215      } else {
1216        Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1217      }
1218      return Success(Result, E);
1219    }
1220  }
1221  if (!LHSTy->isIntegralType() ||
1222      !RHSTy->isIntegralType()) {
1223    // We can't continue from here for non-integral types, and they
1224    // could potentially confuse the following operations.
1225    return false;
1226  }
1227
1228  // The LHS of a constant expr is always evaluated and needed.
1229  if (!Visit(E->getLHS()))
1230    return false; // error in subexpression.
1231
1232  APValue RHSVal;
1233  if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
1234    return false;
1235
1236  // Handle cases like (unsigned long)&a + 4.
1237  if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1238    CharUnits Offset = Result.getLValueOffset();
1239    CharUnits AdditionalOffset = CharUnits::fromQuantity(
1240                                     RHSVal.getInt().getZExtValue());
1241    if (E->getOpcode() == BinaryOperator::Add)
1242      Offset += AdditionalOffset;
1243    else
1244      Offset -= AdditionalOffset;
1245    Result = APValue(Result.getLValueBase(), Offset);
1246    return true;
1247  }
1248
1249  // Handle cases like 4 + (unsigned long)&a
1250  if (E->getOpcode() == BinaryOperator::Add &&
1251        RHSVal.isLValue() && Result.isInt()) {
1252    CharUnits Offset = RHSVal.getLValueOffset();
1253    Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1254    Result = APValue(RHSVal.getLValueBase(), Offset);
1255    return true;
1256  }
1257
1258  // All the following cases expect both operands to be an integer
1259  if (!Result.isInt() || !RHSVal.isInt())
1260    return false;
1261
1262  APSInt& RHS = RHSVal.getInt();
1263
1264  switch (E->getOpcode()) {
1265  default:
1266    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1267  case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1268  case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1269  case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1270  case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1271  case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1272  case BinaryOperator::Or:  return Success(Result.getInt() | RHS, E);
1273  case BinaryOperator::Div:
1274    if (RHS == 0)
1275      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1276    return Success(Result.getInt() / RHS, E);
1277  case BinaryOperator::Rem:
1278    if (RHS == 0)
1279      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1280    return Success(Result.getInt() % RHS, E);
1281  case BinaryOperator::Shl: {
1282    // FIXME: Warn about out of range shift amounts!
1283    unsigned SA =
1284      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1285    return Success(Result.getInt() << SA, E);
1286  }
1287  case BinaryOperator::Shr: {
1288    unsigned SA =
1289      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1290    return Success(Result.getInt() >> SA, E);
1291  }
1292
1293  case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1294  case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1295  case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1296  case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1297  case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1298  case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
1299  }
1300}
1301
1302bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
1303  bool Cond;
1304  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1305    return false;
1306
1307  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1308}
1309
1310CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
1311  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1312  //   the result is the size of the referenced type."
1313  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1314  //   result shall be the alignment of the referenced type."
1315  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1316    T = Ref->getPointeeType();
1317
1318  // Get information about the alignment.
1319  unsigned CharSize = Info.Ctx.Target.getCharWidth();
1320
1321  // __alignof is defined to return the preferred alignment.
1322  return CharUnits::fromQuantity(
1323      Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
1324}
1325
1326CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
1327  E = E->IgnoreParens();
1328
1329  // alignof decl is always accepted, even if it doesn't make sense: we default
1330  // to 1 in those cases.
1331  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1332    return Info.Ctx.getDeclAlign(DRE->getDecl(),
1333                                 /*RefAsPointee*/true);
1334
1335  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
1336    return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1337                                 /*RefAsPointee*/true);
1338
1339  return GetAlignOfType(E->getType());
1340}
1341
1342
1343/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1344/// expression's type.
1345bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1346  // Handle alignof separately.
1347  if (!E->isSizeOf()) {
1348    if (E->isArgumentType())
1349      return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
1350    else
1351      return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
1352  }
1353
1354  QualType SrcTy = E->getTypeOfArgument();
1355  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1356  //   the result is the size of the referenced type."
1357  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1358  //   result shall be the alignment of the referenced type."
1359  if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1360    SrcTy = Ref->getPointeeType();
1361
1362  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1363  // extension.
1364  if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1365    return Success(1, E);
1366
1367  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1368  if (!SrcTy->isConstantSizeType())
1369    return false;
1370
1371  // Get information about the size.
1372  return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
1373}
1374
1375bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1376  // Special case unary operators that do not need their subexpression
1377  // evaluated.  offsetof/sizeof/alignof are all special.
1378  if (E->isOffsetOfOp()) {
1379    // The AST for offsetof is defined in such a way that we can just
1380    // directly Evaluate it as an l-value.
1381    APValue LV;
1382    if (!EvaluateLValue(E->getSubExpr(), LV, Info))
1383      return false;
1384    if (LV.getLValueBase())
1385      return false;
1386    return Success(LV.getLValueOffset().getQuantity(), E);
1387  }
1388
1389  if (E->getOpcode() == UnaryOperator::LNot) {
1390    // LNot's operand isn't necessarily an integer, so we handle it specially.
1391    bool bres;
1392    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1393      return false;
1394    return Success(!bres, E);
1395  }
1396
1397  // Only handle integral operations...
1398  if (!E->getSubExpr()->getType()->isIntegralType())
1399    return false;
1400
1401  // Get the operand value into 'Result'.
1402  if (!Visit(E->getSubExpr()))
1403    return false;
1404
1405  switch (E->getOpcode()) {
1406  default:
1407    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1408    // See C99 6.6p3.
1409    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1410  case UnaryOperator::Extension:
1411    // FIXME: Should extension allow i-c-e extension expressions in its scope?
1412    // If so, we could clear the diagnostic ID.
1413    return true;
1414  case UnaryOperator::Plus:
1415    // The result is always just the subexpr.
1416    return true;
1417  case UnaryOperator::Minus:
1418    if (!Result.isInt()) return false;
1419    return Success(-Result.getInt(), E);
1420  case UnaryOperator::Not:
1421    if (!Result.isInt()) return false;
1422    return Success(~Result.getInt(), E);
1423  }
1424}
1425
1426/// HandleCast - This is used to evaluate implicit or explicit casts where the
1427/// result type is integer.
1428bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
1429  Expr *SubExpr = E->getSubExpr();
1430  QualType DestType = E->getType();
1431  QualType SrcType = SubExpr->getType();
1432
1433  if (DestType->isBooleanType()) {
1434    bool BoolResult;
1435    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1436      return false;
1437    return Success(BoolResult, E);
1438  }
1439
1440  // Handle simple integer->integer casts.
1441  if (SrcType->isIntegralType()) {
1442    if (!Visit(SubExpr))
1443      return false;
1444
1445    if (!Result.isInt()) {
1446      // Only allow casts of lvalues if they are lossless.
1447      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1448    }
1449
1450    return Success(HandleIntToIntCast(DestType, SrcType,
1451                                      Result.getInt(), Info.Ctx), E);
1452  }
1453
1454  // FIXME: Clean this up!
1455  if (SrcType->isPointerType()) {
1456    APValue LV;
1457    if (!EvaluatePointer(SubExpr, LV, Info))
1458      return false;
1459
1460    if (LV.getLValueBase()) {
1461      // Only allow based lvalue casts if they are lossless.
1462      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1463        return false;
1464
1465      Result = LV;
1466      return true;
1467    }
1468
1469    APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1470                                         SrcType);
1471    return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
1472  }
1473
1474  if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1475    // This handles double-conversion cases, where there's both
1476    // an l-value promotion and an implicit conversion to int.
1477    APValue LV;
1478    if (!EvaluateLValue(SubExpr, LV, Info))
1479      return false;
1480
1481    if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1482      return false;
1483
1484    Result = LV;
1485    return true;
1486  }
1487
1488  if (SrcType->isAnyComplexType()) {
1489    APValue C;
1490    if (!EvaluateComplex(SubExpr, C, Info))
1491      return false;
1492    if (C.isComplexFloat())
1493      return Success(HandleFloatToIntCast(DestType, SrcType,
1494                                          C.getComplexFloatReal(), Info.Ctx),
1495                     E);
1496    else
1497      return Success(HandleIntToIntCast(DestType, SrcType,
1498                                        C.getComplexIntReal(), Info.Ctx), E);
1499  }
1500  // FIXME: Handle vectors
1501
1502  if (!SrcType->isRealFloatingType())
1503    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1504
1505  APFloat F(0.0);
1506  if (!EvaluateFloat(SubExpr, F, Info))
1507    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1508
1509  return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1510}
1511
1512bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1513  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1514    APValue LV;
1515    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1516      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1517    return Success(LV.getComplexIntReal(), E);
1518  }
1519
1520  return Visit(E->getSubExpr());
1521}
1522
1523bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1524  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1525    APValue LV;
1526    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1527      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1528    return Success(LV.getComplexIntImag(), E);
1529  }
1530
1531  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1532    Info.EvalResult.HasSideEffects = true;
1533  return Success(0, E);
1534}
1535
1536//===----------------------------------------------------------------------===//
1537// Float Evaluation
1538//===----------------------------------------------------------------------===//
1539
1540namespace {
1541class FloatExprEvaluator
1542  : public StmtVisitor<FloatExprEvaluator, bool> {
1543  EvalInfo &Info;
1544  APFloat &Result;
1545public:
1546  FloatExprEvaluator(EvalInfo &info, APFloat &result)
1547    : Info(info), Result(result) {}
1548
1549  bool VisitStmt(Stmt *S) {
1550    return false;
1551  }
1552
1553  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1554  bool VisitCallExpr(const CallExpr *E);
1555
1556  bool VisitUnaryOperator(const UnaryOperator *E);
1557  bool VisitBinaryOperator(const BinaryOperator *E);
1558  bool VisitFloatingLiteral(const FloatingLiteral *E);
1559  bool VisitCastExpr(CastExpr *E);
1560  bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
1561  bool VisitConditionalOperator(ConditionalOperator *E);
1562
1563  bool VisitChooseExpr(const ChooseExpr *E)
1564    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1565  bool VisitUnaryExtension(const UnaryOperator *E)
1566    { return Visit(E->getSubExpr()); }
1567
1568  // FIXME: Missing: __real__/__imag__, array subscript of vector,
1569  //                 member of vector, ImplicitValueInitExpr
1570};
1571} // end anonymous namespace
1572
1573static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1574  return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1575}
1576
1577static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1578                                  QualType ResultTy,
1579                                  const Expr *Arg,
1580                                  bool SNaN,
1581                                  llvm::APFloat &Result) {
1582  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1583  if (!S) return false;
1584
1585  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1586
1587  llvm::APInt fill;
1588
1589  // Treat empty strings as if they were zero.
1590  if (S->getString().empty())
1591    fill = llvm::APInt(32, 0);
1592  else if (S->getString().getAsInteger(0, fill))
1593    return false;
1594
1595  if (SNaN)
1596    Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1597  else
1598    Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1599  return true;
1600}
1601
1602bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1603  switch (E->isBuiltinCall(Info.Ctx)) {
1604  default: return false;
1605  case Builtin::BI__builtin_huge_val:
1606  case Builtin::BI__builtin_huge_valf:
1607  case Builtin::BI__builtin_huge_vall:
1608  case Builtin::BI__builtin_inf:
1609  case Builtin::BI__builtin_inff:
1610  case Builtin::BI__builtin_infl: {
1611    const llvm::fltSemantics &Sem =
1612      Info.Ctx.getFloatTypeSemantics(E->getType());
1613    Result = llvm::APFloat::getInf(Sem);
1614    return true;
1615  }
1616
1617  case Builtin::BI__builtin_nans:
1618  case Builtin::BI__builtin_nansf:
1619  case Builtin::BI__builtin_nansl:
1620    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1621                                 true, Result);
1622
1623  case Builtin::BI__builtin_nan:
1624  case Builtin::BI__builtin_nanf:
1625  case Builtin::BI__builtin_nanl:
1626    // If this is __builtin_nan() turn this into a nan, otherwise we
1627    // can't constant fold it.
1628    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1629                                 false, Result);
1630
1631  case Builtin::BI__builtin_fabs:
1632  case Builtin::BI__builtin_fabsf:
1633  case Builtin::BI__builtin_fabsl:
1634    if (!EvaluateFloat(E->getArg(0), Result, Info))
1635      return false;
1636
1637    if (Result.isNegative())
1638      Result.changeSign();
1639    return true;
1640
1641  case Builtin::BI__builtin_copysign:
1642  case Builtin::BI__builtin_copysignf:
1643  case Builtin::BI__builtin_copysignl: {
1644    APFloat RHS(0.);
1645    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1646        !EvaluateFloat(E->getArg(1), RHS, Info))
1647      return false;
1648    Result.copySign(RHS);
1649    return true;
1650  }
1651  }
1652}
1653
1654bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1655  if (E->getOpcode() == UnaryOperator::Deref)
1656    return false;
1657
1658  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1659    return false;
1660
1661  switch (E->getOpcode()) {
1662  default: return false;
1663  case UnaryOperator::Plus:
1664    return true;
1665  case UnaryOperator::Minus:
1666    Result.changeSign();
1667    return true;
1668  }
1669}
1670
1671bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1672  if (E->getOpcode() == BinaryOperator::Comma) {
1673    if (!EvaluateFloat(E->getRHS(), Result, Info))
1674      return false;
1675
1676    // If we can't evaluate the LHS, it might have side effects;
1677    // conservatively mark it.
1678    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1679      Info.EvalResult.HasSideEffects = true;
1680
1681    return true;
1682  }
1683
1684  // FIXME: Diagnostics?  I really don't understand how the warnings
1685  // and errors are supposed to work.
1686  APFloat RHS(0.0);
1687  if (!EvaluateFloat(E->getLHS(), Result, Info))
1688    return false;
1689  if (!EvaluateFloat(E->getRHS(), RHS, Info))
1690    return false;
1691
1692  switch (E->getOpcode()) {
1693  default: return false;
1694  case BinaryOperator::Mul:
1695    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1696    return true;
1697  case BinaryOperator::Add:
1698    Result.add(RHS, APFloat::rmNearestTiesToEven);
1699    return true;
1700  case BinaryOperator::Sub:
1701    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1702    return true;
1703  case BinaryOperator::Div:
1704    Result.divide(RHS, APFloat::rmNearestTiesToEven);
1705    return true;
1706  }
1707}
1708
1709bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1710  Result = E->getValue();
1711  return true;
1712}
1713
1714bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1715  Expr* SubExpr = E->getSubExpr();
1716
1717  if (SubExpr->getType()->isIntegralType()) {
1718    APSInt IntResult;
1719    if (!EvaluateInteger(SubExpr, IntResult, Info))
1720      return false;
1721    Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1722                                  IntResult, Info.Ctx);
1723    return true;
1724  }
1725  if (SubExpr->getType()->isRealFloatingType()) {
1726    if (!Visit(SubExpr))
1727      return false;
1728    Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1729                                    Result, Info.Ctx);
1730    return true;
1731  }
1732  // FIXME: Handle complex types
1733
1734  return false;
1735}
1736
1737bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1738  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1739  return true;
1740}
1741
1742bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1743  bool Cond;
1744  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1745    return false;
1746
1747  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1748}
1749
1750//===----------------------------------------------------------------------===//
1751// Complex Evaluation (for float and integer)
1752//===----------------------------------------------------------------------===//
1753
1754namespace {
1755class ComplexExprEvaluator
1756  : public StmtVisitor<ComplexExprEvaluator, APValue> {
1757  EvalInfo &Info;
1758
1759public:
1760  ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
1761
1762  //===--------------------------------------------------------------------===//
1763  //                            Visitor Methods
1764  //===--------------------------------------------------------------------===//
1765
1766  APValue VisitStmt(Stmt *S) {
1767    return APValue();
1768  }
1769
1770  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1771
1772  APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1773    Expr* SubExpr = E->getSubExpr();
1774
1775    if (SubExpr->getType()->isRealFloatingType()) {
1776      APFloat Result(0.0);
1777
1778      if (!EvaluateFloat(SubExpr, Result, Info))
1779        return APValue();
1780
1781      return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
1782                     Result);
1783    } else {
1784      assert(SubExpr->getType()->isIntegerType() &&
1785             "Unexpected imaginary literal.");
1786
1787      llvm::APSInt Result;
1788      if (!EvaluateInteger(SubExpr, Result, Info))
1789        return APValue();
1790
1791      llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1792      Zero = 0;
1793      return APValue(Zero, Result);
1794    }
1795  }
1796
1797  APValue VisitCastExpr(CastExpr *E) {
1798    Expr* SubExpr = E->getSubExpr();
1799    QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
1800    QualType SubType = SubExpr->getType();
1801
1802    if (SubType->isRealFloatingType()) {
1803      APFloat Result(0.0);
1804
1805      if (!EvaluateFloat(SubExpr, Result, Info))
1806        return APValue();
1807
1808      if (EltType->isRealFloatingType()) {
1809        Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
1810        return APValue(Result,
1811                       APFloat(Result.getSemantics(), APFloat::fcZero, false));
1812      } else {
1813        llvm::APSInt IResult;
1814        IResult = HandleFloatToIntCast(EltType, SubType, Result, Info.Ctx);
1815        llvm::APSInt Zero(IResult.getBitWidth(), !IResult.isSigned());
1816        Zero = 0;
1817        return APValue(IResult, Zero);
1818      }
1819    } else if (SubType->isIntegerType()) {
1820      APSInt Result;
1821
1822      if (!EvaluateInteger(SubExpr, Result, Info))
1823        return APValue();
1824
1825      if (EltType->isRealFloatingType()) {
1826        APFloat FResult =
1827            HandleIntToFloatCast(EltType, SubType, Result, Info.Ctx);
1828        return APValue(FResult,
1829                       APFloat(FResult.getSemantics(), APFloat::fcZero, false));
1830      } else {
1831        Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
1832        llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1833        Zero = 0;
1834        return APValue(Result, Zero);
1835      }
1836    } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
1837      APValue Src;
1838
1839      if (!EvaluateComplex(SubExpr, Src, Info))
1840        return APValue();
1841
1842      QualType SrcType = CT->getElementType();
1843
1844      if (Src.isComplexFloat()) {
1845        if (EltType->isRealFloatingType()) {
1846          return APValue(HandleFloatToFloatCast(EltType, SrcType,
1847                                                Src.getComplexFloatReal(),
1848                                                Info.Ctx),
1849                         HandleFloatToFloatCast(EltType, SrcType,
1850                                                Src.getComplexFloatImag(),
1851                                                Info.Ctx));
1852        } else {
1853          return APValue(HandleFloatToIntCast(EltType, SrcType,
1854                                              Src.getComplexFloatReal(),
1855                                              Info.Ctx),
1856                         HandleFloatToIntCast(EltType, SrcType,
1857                                              Src.getComplexFloatImag(),
1858                                              Info.Ctx));
1859        }
1860      } else {
1861        assert(Src.isComplexInt() && "Invalid evaluate result.");
1862        if (EltType->isRealFloatingType()) {
1863          return APValue(HandleIntToFloatCast(EltType, SrcType,
1864                                              Src.getComplexIntReal(),
1865                                              Info.Ctx),
1866                         HandleIntToFloatCast(EltType, SrcType,
1867                                              Src.getComplexIntImag(),
1868                                              Info.Ctx));
1869        } else {
1870          return APValue(HandleIntToIntCast(EltType, SrcType,
1871                                            Src.getComplexIntReal(),
1872                                            Info.Ctx),
1873                         HandleIntToIntCast(EltType, SrcType,
1874                                            Src.getComplexIntImag(),
1875                                            Info.Ctx));
1876        }
1877      }
1878    }
1879
1880    // FIXME: Handle more casts.
1881    return APValue();
1882  }
1883
1884  APValue VisitBinaryOperator(const BinaryOperator *E);
1885  APValue VisitChooseExpr(const ChooseExpr *E)
1886    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1887  APValue VisitUnaryExtension(const UnaryOperator *E)
1888    { return Visit(E->getSubExpr()); }
1889  // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
1890  //                conditional ?:, comma
1891};
1892} // end anonymous namespace
1893
1894static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info) {
1895  Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1896  assert((!Result.isComplexFloat() ||
1897          (&Result.getComplexFloatReal().getSemantics() ==
1898           &Result.getComplexFloatImag().getSemantics())) &&
1899         "Invalid complex evaluation.");
1900  return Result.isComplexFloat() || Result.isComplexInt();
1901}
1902
1903APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1904  APValue Result, RHS;
1905
1906  if (!EvaluateComplex(E->getLHS(), Result, Info))
1907    return APValue();
1908
1909  if (!EvaluateComplex(E->getRHS(), RHS, Info))
1910    return APValue();
1911
1912  assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1913         "Invalid operands to binary operator.");
1914  switch (E->getOpcode()) {
1915  default: return APValue();
1916  case BinaryOperator::Add:
1917    if (Result.isComplexFloat()) {
1918      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1919                                       APFloat::rmNearestTiesToEven);
1920      Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1921                                       APFloat::rmNearestTiesToEven);
1922    } else {
1923      Result.getComplexIntReal() += RHS.getComplexIntReal();
1924      Result.getComplexIntImag() += RHS.getComplexIntImag();
1925    }
1926    break;
1927  case BinaryOperator::Sub:
1928    if (Result.isComplexFloat()) {
1929      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1930                                            APFloat::rmNearestTiesToEven);
1931      Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1932                                            APFloat::rmNearestTiesToEven);
1933    } else {
1934      Result.getComplexIntReal() -= RHS.getComplexIntReal();
1935      Result.getComplexIntImag() -= RHS.getComplexIntImag();
1936    }
1937    break;
1938  case BinaryOperator::Mul:
1939    if (Result.isComplexFloat()) {
1940      APValue LHS = Result;
1941      APFloat &LHS_r = LHS.getComplexFloatReal();
1942      APFloat &LHS_i = LHS.getComplexFloatImag();
1943      APFloat &RHS_r = RHS.getComplexFloatReal();
1944      APFloat &RHS_i = RHS.getComplexFloatImag();
1945
1946      APFloat Tmp = LHS_r;
1947      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1948      Result.getComplexFloatReal() = Tmp;
1949      Tmp = LHS_i;
1950      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1951      Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1952
1953      Tmp = LHS_r;
1954      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1955      Result.getComplexFloatImag() = Tmp;
1956      Tmp = LHS_i;
1957      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1958      Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1959    } else {
1960      APValue LHS = Result;
1961      Result.getComplexIntReal() =
1962        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1963         LHS.getComplexIntImag() * RHS.getComplexIntImag());
1964      Result.getComplexIntImag() =
1965        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1966         LHS.getComplexIntImag() * RHS.getComplexIntReal());
1967    }
1968    break;
1969  }
1970
1971  return Result;
1972}
1973
1974//===----------------------------------------------------------------------===//
1975// Top level Expr::Evaluate method.
1976//===----------------------------------------------------------------------===//
1977
1978/// Evaluate - Return true if this is a constant which we can fold using
1979/// any crazy technique (that has nothing to do with language standards) that
1980/// we want to.  If this function returns true, it returns the folded constant
1981/// in Result.
1982bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1983  EvalInfo Info(Ctx, Result);
1984
1985  if (getType()->isVectorType()) {
1986    if (!EvaluateVector(this, Result.Val, Info))
1987      return false;
1988  } else if (getType()->isIntegerType()) {
1989    if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
1990      return false;
1991  } else if (getType()->hasPointerRepresentation()) {
1992    if (!EvaluatePointer(this, Result.Val, Info))
1993      return false;
1994  } else if (getType()->isRealFloatingType()) {
1995    llvm::APFloat f(0.0);
1996    if (!EvaluateFloat(this, f, Info))
1997      return false;
1998
1999    Result.Val = APValue(f);
2000  } else if (getType()->isAnyComplexType()) {
2001    if (!EvaluateComplex(this, Result.Val, Info))
2002      return false;
2003  } else
2004    return false;
2005
2006  return true;
2007}
2008
2009bool Expr::EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const {
2010  EvalInfo Info(Ctx, Result, true);
2011
2012  if (getType()->isVectorType()) {
2013    if (!EvaluateVector(this, Result.Val, Info))
2014      return false;
2015  } else if (getType()->isIntegerType()) {
2016    if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
2017      return false;
2018  } else if (getType()->hasPointerRepresentation()) {
2019    if (!EvaluatePointer(this, Result.Val, Info))
2020      return false;
2021  } else if (getType()->isRealFloatingType()) {
2022    llvm::APFloat f(0.0);
2023    if (!EvaluateFloat(this, f, Info))
2024      return false;
2025
2026    Result.Val = APValue(f);
2027  } else if (getType()->isAnyComplexType()) {
2028    if (!EvaluateComplex(this, Result.Val, Info))
2029      return false;
2030  } else
2031    return false;
2032
2033  return true;
2034}
2035
2036bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2037  EvalResult Scratch;
2038  EvalInfo Info(Ctx, Scratch);
2039
2040  return HandleConversionToBool(this, Result, Info);
2041}
2042
2043bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2044  EvalInfo Info(Ctx, Result);
2045
2046  return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2047}
2048
2049bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2050  EvalInfo Info(Ctx, Result, true);
2051
2052  return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2053}
2054
2055/// isEvaluatable - Call Evaluate to see if this expression can be constant
2056/// folded, but discard the result.
2057bool Expr::isEvaluatable(ASTContext &Ctx) const {
2058  EvalResult Result;
2059  return Evaluate(Result, Ctx) && !Result.HasSideEffects;
2060}
2061
2062bool Expr::HasSideEffects(ASTContext &Ctx) const {
2063  Expr::EvalResult Result;
2064  EvalInfo Info(Ctx, Result);
2065  return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2066}
2067
2068APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
2069  EvalResult EvalResult;
2070  bool Result = Evaluate(EvalResult, Ctx);
2071  Result = Result;
2072  assert(Result && "Could not evaluate expression");
2073  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
2074
2075  return EvalResult.Val.getInt();
2076}
2077