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