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