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