CGExprScalar.cpp revision 8c3e7e7ddafe26f236741fb25e2898be4f3230ea
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
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 contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CGObjCRuntime.h"
16#include "CodeGenModule.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/RecordLayout.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/Basic/TargetInfo.h"
22#include "llvm/Constants.h"
23#include "llvm/Function.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/Module.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/CFG.h"
29#include "llvm/Target/TargetData.h"
30#include <cstdarg>
31
32using namespace clang;
33using namespace CodeGen;
34using llvm::Value;
35
36//===----------------------------------------------------------------------===//
37//                         Scalar Expression Emitter
38//===----------------------------------------------------------------------===//
39
40struct BinOpInfo {
41  Value *LHS;
42  Value *RHS;
43  QualType Ty;  // Computation Type.
44  const BinaryOperator *E;
45};
46
47namespace {
48class VISIBILITY_HIDDEN ScalarExprEmitter
49  : public StmtVisitor<ScalarExprEmitter, Value*> {
50  CodeGenFunction &CGF;
51  CGBuilderTy &Builder;
52  bool IgnoreResultAssign;
53  llvm::LLVMContext &VMContext;
54public:
55
56  ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
57    : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
58      VMContext(cgf.getLLVMContext()) {
59  }
60
61  //===--------------------------------------------------------------------===//
62  //                               Utilities
63  //===--------------------------------------------------------------------===//
64
65  bool TestAndClearIgnoreResultAssign() {
66    bool I = IgnoreResultAssign;
67    IgnoreResultAssign = false;
68    return I;
69  }
70
71  const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
72  LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
73
74  Value *EmitLoadOfLValue(LValue LV, QualType T) {
75    return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
76  }
77
78  /// EmitLoadOfLValue - Given an expression with complex type that represents a
79  /// value l-value, this method emits the address of the l-value, then loads
80  /// and returns the result.
81  Value *EmitLoadOfLValue(const Expr *E) {
82    return EmitLoadOfLValue(EmitLValue(E), E->getType());
83  }
84
85  /// EmitConversionToBool - Convert the specified expression value to a
86  /// boolean (i1) truth value.  This is equivalent to "Val != 0".
87  Value *EmitConversionToBool(Value *Src, QualType DstTy);
88
89  /// EmitScalarConversion - Emit a conversion from the specified type to the
90  /// specified destination type, both of which are LLVM scalar types.
91  Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
92
93  /// EmitComplexToScalarConversion - Emit a conversion from the specified
94  /// complex type to the specified destination type, where the destination type
95  /// is an LLVM scalar type.
96  Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
97                                       QualType SrcTy, QualType DstTy);
98
99  //===--------------------------------------------------------------------===//
100  //                            Visitor Methods
101  //===--------------------------------------------------------------------===//
102
103  Value *VisitStmt(Stmt *S) {
104    S->dump(CGF.getContext().getSourceManager());
105    assert(0 && "Stmt can't have complex result type!");
106    return 0;
107  }
108  Value *VisitExpr(Expr *S);
109
110  Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
111
112  // Leaves.
113  Value *VisitIntegerLiteral(const IntegerLiteral *E) {
114    return llvm::ConstantInt::get(VMContext, E->getValue());
115  }
116  Value *VisitFloatingLiteral(const FloatingLiteral *E) {
117    return llvm::ConstantFP::get(VMContext, E->getValue());
118  }
119  Value *VisitCharacterLiteral(const CharacterLiteral *E) {
120    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
121  }
122  Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
123    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
124  }
125  Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
126    return llvm::Constant::getNullValue(ConvertType(E->getType()));
127  }
128  Value *VisitGNUNullExpr(const GNUNullExpr *E) {
129    return llvm::Constant::getNullValue(ConvertType(E->getType()));
130  }
131  Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
132    return llvm::ConstantInt::get(ConvertType(E->getType()),
133                                  CGF.getContext().typesAreCompatible(
134                                    E->getArgType1(), E->getArgType2()));
135  }
136  Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
137  Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
138    llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
139    return Builder.CreateBitCast(V, ConvertType(E->getType()));
140  }
141
142  // l-values.
143  Value *VisitDeclRefExpr(DeclRefExpr *E) {
144    Expr::EvalResult Result;
145    if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
146      assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
147      return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
148    }
149    return EmitLoadOfLValue(E);
150  }
151  Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
152    return CGF.EmitObjCSelectorExpr(E);
153  }
154  Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
155    return CGF.EmitObjCProtocolExpr(E);
156  }
157  Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
158    return EmitLoadOfLValue(E);
159  }
160  Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
161    return EmitLoadOfLValue(E);
162  }
163  Value *VisitObjCImplicitSetterGetterRefExpr(
164                        ObjCImplicitSetterGetterRefExpr *E) {
165    return EmitLoadOfLValue(E);
166  }
167  Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
168    return CGF.EmitObjCMessageExpr(E).getScalarVal();
169  }
170
171  Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
172  Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
173  Value *VisitMemberExpr(MemberExpr *E);
174  Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
175  Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
176    return EmitLoadOfLValue(E);
177  }
178  Value *VisitStringLiteral(Expr *E)  { return EmitLValue(E).getAddress(); }
179  Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
180     return EmitLValue(E).getAddress();
181  }
182
183  Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
184
185  Value *VisitInitListExpr(InitListExpr *E);
186
187  Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
188    return llvm::Constant::getNullValue(ConvertType(E->getType()));
189  }
190  Value *VisitCastExpr(const CastExpr *E) {
191    // Make sure to evaluate VLA bounds now so that we have them for later.
192    if (E->getType()->isVariablyModifiedType())
193      CGF.EmitVLASize(E->getType());
194
195    return EmitCastExpr(E);
196  }
197  Value *EmitCastExpr(const CastExpr *E);
198
199  Value *VisitCallExpr(const CallExpr *E) {
200    if (E->getCallReturnType()->isReferenceType())
201      return EmitLoadOfLValue(E);
202
203    return CGF.EmitCallExpr(E).getScalarVal();
204  }
205
206  Value *VisitStmtExpr(const StmtExpr *E);
207
208  Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
209
210  // Unary Operators.
211  Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
212  Value *VisitUnaryPostDec(const UnaryOperator *E) {
213    return VisitPrePostIncDec(E, false, false);
214  }
215  Value *VisitUnaryPostInc(const UnaryOperator *E) {
216    return VisitPrePostIncDec(E, true, false);
217  }
218  Value *VisitUnaryPreDec(const UnaryOperator *E) {
219    return VisitPrePostIncDec(E, false, true);
220  }
221  Value *VisitUnaryPreInc(const UnaryOperator *E) {
222    return VisitPrePostIncDec(E, true, true);
223  }
224  Value *VisitUnaryAddrOf(const UnaryOperator *E) {
225    return EmitLValue(E->getSubExpr()).getAddress();
226  }
227  Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
228  Value *VisitUnaryPlus(const UnaryOperator *E) {
229    // This differs from gcc, though, most likely due to a bug in gcc.
230    TestAndClearIgnoreResultAssign();
231    return Visit(E->getSubExpr());
232  }
233  Value *VisitUnaryMinus    (const UnaryOperator *E);
234  Value *VisitUnaryNot      (const UnaryOperator *E);
235  Value *VisitUnaryLNot     (const UnaryOperator *E);
236  Value *VisitUnaryReal     (const UnaryOperator *E);
237  Value *VisitUnaryImag     (const UnaryOperator *E);
238  Value *VisitUnaryExtension(const UnaryOperator *E) {
239    return Visit(E->getSubExpr());
240  }
241  Value *VisitUnaryOffsetOf(const UnaryOperator *E);
242
243  // C++
244  Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
245    return Visit(DAE->getExpr());
246  }
247  Value *VisitCXXThisExpr(CXXThisExpr *TE) {
248    return CGF.LoadCXXThis();
249  }
250
251  Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
252    return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
253  }
254  Value *VisitCXXNewExpr(const CXXNewExpr *E) {
255    return CGF.EmitCXXNewExpr(E);
256  }
257  Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
258    CGF.EmitCXXDeleteExpr(E);
259    return 0;
260  }
261
262  Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
263    // C++ [expr.pseudo]p1:
264    //   The result shall only be used as the operand for the function call
265    //   operator (), and the result of such a call has type void. The only
266    //   effect is the evaluation of the postfix-expression before the dot or
267    //   arrow.
268    CGF.EmitScalarExpr(E->getBase());
269    return 0;
270  }
271
272  Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
273    return llvm::Constant::getNullValue(ConvertType(E->getType()));
274  }
275
276  Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
277    CGF.EmitCXXThrowExpr(E);
278    return 0;
279  }
280
281  // Binary Operators.
282  Value *EmitMul(const BinOpInfo &Ops) {
283    if (CGF.getContext().getLangOptions().OverflowChecking
284        && Ops.Ty->isSignedIntegerType())
285      return EmitOverflowCheckedBinOp(Ops);
286    if (Ops.LHS->getType()->isFPOrFPVector())
287      return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
288    return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
289  }
290  /// Create a binary op that checks for overflow.
291  /// Currently only supports +, - and *.
292  Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
293  Value *EmitDiv(const BinOpInfo &Ops);
294  Value *EmitRem(const BinOpInfo &Ops);
295  Value *EmitAdd(const BinOpInfo &Ops);
296  Value *EmitSub(const BinOpInfo &Ops);
297  Value *EmitShl(const BinOpInfo &Ops);
298  Value *EmitShr(const BinOpInfo &Ops);
299  Value *EmitAnd(const BinOpInfo &Ops) {
300    return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
301  }
302  Value *EmitXor(const BinOpInfo &Ops) {
303    return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
304  }
305  Value *EmitOr (const BinOpInfo &Ops) {
306    return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
307  }
308
309  BinOpInfo EmitBinOps(const BinaryOperator *E);
310  Value *EmitCompoundAssign(const CompoundAssignOperator *E,
311                            Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
312
313  // Binary operators and binary compound assignment operators.
314#define HANDLEBINOP(OP) \
315  Value *VisitBin ## OP(const BinaryOperator *E) {                         \
316    return Emit ## OP(EmitBinOps(E));                                      \
317  }                                                                        \
318  Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) {       \
319    return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP);          \
320  }
321  HANDLEBINOP(Mul);
322  HANDLEBINOP(Div);
323  HANDLEBINOP(Rem);
324  HANDLEBINOP(Add);
325  HANDLEBINOP(Sub);
326  HANDLEBINOP(Shl);
327  HANDLEBINOP(Shr);
328  HANDLEBINOP(And);
329  HANDLEBINOP(Xor);
330  HANDLEBINOP(Or);
331#undef HANDLEBINOP
332
333  // Comparisons.
334  Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
335                     unsigned SICmpOpc, unsigned FCmpOpc);
336#define VISITCOMP(CODE, UI, SI, FP) \
337    Value *VisitBin##CODE(const BinaryOperator *E) { \
338      return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
339                         llvm::FCmpInst::FP); }
340  VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
341  VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
342  VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
343  VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
344  VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
345  VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
346#undef VISITCOMP
347
348  Value *VisitBinAssign     (const BinaryOperator *E);
349
350  Value *VisitBinLAnd       (const BinaryOperator *E);
351  Value *VisitBinLOr        (const BinaryOperator *E);
352  Value *VisitBinComma      (const BinaryOperator *E);
353
354  Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
355  Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
356
357  // Other Operators.
358  Value *VisitBlockExpr(const BlockExpr *BE);
359  Value *VisitConditionalOperator(const ConditionalOperator *CO);
360  Value *VisitChooseExpr(ChooseExpr *CE);
361  Value *VisitVAArgExpr(VAArgExpr *VE);
362  Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
363    return CGF.EmitObjCStringLiteral(E);
364  }
365};
366}  // end anonymous namespace.
367
368//===----------------------------------------------------------------------===//
369//                                Utilities
370//===----------------------------------------------------------------------===//
371
372/// EmitConversionToBool - Convert the specified expression value to a
373/// boolean (i1) truth value.  This is equivalent to "Val != 0".
374Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
375  assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
376
377  if (SrcType->isRealFloatingType()) {
378    // Compare against 0.0 for fp scalars.
379    llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
380    return Builder.CreateFCmpUNE(Src, Zero, "tobool");
381  }
382
383  if (SrcType->isMemberPointerType()) {
384    // FIXME: This is ABI specific.
385
386    // Compare against -1.
387    llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
388    return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
389  }
390
391  assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
392         "Unknown scalar type to convert");
393
394  // Because of the type rules of C, we often end up computing a logical value,
395  // then zero extending it to int, then wanting it as a logical value again.
396  // Optimize this common case.
397  if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
398    if (ZI->getOperand(0)->getType() ==
399        llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
400      Value *Result = ZI->getOperand(0);
401      // If there aren't any more uses, zap the instruction to save space.
402      // Note that there can be more uses, for example if this
403      // is the result of an assignment.
404      if (ZI->use_empty())
405        ZI->eraseFromParent();
406      return Result;
407    }
408  }
409
410  // Compare against an integer or pointer null.
411  llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
412  return Builder.CreateICmpNE(Src, Zero, "tobool");
413}
414
415/// EmitScalarConversion - Emit a conversion from the specified type to the
416/// specified destination type, both of which are LLVM scalar types.
417Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
418                                               QualType DstType) {
419  SrcType = CGF.getContext().getCanonicalType(SrcType);
420  DstType = CGF.getContext().getCanonicalType(DstType);
421  if (SrcType == DstType) return Src;
422
423  if (DstType->isVoidType()) return 0;
424
425  llvm::LLVMContext &VMContext = CGF.getLLVMContext();
426
427  // Handle conversions to bool first, they are special: comparisons against 0.
428  if (DstType->isBooleanType())
429    return EmitConversionToBool(Src, SrcType);
430
431  const llvm::Type *DstTy = ConvertType(DstType);
432
433  // Ignore conversions like int -> uint.
434  if (Src->getType() == DstTy)
435    return Src;
436
437  // Handle pointer conversions next: pointers can only be converted to/from
438  // other pointers and integers. Check for pointer types in terms of LLVM, as
439  // some native types (like Obj-C id) may map to a pointer type.
440  if (isa<llvm::PointerType>(DstTy)) {
441    // The source value may be an integer, or a pointer.
442    if (isa<llvm::PointerType>(Src->getType()))
443      return Builder.CreateBitCast(Src, DstTy, "conv");
444
445    assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
446    // First, convert to the correct width so that we control the kind of
447    // extension.
448    const llvm::Type *MiddleTy =
449          llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
450    bool InputSigned = SrcType->isSignedIntegerType();
451    llvm::Value* IntResult =
452        Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
453    // Then, cast to pointer.
454    return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
455  }
456
457  if (isa<llvm::PointerType>(Src->getType())) {
458    // Must be an ptr to int cast.
459    assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
460    return Builder.CreatePtrToInt(Src, DstTy, "conv");
461  }
462
463  // A scalar can be splatted to an extended vector of the same element type
464  if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
465    // Cast the scalar to element type
466    QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
467    llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
468
469    // Insert the element in element zero of an undef vector
470    llvm::Value *UnV = llvm::UndefValue::get(DstTy);
471    llvm::Value *Idx =
472        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
473    UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
474
475    // Splat the element across to all elements
476    llvm::SmallVector<llvm::Constant*, 16> Args;
477    unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
478    for (unsigned i = 0; i < NumElements; i++)
479      Args.push_back(llvm::ConstantInt::get(
480                                        llvm::Type::getInt32Ty(VMContext), 0));
481
482    llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
483    llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
484    return Yay;
485  }
486
487  // Allow bitcast from vector to integer/fp of the same size.
488  if (isa<llvm::VectorType>(Src->getType()) ||
489      isa<llvm::VectorType>(DstTy))
490    return Builder.CreateBitCast(Src, DstTy, "conv");
491
492  // Finally, we have the arithmetic types: real int/float.
493  if (isa<llvm::IntegerType>(Src->getType())) {
494    bool InputSigned = SrcType->isSignedIntegerType();
495    if (isa<llvm::IntegerType>(DstTy))
496      return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
497    else if (InputSigned)
498      return Builder.CreateSIToFP(Src, DstTy, "conv");
499    else
500      return Builder.CreateUIToFP(Src, DstTy, "conv");
501  }
502
503  assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
504  if (isa<llvm::IntegerType>(DstTy)) {
505    if (DstType->isSignedIntegerType())
506      return Builder.CreateFPToSI(Src, DstTy, "conv");
507    else
508      return Builder.CreateFPToUI(Src, DstTy, "conv");
509  }
510
511  assert(DstTy->isFloatingPoint() && "Unknown real conversion");
512  if (DstTy->getTypeID() < Src->getType()->getTypeID())
513    return Builder.CreateFPTrunc(Src, DstTy, "conv");
514  else
515    return Builder.CreateFPExt(Src, DstTy, "conv");
516}
517
518/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
519/// type to the specified destination type, where the destination type is an
520/// LLVM scalar type.
521Value *ScalarExprEmitter::
522EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
523                              QualType SrcTy, QualType DstTy) {
524  // Get the source element type.
525  SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
526
527  // Handle conversions to bool first, they are special: comparisons against 0.
528  if (DstTy->isBooleanType()) {
529    //  Complex != 0  -> (Real != 0) | (Imag != 0)
530    Src.first  = EmitScalarConversion(Src.first, SrcTy, DstTy);
531    Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
532    return Builder.CreateOr(Src.first, Src.second, "tobool");
533  }
534
535  // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
536  // the imaginary part of the complex value is discarded and the value of the
537  // real part is converted according to the conversion rules for the
538  // corresponding real type.
539  return EmitScalarConversion(Src.first, SrcTy, DstTy);
540}
541
542
543//===----------------------------------------------------------------------===//
544//                            Visitor Methods
545//===----------------------------------------------------------------------===//
546
547Value *ScalarExprEmitter::VisitExpr(Expr *E) {
548  CGF.ErrorUnsupported(E, "scalar expression");
549  if (E->getType()->isVoidType())
550    return 0;
551  return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
552}
553
554Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
555  llvm::SmallVector<llvm::Constant*, 32> indices;
556  for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
557    indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
558  }
559  Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
560  Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
561  Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
562  return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
563}
564Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
565  Expr::EvalResult Result;
566  if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
567    if (E->isArrow())
568      CGF.EmitScalarExpr(E->getBase());
569    else
570      EmitLValue(E->getBase());
571    return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
572  }
573  return EmitLoadOfLValue(E);
574}
575
576Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
577  TestAndClearIgnoreResultAssign();
578
579  // Emit subscript expressions in rvalue context's.  For most cases, this just
580  // loads the lvalue formed by the subscript expr.  However, we have to be
581  // careful, because the base of a vector subscript is occasionally an rvalue,
582  // so we can't get it as an lvalue.
583  if (!E->getBase()->getType()->isVectorType())
584    return EmitLoadOfLValue(E);
585
586  // Handle the vector case.  The base must be a vector, the index must be an
587  // integer value.
588  Value *Base = Visit(E->getBase());
589  Value *Idx  = Visit(E->getIdx());
590  bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
591  Idx = Builder.CreateIntCast(Idx,
592                              llvm::Type::getInt32Ty(CGF.getLLVMContext()),
593                              IdxSigned,
594                              "vecidxcast");
595  return Builder.CreateExtractElement(Base, Idx, "vecext");
596}
597
598static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
599                                  unsigned Off, const llvm::Type *I32Ty) {
600  int MV = SVI->getMaskValue(Idx);
601  if (MV == -1)
602    return llvm::UndefValue::get(I32Ty);
603  return llvm::ConstantInt::get(I32Ty, Off+MV);
604}
605
606Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
607  bool Ignore = TestAndClearIgnoreResultAssign();
608  (void)Ignore;
609  assert (Ignore == false && "init list ignored");
610  unsigned NumInitElements = E->getNumInits();
611
612  if (E->hadArrayRangeDesignator())
613    CGF.ErrorUnsupported(E, "GNU array range designator extension");
614
615  const llvm::VectorType *VType =
616    dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
617
618  // We have a scalar in braces. Just use the first element.
619  if (!VType)
620    return Visit(E->getInit(0));
621
622  unsigned ResElts = VType->getNumElements();
623  const llvm::Type *I32Ty = llvm::Type::getInt32Ty(CGF.getLLVMContext());
624
625  // Loop over initializers collecting the Value for each, and remembering
626  // whether the source was swizzle (ExtVectorElementExpr).  This will allow
627  // us to fold the shuffle for the swizzle into the shuffle for the vector
628  // initializer, since LLVM optimizers generally do not want to touch
629  // shuffles.
630  unsigned CurIdx = 0;
631  bool VIsUndefShuffle = false;
632  llvm::Value *V = llvm::UndefValue::get(VType);
633  for (unsigned i = 0; i != NumInitElements; ++i) {
634    Expr *IE = E->getInit(i);
635    Value *Init = Visit(IE);
636    llvm::SmallVector<llvm::Constant*, 16> Args;
637
638    const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
639
640    // Handle scalar elements.  If the scalar initializer is actually one
641    // element of a different vector of the same width, use shuffle instead of
642    // extract+insert.
643    if (!VVT) {
644      if (isa<ExtVectorElementExpr>(IE)) {
645        llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
646
647        if (EI->getVectorOperandType()->getNumElements() == ResElts) {
648          llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
649          Value *LHS = 0, *RHS = 0;
650          if (CurIdx == 0) {
651            // insert into undef -> shuffle (src, undef)
652            Args.push_back(C);
653            for (unsigned j = 1; j != ResElts; ++j)
654              Args.push_back(llvm::UndefValue::get(I32Ty));
655
656            LHS = EI->getVectorOperand();
657            RHS = V;
658            VIsUndefShuffle = true;
659          } else if (VIsUndefShuffle) {
660            // insert into undefshuffle && size match -> shuffle (v, src)
661            llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
662            for (unsigned j = 0; j != CurIdx; ++j)
663              Args.push_back(getMaskElt(SVV, j, 0, I32Ty));
664            Args.push_back(llvm::ConstantInt::get(I32Ty,
665                                                  ResElts + C->getZExtValue()));
666            for (unsigned j = CurIdx + 1; j != ResElts; ++j)
667              Args.push_back(llvm::UndefValue::get(I32Ty));
668
669            LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
670            RHS = EI->getVectorOperand();
671            VIsUndefShuffle = false;
672          }
673          if (!Args.empty()) {
674            llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
675            V = Builder.CreateShuffleVector(LHS, RHS, Mask);
676            ++CurIdx;
677            continue;
678          }
679        }
680      }
681      Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx);
682      V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
683      VIsUndefShuffle = false;
684      ++CurIdx;
685      continue;
686    }
687
688    unsigned InitElts = VVT->getNumElements();
689
690    // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
691    // input is the same width as the vector being constructed, generate an
692    // optimized shuffle of the swizzle input into the result.
693    unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
694    if (isa<ExtVectorElementExpr>(IE)) {
695      llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
696      Value *SVOp = SVI->getOperand(0);
697      const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
698
699      if (OpTy->getNumElements() == ResElts) {
700        for (unsigned j = 0; j != CurIdx; ++j) {
701          // If the current vector initializer is a shuffle with undef, merge
702          // this shuffle directly into it.
703          if (VIsUndefShuffle) {
704            Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
705                                      I32Ty));
706          } else {
707            Args.push_back(llvm::ConstantInt::get(I32Ty, j));
708          }
709        }
710        for (unsigned j = 0, je = InitElts; j != je; ++j)
711          Args.push_back(getMaskElt(SVI, j, Offset, I32Ty));
712        for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
713          Args.push_back(llvm::UndefValue::get(I32Ty));
714
715        if (VIsUndefShuffle)
716          V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
717
718        Init = SVOp;
719      }
720    }
721
722    // Extend init to result vector length, and then shuffle its contribution
723    // to the vector initializer into V.
724    if (Args.empty()) {
725      for (unsigned j = 0; j != InitElts; ++j)
726        Args.push_back(llvm::ConstantInt::get(I32Ty, j));
727      for (unsigned j = InitElts; j != ResElts; ++j)
728        Args.push_back(llvm::UndefValue::get(I32Ty));
729      llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
730      Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
731                                         Mask, "vext");
732
733      Args.clear();
734      for (unsigned j = 0; j != CurIdx; ++j)
735        Args.push_back(llvm::ConstantInt::get(I32Ty, j));
736      for (unsigned j = 0; j != InitElts; ++j)
737        Args.push_back(llvm::ConstantInt::get(I32Ty, j+Offset));
738      for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
739        Args.push_back(llvm::UndefValue::get(I32Ty));
740    }
741
742    // If V is undef, make sure it ends up on the RHS of the shuffle to aid
743    // merging subsequent shuffles into this one.
744    if (CurIdx == 0)
745      std::swap(V, Init);
746    llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
747    V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
748    VIsUndefShuffle = isa<llvm::UndefValue>(Init);
749    CurIdx += InitElts;
750  }
751
752  // FIXME: evaluate codegen vs. shuffling against constant null vector.
753  // Emit remaining default initializers.
754  const llvm::Type *EltTy = VType->getElementType();
755
756  // Emit remaining default initializers
757  for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
758    Value *Idx = llvm::ConstantInt::get(I32Ty, CurIdx);
759    llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
760    V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
761  }
762  return V;
763}
764
765static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
766  const Expr *E = CE->getSubExpr();
767
768  if (isa<CXXThisExpr>(E)) {
769    // We always assume that 'this' is never null.
770    return false;
771  }
772
773  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
774    // And that lvalue casts are never null.
775    if (ICE->isLvalueCast())
776      return false;
777  }
778
779  return true;
780}
781
782// VisitCastExpr - Emit code for an explicit or implicit cast.  Implicit casts
783// have to handle a more broad range of conversions than explicit casts, as they
784// handle things like function to ptr-to-function decay etc.
785Value *ScalarExprEmitter::EmitCastExpr(const CastExpr *CE) {
786  const Expr *E = CE->getSubExpr();
787  QualType DestTy = CE->getType();
788  CastExpr::CastKind Kind = CE->getCastKind();
789
790  if (!DestTy->isVoidType())
791    TestAndClearIgnoreResultAssign();
792
793  // Since almost all cast kinds apply to scalars, this switch doesn't have
794  // a default case, so the compiler will warn on a missing case.  The cases
795  // are in the same order as in the CastKind enum.
796  switch (Kind) {
797  case CastExpr::CK_Unknown:
798    //assert(0 && "Unknown cast kind!");
799    break;
800
801  case CastExpr::CK_BitCast: {
802    Value *Src = Visit(const_cast<Expr*>(E));
803    return Builder.CreateBitCast(Src, ConvertType(DestTy));
804  }
805  case CastExpr::CK_NoOp:
806    return Visit(const_cast<Expr*>(E));
807
808  case CastExpr::CK_BaseToDerived: {
809    const CXXRecordDecl *BaseClassDecl =
810      E->getType()->getCXXRecordDeclForPointerType();
811    const CXXRecordDecl *DerivedClassDecl =
812      DestTy->getCXXRecordDeclForPointerType();
813
814    Value *Src = Visit(const_cast<Expr*>(E));
815
816    bool NullCheckValue = ShouldNullCheckClassCastValue(CE);
817    return CGF.GetAddressOfDerivedClass(Src, BaseClassDecl, DerivedClassDecl,
818                                        NullCheckValue);
819  }
820  case CastExpr::CK_DerivedToBase: {
821    const RecordType *DerivedClassTy =
822      E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
823    CXXRecordDecl *DerivedClassDecl =
824      cast<CXXRecordDecl>(DerivedClassTy->getDecl());
825
826    const RecordType *BaseClassTy =
827      DestTy->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
828    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseClassTy->getDecl());
829
830    Value *Src = Visit(const_cast<Expr*>(E));
831
832    bool NullCheckValue = ShouldNullCheckClassCastValue(CE);
833    return CGF.GetAddressOfBaseClass(Src, DerivedClassDecl, BaseClassDecl,
834                                     NullCheckValue);
835  }
836  case CastExpr::CK_Dynamic: {
837    Value *V = Visit(const_cast<Expr*>(E));
838    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
839    return CGF.EmitDynamicCast(V, DCE);
840  }
841  case CastExpr::CK_ToUnion: {
842    assert(0 && "Should be unreachable!");
843    break;
844  }
845  case CastExpr::CK_ArrayToPointerDecay: {
846    assert(E->getType()->isArrayType() &&
847           "Array to pointer decay must have array source type!");
848
849    Value *V = EmitLValue(E).getAddress();  // Bitfields can't be arrays.
850
851    // Note that VLA pointers are always decayed, so we don't need to do
852    // anything here.
853    if (!E->getType()->isVariableArrayType()) {
854      assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
855      assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
856                                 ->getElementType()) &&
857             "Expected pointer to array");
858      V = Builder.CreateStructGEP(V, 0, "arraydecay");
859    }
860
861    return V;
862  }
863  case CastExpr::CK_FunctionToPointerDecay:
864    return EmitLValue(E).getAddress();
865
866  case CastExpr::CK_NullToMemberPointer:
867    return CGF.CGM.EmitNullConstant(DestTy);
868
869  case CastExpr::CK_BaseToDerivedMemberPointer:
870  case CastExpr::CK_DerivedToBaseMemberPointer:
871  case CastExpr::CK_UserDefinedConversion:
872  case CastExpr::CK_ConstructorConversion:
873    break;
874
875  case CastExpr::CK_IntegralToPointer: {
876    Value *Src = Visit(const_cast<Expr*>(E));
877
878    // First, convert to the correct width so that we control the kind of
879    // extension.
880    const llvm::Type *MiddleTy =
881      llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
882    bool InputSigned = E->getType()->isSignedIntegerType();
883    llvm::Value* IntResult =
884      Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
885
886    return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
887  }
888  case CastExpr::CK_PointerToIntegral: {
889    Value *Src = Visit(const_cast<Expr*>(E));
890    return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
891  }
892  case CastExpr::CK_ToVoid: {
893    CGF.EmitAnyExpr(E, 0, false, true);
894    return 0;
895  }
896  case CastExpr::CK_VectorSplat: {
897    const llvm::Type *DstTy = ConvertType(DestTy);
898    Value *Elt = Visit(const_cast<Expr*>(E));
899
900    // Insert the element in element zero of an undef vector
901    llvm::Value *UnV = llvm::UndefValue::get(DstTy);
902    llvm::Value *Idx =
903        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
904    UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
905
906    // Splat the element across to all elements
907    llvm::SmallVector<llvm::Constant*, 16> Args;
908    unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
909    for (unsigned i = 0; i < NumElements; i++)
910      Args.push_back(llvm::ConstantInt::get(
911                                        llvm::Type::getInt32Ty(VMContext), 0));
912
913    llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
914    llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
915    return Yay;
916  }
917  case CastExpr::CK_IntegralCast:
918  case CastExpr::CK_IntegralToFloating:
919  case CastExpr::CK_FloatingToIntegral:
920  case CastExpr::CK_FloatingCast:
921    break;
922
923  case CastExpr::CK_MemberPointerToBoolean: {
924    const MemberPointerType* T = E->getType()->getAs<MemberPointerType>();
925
926    if (T->getPointeeType()->isFunctionType()) {
927      // We have a member function pointer.
928      llvm::Value *Ptr = CGF.CreateTempAlloca(ConvertType(E->getType()));
929
930      CGF.EmitAggExpr(E, Ptr, /*VolatileDest=*/false);
931
932      // Get the pointer.
933      llvm::Value *FuncPtr = Builder.CreateStructGEP(Ptr, 0, "src.ptr");
934      FuncPtr = Builder.CreateLoad(FuncPtr);
935
936      llvm::Value *IsNotNull =
937        Builder.CreateICmpNE(FuncPtr,
938                             llvm::Constant::getNullValue(FuncPtr->getType()),
939                             "tobool");
940
941      return IsNotNull;
942    }
943
944    // We have a regular member pointer.
945    Value *Ptr = Visit(const_cast<Expr*>(E));
946    llvm::Value *IsNotNull =
947      Builder.CreateICmpNE(Ptr, CGF.CGM.EmitNullConstant(E->getType()),
948                           "tobool");
949    return IsNotNull;
950  }
951  }
952
953  // Handle cases where the source is an non-complex type.
954
955  if (!CGF.hasAggregateLLVMType(E->getType())) {
956    Value *Src = Visit(const_cast<Expr*>(E));
957
958    // Use EmitScalarConversion to perform the conversion.
959    return EmitScalarConversion(Src, E->getType(), DestTy);
960  }
961
962  if (E->getType()->isAnyComplexType()) {
963    // Handle cases where the source is a complex type.
964    bool IgnoreImag = true;
965    bool IgnoreImagAssign = true;
966    bool IgnoreReal = IgnoreResultAssign;
967    bool IgnoreRealAssign = IgnoreResultAssign;
968    if (DestTy->isBooleanType())
969      IgnoreImagAssign = IgnoreImag = false;
970    else if (DestTy->isVoidType()) {
971      IgnoreReal = IgnoreImag = false;
972      IgnoreRealAssign = IgnoreImagAssign = true;
973    }
974    CodeGenFunction::ComplexPairTy V
975      = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
976                            IgnoreImagAssign);
977    return EmitComplexToScalarConversion(V, E->getType(), DestTy);
978  }
979
980  // Okay, this is a cast from an aggregate.  It must be a cast to void.  Just
981  // evaluate the result and return.
982  CGF.EmitAggExpr(E, 0, false, true);
983  return 0;
984}
985
986Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
987  return CGF.EmitCompoundStmt(*E->getSubStmt(),
988                              !E->getType()->isVoidType()).getScalarVal();
989}
990
991Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
992  llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
993  if (E->getType().isObjCGCWeak())
994    return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
995  return Builder.CreateLoad(V, false, "tmp");
996}
997
998//===----------------------------------------------------------------------===//
999//                             Unary Operators
1000//===----------------------------------------------------------------------===//
1001
1002Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
1003                                             bool isInc, bool isPre) {
1004  LValue LV = EmitLValue(E->getSubExpr());
1005  QualType ValTy = E->getSubExpr()->getType();
1006  Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
1007
1008  llvm::LLVMContext &VMContext = CGF.getLLVMContext();
1009
1010  int AmountVal = isInc ? 1 : -1;
1011
1012  if (ValTy->isPointerType() &&
1013      ValTy->getAs<PointerType>()->isVariableArrayType()) {
1014    // The amount of the addition/subtraction needs to account for the VLA size
1015    CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
1016  }
1017
1018  Value *NextVal;
1019  if (const llvm::PointerType *PT =
1020         dyn_cast<llvm::PointerType>(InVal->getType())) {
1021    llvm::Constant *Inc =
1022      llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
1023    if (!isa<llvm::FunctionType>(PT->getElementType())) {
1024      QualType PTEE = ValTy->getPointeeType();
1025      if (const ObjCInterfaceType *OIT =
1026          dyn_cast<ObjCInterfaceType>(PTEE)) {
1027        // Handle interface types, which are not represented with a concrete type.
1028        int size = CGF.getContext().getTypeSize(OIT) / 8;
1029        if (!isInc)
1030          size = -size;
1031        Inc = llvm::ConstantInt::get(Inc->getType(), size);
1032        const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1033        InVal = Builder.CreateBitCast(InVal, i8Ty);
1034        NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
1035        llvm::Value *lhs = LV.getAddress();
1036        lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
1037        LV = LValue::MakeAddr(lhs, CGF.MakeQualifiers(ValTy));
1038      } else
1039        NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
1040    } else {
1041      const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1042      NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
1043      NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
1044      NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
1045    }
1046  } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
1047    // Bool++ is an interesting case, due to promotion rules, we get:
1048    // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
1049    // Bool = ((int)Bool+1) != 0
1050    // An interesting aspect of this is that increment is always true.
1051    // Decrement does not have this property.
1052    NextVal = llvm::ConstantInt::getTrue(VMContext);
1053  } else if (isa<llvm::IntegerType>(InVal->getType())) {
1054    NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
1055
1056    // Signed integer overflow is undefined behavior.
1057    if (ValTy->isSignedIntegerType())
1058      NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
1059    else
1060      NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1061  } else {
1062    // Add the inc/dec to the real part.
1063    if (InVal->getType()->isFloatTy())
1064      NextVal =
1065        llvm::ConstantFP::get(VMContext,
1066                              llvm::APFloat(static_cast<float>(AmountVal)));
1067    else if (InVal->getType()->isDoubleTy())
1068      NextVal =
1069        llvm::ConstantFP::get(VMContext,
1070                              llvm::APFloat(static_cast<double>(AmountVal)));
1071    else {
1072      llvm::APFloat F(static_cast<float>(AmountVal));
1073      bool ignored;
1074      F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1075                &ignored);
1076      NextVal = llvm::ConstantFP::get(VMContext, F);
1077    }
1078    NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
1079  }
1080
1081  // Store the updated result through the lvalue.
1082  if (LV.isBitfield())
1083    CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
1084                                       &NextVal);
1085  else
1086    CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
1087
1088  // If this is a postinc, return the value read from memory, otherwise use the
1089  // updated value.
1090  return isPre ? NextVal : InVal;
1091}
1092
1093
1094Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1095  TestAndClearIgnoreResultAssign();
1096  Value *Op = Visit(E->getSubExpr());
1097  if (Op->getType()->isFPOrFPVector())
1098    return Builder.CreateFNeg(Op, "neg");
1099  return Builder.CreateNeg(Op, "neg");
1100}
1101
1102Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1103  TestAndClearIgnoreResultAssign();
1104  Value *Op = Visit(E->getSubExpr());
1105  return Builder.CreateNot(Op, "neg");
1106}
1107
1108Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1109  // Compare operand to zero.
1110  Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1111
1112  // Invert value.
1113  // TODO: Could dynamically modify easy computations here.  For example, if
1114  // the operand is an icmp ne, turn into icmp eq.
1115  BoolVal = Builder.CreateNot(BoolVal, "lnot");
1116
1117  // ZExt result to the expr type.
1118  return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1119}
1120
1121/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1122/// argument of the sizeof expression as an integer.
1123Value *
1124ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1125  QualType TypeToSize = E->getTypeOfArgument();
1126  if (E->isSizeOf()) {
1127    if (const VariableArrayType *VAT =
1128          CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1129      if (E->isArgumentType()) {
1130        // sizeof(type) - make sure to emit the VLA size.
1131        CGF.EmitVLASize(TypeToSize);
1132      } else {
1133        // C99 6.5.3.4p2: If the argument is an expression of type
1134        // VLA, it is evaluated.
1135        CGF.EmitAnyExpr(E->getArgumentExpr());
1136      }
1137
1138      return CGF.GetVLASize(VAT);
1139    }
1140  }
1141
1142  // If this isn't sizeof(vla), the result must be constant; use the constant
1143  // folding logic so we don't have to duplicate it here.
1144  Expr::EvalResult Result;
1145  E->Evaluate(Result, CGF.getContext());
1146  return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
1147}
1148
1149Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1150  Expr *Op = E->getSubExpr();
1151  if (Op->getType()->isAnyComplexType())
1152    return CGF.EmitComplexExpr(Op, false, true, false, true).first;
1153  return Visit(Op);
1154}
1155Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1156  Expr *Op = E->getSubExpr();
1157  if (Op->getType()->isAnyComplexType())
1158    return CGF.EmitComplexExpr(Op, true, false, true, false).second;
1159
1160  // __imag on a scalar returns zero.  Emit the subexpr to ensure side
1161  // effects are evaluated, but not the actual value.
1162  if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
1163    CGF.EmitLValue(Op);
1164  else
1165    CGF.EmitScalarExpr(Op, true);
1166  return llvm::Constant::getNullValue(ConvertType(E->getType()));
1167}
1168
1169Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) {
1170  Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
1171  const llvm::Type* ResultType = ConvertType(E->getType());
1172  return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
1173}
1174
1175//===----------------------------------------------------------------------===//
1176//                           Binary Operators
1177//===----------------------------------------------------------------------===//
1178
1179BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1180  TestAndClearIgnoreResultAssign();
1181  BinOpInfo Result;
1182  Result.LHS = Visit(E->getLHS());
1183  Result.RHS = Visit(E->getRHS());
1184  Result.Ty  = E->getType();
1185  Result.E = E;
1186  return Result;
1187}
1188
1189Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1190                      Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1191  bool Ignore = TestAndClearIgnoreResultAssign();
1192  QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
1193
1194  BinOpInfo OpInfo;
1195
1196  if (E->getComputationResultType()->isAnyComplexType()) {
1197    // This needs to go through the complex expression emitter, but it's a tad
1198    // complicated to do that... I'm leaving it out for now.  (Note that we do
1199    // actually need the imaginary part of the RHS for multiplication and
1200    // division.)
1201    CGF.ErrorUnsupported(E, "complex compound assignment");
1202    return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1203  }
1204
1205  // Emit the RHS first.  __block variables need to have the rhs evaluated
1206  // first, plus this should improve codegen a little.
1207  OpInfo.RHS = Visit(E->getRHS());
1208  OpInfo.Ty = E->getComputationResultType();
1209  OpInfo.E = E;
1210  // Load/convert the LHS.
1211  LValue LHSLV = EmitLValue(E->getLHS());
1212  OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1213  OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1214                                    E->getComputationLHSType());
1215
1216  // Expand the binary operator.
1217  Value *Result = (this->*Func)(OpInfo);
1218
1219  // Convert the result back to the LHS type.
1220  Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1221
1222  // Store the result value into the LHS lvalue. Bit-fields are handled
1223  // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1224  // 'An assignment expression has the value of the left operand after the
1225  // assignment...'.
1226  if (LHSLV.isBitfield()) {
1227    if (!LHSLV.isVolatileQualified()) {
1228      CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1229                                         &Result);
1230      return Result;
1231    } else
1232      CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
1233  } else
1234    CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
1235  if (Ignore)
1236    return 0;
1237  return EmitLoadOfLValue(LHSLV, E->getType());
1238}
1239
1240
1241Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1242  if (Ops.LHS->getType()->isFPOrFPVector())
1243    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1244  else if (Ops.Ty->isUnsignedIntegerType())
1245    return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1246  else
1247    return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1248}
1249
1250Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1251  // Rem in C can't be a floating point type: C99 6.5.5p2.
1252  if (Ops.Ty->isUnsignedIntegerType())
1253    return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1254  else
1255    return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1256}
1257
1258Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1259  unsigned IID;
1260  unsigned OpID = 0;
1261
1262  switch (Ops.E->getOpcode()) {
1263  case BinaryOperator::Add:
1264  case BinaryOperator::AddAssign:
1265    OpID = 1;
1266    IID = llvm::Intrinsic::sadd_with_overflow;
1267    break;
1268  case BinaryOperator::Sub:
1269  case BinaryOperator::SubAssign:
1270    OpID = 2;
1271    IID = llvm::Intrinsic::ssub_with_overflow;
1272    break;
1273  case BinaryOperator::Mul:
1274  case BinaryOperator::MulAssign:
1275    OpID = 3;
1276    IID = llvm::Intrinsic::smul_with_overflow;
1277    break;
1278  default:
1279    assert(false && "Unsupported operation for overflow detection");
1280    IID = 0;
1281  }
1282  OpID <<= 1;
1283  OpID |= 1;
1284
1285  const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1286
1287  llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1288
1289  Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1290  Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1291  Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1292
1293  // Branch in case of overflow.
1294  llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1295  llvm::BasicBlock *overflowBB =
1296    CGF.createBasicBlock("overflow", CGF.CurFn);
1297  llvm::BasicBlock *continueBB =
1298    CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1299
1300  Builder.CreateCondBr(overflow, overflowBB, continueBB);
1301
1302  // Handle overflow
1303
1304  Builder.SetInsertPoint(overflowBB);
1305
1306  // Handler is:
1307  // long long *__overflow_handler)(long long a, long long b, char op,
1308  // char width)
1309  std::vector<const llvm::Type*> handerArgTypes;
1310  handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1311  handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1312  handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1313  handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1314  llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1315      llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
1316  llvm::Value *handlerFunction =
1317    CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
1318        llvm::PointerType::getUnqual(handlerTy));
1319  handlerFunction = Builder.CreateLoad(handlerFunction);
1320
1321  llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
1322      Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1323      Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1324      llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
1325      llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
1326        cast<llvm::IntegerType>(opTy)->getBitWidth()));
1327
1328  handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1329
1330  Builder.CreateBr(continueBB);
1331
1332  // Set up the continuation
1333  Builder.SetInsertPoint(continueBB);
1334  // Get the correct result
1335  llvm::PHINode *phi = Builder.CreatePHI(opTy);
1336  phi->reserveOperandSpace(2);
1337  phi->addIncoming(result, initialBB);
1338  phi->addIncoming(handlerResult, overflowBB);
1339
1340  return phi;
1341}
1342
1343Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1344  if (!Ops.Ty->isAnyPointerType()) {
1345    if (CGF.getContext().getLangOptions().OverflowChecking &&
1346        Ops.Ty->isSignedIntegerType())
1347      return EmitOverflowCheckedBinOp(Ops);
1348
1349    if (Ops.LHS->getType()->isFPOrFPVector())
1350      return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1351
1352    // Signed integer overflow is undefined behavior.
1353    if (Ops.Ty->isSignedIntegerType())
1354      return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1355
1356    return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1357  }
1358
1359  if (Ops.Ty->isPointerType() &&
1360      Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1361    // The amount of the addition needs to account for the VLA size
1362    CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1363  }
1364  Value *Ptr, *Idx;
1365  Expr *IdxExp;
1366  const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
1367  const ObjCObjectPointerType *OPT =
1368    Ops.E->getLHS()->getType()->getAs<ObjCObjectPointerType>();
1369  if (PT || OPT) {
1370    Ptr = Ops.LHS;
1371    Idx = Ops.RHS;
1372    IdxExp = Ops.E->getRHS();
1373  } else {  // int + pointer
1374    PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
1375    OPT = Ops.E->getRHS()->getType()->getAs<ObjCObjectPointerType>();
1376    assert((PT || OPT) && "Invalid add expr");
1377    Ptr = Ops.RHS;
1378    Idx = Ops.LHS;
1379    IdxExp = Ops.E->getLHS();
1380  }
1381
1382  unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1383  if (Width < CGF.LLVMPointerWidth) {
1384    // Zero or sign extend the pointer value based on whether the index is
1385    // signed or not.
1386    const llvm::Type *IdxType =
1387        llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
1388    if (IdxExp->getType()->isSignedIntegerType())
1389      Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1390    else
1391      Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1392  }
1393  const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1394  // Handle interface types, which are not represented with a concrete type.
1395  if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1396    llvm::Value *InterfaceSize =
1397      llvm::ConstantInt::get(Idx->getType(),
1398                             CGF.getContext().getTypeSize(OIT) / 8);
1399    Idx = Builder.CreateMul(Idx, InterfaceSize);
1400    const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1401    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1402    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1403    return Builder.CreateBitCast(Res, Ptr->getType());
1404  }
1405
1406  // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1407  // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1408  // future proof.
1409  if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1410    const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1411    Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1412    Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1413    return Builder.CreateBitCast(Res, Ptr->getType());
1414  }
1415
1416  return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1417}
1418
1419Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1420  if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1421    if (CGF.getContext().getLangOptions().OverflowChecking
1422        && Ops.Ty->isSignedIntegerType())
1423      return EmitOverflowCheckedBinOp(Ops);
1424
1425    if (Ops.LHS->getType()->isFPOrFPVector())
1426      return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1427    return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1428  }
1429
1430  if (Ops.E->getLHS()->getType()->isPointerType() &&
1431      Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1432    // The amount of the addition needs to account for the VLA size for
1433    // ptr-int
1434    // The amount of the division needs to account for the VLA size for
1435    // ptr-ptr.
1436    CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1437  }
1438
1439  const QualType LHSType = Ops.E->getLHS()->getType();
1440  const QualType LHSElementType = LHSType->getPointeeType();
1441  if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1442    // pointer - int
1443    Value *Idx = Ops.RHS;
1444    unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1445    if (Width < CGF.LLVMPointerWidth) {
1446      // Zero or sign extend the pointer value based on whether the index is
1447      // signed or not.
1448      const llvm::Type *IdxType =
1449          llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
1450      if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1451        Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1452      else
1453        Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1454    }
1455    Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1456
1457    // Handle interface types, which are not represented with a concrete type.
1458    if (const ObjCInterfaceType *OIT =
1459        dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1460      llvm::Value *InterfaceSize =
1461        llvm::ConstantInt::get(Idx->getType(),
1462                               CGF.getContext().getTypeSize(OIT) / 8);
1463      Idx = Builder.CreateMul(Idx, InterfaceSize);
1464      const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1465      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1466      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1467      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1468    }
1469
1470    // Explicitly handle GNU void* and function pointer arithmetic
1471    // extensions. The GNU void* casts amount to no-ops since our void* type is
1472    // i8*, but this is future proof.
1473    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1474      const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1475      Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1476      Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1477      return Builder.CreateBitCast(Res, Ops.LHS->getType());
1478    }
1479
1480    return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1481  } else {
1482    // pointer - pointer
1483    Value *LHS = Ops.LHS;
1484    Value *RHS = Ops.RHS;
1485
1486    uint64_t ElementSize;
1487
1488    // Handle GCC extension for pointer arithmetic on void* and function pointer
1489    // types.
1490    if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1491      ElementSize = 1;
1492    } else {
1493      ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1494    }
1495
1496    const llvm::Type *ResultType = ConvertType(Ops.Ty);
1497    LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1498    RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1499    Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1500
1501    // Optimize out the shift for element size of 1.
1502    if (ElementSize == 1)
1503      return BytesBetween;
1504
1505    // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1506    // pointer difference in C is only defined in the case where both operands
1507    // are pointing to elements of an array.
1508    Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
1509    return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
1510  }
1511}
1512
1513Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1514  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1515  // RHS to the same size as the LHS.
1516  Value *RHS = Ops.RHS;
1517  if (Ops.LHS->getType() != RHS->getType())
1518    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1519
1520  return Builder.CreateShl(Ops.LHS, RHS, "shl");
1521}
1522
1523Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1524  // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1525  // RHS to the same size as the LHS.
1526  Value *RHS = Ops.RHS;
1527  if (Ops.LHS->getType() != RHS->getType())
1528    RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1529
1530  if (Ops.Ty->isUnsignedIntegerType())
1531    return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1532  return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1533}
1534
1535Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1536                                      unsigned SICmpOpc, unsigned FCmpOpc) {
1537  TestAndClearIgnoreResultAssign();
1538  Value *Result;
1539  QualType LHSTy = E->getLHS()->getType();
1540  if (!LHSTy->isAnyComplexType()) {
1541    Value *LHS = Visit(E->getLHS());
1542    Value *RHS = Visit(E->getRHS());
1543
1544    if (LHS->getType()->isFPOrFPVector()) {
1545      Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1546                                  LHS, RHS, "cmp");
1547    } else if (LHSTy->isSignedIntegerType()) {
1548      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1549                                  LHS, RHS, "cmp");
1550    } else {
1551      // Unsigned integers and pointers.
1552      Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1553                                  LHS, RHS, "cmp");
1554    }
1555
1556    // If this is a vector comparison, sign extend the result to the appropriate
1557    // vector integer type and return it (don't convert to bool).
1558    if (LHSTy->isVectorType())
1559      return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1560
1561  } else {
1562    // Complex Comparison: can only be an equality comparison.
1563    CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1564    CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1565
1566    QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
1567
1568    Value *ResultR, *ResultI;
1569    if (CETy->isRealFloatingType()) {
1570      ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1571                                   LHS.first, RHS.first, "cmp.r");
1572      ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1573                                   LHS.second, RHS.second, "cmp.i");
1574    } else {
1575      // Complex comparisons can only be equality comparisons.  As such, signed
1576      // and unsigned opcodes are the same.
1577      ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1578                                   LHS.first, RHS.first, "cmp.r");
1579      ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1580                                   LHS.second, RHS.second, "cmp.i");
1581    }
1582
1583    if (E->getOpcode() == BinaryOperator::EQ) {
1584      Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1585    } else {
1586      assert(E->getOpcode() == BinaryOperator::NE &&
1587             "Complex comparison other than == or != ?");
1588      Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1589    }
1590  }
1591
1592  return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
1593}
1594
1595Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1596  bool Ignore = TestAndClearIgnoreResultAssign();
1597
1598  // __block variables need to have the rhs evaluated first, plus this should
1599  // improve codegen just a little.
1600  Value *RHS = Visit(E->getRHS());
1601  LValue LHS = EmitLValue(E->getLHS());
1602
1603  // Store the value into the LHS.  Bit-fields are handled specially
1604  // because the result is altered by the store, i.e., [C99 6.5.16p1]
1605  // 'An assignment expression has the value of the left operand after
1606  // the assignment...'.
1607  if (LHS.isBitfield()) {
1608    if (!LHS.isVolatileQualified()) {
1609      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1610                                         &RHS);
1611      return RHS;
1612    } else
1613      CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1614  } else
1615    CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1616  if (Ignore)
1617    return 0;
1618  return EmitLoadOfLValue(LHS, E->getType());
1619}
1620
1621Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1622  const llvm::Type *ResTy = ConvertType(E->getType());
1623
1624  // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1625  // If we have 1 && X, just emit X without inserting the control flow.
1626  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1627    if (Cond == 1) { // If we have 1 && X, just emit X.
1628      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1629      // ZExt result to int or bool.
1630      return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
1631    }
1632
1633    // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
1634    if (!CGF.ContainsLabel(E->getRHS()))
1635      return llvm::Constant::getNullValue(ResTy);
1636  }
1637
1638  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1639  llvm::BasicBlock *RHSBlock  = CGF.createBasicBlock("land.rhs");
1640
1641  // Branch on the LHS first.  If it is false, go to the failure (cont) block.
1642  CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1643
1644  // Any edges into the ContBlock are now from an (indeterminate number of)
1645  // edges from this first condition.  All of these values will be false.  Start
1646  // setting up the PHI node in the Cont Block for this.
1647  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1648                                            "", ContBlock);
1649  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1650  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1651       PI != PE; ++PI)
1652    PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
1653
1654  CGF.StartConditionalBranch();
1655  CGF.EmitBlock(RHSBlock);
1656  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1657  CGF.FinishConditionalBranch();
1658
1659  // Reaquire the RHS block, as there may be subblocks inserted.
1660  RHSBlock = Builder.GetInsertBlock();
1661
1662  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1663  // into the phi node for the edge with the value of RHSCond.
1664  CGF.EmitBlock(ContBlock);
1665  PN->addIncoming(RHSCond, RHSBlock);
1666
1667  // ZExt result to int.
1668  return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
1669}
1670
1671Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1672  const llvm::Type *ResTy = ConvertType(E->getType());
1673
1674  // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1675  // If we have 0 || X, just emit X without inserting the control flow.
1676  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1677    if (Cond == -1) { // If we have 0 || X, just emit X.
1678      Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1679      // ZExt result to int or bool.
1680      return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
1681    }
1682
1683    // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
1684    if (!CGF.ContainsLabel(E->getRHS()))
1685      return llvm::ConstantInt::get(ResTy, 1);
1686  }
1687
1688  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1689  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1690
1691  // Branch on the LHS first.  If it is true, go to the success (cont) block.
1692  CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1693
1694  // Any edges into the ContBlock are now from an (indeterminate number of)
1695  // edges from this first condition.  All of these values will be true.  Start
1696  // setting up the PHI node in the Cont Block for this.
1697  llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1698                                            "", ContBlock);
1699  PN->reserveOperandSpace(2);  // Normal case, two inputs.
1700  for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1701       PI != PE; ++PI)
1702    PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
1703
1704  CGF.StartConditionalBranch();
1705
1706  // Emit the RHS condition as a bool value.
1707  CGF.EmitBlock(RHSBlock);
1708  Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1709
1710  CGF.FinishConditionalBranch();
1711
1712  // Reaquire the RHS block, as there may be subblocks inserted.
1713  RHSBlock = Builder.GetInsertBlock();
1714
1715  // Emit an unconditional branch from this block to ContBlock.  Insert an entry
1716  // into the phi node for the edge with the value of RHSCond.
1717  CGF.EmitBlock(ContBlock);
1718  PN->addIncoming(RHSCond, RHSBlock);
1719
1720  // ZExt result to int.
1721  return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
1722}
1723
1724Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1725  CGF.EmitStmt(E->getLHS());
1726  CGF.EnsureInsertPoint();
1727  return Visit(E->getRHS());
1728}
1729
1730//===----------------------------------------------------------------------===//
1731//                             Other Operators
1732//===----------------------------------------------------------------------===//
1733
1734/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1735/// expression is cheap enough and side-effect-free enough to evaluate
1736/// unconditionally instead of conditionally.  This is used to convert control
1737/// flow into selects in some cases.
1738static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
1739                                                   CodeGenFunction &CGF) {
1740  if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1741    return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
1742
1743  // TODO: Allow anything we can constant fold to an integer or fp constant.
1744  if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1745      isa<FloatingLiteral>(E))
1746    return true;
1747
1748  // Non-volatile automatic variables too, to get "cond ? X : Y" where
1749  // X and Y are local variables.
1750  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1751    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1752      if (VD->hasLocalStorage() && !(CGF.getContext()
1753                                     .getCanonicalType(VD->getType())
1754                                     .isVolatileQualified()))
1755        return true;
1756
1757  return false;
1758}
1759
1760
1761Value *ScalarExprEmitter::
1762VisitConditionalOperator(const ConditionalOperator *E) {
1763  TestAndClearIgnoreResultAssign();
1764  // If the condition constant folds and can be elided, try to avoid emitting
1765  // the condition and the dead arm.
1766  if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
1767    Expr *Live = E->getLHS(), *Dead = E->getRHS();
1768    if (Cond == -1)
1769      std::swap(Live, Dead);
1770
1771    // If the dead side doesn't have labels we need, and if the Live side isn't
1772    // the gnu missing ?: extension (which we could handle, but don't bother
1773    // to), just emit the Live part.
1774    if ((!Dead || !CGF.ContainsLabel(Dead)) &&  // No labels in dead part
1775        Live)                                   // Live part isn't missing.
1776      return Visit(Live);
1777  }
1778
1779
1780  // If this is a really simple expression (like x ? 4 : 5), emit this as a
1781  // select instead of as control flow.  We can only do this if it is cheap and
1782  // safe to evaluate the LHS and RHS unconditionally.
1783  if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
1784                                                            CGF) &&
1785      isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
1786    llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1787    llvm::Value *LHS = Visit(E->getLHS());
1788    llvm::Value *RHS = Visit(E->getRHS());
1789    return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1790  }
1791
1792
1793  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1794  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1795  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1796  Value *CondVal = 0;
1797
1798  // If we don't have the GNU missing condition extension, emit a branch on bool
1799  // the normal way.
1800  if (E->getLHS()) {
1801    // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1802    // the branch on bool.
1803    CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1804  } else {
1805    // Otherwise, for the ?: extension, evaluate the conditional and then
1806    // convert it to bool the hard way.  We do this explicitly because we need
1807    // the unconverted value for the missing middle value of the ?:.
1808    CondVal = CGF.EmitScalarExpr(E->getCond());
1809
1810    // In some cases, EmitScalarConversion will delete the "CondVal" expression
1811    // if there are no extra uses (an optimization).  Inhibit this by making an
1812    // extra dead use, because we're going to add a use of CondVal later.  We
1813    // don't use the builder for this, because we don't want it to get optimized
1814    // away.  This leaves dead code, but the ?: extension isn't common.
1815    new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1816                          Builder.GetInsertBlock());
1817
1818    Value *CondBoolVal =
1819      CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1820                               CGF.getContext().BoolTy);
1821    Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
1822  }
1823
1824  CGF.StartConditionalBranch();
1825  CGF.EmitBlock(LHSBlock);
1826
1827  // Handle the GNU extension for missing LHS.
1828  Value *LHS;
1829  if (E->getLHS())
1830    LHS = Visit(E->getLHS());
1831  else    // Perform promotions, to handle cases like "short ?: int"
1832    LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1833
1834  CGF.FinishConditionalBranch();
1835  LHSBlock = Builder.GetInsertBlock();
1836  CGF.EmitBranch(ContBlock);
1837
1838  CGF.StartConditionalBranch();
1839  CGF.EmitBlock(RHSBlock);
1840
1841  Value *RHS = Visit(E->getRHS());
1842  CGF.FinishConditionalBranch();
1843  RHSBlock = Builder.GetInsertBlock();
1844  CGF.EmitBranch(ContBlock);
1845
1846  CGF.EmitBlock(ContBlock);
1847
1848  if (!LHS || !RHS) {
1849    assert(E->getType()->isVoidType() && "Non-void value should have a value");
1850    return 0;
1851  }
1852
1853  // Create a PHI node for the real part.
1854  llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1855  PN->reserveOperandSpace(2);
1856  PN->addIncoming(LHS, LHSBlock);
1857  PN->addIncoming(RHS, RHSBlock);
1858  return PN;
1859}
1860
1861Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1862  return Visit(E->getChosenSubExpr(CGF.getContext()));
1863}
1864
1865Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1866  llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
1867  llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1868
1869  // If EmitVAArg fails, we fall back to the LLVM instruction.
1870  if (!ArgPtr)
1871    return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1872
1873  // FIXME Volatility.
1874  return Builder.CreateLoad(ArgPtr);
1875}
1876
1877Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
1878  return CGF.BuildBlockLiteralTmp(BE);
1879}
1880
1881//===----------------------------------------------------------------------===//
1882//                         Entry Point into this File
1883//===----------------------------------------------------------------------===//
1884
1885/// EmitScalarExpr - Emit the computation of the specified expression of scalar
1886/// type, ignoring the result.
1887Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
1888  assert(E && !hasAggregateLLVMType(E->getType()) &&
1889         "Invalid scalar expression to emit");
1890
1891  return ScalarExprEmitter(*this, IgnoreResultAssign)
1892    .Visit(const_cast<Expr*>(E));
1893}
1894
1895/// EmitScalarConversion - Emit a conversion from the specified type to the
1896/// specified destination type, both of which are LLVM scalar types.
1897Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1898                                             QualType DstTy) {
1899  assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1900         "Invalid scalar expression to emit");
1901  return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1902}
1903
1904/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
1905/// type to the specified destination type, where the destination type is an
1906/// LLVM scalar type.
1907Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1908                                                      QualType SrcTy,
1909                                                      QualType DstTy) {
1910  assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
1911         "Invalid complex -> scalar conversion");
1912  return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1913                                                                DstTy);
1914}
1915
1916Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1917  assert(V1->getType() == V2->getType() &&
1918         "Vector operands must be of the same type");
1919  unsigned NumElements =
1920    cast<llvm::VectorType>(V1->getType())->getNumElements();
1921
1922  va_list va;
1923  va_start(va, V2);
1924
1925  llvm::SmallVector<llvm::Constant*, 16> Args;
1926  for (unsigned i = 0; i < NumElements; i++) {
1927    int n = va_arg(va, int);
1928    assert(n >= 0 && n < (int)NumElements * 2 &&
1929           "Vector shuffle index out of bounds!");
1930    Args.push_back(llvm::ConstantInt::get(
1931                                         llvm::Type::getInt32Ty(VMContext), n));
1932  }
1933
1934  const char *Name = va_arg(va, const char *);
1935  va_end(va);
1936
1937  llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1938
1939  return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1940}
1941
1942llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1943                                         unsigned NumVals, bool isSplat) {
1944  llvm::Value *Vec
1945    = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1946
1947  for (unsigned i = 0, e = NumVals; i != e; ++i) {
1948    llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1949    llvm::Value *Idx = llvm::ConstantInt::get(
1950                                          llvm::Type::getInt32Ty(VMContext), i);
1951    Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
1952  }
1953
1954  return Vec;
1955}
1956