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