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