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