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