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