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