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