Home | History | Annotate | Download | only in X86
      1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
      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 file defines the interfaces that X86 uses to lower LLVM code into a
     11 // selection DAG.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #define DEBUG_TYPE "x86-isel"
     16 #include "X86ISelLowering.h"
     17 #include "Utils/X86ShuffleDecode.h"
     18 #include "X86.h"
     19 #include "X86InstrBuilder.h"
     20 #include "X86TargetMachine.h"
     21 #include "X86TargetObjectFile.h"
     22 #include "llvm/ADT/SmallSet.h"
     23 #include "llvm/ADT/Statistic.h"
     24 #include "llvm/ADT/StringExtras.h"
     25 #include "llvm/ADT/VariadicFunction.h"
     26 #include "llvm/CodeGen/IntrinsicLowering.h"
     27 #include "llvm/CodeGen/MachineFrameInfo.h"
     28 #include "llvm/CodeGen/MachineFunction.h"
     29 #include "llvm/CodeGen/MachineInstrBuilder.h"
     30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
     31 #include "llvm/CodeGen/MachineModuleInfo.h"
     32 #include "llvm/CodeGen/MachineRegisterInfo.h"
     33 #include "llvm/IR/CallingConv.h"
     34 #include "llvm/IR/Constants.h"
     35 #include "llvm/IR/DerivedTypes.h"
     36 #include "llvm/IR/Function.h"
     37 #include "llvm/IR/GlobalAlias.h"
     38 #include "llvm/IR/GlobalVariable.h"
     39 #include "llvm/IR/Instructions.h"
     40 #include "llvm/IR/Intrinsics.h"
     41 #include "llvm/IR/LLVMContext.h"
     42 #include "llvm/MC/MCAsmInfo.h"
     43 #include "llvm/MC/MCContext.h"
     44 #include "llvm/MC/MCExpr.h"
     45 #include "llvm/MC/MCSymbol.h"
     46 #include "llvm/Support/CallSite.h"
     47 #include "llvm/Support/Debug.h"
     48 #include "llvm/Support/ErrorHandling.h"
     49 #include "llvm/Support/MathExtras.h"
     50 #include "llvm/Target/TargetOptions.h"
     51 #include <bitset>
     52 #include <cctype>
     53 using namespace llvm;
     54 
     55 STATISTIC(NumTailCalls, "Number of tail calls");
     56 
     57 // Forward declarations.
     58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
     59                        SDValue V2);
     60 
     61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
     62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
     63 /// simple subregister reference.  Idx is an index in the 128 bits we
     64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
     65 /// lowering EXTRACT_VECTOR_ELT operations easier.
     66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
     67                                    SelectionDAG &DAG, DebugLoc dl) {
     68   EVT VT = Vec.getValueType();
     69   assert(VT.is256BitVector() && "Unexpected vector size!");
     70   EVT ElVT = VT.getVectorElementType();
     71   unsigned Factor = VT.getSizeInBits()/128;
     72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
     73                                   VT.getVectorNumElements()/Factor);
     74 
     75   // Extract from UNDEF is UNDEF.
     76   if (Vec.getOpcode() == ISD::UNDEF)
     77     return DAG.getUNDEF(ResultVT);
     78 
     79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
     80   // we can match to VEXTRACTF128.
     81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
     82 
     83   // This is the index of the first element of the 128-bit chunk
     84   // we want.
     85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
     86                                * ElemsPerChunk);
     87 
     88   // If the input is a buildvector just emit a smaller one.
     89   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
     90     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
     91                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
     92 
     93   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
     94   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
     95                                VecIdx);
     96 
     97   return Result;
     98 }
     99 
    100 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
    101 /// sets things up to match to an AVX VINSERTF128 instruction or a
    102 /// simple superregister reference.  Idx is an index in the 128 bits
    103 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
    104 /// lowering INSERT_VECTOR_ELT operations easier.
    105 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
    106                                   unsigned IdxVal, SelectionDAG &DAG,
    107                                   DebugLoc dl) {
    108   // Inserting UNDEF is Result
    109   if (Vec.getOpcode() == ISD::UNDEF)
    110     return Result;
    111 
    112   EVT VT = Vec.getValueType();
    113   assert(VT.is128BitVector() && "Unexpected vector size!");
    114 
    115   EVT ElVT = VT.getVectorElementType();
    116   EVT ResultVT = Result.getValueType();
    117 
    118   // Insert the relevant 128 bits.
    119   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
    120 
    121   // This is the index of the first element of the 128-bit chunk
    122   // we want.
    123   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
    124                                * ElemsPerChunk);
    125 
    126   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
    127   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
    128                      VecIdx);
    129 }
    130 
    131 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
    132 /// instructions. This is used because creating CONCAT_VECTOR nodes of
    133 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
    134 /// large BUILD_VECTORS.
    135 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
    136                                    unsigned NumElems, SelectionDAG &DAG,
    137                                    DebugLoc dl) {
    138   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
    139   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
    140 }
    141 
    142 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
    143   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
    144   bool is64Bit = Subtarget->is64Bit();
    145 
    146   if (Subtarget->isTargetEnvMacho()) {
    147     if (is64Bit)
    148       return new X86_64MachoTargetObjectFile();
    149     return new TargetLoweringObjectFileMachO();
    150   }
    151 
    152   if (Subtarget->isTargetLinux())
    153     return new X86LinuxTargetObjectFile();
    154   if (Subtarget->isTargetELF())
    155     return new TargetLoweringObjectFileELF();
    156   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
    157     return new TargetLoweringObjectFileCOFF();
    158   llvm_unreachable("unknown subtarget type");
    159 }
    160 
    161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
    162   : TargetLowering(TM, createTLOF(TM)) {
    163   Subtarget = &TM.getSubtarget<X86Subtarget>();
    164   X86ScalarSSEf64 = Subtarget->hasSSE2();
    165   X86ScalarSSEf32 = Subtarget->hasSSE1();
    166 
    167   RegInfo = TM.getRegisterInfo();
    168   TD = getDataLayout();
    169 
    170   // Set up the TargetLowering object.
    171   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
    172 
    173   // X86 is weird, it always uses i8 for shift amounts and setcc results.
    174   setBooleanContents(ZeroOrOneBooleanContent);
    175   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
    176   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
    177 
    178   // For 64-bit since we have so many registers use the ILP scheduler, for
    179   // 32-bit code use the register pressure specific scheduling.
    180   // For Atom, always use ILP scheduling.
    181   if (Subtarget->isAtom())
    182     setSchedulingPreference(Sched::ILP);
    183   else if (Subtarget->is64Bit())
    184     setSchedulingPreference(Sched::ILP);
    185   else
    186     setSchedulingPreference(Sched::RegPressure);
    187   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
    188 
    189   // Bypass expensive divides on Atom when compiling with O2
    190   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
    191     addBypassSlowDiv(32, 8);
    192     if (Subtarget->is64Bit())
    193       addBypassSlowDiv(64, 16);
    194   }
    195 
    196   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
    197     // Setup Windows compiler runtime calls.
    198     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
    199     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
    200     setLibcallName(RTLIB::SREM_I64, "_allrem");
    201     setLibcallName(RTLIB::UREM_I64, "_aullrem");
    202     setLibcallName(RTLIB::MUL_I64, "_allmul");
    203     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
    204     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
    205     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
    206     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
    207     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
    208 
    209     // The _ftol2 runtime function has an unusual calling conv, which
    210     // is modeled by a special pseudo-instruction.
    211     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
    212     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
    213     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
    214     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
    215   }
    216 
    217   if (Subtarget->isTargetDarwin()) {
    218     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
    219     setUseUnderscoreSetJmp(false);
    220     setUseUnderscoreLongJmp(false);
    221   } else if (Subtarget->isTargetMingw()) {
    222     // MS runtime is weird: it exports _setjmp, but longjmp!
    223     setUseUnderscoreSetJmp(true);
    224     setUseUnderscoreLongJmp(false);
    225   } else {
    226     setUseUnderscoreSetJmp(true);
    227     setUseUnderscoreLongJmp(true);
    228   }
    229 
    230   // Set up the register classes.
    231   addRegisterClass(MVT::i8, &X86::GR8RegClass);
    232   addRegisterClass(MVT::i16, &X86::GR16RegClass);
    233   addRegisterClass(MVT::i32, &X86::GR32RegClass);
    234   if (Subtarget->is64Bit())
    235     addRegisterClass(MVT::i64, &X86::GR64RegClass);
    236 
    237   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
    238 
    239   // We don't accept any truncstore of integer registers.
    240   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
    241   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
    242   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
    243   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
    244   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
    245   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
    246 
    247   // SETOEQ and SETUNE require checking two conditions.
    248   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
    249   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
    250   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
    251   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
    252   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
    253   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
    254 
    255   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
    256   // operation.
    257   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
    258   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
    259   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
    260 
    261   if (Subtarget->is64Bit()) {
    262     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
    263     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
    264   } else if (!TM.Options.UseSoftFloat) {
    265     // We have an algorithm for SSE2->double, and we turn this into a
    266     // 64-bit FILD followed by conditional FADD for other targets.
    267     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
    268     // We have an algorithm for SSE2, and we turn this into a 64-bit
    269     // FILD for other targets.
    270     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
    271   }
    272 
    273   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
    274   // this operation.
    275   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
    276   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
    277 
    278   if (!TM.Options.UseSoftFloat) {
    279     // SSE has no i16 to fp conversion, only i32
    280     if (X86ScalarSSEf32) {
    281       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
    282       // f32 and f64 cases are Legal, f80 case is not
    283       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
    284     } else {
    285       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
    286       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
    287     }
    288   } else {
    289     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
    290     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
    291   }
    292 
    293   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
    294   // are Legal, f80 is custom lowered.
    295   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
    296   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
    297 
    298   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
    299   // this operation.
    300   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
    301   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
    302 
    303   if (X86ScalarSSEf32) {
    304     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
    305     // f32 and f64 cases are Legal, f80 case is not
    306     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
    307   } else {
    308     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
    309     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
    310   }
    311 
    312   // Handle FP_TO_UINT by promoting the destination to a larger signed
    313   // conversion.
    314   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
    315   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
    316   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
    317 
    318   if (Subtarget->is64Bit()) {
    319     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
    320     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
    321   } else if (!TM.Options.UseSoftFloat) {
    322     // Since AVX is a superset of SSE3, only check for SSE here.
    323     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
    324       // Expand FP_TO_UINT into a select.
    325       // FIXME: We would like to use a Custom expander here eventually to do
    326       // the optimal thing for SSE vs. the default expansion in the legalizer.
    327       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
    328     else
    329       // With SSE3 we can use fisttpll to convert to a signed i64; without
    330       // SSE, we're stuck with a fistpll.
    331       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
    332   }
    333 
    334   if (isTargetFTOL()) {
    335     // Use the _ftol2 runtime function, which has a pseudo-instruction
    336     // to handle its weird calling convention.
    337     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
    338   }
    339 
    340   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
    341   if (!X86ScalarSSEf64) {
    342     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
    343     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
    344     if (Subtarget->is64Bit()) {
    345       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
    346       // Without SSE, i64->f64 goes through memory.
    347       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
    348     }
    349   }
    350 
    351   // Scalar integer divide and remainder are lowered to use operations that
    352   // produce two results, to match the available instructions. This exposes
    353   // the two-result form to trivial CSE, which is able to combine x/y and x%y
    354   // into a single instruction.
    355   //
    356   // Scalar integer multiply-high is also lowered to use two-result
    357   // operations, to match the available instructions. However, plain multiply
    358   // (low) operations are left as Legal, as there are single-result
    359   // instructions for this in x86. Using the two-result multiply instructions
    360   // when both high and low results are needed must be arranged by dagcombine.
    361   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
    362     MVT VT = IntVTs[i];
    363     setOperationAction(ISD::MULHS, VT, Expand);
    364     setOperationAction(ISD::MULHU, VT, Expand);
    365     setOperationAction(ISD::SDIV, VT, Expand);
    366     setOperationAction(ISD::UDIV, VT, Expand);
    367     setOperationAction(ISD::SREM, VT, Expand);
    368     setOperationAction(ISD::UREM, VT, Expand);
    369 
    370     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
    371     setOperationAction(ISD::ADDC, VT, Custom);
    372     setOperationAction(ISD::ADDE, VT, Custom);
    373     setOperationAction(ISD::SUBC, VT, Custom);
    374     setOperationAction(ISD::SUBE, VT, Custom);
    375   }
    376 
    377   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
    378   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
    379   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
    380   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
    381   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
    382   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
    383   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
    384   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
    385   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
    386   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
    387   if (Subtarget->is64Bit())
    388     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
    389   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
    390   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
    391   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
    392   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
    393   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
    394   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
    395   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
    396   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
    397 
    398   // Promote the i8 variants and force them on up to i32 which has a shorter
    399   // encoding.
    400   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
    401   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
    402   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
    403   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
    404   if (Subtarget->hasBMI()) {
    405     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
    406     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
    407     if (Subtarget->is64Bit())
    408       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
    409   } else {
    410     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
    411     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
    412     if (Subtarget->is64Bit())
    413       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
    414   }
    415 
    416   if (Subtarget->hasLZCNT()) {
    417     // When promoting the i8 variants, force them to i32 for a shorter
    418     // encoding.
    419     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
    420     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
    421     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
    422     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
    423     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
    424     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
    425     if (Subtarget->is64Bit())
    426       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
    427   } else {
    428     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
    429     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
    430     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
    431     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
    432     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
    433     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
    434     if (Subtarget->is64Bit()) {
    435       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
    436       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
    437     }
    438   }
    439 
    440   if (Subtarget->hasPOPCNT()) {
    441     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
    442   } else {
    443     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
    444     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
    445     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
    446     if (Subtarget->is64Bit())
    447       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
    448   }
    449 
    450   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
    451   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
    452 
    453   // These should be promoted to a larger select which is supported.
    454   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
    455   // X86 wants to expand cmov itself.
    456   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
    457   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
    458   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
    459   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
    460   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
    461   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
    462   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
    463   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
    464   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
    465   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
    466   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
    467   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
    468   if (Subtarget->is64Bit()) {
    469     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
    470     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
    471   }
    472   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
    473   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
    474   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
    475   // support continuation, user-level threading, and etc.. As a result, no
    476   // other SjLj exception interfaces are implemented and please don't build
    477   // your own exception handling based on them.
    478   // LLVM/Clang supports zero-cost DWARF exception handling.
    479   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
    480   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
    481 
    482   // Darwin ABI issue.
    483   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
    484   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
    485   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
    486   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
    487   if (Subtarget->is64Bit())
    488     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
    489   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
    490   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
    491   if (Subtarget->is64Bit()) {
    492     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
    493     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
    494     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
    495     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
    496     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
    497   }
    498   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
    499   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
    500   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
    501   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
    502   if (Subtarget->is64Bit()) {
    503     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
    504     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
    505     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
    506   }
    507 
    508   if (Subtarget->hasSSE1())
    509     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
    510 
    511   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
    512   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
    513 
    514   // On X86 and X86-64, atomic operations are lowered to locked instructions.
    515   // Locked instructions, in turn, have implicit fence semantics (all memory
    516   // operations are flushed before issuing the locked instruction, and they
    517   // are not buffered), so we can fold away the common pattern of
    518   // fence-atomic-fence.
    519   setShouldFoldAtomicFences(true);
    520 
    521   // Expand certain atomics
    522   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
    523     MVT VT = IntVTs[i];
    524     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
    525     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
    526     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
    527   }
    528 
    529   if (!Subtarget->is64Bit()) {
    530     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
    531     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
    532     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
    533     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
    534     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
    535     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
    536     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
    537     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
    538     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
    539     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
    540     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
    541     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
    542   }
    543 
    544   if (Subtarget->hasCmpxchg16b()) {
    545     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
    546   }
    547 
    548   // FIXME - use subtarget debug flags
    549   if (!Subtarget->isTargetDarwin() &&
    550       !Subtarget->isTargetELF() &&
    551       !Subtarget->isTargetCygMing()) {
    552     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
    553   }
    554 
    555   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
    556   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
    557   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
    558   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
    559   if (Subtarget->is64Bit()) {
    560     setExceptionPointerRegister(X86::RAX);
    561     setExceptionSelectorRegister(X86::RDX);
    562   } else {
    563     setExceptionPointerRegister(X86::EAX);
    564     setExceptionSelectorRegister(X86::EDX);
    565   }
    566   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
    567   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
    568 
    569   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
    570   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
    571 
    572   setOperationAction(ISD::TRAP, MVT::Other, Legal);
    573   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
    574 
    575   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
    576   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
    577   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
    578   if (Subtarget->is64Bit()) {
    579     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
    580     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
    581   } else {
    582     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
    583     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
    584   }
    585 
    586   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
    587   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
    588 
    589   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
    590     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
    591                        MVT::i64 : MVT::i32, Custom);
    592   else if (TM.Options.EnableSegmentedStacks)
    593     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
    594                        MVT::i64 : MVT::i32, Custom);
    595   else
    596     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
    597                        MVT::i64 : MVT::i32, Expand);
    598 
    599   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
    600     // f32 and f64 use SSE.
    601     // Set up the FP register classes.
    602     addRegisterClass(MVT::f32, &X86::FR32RegClass);
    603     addRegisterClass(MVT::f64, &X86::FR64RegClass);
    604 
    605     // Use ANDPD to simulate FABS.
    606     setOperationAction(ISD::FABS , MVT::f64, Custom);
    607     setOperationAction(ISD::FABS , MVT::f32, Custom);
    608 
    609     // Use XORP to simulate FNEG.
    610     setOperationAction(ISD::FNEG , MVT::f64, Custom);
    611     setOperationAction(ISD::FNEG , MVT::f32, Custom);
    612 
    613     // Use ANDPD and ORPD to simulate FCOPYSIGN.
    614     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
    615     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
    616 
    617     // Lower this to FGETSIGNx86 plus an AND.
    618     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
    619     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
    620 
    621     // We don't support sin/cos/fmod
    622     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
    623     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
    624     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
    625     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
    626     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
    627     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
    628 
    629     // Expand FP immediates into loads from the stack, except for the special
    630     // cases we handle.
    631     addLegalFPImmediate(APFloat(+0.0)); // xorpd
    632     addLegalFPImmediate(APFloat(+0.0f)); // xorps
    633   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
    634     // Use SSE for f32, x87 for f64.
    635     // Set up the FP register classes.
    636     addRegisterClass(MVT::f32, &X86::FR32RegClass);
    637     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
    638 
    639     // Use ANDPS to simulate FABS.
    640     setOperationAction(ISD::FABS , MVT::f32, Custom);
    641 
    642     // Use XORP to simulate FNEG.
    643     setOperationAction(ISD::FNEG , MVT::f32, Custom);
    644 
    645     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
    646 
    647     // Use ANDPS and ORPS to simulate FCOPYSIGN.
    648     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
    649     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
    650 
    651     // We don't support sin/cos/fmod
    652     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
    653     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
    654     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
    655 
    656     // Special cases we handle for FP constants.
    657     addLegalFPImmediate(APFloat(+0.0f)); // xorps
    658     addLegalFPImmediate(APFloat(+0.0)); // FLD0
    659     addLegalFPImmediate(APFloat(+1.0)); // FLD1
    660     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
    661     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
    662 
    663     if (!TM.Options.UnsafeFPMath) {
    664       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
    665       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
    666       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
    667     }
    668   } else if (!TM.Options.UseSoftFloat) {
    669     // f32 and f64 in x87.
    670     // Set up the FP register classes.
    671     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
    672     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
    673 
    674     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
    675     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
    676     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
    677     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
    678 
    679     if (!TM.Options.UnsafeFPMath) {
    680       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
    681       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
    682       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
    683       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
    684       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
    685       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
    686     }
    687     addLegalFPImmediate(APFloat(+0.0)); // FLD0
    688     addLegalFPImmediate(APFloat(+1.0)); // FLD1
    689     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
    690     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
    691     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
    692     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
    693     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
    694     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
    695   }
    696 
    697   // We don't support FMA.
    698   setOperationAction(ISD::FMA, MVT::f64, Expand);
    699   setOperationAction(ISD::FMA, MVT::f32, Expand);
    700 
    701   // Long double always uses X87.
    702   if (!TM.Options.UseSoftFloat) {
    703     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
    704     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
    705     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
    706     {
    707       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
    708       addLegalFPImmediate(TmpFlt);  // FLD0
    709       TmpFlt.changeSign();
    710       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
    711 
    712       bool ignored;
    713       APFloat TmpFlt2(+1.0);
    714       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
    715                       &ignored);
    716       addLegalFPImmediate(TmpFlt2);  // FLD1
    717       TmpFlt2.changeSign();
    718       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
    719     }
    720 
    721     if (!TM.Options.UnsafeFPMath) {
    722       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
    723       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
    724       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
    725     }
    726 
    727     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
    728     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
    729     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
    730     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
    731     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
    732     setOperationAction(ISD::FMA, MVT::f80, Expand);
    733   }
    734 
    735   // Always use a library call for pow.
    736   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
    737   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
    738   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
    739 
    740   setOperationAction(ISD::FLOG, MVT::f80, Expand);
    741   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
    742   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
    743   setOperationAction(ISD::FEXP, MVT::f80, Expand);
    744   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
    745 
    746   // First set operation action for all vector types to either promote
    747   // (for widening) or expand (for scalarization). Then we will selectively
    748   // turn on ones that can be effectively codegen'd.
    749   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
    750            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
    751     MVT VT = (MVT::SimpleValueType)i;
    752     setOperationAction(ISD::ADD , VT, Expand);
    753     setOperationAction(ISD::SUB , VT, Expand);
    754     setOperationAction(ISD::FADD, VT, Expand);
    755     setOperationAction(ISD::FNEG, VT, Expand);
    756     setOperationAction(ISD::FSUB, VT, Expand);
    757     setOperationAction(ISD::MUL , VT, Expand);
    758     setOperationAction(ISD::FMUL, VT, Expand);
    759     setOperationAction(ISD::SDIV, VT, Expand);
    760     setOperationAction(ISD::UDIV, VT, Expand);
    761     setOperationAction(ISD::FDIV, VT, Expand);
    762     setOperationAction(ISD::SREM, VT, Expand);
    763     setOperationAction(ISD::UREM, VT, Expand);
    764     setOperationAction(ISD::LOAD, VT, Expand);
    765     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
    766     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
    767     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
    768     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
    769     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
    770     setOperationAction(ISD::FABS, VT, Expand);
    771     setOperationAction(ISD::FSIN, VT, Expand);
    772     setOperationAction(ISD::FSINCOS, VT, Expand);
    773     setOperationAction(ISD::FCOS, VT, Expand);
    774     setOperationAction(ISD::FSINCOS, VT, Expand);
    775     setOperationAction(ISD::FREM, VT, Expand);
    776     setOperationAction(ISD::FMA,  VT, Expand);
    777     setOperationAction(ISD::FPOWI, VT, Expand);
    778     setOperationAction(ISD::FSQRT, VT, Expand);
    779     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
    780     setOperationAction(ISD::FFLOOR, VT, Expand);
    781     setOperationAction(ISD::FCEIL, VT, Expand);
    782     setOperationAction(ISD::FTRUNC, VT, Expand);
    783     setOperationAction(ISD::FRINT, VT, Expand);
    784     setOperationAction(ISD::FNEARBYINT, VT, Expand);
    785     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
    786     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
    787     setOperationAction(ISD::SDIVREM, VT, Expand);
    788     setOperationAction(ISD::UDIVREM, VT, Expand);
    789     setOperationAction(ISD::FPOW, VT, Expand);
    790     setOperationAction(ISD::CTPOP, VT, Expand);
    791     setOperationAction(ISD::CTTZ, VT, Expand);
    792     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
    793     setOperationAction(ISD::CTLZ, VT, Expand);
    794     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
    795     setOperationAction(ISD::SHL, VT, Expand);
    796     setOperationAction(ISD::SRA, VT, Expand);
    797     setOperationAction(ISD::SRL, VT, Expand);
    798     setOperationAction(ISD::ROTL, VT, Expand);
    799     setOperationAction(ISD::ROTR, VT, Expand);
    800     setOperationAction(ISD::BSWAP, VT, Expand);
    801     setOperationAction(ISD::SETCC, VT, Expand);
    802     setOperationAction(ISD::FLOG, VT, Expand);
    803     setOperationAction(ISD::FLOG2, VT, Expand);
    804     setOperationAction(ISD::FLOG10, VT, Expand);
    805     setOperationAction(ISD::FEXP, VT, Expand);
    806     setOperationAction(ISD::FEXP2, VT, Expand);
    807     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
    808     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
    809     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
    810     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
    811     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
    812     setOperationAction(ISD::TRUNCATE, VT, Expand);
    813     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
    814     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
    815     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
    816     setOperationAction(ISD::VSELECT, VT, Expand);
    817     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
    818              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
    819       setTruncStoreAction(VT,
    820                           (MVT::SimpleValueType)InnerVT, Expand);
    821     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
    822     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
    823     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
    824   }
    825 
    826   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
    827   // with -msoft-float, disable use of MMX as well.
    828   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
    829     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
    830     // No operations on x86mmx supported, everything uses intrinsics.
    831   }
    832 
    833   // MMX-sized vectors (other than x86mmx) are expected to be expanded
    834   // into smaller operations.
    835   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
    836   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
    837   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
    838   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
    839   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
    840   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
    841   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
    842   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
    843   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
    844   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
    845   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
    846   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
    847   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
    848   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
    849   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
    850   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
    851   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
    852   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
    853   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
    854   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
    855   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
    856   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
    857   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
    858   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
    859   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
    860   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
    861   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
    862   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
    863   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
    864 
    865   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
    866     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
    867 
    868     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
    869     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
    870     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
    871     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
    872     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
    873     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
    874     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
    875     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
    876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
    877     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
    878     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
    879     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
    880   }
    881 
    882   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
    883     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
    884 
    885     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
    886     // registers cannot be used even for integer operations.
    887     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
    888     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
    889     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
    890     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
    891 
    892     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
    893     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
    894     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
    895     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
    896     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
    897     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
    898     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
    899     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
    900     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
    901     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
    902     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
    903     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
    904     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
    905     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
    906     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
    907     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
    908     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
    909     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
    910 
    911     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
    912     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
    913     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
    914     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
    915 
    916     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
    917     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
    918     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
    919     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
    920     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
    921 
    922     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
    923     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
    924       MVT VT = (MVT::SimpleValueType)i;
    925       // Do not attempt to custom lower non-power-of-2 vectors
    926       if (!isPowerOf2_32(VT.getVectorNumElements()))
    927         continue;
    928       // Do not attempt to custom lower non-128-bit vectors
    929       if (!VT.is128BitVector())
    930         continue;
    931       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
    932       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
    933       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
    934     }
    935 
    936     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
    937     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
    938     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
    939     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
    940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
    941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
    942 
    943     if (Subtarget->is64Bit()) {
    944       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
    945       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
    946     }
    947 
    948     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
    949     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
    950       MVT VT = (MVT::SimpleValueType)i;
    951 
    952       // Do not attempt to promote non-128-bit vectors
    953       if (!VT.is128BitVector())
    954         continue;
    955 
    956       setOperationAction(ISD::AND,    VT, Promote);
    957       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
    958       setOperationAction(ISD::OR,     VT, Promote);
    959       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
    960       setOperationAction(ISD::XOR,    VT, Promote);
    961       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
    962       setOperationAction(ISD::LOAD,   VT, Promote);
    963       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
    964       setOperationAction(ISD::SELECT, VT, Promote);
    965       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
    966     }
    967 
    968     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
    969 
    970     // Custom lower v2i64 and v2f64 selects.
    971     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
    972     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
    973     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
    974     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
    975 
    976     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
    977     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
    978 
    979     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
    980     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
    981     // As there is no 64-bit GPR available, we need build a special custom
    982     // sequence to convert from v2i32 to v2f32.
    983     if (!Subtarget->is64Bit())
    984       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
    985 
    986     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
    987     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
    988 
    989     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
    990   }
    991 
    992   if (Subtarget->hasSSE41()) {
    993     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
    994     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
    995     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
    996     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
    997     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
    998     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
    999     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
   1000     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
   1001     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
   1002     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
   1003 
   1004     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
   1005     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
   1006     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
   1007     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
   1008     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
   1009     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
   1010     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
   1011     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
   1012     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
   1013     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
   1014 
   1015     // FIXME: Do we need to handle scalar-to-vector here?
   1016     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
   1017 
   1018     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
   1019     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
   1020     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
   1021     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
   1022     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
   1023 
   1024     // i8 and i16 vectors are custom , because the source register and source
   1025     // source memory operand types are not the same width.  f32 vectors are
   1026     // custom since the immediate controlling the insert encodes additional
   1027     // information.
   1028     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
   1029     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
   1030     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
   1031     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
   1032 
   1033     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
   1034     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
   1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
   1036     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
   1037 
   1038     // FIXME: these should be Legal but thats only for the case where
   1039     // the index is constant.  For now custom expand to deal with that.
   1040     if (Subtarget->is64Bit()) {
   1041       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
   1042       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
   1043     }
   1044   }
   1045 
   1046   if (Subtarget->hasSSE2()) {
   1047     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
   1048     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
   1049 
   1050     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
   1051     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
   1052 
   1053     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
   1054     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
   1055 
   1056     if (Subtarget->hasInt256()) {
   1057       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
   1058       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
   1059 
   1060       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
   1061       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
   1062 
   1063       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
   1064     } else {
   1065       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
   1066       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
   1067 
   1068       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
   1069       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
   1070 
   1071       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
   1072     }
   1073     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
   1074     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
   1075   }
   1076 
   1077   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
   1078     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
   1079     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
   1080     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
   1081     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
   1082     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
   1083     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
   1084 
   1085     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
   1086     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
   1087     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
   1088 
   1089     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
   1090     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
   1091     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
   1092     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
   1093     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
   1094     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
   1095     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
   1096     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
   1097     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
   1098     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
   1099     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
   1100     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
   1101 
   1102     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
   1103     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
   1104     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
   1105     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
   1106     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
   1107     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
   1108     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
   1109     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
   1110     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
   1111     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
   1112     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
   1113     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
   1114 
   1115     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
   1116     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
   1117 
   1118     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
   1119 
   1120     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
   1121     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
   1122     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
   1123 
   1124     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
   1125     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
   1126     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
   1127 
   1128     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
   1129 
   1130     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
   1131     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
   1132 
   1133     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
   1134     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
   1135 
   1136     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
   1137     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
   1138 
   1139     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
   1140 
   1141     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
   1142     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
   1143     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
   1144     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
   1145 
   1146     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
   1147     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
   1148     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
   1149 
   1150     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
   1151     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
   1152     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
   1153     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
   1154 
   1155     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
   1156     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
   1157     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
   1158     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
   1159     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
   1160     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
   1161 
   1162     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
   1163       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
   1164       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
   1165       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
   1166       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
   1167       setOperationAction(ISD::FMA,             MVT::f32, Legal);
   1168       setOperationAction(ISD::FMA,             MVT::f64, Legal);
   1169     }
   1170 
   1171     if (Subtarget->hasInt256()) {
   1172       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
   1173       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
   1174       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
   1175       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
   1176 
   1177       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
   1178       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
   1179       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
   1180       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
   1181 
   1182       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
   1183       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
   1184       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
   1185       // Don't lower v32i8 because there is no 128-bit byte mul
   1186 
   1187       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
   1188 
   1189       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
   1190       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
   1191 
   1192       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
   1193       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
   1194 
   1195       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
   1196 
   1197       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
   1198     } else {
   1199       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
   1200       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
   1201       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
   1202       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
   1203 
   1204       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
   1205       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
   1206       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
   1207       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
   1208 
   1209       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
   1210       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
   1211       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
   1212       // Don't lower v32i8 because there is no 128-bit byte mul
   1213 
   1214       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
   1215       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
   1216 
   1217       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
   1218       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
   1219 
   1220       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
   1221     }
   1222 
   1223     // Custom lower several nodes for 256-bit types.
   1224     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
   1225              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
   1226       MVT VT = (MVT::SimpleValueType)i;
   1227 
   1228       // Extract subvector is special because the value type
   1229       // (result) is 128-bit but the source is 256-bit wide.
   1230       if (VT.is128BitVector())
   1231         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
   1232 
   1233       // Do not attempt to custom lower other non-256-bit vectors
   1234       if (!VT.is256BitVector())
   1235         continue;
   1236 
   1237       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
   1238       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
   1239       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
   1240       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
   1241       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
   1242       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
   1243       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
   1244     }
   1245 
   1246     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
   1247     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
   1248       MVT VT = (MVT::SimpleValueType)i;
   1249 
   1250       // Do not attempt to promote non-256-bit vectors
   1251       if (!VT.is256BitVector())
   1252         continue;
   1253 
   1254       setOperationAction(ISD::AND,    VT, Promote);
   1255       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
   1256       setOperationAction(ISD::OR,     VT, Promote);
   1257       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
   1258       setOperationAction(ISD::XOR,    VT, Promote);
   1259       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
   1260       setOperationAction(ISD::LOAD,   VT, Promote);
   1261       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
   1262       setOperationAction(ISD::SELECT, VT, Promote);
   1263       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
   1264     }
   1265   }
   1266 
   1267   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
   1268   // of this type with custom code.
   1269   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
   1270            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
   1271     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
   1272                        Custom);
   1273   }
   1274 
   1275   // We want to custom lower some of our intrinsics.
   1276   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
   1277   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
   1278 
   1279   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
   1280   // handle type legalization for these operations here.
   1281   //
   1282   // FIXME: We really should do custom legalization for addition and
   1283   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
   1284   // than generic legalization for 64-bit multiplication-with-overflow, though.
   1285   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
   1286     // Add/Sub/Mul with overflow operations are custom lowered.
   1287     MVT VT = IntVTs[i];
   1288     setOperationAction(ISD::SADDO, VT, Custom);
   1289     setOperationAction(ISD::UADDO, VT, Custom);
   1290     setOperationAction(ISD::SSUBO, VT, Custom);
   1291     setOperationAction(ISD::USUBO, VT, Custom);
   1292     setOperationAction(ISD::SMULO, VT, Custom);
   1293     setOperationAction(ISD::UMULO, VT, Custom);
   1294   }
   1295 
   1296   // There are no 8-bit 3-address imul/mul instructions
   1297   setOperationAction(ISD::SMULO, MVT::i8, Expand);
   1298   setOperationAction(ISD::UMULO, MVT::i8, Expand);
   1299 
   1300   if (!Subtarget->is64Bit()) {
   1301     // These libcalls are not available in 32-bit.
   1302     setLibcallName(RTLIB::SHL_I128, 0);
   1303     setLibcallName(RTLIB::SRL_I128, 0);
   1304     setLibcallName(RTLIB::SRA_I128, 0);
   1305   }
   1306 
   1307   // Combine sin / cos into one node or libcall if possible.
   1308   if (Subtarget->hasSinCos()) {
   1309     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
   1310     setLibcallName(RTLIB::SINCOS_F64, "sincos");
   1311     if (Subtarget->isTargetDarwin()) {
   1312       // For MacOSX, we don't want to the normal expansion of a libcall to
   1313       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
   1314       // traffic.
   1315       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
   1316       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
   1317     }
   1318   }
   1319 
   1320   // We have target-specific dag combine patterns for the following nodes:
   1321   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
   1322   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
   1323   setTargetDAGCombine(ISD::VSELECT);
   1324   setTargetDAGCombine(ISD::SELECT);
   1325   setTargetDAGCombine(ISD::SHL);
   1326   setTargetDAGCombine(ISD::SRA);
   1327   setTargetDAGCombine(ISD::SRL);
   1328   setTargetDAGCombine(ISD::OR);
   1329   setTargetDAGCombine(ISD::AND);
   1330   setTargetDAGCombine(ISD::ADD);
   1331   setTargetDAGCombine(ISD::FADD);
   1332   setTargetDAGCombine(ISD::FSUB);
   1333   setTargetDAGCombine(ISD::FMA);
   1334   setTargetDAGCombine(ISD::SUB);
   1335   setTargetDAGCombine(ISD::LOAD);
   1336   setTargetDAGCombine(ISD::STORE);
   1337   setTargetDAGCombine(ISD::ZERO_EXTEND);
   1338   setTargetDAGCombine(ISD::ANY_EXTEND);
   1339   setTargetDAGCombine(ISD::SIGN_EXTEND);
   1340   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
   1341   setTargetDAGCombine(ISD::TRUNCATE);
   1342   setTargetDAGCombine(ISD::SINT_TO_FP);
   1343   setTargetDAGCombine(ISD::SETCC);
   1344   if (Subtarget->is64Bit())
   1345     setTargetDAGCombine(ISD::MUL);
   1346   setTargetDAGCombine(ISD::XOR);
   1347 
   1348   computeRegisterProperties();
   1349 
   1350   // On Darwin, -Os means optimize for size without hurting performance,
   1351   // do not reduce the limit.
   1352   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
   1353   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
   1354   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
   1355   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
   1356   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
   1357   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
   1358   setPrefLoopAlignment(4); // 2^4 bytes.
   1359   BenefitFromCodePlacementOpt = true;
   1360 
   1361   // Predictable cmov don't hurt on atom because it's in-order.
   1362   PredictableSelectIsExpensive = !Subtarget->isAtom();
   1363 
   1364   setPrefFunctionAlignment(4); // 2^4 bytes.
   1365 }
   1366 
   1367 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
   1368   if (!VT.isVector()) return MVT::i8;
   1369   return VT.changeVectorElementTypeToInteger();
   1370 }
   1371 
   1372 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
   1373 /// the desired ByVal argument alignment.
   1374 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
   1375   if (MaxAlign == 16)
   1376     return;
   1377   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
   1378     if (VTy->getBitWidth() == 128)
   1379       MaxAlign = 16;
   1380   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
   1381     unsigned EltAlign = 0;
   1382     getMaxByValAlign(ATy->getElementType(), EltAlign);
   1383     if (EltAlign > MaxAlign)
   1384       MaxAlign = EltAlign;
   1385   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
   1386     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
   1387       unsigned EltAlign = 0;
   1388       getMaxByValAlign(STy->getElementType(i), EltAlign);
   1389       if (EltAlign > MaxAlign)
   1390         MaxAlign = EltAlign;
   1391       if (MaxAlign == 16)
   1392         break;
   1393     }
   1394   }
   1395 }
   1396 
   1397 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
   1398 /// function arguments in the caller parameter area. For X86, aggregates
   1399 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
   1400 /// are at 4-byte boundaries.
   1401 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
   1402   if (Subtarget->is64Bit()) {
   1403     // Max of 8 and alignment of type.
   1404     unsigned TyAlign = TD->getABITypeAlignment(Ty);
   1405     if (TyAlign > 8)
   1406       return TyAlign;
   1407     return 8;
   1408   }
   1409 
   1410   unsigned Align = 4;
   1411   if (Subtarget->hasSSE1())
   1412     getMaxByValAlign(Ty, Align);
   1413   return Align;
   1414 }
   1415 
   1416 /// getOptimalMemOpType - Returns the target specific optimal type for load
   1417 /// and store operations as a result of memset, memcpy, and memmove
   1418 /// lowering. If DstAlign is zero that means it's safe to destination
   1419 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
   1420 /// means there isn't a need to check it against alignment requirement,
   1421 /// probably because the source does not need to be loaded. If 'IsMemset' is
   1422 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
   1423 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
   1424 /// source is constant so it does not need to be loaded.
   1425 /// It returns EVT::Other if the type should be determined using generic
   1426 /// target-independent logic.
   1427 EVT
   1428 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
   1429                                        unsigned DstAlign, unsigned SrcAlign,
   1430                                        bool IsMemset, bool ZeroMemset,
   1431                                        bool MemcpyStrSrc,
   1432                                        MachineFunction &MF) const {
   1433   const Function *F = MF.getFunction();
   1434   if ((!IsMemset || ZeroMemset) &&
   1435       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
   1436                                        Attribute::NoImplicitFloat)) {
   1437     if (Size >= 16 &&
   1438         (Subtarget->isUnalignedMemAccessFast() ||
   1439          ((DstAlign == 0 || DstAlign >= 16) &&
   1440           (SrcAlign == 0 || SrcAlign >= 16)))) {
   1441       if (Size >= 32) {
   1442         if (Subtarget->hasInt256())
   1443           return MVT::v8i32;
   1444         if (Subtarget->hasFp256())
   1445           return MVT::v8f32;
   1446       }
   1447       if (Subtarget->hasSSE2())
   1448         return MVT::v4i32;
   1449       if (Subtarget->hasSSE1())
   1450         return MVT::v4f32;
   1451     } else if (!MemcpyStrSrc && Size >= 8 &&
   1452                !Subtarget->is64Bit() &&
   1453                Subtarget->hasSSE2()) {
   1454       // Do not use f64 to lower memcpy if source is string constant. It's
   1455       // better to use i32 to avoid the loads.
   1456       return MVT::f64;
   1457     }
   1458   }
   1459   if (Subtarget->is64Bit() && Size >= 8)
   1460     return MVT::i64;
   1461   return MVT::i32;
   1462 }
   1463 
   1464 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
   1465   if (VT == MVT::f32)
   1466     return X86ScalarSSEf32;
   1467   else if (VT == MVT::f64)
   1468     return X86ScalarSSEf64;
   1469   return true;
   1470 }
   1471 
   1472 bool
   1473 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
   1474   if (Fast)
   1475     *Fast = Subtarget->isUnalignedMemAccessFast();
   1476   return true;
   1477 }
   1478 
   1479 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
   1480 /// current function.  The returned value is a member of the
   1481 /// MachineJumpTableInfo::JTEntryKind enum.
   1482 unsigned X86TargetLowering::getJumpTableEncoding() const {
   1483   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
   1484   // symbol.
   1485   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
   1486       Subtarget->isPICStyleGOT())
   1487     return MachineJumpTableInfo::EK_Custom32;
   1488 
   1489   // Otherwise, use the normal jump table encoding heuristics.
   1490   return TargetLowering::getJumpTableEncoding();
   1491 }
   1492 
   1493 const MCExpr *
   1494 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
   1495                                              const MachineBasicBlock *MBB,
   1496                                              unsigned uid,MCContext &Ctx) const{
   1497   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
   1498          Subtarget->isPICStyleGOT());
   1499   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
   1500   // entries.
   1501   return MCSymbolRefExpr::Create(MBB->getSymbol(),
   1502                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
   1503 }
   1504 
   1505 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
   1506 /// jumptable.
   1507 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
   1508                                                     SelectionDAG &DAG) const {
   1509   if (!Subtarget->is64Bit())
   1510     // This doesn't have DebugLoc associated with it, but is not really the
   1511     // same as a Register.
   1512     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
   1513   return Table;
   1514 }
   1515 
   1516 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
   1517 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
   1518 /// MCExpr.
   1519 const MCExpr *X86TargetLowering::
   1520 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
   1521                              MCContext &Ctx) const {
   1522   // X86-64 uses RIP relative addressing based on the jump table label.
   1523   if (Subtarget->isPICStyleRIPRel())
   1524     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
   1525 
   1526   // Otherwise, the reference is relative to the PIC base.
   1527   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
   1528 }
   1529 
   1530 // FIXME: Why this routine is here? Move to RegInfo!
   1531 std::pair<const TargetRegisterClass*, uint8_t>
   1532 X86TargetLowering::findRepresentativeClass(MVT VT) const{
   1533   const TargetRegisterClass *RRC = 0;
   1534   uint8_t Cost = 1;
   1535   switch (VT.SimpleTy) {
   1536   default:
   1537     return TargetLowering::findRepresentativeClass(VT);
   1538   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
   1539     RRC = Subtarget->is64Bit() ?
   1540       (const TargetRegisterClass*)&X86::GR64RegClass :
   1541       (const TargetRegisterClass*)&X86::GR32RegClass;
   1542     break;
   1543   case MVT::x86mmx:
   1544     RRC = &X86::VR64RegClass;
   1545     break;
   1546   case MVT::f32: case MVT::f64:
   1547   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
   1548   case MVT::v4f32: case MVT::v2f64:
   1549   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
   1550   case MVT::v4f64:
   1551     RRC = &X86::VR128RegClass;
   1552     break;
   1553   }
   1554   return std::make_pair(RRC, Cost);
   1555 }
   1556 
   1557 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
   1558                                                unsigned &Offset) const {
   1559   if (!Subtarget->isTargetLinux())
   1560     return false;
   1561 
   1562   if (Subtarget->is64Bit()) {
   1563     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
   1564     Offset = 0x28;
   1565     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
   1566       AddressSpace = 256;
   1567     else
   1568       AddressSpace = 257;
   1569   } else {
   1570     // %gs:0x14 on i386
   1571     Offset = 0x14;
   1572     AddressSpace = 256;
   1573   }
   1574   return true;
   1575 }
   1576 
   1577 //===----------------------------------------------------------------------===//
   1578 //               Return Value Calling Convention Implementation
   1579 //===----------------------------------------------------------------------===//
   1580 
   1581 #include "X86GenCallingConv.inc"
   1582 
   1583 bool
   1584 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
   1585                                   MachineFunction &MF, bool isVarArg,
   1586                         const SmallVectorImpl<ISD::OutputArg> &Outs,
   1587                         LLVMContext &Context) const {
   1588   SmallVector<CCValAssign, 16> RVLocs;
   1589   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
   1590                  RVLocs, Context);
   1591   return CCInfo.CheckReturn(Outs, RetCC_X86);
   1592 }
   1593 
   1594 SDValue
   1595 X86TargetLowering::LowerReturn(SDValue Chain,
   1596                                CallingConv::ID CallConv, bool isVarArg,
   1597                                const SmallVectorImpl<ISD::OutputArg> &Outs,
   1598                                const SmallVectorImpl<SDValue> &OutVals,
   1599                                DebugLoc dl, SelectionDAG &DAG) const {
   1600   MachineFunction &MF = DAG.getMachineFunction();
   1601   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
   1602 
   1603   SmallVector<CCValAssign, 16> RVLocs;
   1604   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
   1605                  RVLocs, *DAG.getContext());
   1606   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
   1607 
   1608   SDValue Flag;
   1609   SmallVector<SDValue, 6> RetOps;
   1610   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
   1611   // Operand #1 = Bytes To Pop
   1612   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
   1613                    MVT::i16));
   1614 
   1615   // Copy the result values into the output registers.
   1616   for (unsigned i = 0; i != RVLocs.size(); ++i) {
   1617     CCValAssign &VA = RVLocs[i];
   1618     assert(VA.isRegLoc() && "Can only return in registers!");
   1619     SDValue ValToCopy = OutVals[i];
   1620     EVT ValVT = ValToCopy.getValueType();
   1621 
   1622     // Promote values to the appropriate types
   1623     if (VA.getLocInfo() == CCValAssign::SExt)
   1624       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
   1625     else if (VA.getLocInfo() == CCValAssign::ZExt)
   1626       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
   1627     else if (VA.getLocInfo() == CCValAssign::AExt)
   1628       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
   1629     else if (VA.getLocInfo() == CCValAssign::BCvt)
   1630       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
   1631 
   1632     // If this is x86-64, and we disabled SSE, we can't return FP values,
   1633     // or SSE or MMX vectors.
   1634     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
   1635          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
   1636           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
   1637       report_fatal_error("SSE register return with SSE disabled");
   1638     }
   1639     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
   1640     // llvm-gcc has never done it right and no one has noticed, so this
   1641     // should be OK for now.
   1642     if (ValVT == MVT::f64 &&
   1643         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
   1644       report_fatal_error("SSE2 register return with SSE2 disabled");
   1645 
   1646     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
   1647     // the RET instruction and handled by the FP Stackifier.
   1648     if (VA.getLocReg() == X86::ST0 ||
   1649         VA.getLocReg() == X86::ST1) {
   1650       // If this is a copy from an xmm register to ST(0), use an FPExtend to
   1651       // change the value to the FP stack register class.
   1652       if (isScalarFPTypeInSSEReg(VA.getValVT()))
   1653         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
   1654       RetOps.push_back(ValToCopy);
   1655       // Don't emit a copytoreg.
   1656       continue;
   1657     }
   1658 
   1659     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
   1660     // which is returned in RAX / RDX.
   1661     if (Subtarget->is64Bit()) {
   1662       if (ValVT == MVT::x86mmx) {
   1663         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
   1664           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
   1665           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
   1666                                   ValToCopy);
   1667           // If we don't have SSE2 available, convert to v4f32 so the generated
   1668           // register is legal.
   1669           if (!Subtarget->hasSSE2())
   1670             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
   1671         }
   1672       }
   1673     }
   1674 
   1675     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
   1676     Flag = Chain.getValue(1);
   1677     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
   1678   }
   1679 
   1680   // The x86-64 ABIs require that for returning structs by value we copy
   1681   // the sret argument into %rax/%eax (depending on ABI) for the return.
   1682   // We saved the argument into a virtual register in the entry block,
   1683   // so now we copy the value out and into %rax/%eax.
   1684   if (Subtarget->is64Bit() &&
   1685       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
   1686     MachineFunction &MF = DAG.getMachineFunction();
   1687     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
   1688     unsigned Reg = FuncInfo->getSRetReturnReg();
   1689     assert(Reg &&
   1690            "SRetReturnReg should have been set in LowerFormalArguments().");
   1691     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
   1692 
   1693     unsigned RetValReg = Subtarget->isTarget64BitILP32() ? X86::EAX : X86::RAX;
   1694     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
   1695     Flag = Chain.getValue(1);
   1696 
   1697     // RAX/EAX now acts like a return value.
   1698     RetOps.push_back(DAG.getRegister(RetValReg, MVT::i64));
   1699   }
   1700 
   1701   RetOps[0] = Chain;  // Update chain.
   1702 
   1703   // Add the flag if we have it.
   1704   if (Flag.getNode())
   1705     RetOps.push_back(Flag);
   1706 
   1707   return DAG.getNode(X86ISD::RET_FLAG, dl,
   1708                      MVT::Other, &RetOps[0], RetOps.size());
   1709 }
   1710 
   1711 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
   1712   if (N->getNumValues() != 1)
   1713     return false;
   1714   if (!N->hasNUsesOfValue(1, 0))
   1715     return false;
   1716 
   1717   SDValue TCChain = Chain;
   1718   SDNode *Copy = *N->use_begin();
   1719   if (Copy->getOpcode() == ISD::CopyToReg) {
   1720     // If the copy has a glue operand, we conservatively assume it isn't safe to
   1721     // perform a tail call.
   1722     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
   1723       return false;
   1724     TCChain = Copy->getOperand(0);
   1725   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
   1726     return false;
   1727 
   1728   bool HasRet = false;
   1729   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
   1730        UI != UE; ++UI) {
   1731     if (UI->getOpcode() != X86ISD::RET_FLAG)
   1732       return false;
   1733     HasRet = true;
   1734   }
   1735 
   1736   if (!HasRet)
   1737     return false;
   1738 
   1739   Chain = TCChain;
   1740   return true;
   1741 }
   1742 
   1743 MVT
   1744 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
   1745                                             ISD::NodeType ExtendKind) const {
   1746   MVT ReturnMVT;
   1747   // TODO: Is this also valid on 32-bit?
   1748   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
   1749     ReturnMVT = MVT::i8;
   1750   else
   1751     ReturnMVT = MVT::i32;
   1752 
   1753   MVT MinVT = getRegisterType(ReturnMVT);
   1754   return VT.bitsLT(MinVT) ? MinVT : VT;
   1755 }
   1756 
   1757 /// LowerCallResult - Lower the result values of a call into the
   1758 /// appropriate copies out of appropriate physical registers.
   1759 ///
   1760 SDValue
   1761 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
   1762                                    CallingConv::ID CallConv, bool isVarArg,
   1763                                    const SmallVectorImpl<ISD::InputArg> &Ins,
   1764                                    DebugLoc dl, SelectionDAG &DAG,
   1765                                    SmallVectorImpl<SDValue> &InVals) const {
   1766 
   1767   // Assign locations to each value returned by this call.
   1768   SmallVector<CCValAssign, 16> RVLocs;
   1769   bool Is64Bit = Subtarget->is64Bit();
   1770   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
   1771                  getTargetMachine(), RVLocs, *DAG.getContext());
   1772   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
   1773 
   1774   // Copy all of the result registers out of their specified physreg.
   1775   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
   1776     CCValAssign &VA = RVLocs[i];
   1777     EVT CopyVT = VA.getValVT();
   1778 
   1779     // If this is x86-64, and we disabled SSE, we can't return FP values
   1780     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
   1781         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
   1782       report_fatal_error("SSE register return with SSE disabled");
   1783     }
   1784 
   1785     SDValue Val;
   1786 
   1787     // If this is a call to a function that returns an fp value on the floating
   1788     // point stack, we must guarantee the value is popped from the stack, so
   1789     // a CopyFromReg is not good enough - the copy instruction may be eliminated
   1790     // if the return value is not used. We use the FpPOP_RETVAL instruction
   1791     // instead.
   1792     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
   1793       // If we prefer to use the value in xmm registers, copy it out as f80 and
   1794       // use a truncate to move it from fp stack reg to xmm reg.
   1795       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
   1796       SDValue Ops[] = { Chain, InFlag };
   1797       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
   1798                                          MVT::Other, MVT::Glue, Ops, 2), 1);
   1799       Val = Chain.getValue(0);
   1800 
   1801       // Round the f80 to the right size, which also moves it to the appropriate
   1802       // xmm register.
   1803       if (CopyVT != VA.getValVT())
   1804         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
   1805                           // This truncation won't change the value.
   1806                           DAG.getIntPtrConstant(1));
   1807     } else {
   1808       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
   1809                                  CopyVT, InFlag).getValue(1);
   1810       Val = Chain.getValue(0);
   1811     }
   1812     InFlag = Chain.getValue(2);
   1813     InVals.push_back(Val);
   1814   }
   1815 
   1816   return Chain;
   1817 }
   1818 
   1819 //===----------------------------------------------------------------------===//
   1820 //                C & StdCall & Fast Calling Convention implementation
   1821 //===----------------------------------------------------------------------===//
   1822 //  StdCall calling convention seems to be standard for many Windows' API
   1823 //  routines and around. It differs from C calling convention just a little:
   1824 //  callee should clean up the stack, not caller. Symbols should be also
   1825 //  decorated in some fancy way :) It doesn't support any vector arguments.
   1826 //  For info on fast calling convention see Fast Calling Convention (tail call)
   1827 //  implementation LowerX86_32FastCCCallTo.
   1828 
   1829 /// CallIsStructReturn - Determines whether a call uses struct return
   1830 /// semantics.
   1831 enum StructReturnType {
   1832   NotStructReturn,
   1833   RegStructReturn,
   1834   StackStructReturn
   1835 };
   1836 static StructReturnType
   1837 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
   1838   if (Outs.empty())
   1839     return NotStructReturn;
   1840 
   1841   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
   1842   if (!Flags.isSRet())
   1843     return NotStructReturn;
   1844   if (Flags.isInReg())
   1845     return RegStructReturn;
   1846   return StackStructReturn;
   1847 }
   1848 
   1849 /// ArgsAreStructReturn - Determines whether a function uses struct
   1850 /// return semantics.
   1851 static StructReturnType
   1852 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
   1853   if (Ins.empty())
   1854     return NotStructReturn;
   1855 
   1856   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
   1857   if (!Flags.isSRet())
   1858     return NotStructReturn;
   1859   if (Flags.isInReg())
   1860     return RegStructReturn;
   1861   return StackStructReturn;
   1862 }
   1863 
   1864 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
   1865 /// by "Src" to address "Dst" with size and alignment information specified by
   1866 /// the specific parameter attribute. The copy will be passed as a byval
   1867 /// function parameter.
   1868 static SDValue
   1869 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
   1870                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
   1871                           DebugLoc dl) {
   1872   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
   1873 
   1874   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
   1875                        /*isVolatile*/false, /*AlwaysInline=*/true,
   1876                        MachinePointerInfo(), MachinePointerInfo());
   1877 }
   1878 
   1879 /// IsTailCallConvention - Return true if the calling convention is one that
   1880 /// supports tail call optimization.
   1881 static bool IsTailCallConvention(CallingConv::ID CC) {
   1882   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
   1883           CC == CallingConv::HiPE);
   1884 }
   1885 
   1886 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
   1887   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
   1888     return false;
   1889 
   1890   CallSite CS(CI);
   1891   CallingConv::ID CalleeCC = CS.getCallingConv();
   1892   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
   1893     return false;
   1894 
   1895   return true;
   1896 }
   1897 
   1898 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
   1899 /// a tailcall target by changing its ABI.
   1900 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
   1901                                    bool GuaranteedTailCallOpt) {
   1902   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
   1903 }
   1904 
   1905 SDValue
   1906 X86TargetLowering::LowerMemArgument(SDValue Chain,
   1907                                     CallingConv::ID CallConv,
   1908                                     const SmallVectorImpl<ISD::InputArg> &Ins,
   1909                                     DebugLoc dl, SelectionDAG &DAG,
   1910                                     const CCValAssign &VA,
   1911                                     MachineFrameInfo *MFI,
   1912                                     unsigned i) const {
   1913   // Create the nodes corresponding to a load from this parameter slot.
   1914   ISD::ArgFlagsTy Flags = Ins[i].Flags;
   1915   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
   1916                               getTargetMachine().Options.GuaranteedTailCallOpt);
   1917   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
   1918   EVT ValVT;
   1919 
   1920   // If value is passed by pointer we have address passed instead of the value
   1921   // itself.
   1922   if (VA.getLocInfo() == CCValAssign::Indirect)
   1923     ValVT = VA.getLocVT();
   1924   else
   1925     ValVT = VA.getValVT();
   1926 
   1927   // FIXME: For now, all byval parameter objects are marked mutable. This can be
   1928   // changed with more analysis.
   1929   // In case of tail call optimization mark all arguments mutable. Since they
   1930   // could be overwritten by lowering of arguments in case of a tail call.
   1931   if (Flags.isByVal()) {
   1932     unsigned Bytes = Flags.getByValSize();
   1933     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
   1934     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
   1935     return DAG.getFrameIndex(FI, getPointerTy());
   1936   } else {
   1937     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
   1938                                     VA.getLocMemOffset(), isImmutable);
   1939     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
   1940     return DAG.getLoad(ValVT, dl, Chain, FIN,
   1941                        MachinePointerInfo::getFixedStack(FI),
   1942                        false, false, false, 0);
   1943   }
   1944 }
   1945 
   1946 SDValue
   1947 X86TargetLowering::LowerFormalArguments(SDValue Chain,
   1948                                         CallingConv::ID CallConv,
   1949                                         bool isVarArg,
   1950                                       const SmallVectorImpl<ISD::InputArg> &Ins,
   1951                                         DebugLoc dl,
   1952                                         SelectionDAG &DAG,
   1953                                         SmallVectorImpl<SDValue> &InVals)
   1954                                           const {
   1955   MachineFunction &MF = DAG.getMachineFunction();
   1956   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
   1957 
   1958   const Function* Fn = MF.getFunction();
   1959   if (Fn->hasExternalLinkage() &&
   1960       Subtarget->isTargetCygMing() &&
   1961       Fn->getName() == "main")
   1962     FuncInfo->setForceFramePointer(true);
   1963 
   1964   MachineFrameInfo *MFI = MF.getFrameInfo();
   1965   bool Is64Bit = Subtarget->is64Bit();
   1966   bool IsWindows = Subtarget->isTargetWindows();
   1967   bool IsWin64 = Subtarget->isTargetWin64();
   1968 
   1969   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
   1970          "Var args not supported with calling convention fastcc, ghc or hipe");
   1971 
   1972   // Assign locations to all of the incoming arguments.
   1973   SmallVector<CCValAssign, 16> ArgLocs;
   1974   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
   1975                  ArgLocs, *DAG.getContext());
   1976 
   1977   // Allocate shadow area for Win64
   1978   if (IsWin64) {
   1979     CCInfo.AllocateStack(32, 8);
   1980   }
   1981 
   1982   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
   1983 
   1984   unsigned LastVal = ~0U;
   1985   SDValue ArgValue;
   1986   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
   1987     CCValAssign &VA = ArgLocs[i];
   1988     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
   1989     // places.
   1990     assert(VA.getValNo() != LastVal &&
   1991            "Don't support value assigned to multiple locs yet");
   1992     (void)LastVal;
   1993     LastVal = VA.getValNo();
   1994 
   1995     if (VA.isRegLoc()) {
   1996       EVT RegVT = VA.getLocVT();
   1997       const TargetRegisterClass *RC;
   1998       if (RegVT == MVT::i32)
   1999         RC = &X86::GR32RegClass;
   2000       else if (Is64Bit && RegVT == MVT::i64)
   2001         RC = &X86::GR64RegClass;
   2002       else if (RegVT == MVT::f32)
   2003         RC = &X86::FR32RegClass;
   2004       else if (RegVT == MVT::f64)
   2005         RC = &X86::FR64RegClass;
   2006       else if (RegVT.is256BitVector())
   2007         RC = &X86::VR256RegClass;
   2008       else if (RegVT.is128BitVector())
   2009         RC = &X86::VR128RegClass;
   2010       else if (RegVT == MVT::x86mmx)
   2011         RC = &X86::VR64RegClass;
   2012       else
   2013         llvm_unreachable("Unknown argument type!");
   2014 
   2015       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
   2016       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
   2017 
   2018       // If this is an 8 or 16-bit value, it is really passed promoted to 32
   2019       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
   2020       // right size.
   2021       if (VA.getLocInfo() == CCValAssign::SExt)
   2022         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
   2023                                DAG.getValueType(VA.getValVT()));
   2024       else if (VA.getLocInfo() == CCValAssign::ZExt)
   2025         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
   2026                                DAG.getValueType(VA.getValVT()));
   2027       else if (VA.getLocInfo() == CCValAssign::BCvt)
   2028         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
   2029 
   2030       if (VA.isExtInLoc()) {
   2031         // Handle MMX values passed in XMM regs.
   2032         if (RegVT.isVector())
   2033           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
   2034         else
   2035           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
   2036       }
   2037     } else {
   2038       assert(VA.isMemLoc());
   2039       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
   2040     }
   2041 
   2042     // If value is passed via pointer - do a load.
   2043     if (VA.getLocInfo() == CCValAssign::Indirect)
   2044       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
   2045                              MachinePointerInfo(), false, false, false, 0);
   2046 
   2047     InVals.push_back(ArgValue);
   2048   }
   2049 
   2050   // The x86-64 ABIs require that for returning structs by value we copy
   2051   // the sret argument into %rax/%eax (depending on ABI) for the return.
   2052   // Save the argument into a virtual register so that we can access it
   2053   // from the return points.
   2054   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
   2055     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
   2056     unsigned Reg = FuncInfo->getSRetReturnReg();
   2057     if (!Reg) {
   2058       MVT PtrTy = getPointerTy();
   2059       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
   2060       FuncInfo->setSRetReturnReg(Reg);
   2061     }
   2062     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
   2063     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
   2064   }
   2065 
   2066   unsigned StackSize = CCInfo.getNextStackOffset();
   2067   // Align stack specially for tail calls.
   2068   if (FuncIsMadeTailCallSafe(CallConv,
   2069                              MF.getTarget().Options.GuaranteedTailCallOpt))
   2070     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
   2071 
   2072   // If the function takes variable number of arguments, make a frame index for
   2073   // the start of the first vararg value... for expansion of llvm.va_start.
   2074   if (isVarArg) {
   2075     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
   2076                     CallConv != CallingConv::X86_ThisCall)) {
   2077       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
   2078     }
   2079     if (Is64Bit) {
   2080       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
   2081 
   2082       // FIXME: We should really autogenerate these arrays
   2083       static const uint16_t GPR64ArgRegsWin64[] = {
   2084         X86::RCX, X86::RDX, X86::R8,  X86::R9
   2085       };
   2086       static const uint16_t GPR64ArgRegs64Bit[] = {
   2087         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
   2088       };
   2089       static const uint16_t XMMArgRegs64Bit[] = {
   2090         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
   2091         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
   2092       };
   2093       const uint16_t *GPR64ArgRegs;
   2094       unsigned NumXMMRegs = 0;
   2095 
   2096       if (IsWin64) {
   2097         // The XMM registers which might contain var arg parameters are shadowed
   2098         // in their paired GPR.  So we only need to save the GPR to their home
   2099         // slots.
   2100         TotalNumIntRegs = 4;
   2101         GPR64ArgRegs = GPR64ArgRegsWin64;
   2102       } else {
   2103         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
   2104         GPR64ArgRegs = GPR64ArgRegs64Bit;
   2105 
   2106         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
   2107                                                 TotalNumXMMRegs);
   2108       }
   2109       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
   2110                                                        TotalNumIntRegs);
   2111 
   2112       bool NoImplicitFloatOps = Fn->getAttributes().
   2113         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
   2114       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
   2115              "SSE register cannot be used when SSE is disabled!");
   2116       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
   2117                NoImplicitFloatOps) &&
   2118              "SSE register cannot be used when SSE is disabled!");
   2119       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
   2120           !Subtarget->hasSSE1())
   2121         // Kernel mode asks for SSE to be disabled, so don't push them
   2122         // on the stack.
   2123         TotalNumXMMRegs = 0;
   2124 
   2125       if (IsWin64) {
   2126         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
   2127         // Get to the caller-allocated home save location.  Add 8 to account
   2128         // for the return address.
   2129         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
   2130         FuncInfo->setRegSaveFrameIndex(
   2131           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
   2132         // Fixup to set vararg frame on shadow area (4 x i64).
   2133         if (NumIntRegs < 4)
   2134           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
   2135       } else {
   2136         // For X86-64, if there are vararg parameters that are passed via
   2137         // registers, then we must store them to their spots on the stack so
   2138         // they may be loaded by deferencing the result of va_next.
   2139         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
   2140         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
   2141         FuncInfo->setRegSaveFrameIndex(
   2142           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
   2143                                false));
   2144       }
   2145 
   2146       // Store the integer parameter registers.
   2147       SmallVector<SDValue, 8> MemOps;
   2148       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
   2149                                         getPointerTy());
   2150       unsigned Offset = FuncInfo->getVarArgsGPOffset();
   2151       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
   2152         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
   2153                                   DAG.getIntPtrConstant(Offset));
   2154         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
   2155                                      &X86::GR64RegClass);
   2156         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
   2157         SDValue Store =
   2158           DAG.getStore(Val.getValue(1), dl, Val, FIN,
   2159                        MachinePointerInfo::getFixedStack(
   2160                          FuncInfo->getRegSaveFrameIndex(), Offset),
   2161                        false, false, 0);
   2162         MemOps.push_back(Store);
   2163         Offset += 8;
   2164       }
   2165 
   2166       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
   2167         // Now store the XMM (fp + vector) parameter registers.
   2168         SmallVector<SDValue, 11> SaveXMMOps;
   2169         SaveXMMOps.push_back(Chain);
   2170 
   2171         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
   2172         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
   2173         SaveXMMOps.push_back(ALVal);
   2174 
   2175         SaveXMMOps.push_back(DAG.getIntPtrConstant(
   2176                                FuncInfo->getRegSaveFrameIndex()));
   2177         SaveXMMOps.push_back(DAG.getIntPtrConstant(
   2178                                FuncInfo->getVarArgsFPOffset()));
   2179 
   2180         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
   2181           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
   2182                                        &X86::VR128RegClass);
   2183           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
   2184           SaveXMMOps.push_back(Val);
   2185         }
   2186         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
   2187                                      MVT::Other,
   2188                                      &SaveXMMOps[0], SaveXMMOps.size()));
   2189       }
   2190 
   2191       if (!MemOps.empty())
   2192         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
   2193                             &MemOps[0], MemOps.size());
   2194     }
   2195   }
   2196 
   2197   // Some CCs need callee pop.
   2198   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
   2199                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
   2200     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
   2201   } else {
   2202     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
   2203     // If this is an sret function, the return should pop the hidden pointer.
   2204     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
   2205         argsAreStructReturn(Ins) == StackStructReturn)
   2206       FuncInfo->setBytesToPopOnReturn(4);
   2207   }
   2208 
   2209   if (!Is64Bit) {
   2210     // RegSaveFrameIndex is X86-64 only.
   2211     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
   2212     if (CallConv == CallingConv::X86_FastCall ||
   2213         CallConv == CallingConv::X86_ThisCall)
   2214       // fastcc functions can't have varargs.
   2215       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
   2216   }
   2217 
   2218   FuncInfo->setArgumentStackSize(StackSize);
   2219 
   2220   return Chain;
   2221 }
   2222 
   2223 SDValue
   2224 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
   2225                                     SDValue StackPtr, SDValue Arg,
   2226                                     DebugLoc dl, SelectionDAG &DAG,
   2227                                     const CCValAssign &VA,
   2228                                     ISD::ArgFlagsTy Flags) const {
   2229   unsigned LocMemOffset = VA.getLocMemOffset();
   2230   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
   2231   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
   2232   if (Flags.isByVal())
   2233     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
   2234 
   2235   return DAG.getStore(Chain, dl, Arg, PtrOff,
   2236                       MachinePointerInfo::getStack(LocMemOffset),
   2237                       false, false, 0);
   2238 }
   2239 
   2240 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
   2241 /// optimization is performed and it is required.
   2242 SDValue
   2243 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
   2244                                            SDValue &OutRetAddr, SDValue Chain,
   2245                                            bool IsTailCall, bool Is64Bit,
   2246                                            int FPDiff, DebugLoc dl) const {
   2247   // Adjust the Return address stack slot.
   2248   EVT VT = getPointerTy();
   2249   OutRetAddr = getReturnAddressFrameIndex(DAG);
   2250 
   2251   // Load the "old" Return address.
   2252   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
   2253                            false, false, false, 0);
   2254   return SDValue(OutRetAddr.getNode(), 1);
   2255 }
   2256 
   2257 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
   2258 /// optimization is performed and it is required (FPDiff!=0).
   2259 static SDValue
   2260 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
   2261                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
   2262                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
   2263   // Store the return address to the appropriate stack slot.
   2264   if (!FPDiff) return Chain;
   2265   // Calculate the new stack slot for the return address.
   2266   int NewReturnAddrFI =
   2267     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
   2268   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
   2269   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
   2270                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
   2271                        false, false, 0);
   2272   return Chain;
   2273 }
   2274 
   2275 SDValue
   2276 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
   2277                              SmallVectorImpl<SDValue> &InVals) const {
   2278   SelectionDAG &DAG                     = CLI.DAG;
   2279   DebugLoc &dl                          = CLI.DL;
   2280   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
   2281   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
   2282   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
   2283   SDValue Chain                         = CLI.Chain;
   2284   SDValue Callee                        = CLI.Callee;
   2285   CallingConv::ID CallConv              = CLI.CallConv;
   2286   bool &isTailCall                      = CLI.IsTailCall;
   2287   bool isVarArg                         = CLI.IsVarArg;
   2288 
   2289   MachineFunction &MF = DAG.getMachineFunction();
   2290   bool Is64Bit        = Subtarget->is64Bit();
   2291   bool IsWin64        = Subtarget->isTargetWin64();
   2292   bool IsWindows      = Subtarget->isTargetWindows();
   2293   StructReturnType SR = callIsStructReturn(Outs);
   2294   bool IsSibcall      = false;
   2295 
   2296   if (MF.getTarget().Options.DisableTailCalls)
   2297     isTailCall = false;
   2298 
   2299   if (isTailCall) {
   2300     // Check if it's really possible to do a tail call.
   2301     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
   2302                     isVarArg, SR != NotStructReturn,
   2303                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
   2304                     Outs, OutVals, Ins, DAG);
   2305 
   2306     // Sibcalls are automatically detected tailcalls which do not require
   2307     // ABI changes.
   2308     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
   2309       IsSibcall = true;
   2310 
   2311     if (isTailCall)
   2312       ++NumTailCalls;
   2313   }
   2314 
   2315   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
   2316          "Var args not supported with calling convention fastcc, ghc or hipe");
   2317 
   2318   // Analyze operands of the call, assigning locations to each operand.
   2319   SmallVector<CCValAssign, 16> ArgLocs;
   2320   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
   2321                  ArgLocs, *DAG.getContext());
   2322 
   2323   // Allocate shadow area for Win64
   2324   if (IsWin64) {
   2325     CCInfo.AllocateStack(32, 8);
   2326   }
   2327 
   2328   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
   2329 
   2330   // Get a count of how many bytes are to be pushed on the stack.
   2331   unsigned NumBytes = CCInfo.getNextStackOffset();
   2332   if (IsSibcall)
   2333     // This is a sibcall. The memory operands are available in caller's
   2334     // own caller's stack.
   2335     NumBytes = 0;
   2336   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
   2337            IsTailCallConvention(CallConv))
   2338     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
   2339 
   2340   int FPDiff = 0;
   2341   if (isTailCall && !IsSibcall) {
   2342     // Lower arguments at fp - stackoffset + fpdiff.
   2343     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
   2344     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
   2345 
   2346     FPDiff = NumBytesCallerPushed - NumBytes;
   2347 
   2348     // Set the delta of movement of the returnaddr stackslot.
   2349     // But only set if delta is greater than previous delta.
   2350     if (FPDiff < X86Info->getTCReturnAddrDelta())
   2351       X86Info->setTCReturnAddrDelta(FPDiff);
   2352   }
   2353 
   2354   if (!IsSibcall)
   2355     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
   2356 
   2357   SDValue RetAddrFrIdx;
   2358   // Load return address for tail calls.
   2359   if (isTailCall && FPDiff)
   2360     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
   2361                                     Is64Bit, FPDiff, dl);
   2362 
   2363   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
   2364   SmallVector<SDValue, 8> MemOpChains;
   2365   SDValue StackPtr;
   2366 
   2367   // Walk the register/memloc assignments, inserting copies/loads.  In the case
   2368   // of tail call optimization arguments are handle later.
   2369   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
   2370     CCValAssign &VA = ArgLocs[i];
   2371     EVT RegVT = VA.getLocVT();
   2372     SDValue Arg = OutVals[i];
   2373     ISD::ArgFlagsTy Flags = Outs[i].Flags;
   2374     bool isByVal = Flags.isByVal();
   2375 
   2376     // Promote the value if needed.
   2377     switch (VA.getLocInfo()) {
   2378     default: llvm_unreachable("Unknown loc info!");
   2379     case CCValAssign::Full: break;
   2380     case CCValAssign::SExt:
   2381       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
   2382       break;
   2383     case CCValAssign::ZExt:
   2384       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
   2385       break;
   2386     case CCValAssign::AExt:
   2387       if (RegVT.is128BitVector()) {
   2388         // Special case: passing MMX values in XMM registers.
   2389         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
   2390         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
   2391         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
   2392       } else
   2393         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
   2394       break;
   2395     case CCValAssign::BCvt:
   2396       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
   2397       break;
   2398     case CCValAssign::Indirect: {
   2399       // Store the argument.
   2400       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
   2401       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
   2402       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
   2403                            MachinePointerInfo::getFixedStack(FI),
   2404                            false, false, 0);
   2405       Arg = SpillSlot;
   2406       break;
   2407     }
   2408     }
   2409 
   2410     if (VA.isRegLoc()) {
   2411       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
   2412       if (isVarArg && IsWin64) {
   2413         // Win64 ABI requires argument XMM reg to be copied to the corresponding
   2414         // shadow reg if callee is a varargs function.
   2415         unsigned ShadowReg = 0;
   2416         switch (VA.getLocReg()) {
   2417         case X86::XMM0: ShadowReg = X86::RCX; break;
   2418         case X86::XMM1: ShadowReg = X86::RDX; break;
   2419         case X86::XMM2: ShadowReg = X86::R8; break;
   2420         case X86::XMM3: ShadowReg = X86::R9; break;
   2421         }
   2422         if (ShadowReg)
   2423           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
   2424       }
   2425     } else if (!IsSibcall && (!isTailCall || isByVal)) {
   2426       assert(VA.isMemLoc());
   2427       if (StackPtr.getNode() == 0)
   2428         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
   2429                                       getPointerTy());
   2430       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
   2431                                              dl, DAG, VA, Flags));
   2432     }
   2433   }
   2434 
   2435   if (!MemOpChains.empty())
   2436     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
   2437                         &MemOpChains[0], MemOpChains.size());
   2438 
   2439   if (Subtarget->isPICStyleGOT()) {
   2440     // ELF / PIC requires GOT in the EBX register before function calls via PLT
   2441     // GOT pointer.
   2442     if (!isTailCall) {
   2443       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
   2444                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
   2445     } else {
   2446       // If we are tail calling and generating PIC/GOT style code load the
   2447       // address of the callee into ECX. The value in ecx is used as target of
   2448       // the tail jump. This is done to circumvent the ebx/callee-saved problem
   2449       // for tail calls on PIC/GOT architectures. Normally we would just put the
   2450       // address of GOT into ebx and then call target@PLT. But for tail calls
   2451       // ebx would be restored (since ebx is callee saved) before jumping to the
   2452       // target@PLT.
   2453 
   2454       // Note: The actual moving to ECX is done further down.
   2455       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
   2456       if (G && !G->getGlobal()->hasHiddenVisibility() &&
   2457           !G->getGlobal()->hasProtectedVisibility())
   2458         Callee = LowerGlobalAddress(Callee, DAG);
   2459       else if (isa<ExternalSymbolSDNode>(Callee))
   2460         Callee = LowerExternalSymbol(Callee, DAG);
   2461     }
   2462   }
   2463 
   2464   if (Is64Bit && isVarArg && !IsWin64) {
   2465     // From AMD64 ABI document:
   2466     // For calls that may call functions that use varargs or stdargs
   2467     // (prototype-less calls or calls to functions containing ellipsis (...) in
   2468     // the declaration) %al is used as hidden argument to specify the number
   2469     // of SSE registers used. The contents of %al do not need to match exactly
   2470     // the number of registers, but must be an ubound on the number of SSE
   2471     // registers used and is in the range 0 - 8 inclusive.
   2472 
   2473     // Count the number of XMM registers allocated.
   2474     static const uint16_t XMMArgRegs[] = {
   2475       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
   2476       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
   2477     };
   2478     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
   2479     assert((Subtarget->hasSSE1() || !NumXMMRegs)
   2480            && "SSE registers cannot be used when SSE is disabled");
   2481 
   2482     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
   2483                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
   2484   }
   2485 
   2486   // For tail calls lower the arguments to the 'real' stack slot.
   2487   if (isTailCall) {
   2488     // Force all the incoming stack arguments to be loaded from the stack
   2489     // before any new outgoing arguments are stored to the stack, because the
   2490     // outgoing stack slots may alias the incoming argument stack slots, and
   2491     // the alias isn't otherwise explicit. This is slightly more conservative
   2492     // than necessary, because it means that each store effectively depends
   2493     // on every argument instead of just those arguments it would clobber.
   2494     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
   2495 
   2496     SmallVector<SDValue, 8> MemOpChains2;
   2497     SDValue FIN;
   2498     int FI = 0;
   2499     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
   2500       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
   2501         CCValAssign &VA = ArgLocs[i];
   2502         if (VA.isRegLoc())
   2503           continue;
   2504         assert(VA.isMemLoc());
   2505         SDValue Arg = OutVals[i];
   2506         ISD::ArgFlagsTy Flags = Outs[i].Flags;
   2507         // Create frame index.
   2508         int32_t Offset = VA.getLocMemOffset()+FPDiff;
   2509         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
   2510         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
   2511         FIN = DAG.getFrameIndex(FI, getPointerTy());
   2512 
   2513         if (Flags.isByVal()) {
   2514           // Copy relative to framepointer.
   2515           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
   2516           if (StackPtr.getNode() == 0)
   2517             StackPtr = DAG.getCopyFromReg(Chain, dl,
   2518                                           RegInfo->getStackRegister(),
   2519                                           getPointerTy());
   2520           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
   2521 
   2522           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
   2523                                                            ArgChain,
   2524                                                            Flags, DAG, dl));
   2525         } else {
   2526           // Store relative to framepointer.
   2527           MemOpChains2.push_back(
   2528             DAG.getStore(ArgChain, dl, Arg, FIN,
   2529                          MachinePointerInfo::getFixedStack(FI),
   2530                          false, false, 0));
   2531         }
   2532       }
   2533     }
   2534 
   2535     if (!MemOpChains2.empty())
   2536       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
   2537                           &MemOpChains2[0], MemOpChains2.size());
   2538 
   2539     // Store the return address to the appropriate stack slot.
   2540     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
   2541                                      getPointerTy(), RegInfo->getSlotSize(),
   2542                                      FPDiff, dl);
   2543   }
   2544 
   2545   // Build a sequence of copy-to-reg nodes chained together with token chain
   2546   // and flag operands which copy the outgoing args into registers.
   2547   SDValue InFlag;
   2548   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
   2549     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
   2550                              RegsToPass[i].second, InFlag);
   2551     InFlag = Chain.getValue(1);
   2552   }
   2553 
   2554   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
   2555     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
   2556     // In the 64-bit large code model, we have to make all calls
   2557     // through a register, since the call instruction's 32-bit
   2558     // pc-relative offset may not be large enough to hold the whole
   2559     // address.
   2560   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
   2561     // If the callee is a GlobalAddress node (quite common, every direct call
   2562     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
   2563     // it.
   2564 
   2565     // We should use extra load for direct calls to dllimported functions in
   2566     // non-JIT mode.
   2567     const GlobalValue *GV = G->getGlobal();
   2568     if (!GV->hasDLLImportLinkage()) {
   2569       unsigned char OpFlags = 0;
   2570       bool ExtraLoad = false;
   2571       unsigned WrapperKind = ISD::DELETED_NODE;
   2572 
   2573       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
   2574       // external symbols most go through the PLT in PIC mode.  If the symbol
   2575       // has hidden or protected visibility, or if it is static or local, then
   2576       // we don't need to use the PLT - we can directly call it.
   2577       if (Subtarget->isTargetELF() &&
   2578           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
   2579           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
   2580         OpFlags = X86II::MO_PLT;
   2581       } else if (Subtarget->isPICStyleStubAny() &&
   2582                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
   2583                  (!Subtarget->getTargetTriple().isMacOSX() ||
   2584                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
   2585         // PC-relative references to external symbols should go through $stub,
   2586         // unless we're building with the leopard linker or later, which
   2587         // automatically synthesizes these stubs.
   2588         OpFlags = X86II::MO_DARWIN_STUB;
   2589       } else if (Subtarget->isPICStyleRIPRel() &&
   2590                  isa<Function>(GV) &&
   2591                  cast<Function>(GV)->getAttributes().
   2592                    hasAttribute(AttributeSet::FunctionIndex,
   2593                                 Attribute::NonLazyBind)) {
   2594         // If the function is marked as non-lazy, generate an indirect call
   2595         // which loads from the GOT directly. This avoids runtime overhead
   2596         // at the cost of eager binding (and one extra byte of encoding).
   2597         OpFlags = X86II::MO_GOTPCREL;
   2598         WrapperKind = X86ISD::WrapperRIP;
   2599         ExtraLoad = true;
   2600       }
   2601 
   2602       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
   2603                                           G->getOffset(), OpFlags);
   2604 
   2605       // Add a wrapper if needed.
   2606       if (WrapperKind != ISD::DELETED_NODE)
   2607         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
   2608       // Add extra indirection if needed.
   2609       if (ExtraLoad)
   2610         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
   2611                              MachinePointerInfo::getGOT(),
   2612                              false, false, false, 0);
   2613     }
   2614   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
   2615     unsigned char OpFlags = 0;
   2616 
   2617     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
   2618     // external symbols should go through the PLT.
   2619     if (Subtarget->isTargetELF() &&
   2620         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
   2621       OpFlags = X86II::MO_PLT;
   2622     } else if (Subtarget->isPICStyleStubAny() &&
   2623                (!Subtarget->getTargetTriple().isMacOSX() ||
   2624                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
   2625       // PC-relative references to external symbols should go through $stub,
   2626       // unless we're building with the leopard linker or later, which
   2627       // automatically synthesizes these stubs.
   2628       OpFlags = X86II::MO_DARWIN_STUB;
   2629     }
   2630 
   2631     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
   2632                                          OpFlags);
   2633   }
   2634 
   2635   // Returns a chain & a flag for retval copy to use.
   2636   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
   2637   SmallVector<SDValue, 8> Ops;
   2638 
   2639   if (!IsSibcall && isTailCall) {
   2640     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
   2641                            DAG.getIntPtrConstant(0, true), InFlag);
   2642     InFlag = Chain.getValue(1);
   2643   }
   2644 
   2645   Ops.push_back(Chain);
   2646   Ops.push_back(Callee);
   2647 
   2648   if (isTailCall)
   2649     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
   2650 
   2651   // Add argument registers to the end of the list so that they are known live
   2652   // into the call.
   2653   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
   2654     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
   2655                                   RegsToPass[i].second.getValueType()));
   2656 
   2657   // Add a register mask operand representing the call-preserved registers.
   2658   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
   2659   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
   2660   assert(Mask && "Missing call preserved mask for calling convention");
   2661   Ops.push_back(DAG.getRegisterMask(Mask));
   2662 
   2663   if (InFlag.getNode())
   2664     Ops.push_back(InFlag);
   2665 
   2666   if (isTailCall) {
   2667     // We used to do:
   2668     //// If this is the first return lowered for this function, add the regs
   2669     //// to the liveout set for the function.
   2670     // This isn't right, although it's probably harmless on x86; liveouts
   2671     // should be computed from returns not tail calls.  Consider a void
   2672     // function making a tail call to a function returning int.
   2673     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
   2674   }
   2675 
   2676   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
   2677   InFlag = Chain.getValue(1);
   2678 
   2679   // Create the CALLSEQ_END node.
   2680   unsigned NumBytesForCalleeToPush;
   2681   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
   2682                        getTargetMachine().Options.GuaranteedTailCallOpt))
   2683     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
   2684   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
   2685            SR == StackStructReturn)
   2686     // If this is a call to a struct-return function, the callee
   2687     // pops the hidden struct pointer, so we have to push it back.
   2688     // This is common for Darwin/X86, Linux & Mingw32 targets.
   2689     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
   2690     NumBytesForCalleeToPush = 4;
   2691   else
   2692     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
   2693 
   2694   // Returns a flag for retval copy to use.
   2695   if (!IsSibcall) {
   2696     Chain = DAG.getCALLSEQ_END(Chain,
   2697                                DAG.getIntPtrConstant(NumBytes, true),
   2698                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
   2699                                                      true),
   2700                                InFlag);
   2701     InFlag = Chain.getValue(1);
   2702   }
   2703 
   2704   // Handle result values, copying them out of physregs into vregs that we
   2705   // return.
   2706   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
   2707                          Ins, dl, DAG, InVals);
   2708 }
   2709 
   2710 //===----------------------------------------------------------------------===//
   2711 //                Fast Calling Convention (tail call) implementation
   2712 //===----------------------------------------------------------------------===//
   2713 
   2714 //  Like std call, callee cleans arguments, convention except that ECX is
   2715 //  reserved for storing the tail called function address. Only 2 registers are
   2716 //  free for argument passing (inreg). Tail call optimization is performed
   2717 //  provided:
   2718 //                * tailcallopt is enabled
   2719 //                * caller/callee are fastcc
   2720 //  On X86_64 architecture with GOT-style position independent code only local
   2721 //  (within module) calls are supported at the moment.
   2722 //  To keep the stack aligned according to platform abi the function
   2723 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
   2724 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
   2725 //  If a tail called function callee has more arguments than the caller the
   2726 //  caller needs to make sure that there is room to move the RETADDR to. This is
   2727 //  achieved by reserving an area the size of the argument delta right after the
   2728 //  original REtADDR, but before the saved framepointer or the spilled registers
   2729 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
   2730 //  stack layout:
   2731 //    arg1
   2732 //    arg2
   2733 //    RETADDR
   2734 //    [ new RETADDR
   2735 //      move area ]
   2736 //    (possible EBP)
   2737 //    ESI
   2738 //    EDI
   2739 //    local1 ..
   2740 
   2741 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
   2742 /// for a 16 byte align requirement.
   2743 unsigned
   2744 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
   2745                                                SelectionDAG& DAG) const {
   2746   MachineFunction &MF = DAG.getMachineFunction();
   2747   const TargetMachine &TM = MF.getTarget();
   2748   const TargetFrameLowering &TFI = *TM.getFrameLowering();
   2749   unsigned StackAlignment = TFI.getStackAlignment();
   2750   uint64_t AlignMask = StackAlignment - 1;
   2751   int64_t Offset = StackSize;
   2752   unsigned SlotSize = RegInfo->getSlotSize();
   2753   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
   2754     // Number smaller than 12 so just add the difference.
   2755     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
   2756   } else {
   2757     // Mask out lower bits, add stackalignment once plus the 12 bytes.
   2758     Offset = ((~AlignMask) & Offset) + StackAlignment +
   2759       (StackAlignment-SlotSize);
   2760   }
   2761   return Offset;
   2762 }
   2763 
   2764 /// MatchingStackOffset - Return true if the given stack call argument is
   2765 /// already available in the same position (relatively) of the caller's
   2766 /// incoming argument stack.
   2767 static
   2768 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
   2769                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
   2770                          const X86InstrInfo *TII) {
   2771   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
   2772   int FI = INT_MAX;
   2773   if (Arg.getOpcode() == ISD::CopyFromReg) {
   2774     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
   2775     if (!TargetRegisterInfo::isVirtualRegister(VR))
   2776       return false;
   2777     MachineInstr *Def = MRI->getVRegDef(VR);
   2778     if (!Def)
   2779       return false;
   2780     if (!Flags.isByVal()) {
   2781       if (!TII->isLoadFromStackSlot(Def, FI))
   2782         return false;
   2783     } else {
   2784       unsigned Opcode = Def->getOpcode();
   2785       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
   2786           Def->getOperand(1).isFI()) {
   2787         FI = Def->getOperand(1).getIndex();
   2788         Bytes = Flags.getByValSize();
   2789       } else
   2790         return false;
   2791     }
   2792   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
   2793     if (Flags.isByVal())
   2794       // ByVal argument is passed in as a pointer but it's now being
   2795       // dereferenced. e.g.
   2796       // define @foo(%struct.X* %A) {
   2797       //   tail call @bar(%struct.X* byval %A)
   2798       // }
   2799       return false;
   2800     SDValue Ptr = Ld->getBasePtr();
   2801     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
   2802     if (!FINode)
   2803       return false;
   2804     FI = FINode->getIndex();
   2805   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
   2806     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
   2807     FI = FINode->getIndex();
   2808     Bytes = Flags.getByValSize();
   2809   } else
   2810     return false;
   2811 
   2812   assert(FI != INT_MAX);
   2813   if (!MFI->isFixedObjectIndex(FI))
   2814     return false;
   2815   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
   2816 }
   2817 
   2818 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
   2819 /// for tail call optimization. Targets which want to do tail call
   2820 /// optimization should implement this function.
   2821 bool
   2822 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
   2823                                                      CallingConv::ID CalleeCC,
   2824                                                      bool isVarArg,
   2825                                                      bool isCalleeStructRet,
   2826                                                      bool isCallerStructRet,
   2827                                                      Type *RetTy,
   2828                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
   2829                                     const SmallVectorImpl<SDValue> &OutVals,
   2830                                     const SmallVectorImpl<ISD::InputArg> &Ins,
   2831                                                      SelectionDAG &DAG) const {
   2832   if (!IsTailCallConvention(CalleeCC) &&
   2833       CalleeCC != CallingConv::C)
   2834     return false;
   2835 
   2836   // If -tailcallopt is specified, make fastcc functions tail-callable.
   2837   const MachineFunction &MF = DAG.getMachineFunction();
   2838   const Function *CallerF = DAG.getMachineFunction().getFunction();
   2839 
   2840   // If the function return type is x86_fp80 and the callee return type is not,
   2841   // then the FP_EXTEND of the call result is not a nop. It's not safe to
   2842   // perform a tailcall optimization here.
   2843   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
   2844     return false;
   2845 
   2846   CallingConv::ID CallerCC = CallerF->getCallingConv();
   2847   bool CCMatch = CallerCC == CalleeCC;
   2848 
   2849   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
   2850     if (IsTailCallConvention(CalleeCC) && CCMatch)
   2851       return true;
   2852     return false;
   2853   }
   2854 
   2855   // Look for obvious safe cases to perform tail call optimization that do not
   2856   // require ABI changes. This is what gcc calls sibcall.
   2857 
   2858   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
   2859   // emit a special epilogue.
   2860   if (RegInfo->needsStackRealignment(MF))
   2861     return false;
   2862 
   2863   // Also avoid sibcall optimization if either caller or callee uses struct
   2864   // return semantics.
   2865   if (isCalleeStructRet || isCallerStructRet)
   2866     return false;
   2867 
   2868   // An stdcall caller is expected to clean up its arguments; the callee
   2869   // isn't going to do that.
   2870   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
   2871     return false;
   2872 
   2873   // Do not sibcall optimize vararg calls unless all arguments are passed via
   2874   // registers.
   2875   if (isVarArg && !Outs.empty()) {
   2876 
   2877     // Optimizing for varargs on Win64 is unlikely to be safe without
   2878     // additional testing.
   2879     if (Subtarget->isTargetWin64())
   2880       return false;
   2881 
   2882     SmallVector<CCValAssign, 16> ArgLocs;
   2883     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
   2884                    getTargetMachine(), ArgLocs, *DAG.getContext());
   2885 
   2886     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
   2887     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
   2888       if (!ArgLocs[i].isRegLoc())
   2889         return false;
   2890   }
   2891 
   2892   // If the call result is in ST0 / ST1, it needs to be popped off the x87
   2893   // stack.  Therefore, if it's not used by the call it is not safe to optimize
   2894   // this into a sibcall.
   2895   bool Unused = false;
   2896   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
   2897     if (!Ins[i].Used) {
   2898       Unused = true;
   2899       break;
   2900     }
   2901   }
   2902   if (Unused) {
   2903     SmallVector<CCValAssign, 16> RVLocs;
   2904     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
   2905                    getTargetMachine(), RVLocs, *DAG.getContext());
   2906     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
   2907     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
   2908       CCValAssign &VA = RVLocs[i];
   2909       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
   2910         return false;
   2911     }
   2912   }
   2913 
   2914   // If the calling conventions do not match, then we'd better make sure the
   2915   // results are returned in the same way as what the caller expects.
   2916   if (!CCMatch) {
   2917     SmallVector<CCValAssign, 16> RVLocs1;
   2918     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
   2919                     getTargetMachine(), RVLocs1, *DAG.getContext());
   2920     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
   2921 
   2922     SmallVector<CCValAssign, 16> RVLocs2;
   2923     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
   2924                     getTargetMachine(), RVLocs2, *DAG.getContext());
   2925     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
   2926 
   2927     if (RVLocs1.size() != RVLocs2.size())
   2928       return false;
   2929     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
   2930       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
   2931         return false;
   2932       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
   2933         return false;
   2934       if (RVLocs1[i].isRegLoc()) {
   2935         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
   2936           return false;
   2937       } else {
   2938         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
   2939           return false;
   2940       }
   2941     }
   2942   }
   2943 
   2944   // If the callee takes no arguments then go on to check the results of the
   2945   // call.
   2946   if (!Outs.empty()) {
   2947     // Check if stack adjustment is needed. For now, do not do this if any
   2948     // argument is passed on the stack.
   2949     SmallVector<CCValAssign, 16> ArgLocs;
   2950     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
   2951                    getTargetMachine(), ArgLocs, *DAG.getContext());
   2952 
   2953     // Allocate shadow area for Win64
   2954     if (Subtarget->isTargetWin64()) {
   2955       CCInfo.AllocateStack(32, 8);
   2956     }
   2957 
   2958     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
   2959     if (CCInfo.getNextStackOffset()) {
   2960       MachineFunction &MF = DAG.getMachineFunction();
   2961       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
   2962         return false;
   2963 
   2964       // Check if the arguments are already laid out in the right way as
   2965       // the caller's fixed stack objects.
   2966       MachineFrameInfo *MFI = MF.getFrameInfo();
   2967       const MachineRegisterInfo *MRI = &MF.getRegInfo();
   2968       const X86InstrInfo *TII =
   2969         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
   2970       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
   2971         CCValAssign &VA = ArgLocs[i];
   2972         SDValue Arg = OutVals[i];
   2973         ISD::ArgFlagsTy Flags = Outs[i].Flags;
   2974         if (VA.getLocInfo() == CCValAssign::Indirect)
   2975           return false;
   2976         if (!VA.isRegLoc()) {
   2977           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
   2978                                    MFI, MRI, TII))
   2979             return false;
   2980         }
   2981       }
   2982     }
   2983 
   2984     // If the tailcall address may be in a register, then make sure it's
   2985     // possible to register allocate for it. In 32-bit, the call address can
   2986     // only target EAX, EDX, or ECX since the tail call must be scheduled after
   2987     // callee-saved registers are restored. These happen to be the same
   2988     // registers used to pass 'inreg' arguments so watch out for those.
   2989     if (!Subtarget->is64Bit() &&
   2990         ((!isa<GlobalAddressSDNode>(Callee) &&
   2991           !isa<ExternalSymbolSDNode>(Callee)) ||
   2992          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
   2993       unsigned NumInRegs = 0;
   2994       // In PIC we need an extra register to formulate the address computation
   2995       // for the callee.
   2996       unsigned MaxInRegs =
   2997           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
   2998 
   2999       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
   3000         CCValAssign &VA = ArgLocs[i];
   3001         if (!VA.isRegLoc())
   3002           continue;
   3003         unsigned Reg = VA.getLocReg();
   3004         switch (Reg) {
   3005         default: break;
   3006         case X86::EAX: case X86::EDX: case X86::ECX:
   3007           if (++NumInRegs == MaxInRegs)
   3008             return false;
   3009           break;
   3010         }
   3011       }
   3012     }
   3013   }
   3014 
   3015   return true;
   3016 }
   3017 
   3018 FastISel *
   3019 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
   3020                                   const TargetLibraryInfo *libInfo) const {
   3021   return X86::createFastISel(funcInfo, libInfo);
   3022 }
   3023 
   3024 //===----------------------------------------------------------------------===//
   3025 //                           Other Lowering Hooks
   3026 //===----------------------------------------------------------------------===//
   3027 
   3028 static bool MayFoldLoad(SDValue Op) {
   3029   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
   3030 }
   3031 
   3032 static bool MayFoldIntoStore(SDValue Op) {
   3033   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
   3034 }
   3035 
   3036 static bool isTargetShuffle(unsigned Opcode) {
   3037   switch(Opcode) {
   3038   default: return false;
   3039   case X86ISD::PSHUFD:
   3040   case X86ISD::PSHUFHW:
   3041   case X86ISD::PSHUFLW:
   3042   case X86ISD::SHUFP:
   3043   case X86ISD::PALIGNR:
   3044   case X86ISD::MOVLHPS:
   3045   case X86ISD::MOVLHPD:
   3046   case X86ISD::MOVHLPS:
   3047   case X86ISD::MOVLPS:
   3048   case X86ISD::MOVLPD:
   3049   case X86ISD::MOVSHDUP:
   3050   case X86ISD::MOVSLDUP:
   3051   case X86ISD::MOVDDUP:
   3052   case X86ISD::MOVSS:
   3053   case X86ISD::MOVSD:
   3054   case X86ISD::UNPCKL:
   3055   case X86ISD::UNPCKH:
   3056   case X86ISD::VPERMILP:
   3057   case X86ISD::VPERM2X128:
   3058   case X86ISD::VPERMI:
   3059     return true;
   3060   }
   3061 }
   3062 
   3063 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
   3064                                     SDValue V1, SelectionDAG &DAG) {
   3065   switch(Opc) {
   3066   default: llvm_unreachable("Unknown x86 shuffle node");
   3067   case X86ISD::MOVSHDUP:
   3068   case X86ISD::MOVSLDUP:
   3069   case X86ISD::MOVDDUP:
   3070     return DAG.getNode(Opc, dl, VT, V1);
   3071   }
   3072 }
   3073 
   3074 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
   3075                                     SDValue V1, unsigned TargetMask,
   3076                                     SelectionDAG &DAG) {
   3077   switch(Opc) {
   3078   default: llvm_unreachable("Unknown x86 shuffle node");
   3079   case X86ISD::PSHUFD:
   3080   case X86ISD::PSHUFHW:
   3081   case X86ISD::PSHUFLW:
   3082   case X86ISD::VPERMILP:
   3083   case X86ISD::VPERMI:
   3084     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
   3085   }
   3086 }
   3087 
   3088 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
   3089                                     SDValue V1, SDValue V2, unsigned TargetMask,
   3090                                     SelectionDAG &DAG) {
   3091   switch(Opc) {
   3092   default: llvm_unreachable("Unknown x86 shuffle node");
   3093   case X86ISD::PALIGNR:
   3094   case X86ISD::SHUFP:
   3095   case X86ISD::VPERM2X128:
   3096     return DAG.getNode(Opc, dl, VT, V1, V2,
   3097                        DAG.getConstant(TargetMask, MVT::i8));
   3098   }
   3099 }
   3100 
   3101 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
   3102                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
   3103   switch(Opc) {
   3104   default: llvm_unreachable("Unknown x86 shuffle node");
   3105   case X86ISD::MOVLHPS:
   3106   case X86ISD::MOVLHPD:
   3107   case X86ISD::MOVHLPS:
   3108   case X86ISD::MOVLPS:
   3109   case X86ISD::MOVLPD:
   3110   case X86ISD::MOVSS:
   3111   case X86ISD::MOVSD:
   3112   case X86ISD::UNPCKL:
   3113   case X86ISD::UNPCKH:
   3114     return DAG.getNode(Opc, dl, VT, V1, V2);
   3115   }
   3116 }
   3117 
   3118 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
   3119   MachineFunction &MF = DAG.getMachineFunction();
   3120   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
   3121   int ReturnAddrIndex = FuncInfo->getRAIndex();
   3122 
   3123   if (ReturnAddrIndex == 0) {
   3124     // Set up a frame object for the return address.
   3125     unsigned SlotSize = RegInfo->getSlotSize();
   3126     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
   3127                                                            false);
   3128     FuncInfo->setRAIndex(ReturnAddrIndex);
   3129   }
   3130 
   3131   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
   3132 }
   3133 
   3134 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
   3135                                        bool hasSymbolicDisplacement) {
   3136   // Offset should fit into 32 bit immediate field.
   3137   if (!isInt<32>(Offset))
   3138     return false;
   3139 
   3140   // If we don't have a symbolic displacement - we don't have any extra
   3141   // restrictions.
   3142   if (!hasSymbolicDisplacement)
   3143     return true;
   3144 
   3145   // FIXME: Some tweaks might be needed for medium code model.
   3146   if (M != CodeModel::Small && M != CodeModel::Kernel)
   3147     return false;
   3148 
   3149   // For small code model we assume that latest object is 16MB before end of 31
   3150   // bits boundary. We may also accept pretty large negative constants knowing
   3151   // that all objects are in the positive half of address space.
   3152   if (M == CodeModel::Small && Offset < 16*1024*1024)
   3153     return true;
   3154 
   3155   // For kernel code model we know that all object resist in the negative half
   3156   // of 32bits address space. We may not accept negative offsets, since they may
   3157   // be just off and we may accept pretty large positive ones.
   3158   if (M == CodeModel::Kernel && Offset > 0)
   3159     return true;
   3160 
   3161   return false;
   3162 }
   3163 
   3164 /// isCalleePop - Determines whether the callee is required to pop its
   3165 /// own arguments. Callee pop is necessary to support tail calls.
   3166 bool X86::isCalleePop(CallingConv::ID CallingConv,
   3167                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
   3168   if (IsVarArg)
   3169     return false;
   3170 
   3171   switch (CallingConv) {
   3172   default:
   3173     return false;
   3174   case CallingConv::X86_StdCall:
   3175     return !is64Bit;
   3176   case CallingConv::X86_FastCall:
   3177     return !is64Bit;
   3178   case CallingConv::X86_ThisCall:
   3179     return !is64Bit;
   3180   case CallingConv::Fast:
   3181     return TailCallOpt;
   3182   case CallingConv::GHC:
   3183     return TailCallOpt;
   3184   case CallingConv::HiPE:
   3185     return TailCallOpt;
   3186   }
   3187 }
   3188 
   3189 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
   3190 /// specific condition code, returning the condition code and the LHS/RHS of the
   3191 /// comparison to make.
   3192 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
   3193                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
   3194   if (!isFP) {
   3195     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
   3196       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
   3197         // X > -1   -> X == 0, jump !sign.
   3198         RHS = DAG.getConstant(0, RHS.getValueType());
   3199         return X86::COND_NS;
   3200       }
   3201       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
   3202         // X < 0   -> X == 0, jump on sign.
   3203         return X86::COND_S;
   3204       }
   3205       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
   3206         // X < 1   -> X <= 0
   3207         RHS = DAG.getConstant(0, RHS.getValueType());
   3208         return X86::COND_LE;
   3209       }
   3210     }
   3211 
   3212     switch (SetCCOpcode) {
   3213     default: llvm_unreachable("Invalid integer condition!");
   3214     case ISD::SETEQ:  return X86::COND_E;
   3215     case ISD::SETGT:  return X86::COND_G;
   3216     case ISD::SETGE:  return X86::COND_GE;
   3217     case ISD::SETLT:  return X86::COND_L;
   3218     case ISD::SETLE:  return X86::COND_LE;
   3219     case ISD::SETNE:  return X86::COND_NE;
   3220     case ISD::SETULT: return X86::COND_B;
   3221     case ISD::SETUGT: return X86::COND_A;
   3222     case ISD::SETULE: return X86::COND_BE;
   3223     case ISD::SETUGE: return X86::COND_AE;
   3224     }
   3225   }
   3226 
   3227   // First determine if it is required or is profitable to flip the operands.
   3228 
   3229   // If LHS is a foldable load, but RHS is not, flip the condition.
   3230   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
   3231       !ISD::isNON_EXTLoad(RHS.getNode())) {
   3232     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
   3233     std::swap(LHS, RHS);
   3234   }
   3235 
   3236   switch (SetCCOpcode) {
   3237   default: break;
   3238   case ISD::SETOLT:
   3239   case ISD::SETOLE:
   3240   case ISD::SETUGT:
   3241   case ISD::SETUGE:
   3242     std::swap(LHS, RHS);
   3243     break;
   3244   }
   3245 
   3246   // On a floating point condition, the flags are set as follows:
   3247   // ZF  PF  CF   op
   3248   //  0 | 0 | 0 | X > Y
   3249   //  0 | 0 | 1 | X < Y
   3250   //  1 | 0 | 0 | X == Y
   3251   //  1 | 1 | 1 | unordered
   3252   switch (SetCCOpcode) {
   3253   default: llvm_unreachable("Condcode should be pre-legalized away");
   3254   case ISD::SETUEQ:
   3255   case ISD::SETEQ:   return X86::COND_E;
   3256   case ISD::SETOLT:              // flipped
   3257   case ISD::SETOGT:
   3258   case ISD::SETGT:   return X86::COND_A;
   3259   case ISD::SETOLE:              // flipped
   3260   case ISD::SETOGE:
   3261   case ISD::SETGE:   return X86::COND_AE;
   3262   case ISD::SETUGT:              // flipped
   3263   case ISD::SETULT:
   3264   case ISD::SETLT:   return X86::COND_B;
   3265   case ISD::SETUGE:              // flipped
   3266   case ISD::SETULE:
   3267   case ISD::SETLE:   return X86::COND_BE;
   3268   case ISD::SETONE:
   3269   case ISD::SETNE:   return X86::COND_NE;
   3270   case ISD::SETUO:   return X86::COND_P;
   3271   case ISD::SETO:    return X86::COND_NP;
   3272   case ISD::SETOEQ:
   3273   case ISD::SETUNE:  return X86::COND_INVALID;
   3274   }
   3275 }
   3276 
   3277 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
   3278 /// code. Current x86 isa includes the following FP cmov instructions:
   3279 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
   3280 static bool hasFPCMov(unsigned X86CC) {
   3281   switch (X86CC) {
   3282   default:
   3283     return false;
   3284   case X86::COND_B:
   3285   case X86::COND_BE:
   3286   case X86::COND_E:
   3287   case X86::COND_P:
   3288   case X86::COND_A:
   3289   case X86::COND_AE:
   3290   case X86::COND_NE:
   3291   case X86::COND_NP:
   3292     return true;
   3293   }
   3294 }
   3295 
   3296 /// isFPImmLegal - Returns true if the target can instruction select the
   3297 /// specified FP immediate natively. If false, the legalizer will
   3298 /// materialize the FP immediate as a load from a constant pool.
   3299 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
   3300   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
   3301     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
   3302       return true;
   3303   }
   3304   return false;
   3305 }
   3306 
   3307 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
   3308 /// the specified range (L, H].
   3309 static bool isUndefOrInRange(int Val, int Low, int Hi) {
   3310   return (Val < 0) || (Val >= Low && Val < Hi);
   3311 }
   3312 
   3313 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
   3314 /// specified value.
   3315 static bool isUndefOrEqual(int Val, int CmpVal) {
   3316   return (Val < 0 || Val == CmpVal);
   3317 }
   3318 
   3319 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
   3320 /// from position Pos and ending in Pos+Size, falls within the specified
   3321 /// sequential range (L, L+Pos]. or is undef.
   3322 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
   3323                                        unsigned Pos, unsigned Size, int Low) {
   3324   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
   3325     if (!isUndefOrEqual(Mask[i], Low))
   3326       return false;
   3327   return true;
   3328 }
   3329 
   3330 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
   3331 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
   3332 /// the second operand.
   3333 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
   3334   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
   3335     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
   3336   if (VT == MVT::v2f64 || VT == MVT::v2i64)
   3337     return (Mask[0] < 2 && Mask[1] < 2);
   3338   return false;
   3339 }
   3340 
   3341 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
   3342 /// is suitable for input to PSHUFHW.
   3343 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
   3344   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
   3345     return false;
   3346 
   3347   // Lower quadword copied in order or undef.
   3348   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
   3349     return false;
   3350 
   3351   // Upper quadword shuffled.
   3352   for (unsigned i = 4; i != 8; ++i)
   3353     if (!isUndefOrInRange(Mask[i], 4, 8))
   3354       return false;
   3355 
   3356   if (VT == MVT::v16i16) {
   3357     // Lower quadword copied in order or undef.
   3358     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
   3359       return false;
   3360 
   3361     // Upper quadword shuffled.
   3362     for (unsigned i = 12; i != 16; ++i)
   3363       if (!isUndefOrInRange(Mask[i], 12, 16))
   3364         return false;
   3365   }
   3366 
   3367   return true;
   3368 }
   3369 
   3370 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
   3371 /// is suitable for input to PSHUFLW.
   3372 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
   3373   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
   3374     return false;
   3375 
   3376   // Upper quadword copied in order.
   3377   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
   3378     return false;
   3379 
   3380   // Lower quadword shuffled.
   3381   for (unsigned i = 0; i != 4; ++i)
   3382     if (!isUndefOrInRange(Mask[i], 0, 4))
   3383       return false;
   3384 
   3385   if (VT == MVT::v16i16) {
   3386     // Upper quadword copied in order.
   3387     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
   3388       return false;
   3389 
   3390     // Lower quadword shuffled.
   3391     for (unsigned i = 8; i != 12; ++i)
   3392       if (!isUndefOrInRange(Mask[i], 8, 12))
   3393         return false;
   3394   }
   3395 
   3396   return true;
   3397 }
   3398 
   3399 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
   3400 /// is suitable for input to PALIGNR.
   3401 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
   3402                           const X86Subtarget *Subtarget) {
   3403   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
   3404       (VT.is256BitVector() && !Subtarget->hasInt256()))
   3405     return false;
   3406 
   3407   unsigned NumElts = VT.getVectorNumElements();
   3408   unsigned NumLanes = VT.getSizeInBits()/128;
   3409   unsigned NumLaneElts = NumElts/NumLanes;
   3410 
   3411   // Do not handle 64-bit element shuffles with palignr.
   3412   if (NumLaneElts == 2)
   3413     return false;
   3414 
   3415   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
   3416     unsigned i;
   3417     for (i = 0; i != NumLaneElts; ++i) {
   3418       if (Mask[i+l] >= 0)
   3419         break;
   3420     }
   3421 
   3422     // Lane is all undef, go to next lane
   3423     if (i == NumLaneElts)
   3424       continue;
   3425 
   3426     int Start = Mask[i+l];
   3427 
   3428     // Make sure its in this lane in one of the sources
   3429     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
   3430         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
   3431       return false;
   3432 
   3433     // If not lane 0, then we must match lane 0
   3434     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
   3435       return false;
   3436 
   3437     // Correct second source to be contiguous with first source
   3438     if (Start >= (int)NumElts)
   3439       Start -= NumElts - NumLaneElts;
   3440 
   3441     // Make sure we're shifting in the right direction.
   3442     if (Start <= (int)(i+l))
   3443       return false;
   3444 
   3445     Start -= i;
   3446 
   3447     // Check the rest of the elements to see if they are consecutive.
   3448     for (++i; i != NumLaneElts; ++i) {
   3449       int Idx = Mask[i+l];
   3450 
   3451       // Make sure its in this lane
   3452       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
   3453           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
   3454         return false;
   3455 
   3456       // If not lane 0, then we must match lane 0
   3457       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
   3458         return false;
   3459 
   3460       if (Idx >= (int)NumElts)
   3461         Idx -= NumElts - NumLaneElts;
   3462 
   3463       if (!isUndefOrEqual(Idx, Start+i))
   3464         return false;
   3465 
   3466     }
   3467   }
   3468 
   3469   return true;
   3470 }
   3471 
   3472 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
   3473 /// the two vector operands have swapped position.
   3474 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
   3475                                      unsigned NumElems) {
   3476   for (unsigned i = 0; i != NumElems; ++i) {
   3477     int idx = Mask[i];
   3478     if (idx < 0)
   3479       continue;
   3480     else if (idx < (int)NumElems)
   3481       Mask[i] = idx + NumElems;
   3482     else
   3483       Mask[i] = idx - NumElems;
   3484   }
   3485 }
   3486 
   3487 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
   3488 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
   3489 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
   3490 /// reverse of what x86 shuffles want.
   3491 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
   3492                         bool Commuted = false) {
   3493   if (!HasFp256 && VT.is256BitVector())
   3494     return false;
   3495 
   3496   unsigned NumElems = VT.getVectorNumElements();
   3497   unsigned NumLanes = VT.getSizeInBits()/128;
   3498   unsigned NumLaneElems = NumElems/NumLanes;
   3499 
   3500   if (NumLaneElems != 2 && NumLaneElems != 4)
   3501     return false;
   3502 
   3503   // VSHUFPSY divides the resulting vector into 4 chunks.
   3504   // The sources are also splitted into 4 chunks, and each destination
   3505   // chunk must come from a different source chunk.
   3506   //
   3507   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
   3508   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
   3509   //
   3510   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
   3511   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
   3512   //
   3513   // VSHUFPDY divides the resulting vector into 4 chunks.
   3514   // The sources are also splitted into 4 chunks, and each destination
   3515   // chunk must come from a different source chunk.
   3516   //
   3517   //  SRC1 =>      X3       X2       X1       X0
   3518   //  SRC2 =>      Y3       Y2       Y1       Y0
   3519   //
   3520   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
   3521   //
   3522   unsigned HalfLaneElems = NumLaneElems/2;
   3523   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
   3524     for (unsigned i = 0; i != NumLaneElems; ++i) {
   3525       int Idx = Mask[i+l];
   3526       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
   3527       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
   3528         return false;
   3529       // For VSHUFPSY, the mask of the second half must be the same as the
   3530       // first but with the appropriate offsets. This works in the same way as
   3531       // VPERMILPS works with masks.
   3532       if (NumElems != 8 || l == 0 || Mask[i] < 0)
   3533         continue;
   3534       if (!isUndefOrEqual(Idx, Mask[i]+l))
   3535         return false;
   3536     }
   3537   }
   3538 
   3539   return true;
   3540 }
   3541 
   3542 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
   3543 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
   3544 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
   3545   if (!VT.is128BitVector())
   3546     return false;
   3547 
   3548   unsigned NumElems = VT.getVectorNumElements();
   3549 
   3550   if (NumElems != 4)
   3551     return false;
   3552 
   3553   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
   3554   return isUndefOrEqual(Mask[0], 6) &&
   3555          isUndefOrEqual(Mask[1], 7) &&
   3556          isUndefOrEqual(Mask[2], 2) &&
   3557          isUndefOrEqual(Mask[3], 3);
   3558 }
   3559 
   3560 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
   3561 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
   3562 /// <2, 3, 2, 3>
   3563 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
   3564   if (!VT.is128BitVector())
   3565     return false;
   3566 
   3567   unsigned NumElems = VT.getVectorNumElements();
   3568 
   3569   if (NumElems != 4)
   3570     return false;
   3571 
   3572   return isUndefOrEqual(Mask[0], 2) &&
   3573          isUndefOrEqual(Mask[1], 3) &&
   3574          isUndefOrEqual(Mask[2], 2) &&
   3575          isUndefOrEqual(Mask[3], 3);
   3576 }
   3577 
   3578 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
   3579 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
   3580 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
   3581   if (!VT.is128BitVector())
   3582     return false;
   3583 
   3584   unsigned NumElems = VT.getVectorNumElements();
   3585 
   3586   if (NumElems != 2 && NumElems != 4)
   3587     return false;
   3588 
   3589   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
   3590     if (!isUndefOrEqual(Mask[i], i + NumElems))
   3591       return false;
   3592 
   3593   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
   3594     if (!isUndefOrEqual(Mask[i], i))
   3595       return false;
   3596 
   3597   return true;
   3598 }
   3599 
   3600 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
   3601 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
   3602 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
   3603   if (!VT.is128BitVector())
   3604     return false;
   3605 
   3606   unsigned NumElems = VT.getVectorNumElements();
   3607 
   3608   if (NumElems != 2 && NumElems != 4)
   3609     return false;
   3610 
   3611   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
   3612     if (!isUndefOrEqual(Mask[i], i))
   3613       return false;
   3614 
   3615   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
   3616     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
   3617       return false;
   3618 
   3619   return true;
   3620 }
   3621 
   3622 //
   3623 // Some special combinations that can be optimized.
   3624 //
   3625 static
   3626 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
   3627                                SelectionDAG &DAG) {
   3628   MVT VT = SVOp->getValueType(0).getSimpleVT();
   3629   DebugLoc dl = SVOp->getDebugLoc();
   3630 
   3631   if (VT != MVT::v8i32 && VT != MVT::v8f32)
   3632     return SDValue();
   3633 
   3634   ArrayRef<int> Mask = SVOp->getMask();
   3635 
   3636   // These are the special masks that may be optimized.
   3637   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
   3638   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
   3639   bool MatchEvenMask = true;
   3640   bool MatchOddMask  = true;
   3641   for (int i=0; i<8; ++i) {
   3642     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
   3643       MatchEvenMask = false;
   3644     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
   3645       MatchOddMask = false;
   3646   }
   3647 
   3648   if (!MatchEvenMask && !MatchOddMask)
   3649     return SDValue();
   3650 
   3651   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
   3652 
   3653   SDValue Op0 = SVOp->getOperand(0);
   3654   SDValue Op1 = SVOp->getOperand(1);
   3655 
   3656   if (MatchEvenMask) {
   3657     // Shift the second operand right to 32 bits.
   3658     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
   3659     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
   3660   } else {
   3661     // Shift the first operand left to 32 bits.
   3662     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
   3663     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
   3664   }
   3665   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
   3666   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
   3667 }
   3668 
   3669 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
   3670 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
   3671 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
   3672                          bool HasInt256, bool V2IsSplat = false) {
   3673   unsigned NumElts = VT.getVectorNumElements();
   3674 
   3675   assert((VT.is128BitVector() || VT.is256BitVector()) &&
   3676          "Unsupported vector type for unpckh");
   3677 
   3678   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
   3679       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
   3680     return false;
   3681 
   3682   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
   3683   // independently on 128-bit lanes.
   3684   unsigned NumLanes = VT.getSizeInBits()/128;
   3685   unsigned NumLaneElts = NumElts/NumLanes;
   3686 
   3687   for (unsigned l = 0; l != NumLanes; ++l) {
   3688     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
   3689          i != (l+1)*NumLaneElts;
   3690          i += 2, ++j) {
   3691       int BitI  = Mask[i];
   3692       int BitI1 = Mask[i+1];
   3693       if (!isUndefOrEqual(BitI, j))
   3694         return false;
   3695       if (V2IsSplat) {
   3696         if (!isUndefOrEqual(BitI1, NumElts))
   3697           return false;
   3698       } else {
   3699         if (!isUndefOrEqual(BitI1, j + NumElts))
   3700           return false;
   3701       }
   3702     }
   3703   }
   3704 
   3705   return true;
   3706 }
   3707 
   3708 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
   3709 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
   3710 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
   3711                          bool HasInt256, bool V2IsSplat = false) {
   3712   unsigned NumElts = VT.getVectorNumElements();
   3713 
   3714   assert((VT.is128BitVector() || VT.is256BitVector()) &&
   3715          "Unsupported vector type for unpckh");
   3716 
   3717   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
   3718       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
   3719     return false;
   3720 
   3721   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
   3722   // independently on 128-bit lanes.
   3723   unsigned NumLanes = VT.getSizeInBits()/128;
   3724   unsigned NumLaneElts = NumElts/NumLanes;
   3725 
   3726   for (unsigned l = 0; l != NumLanes; ++l) {
   3727     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
   3728          i != (l+1)*NumLaneElts; i += 2, ++j) {
   3729       int BitI  = Mask[i];
   3730       int BitI1 = Mask[i+1];
   3731       if (!isUndefOrEqual(BitI, j))
   3732         return false;
   3733       if (V2IsSplat) {
   3734         if (isUndefOrEqual(BitI1, NumElts))
   3735           return false;
   3736       } else {
   3737         if (!isUndefOrEqual(BitI1, j+NumElts))
   3738           return false;
   3739       }
   3740     }
   3741   }
   3742   return true;
   3743 }
   3744 
   3745 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
   3746 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
   3747 /// <0, 0, 1, 1>
   3748 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
   3749   unsigned NumElts = VT.getVectorNumElements();
   3750   bool Is256BitVec = VT.is256BitVector();
   3751 
   3752   assert((VT.is128BitVector() || VT.is256BitVector()) &&
   3753          "Unsupported vector type for unpckh");
   3754 
   3755   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
   3756       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
   3757     return false;
   3758 
   3759   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
   3760   // FIXME: Need a better way to get rid of this, there's no latency difference
   3761   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
   3762   // the former later. We should also remove the "_undef" special mask.
   3763   if (NumElts == 4 && Is256BitVec)
   3764     return false;
   3765 
   3766   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
   3767   // independently on 128-bit lanes.
   3768   unsigned NumLanes = VT.getSizeInBits()/128;
   3769   unsigned NumLaneElts = NumElts/NumLanes;
   3770 
   3771   for (unsigned l = 0; l != NumLanes; ++l) {
   3772     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
   3773          i != (l+1)*NumLaneElts;
   3774          i += 2, ++j) {
   3775       int BitI  = Mask[i];
   3776       int BitI1 = Mask[i+1];
   3777 
   3778       if (!isUndefOrEqual(BitI, j))
   3779         return false;
   3780       if (!isUndefOrEqual(BitI1, j))
   3781         return false;
   3782     }
   3783   }
   3784 
   3785   return true;
   3786 }
   3787 
   3788 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
   3789 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
   3790 /// <2, 2, 3, 3>
   3791 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
   3792   unsigned NumElts = VT.getVectorNumElements();
   3793 
   3794   assert((VT.is128BitVector() || VT.is256BitVector()) &&
   3795          "Unsupported vector type for unpckh");
   3796 
   3797   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
   3798       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
   3799     return false;
   3800 
   3801   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
   3802   // independently on 128-bit lanes.
   3803   unsigned NumLanes = VT.getSizeInBits()/128;
   3804   unsigned NumLaneElts = NumElts/NumLanes;
   3805 
   3806   for (unsigned l = 0; l != NumLanes; ++l) {
   3807     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
   3808          i != (l+1)*NumLaneElts; i += 2, ++j) {
   3809       int BitI  = Mask[i];
   3810       int BitI1 = Mask[i+1];
   3811       if (!isUndefOrEqual(BitI, j))
   3812         return false;
   3813       if (!isUndefOrEqual(BitI1, j))
   3814         return false;
   3815     }
   3816   }
   3817   return true;
   3818 }
   3819 
   3820 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
   3821 /// specifies a shuffle of elements that is suitable for input to MOVSS,
   3822 /// MOVSD, and MOVD, i.e. setting the lowest element.
   3823 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
   3824   if (VT.getVectorElementType().getSizeInBits() < 32)
   3825     return false;
   3826   if (!VT.is128BitVector())
   3827     return false;
   3828 
   3829   unsigned NumElts = VT.getVectorNumElements();
   3830 
   3831   if (!isUndefOrEqual(Mask[0], NumElts))
   3832     return false;
   3833 
   3834   for (unsigned i = 1; i != NumElts; ++i)
   3835     if (!isUndefOrEqual(Mask[i], i))
   3836       return false;
   3837 
   3838   return true;
   3839 }
   3840 
   3841 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
   3842 /// as permutations between 128-bit chunks or halves. As an example: this
   3843 /// shuffle bellow:
   3844 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
   3845 /// The first half comes from the second half of V1 and the second half from the
   3846 /// the second half of V2.
   3847 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
   3848   if (!HasFp256 || !VT.is256BitVector())
   3849     return false;
   3850 
   3851   // The shuffle result is divided into half A and half B. In total the two
   3852   // sources have 4 halves, namely: C, D, E, F. The final values of A and
   3853   // B must come from C, D, E or F.
   3854   unsigned HalfSize = VT.getVectorNumElements()/2;
   3855   bool MatchA = false, MatchB = false;
   3856 
   3857   // Check if A comes from one of C, D, E, F.
   3858   for (unsigned Half = 0; Half != 4; ++Half) {
   3859     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
   3860       MatchA = true;
   3861       break;
   3862     }
   3863   }
   3864 
   3865   // Check if B comes from one of C, D, E, F.
   3866   for (unsigned Half = 0; Half != 4; ++Half) {
   3867     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
   3868       MatchB = true;
   3869       break;
   3870     }
   3871   }
   3872 
   3873   return MatchA && MatchB;
   3874 }
   3875 
   3876 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
   3877 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
   3878 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
   3879   MVT VT = SVOp->getValueType(0).getSimpleVT();
   3880 
   3881   unsigned HalfSize = VT.getVectorNumElements()/2;
   3882 
   3883   unsigned FstHalf = 0, SndHalf = 0;
   3884   for (unsigned i = 0; i < HalfSize; ++i) {
   3885     if (SVOp->getMaskElt(i) > 0) {
   3886       FstHalf = SVOp->getMaskElt(i)/HalfSize;
   3887       break;
   3888     }
   3889   }
   3890   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
   3891     if (SVOp->getMaskElt(i) > 0) {
   3892       SndHalf = SVOp->getMaskElt(i)/HalfSize;
   3893       break;
   3894     }
   3895   }
   3896 
   3897   return (FstHalf | (SndHalf << 4));
   3898 }
   3899 
   3900 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
   3901 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
   3902 /// Note that VPERMIL mask matching is different depending whether theunderlying
   3903 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
   3904 /// to the same elements of the low, but to the higher half of the source.
   3905 /// In VPERMILPD the two lanes could be shuffled independently of each other
   3906 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
   3907 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
   3908   if (!HasFp256)
   3909     return false;
   3910 
   3911   unsigned NumElts = VT.getVectorNumElements();
   3912   // Only match 256-bit with 32/64-bit types
   3913   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
   3914     return false;
   3915 
   3916   unsigned NumLanes = VT.getSizeInBits()/128;
   3917   unsigned LaneSize = NumElts/NumLanes;
   3918   for (unsigned l = 0; l != NumElts; l += LaneSize) {
   3919     for (unsigned i = 0; i != LaneSize; ++i) {
   3920       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
   3921         return false;
   3922       if (NumElts != 8 || l == 0)
   3923         continue;
   3924       // VPERMILPS handling
   3925       if (Mask[i] < 0)
   3926         continue;
   3927       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
   3928         return false;
   3929     }
   3930   }
   3931 
   3932   return true;
   3933 }
   3934 
   3935 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
   3936 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
   3937 /// element of vector 2 and the other elements to come from vector 1 in order.
   3938 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
   3939                                bool V2IsSplat = false, bool V2IsUndef = false) {
   3940   if (!VT.is128BitVector())
   3941     return false;
   3942 
   3943   unsigned NumOps = VT.getVectorNumElements();
   3944   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
   3945     return false;
   3946 
   3947   if (!isUndefOrEqual(Mask[0], 0))
   3948     return false;
   3949 
   3950   for (unsigned i = 1; i != NumOps; ++i)
   3951     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
   3952           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
   3953           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
   3954       return false;
   3955 
   3956   return true;
   3957 }
   3958 
   3959 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
   3960 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
   3961 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
   3962 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
   3963                            const X86Subtarget *Subtarget) {
   3964   if (!Subtarget->hasSSE3())
   3965     return false;
   3966 
   3967   unsigned NumElems = VT.getVectorNumElements();
   3968 
   3969   if ((VT.is128BitVector() && NumElems != 4) ||
   3970       (VT.is256BitVector() && NumElems != 8))
   3971     return false;
   3972 
   3973   // "i+1" is the value the indexed mask element must have
   3974   for (unsigned i = 0; i != NumElems; i += 2)
   3975     if (!isUndefOrEqual(Mask[i], i+1) ||
   3976         !isUndefOrEqual(Mask[i+1], i+1))
   3977       return false;
   3978 
   3979   return true;
   3980 }
   3981 
   3982 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
   3983 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
   3984 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
   3985 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
   3986                            const X86Subtarget *Subtarget) {
   3987   if (!Subtarget->hasSSE3())
   3988     return false;
   3989 
   3990   unsigned NumElems = VT.getVectorNumElements();
   3991 
   3992   if ((VT.is128BitVector() && NumElems != 4) ||
   3993       (VT.is256BitVector() && NumElems != 8))
   3994     return false;
   3995 
   3996   // "i" is the value the indexed mask element must have
   3997   for (unsigned i = 0; i != NumElems; i += 2)
   3998     if (!isUndefOrEqual(Mask[i], i) ||
   3999         !isUndefOrEqual(Mask[i+1], i))
   4000       return false;
   4001 
   4002   return true;
   4003 }
   4004 
   4005 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
   4006 /// specifies a shuffle of elements that is suitable for input to 256-bit
   4007 /// version of MOVDDUP.
   4008 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
   4009   if (!HasFp256 || !VT.is256BitVector())
   4010     return false;
   4011 
   4012   unsigned NumElts = VT.getVectorNumElements();
   4013   if (NumElts != 4)
   4014     return false;
   4015 
   4016   for (unsigned i = 0; i != NumElts/2; ++i)
   4017     if (!isUndefOrEqual(Mask[i], 0))
   4018       return false;
   4019   for (unsigned i = NumElts/2; i != NumElts; ++i)
   4020     if (!isUndefOrEqual(Mask[i], NumElts/2))
   4021       return false;
   4022   return true;
   4023 }
   4024 
   4025 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
   4026 /// specifies a shuffle of elements that is suitable for input to 128-bit
   4027 /// version of MOVDDUP.
   4028 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
   4029   if (!VT.is128BitVector())
   4030     return false;
   4031 
   4032   unsigned e = VT.getVectorNumElements() / 2;
   4033   for (unsigned i = 0; i != e; ++i)
   4034     if (!isUndefOrEqual(Mask[i], i))
   4035       return false;
   4036   for (unsigned i = 0; i != e; ++i)
   4037     if (!isUndefOrEqual(Mask[e+i], i))
   4038       return false;
   4039   return true;
   4040 }
   4041 
   4042 /// isVEXTRACTF128Index - Return true if the specified
   4043 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
   4044 /// suitable for input to VEXTRACTF128.
   4045 bool X86::isVEXTRACTF128Index(SDNode *N) {
   4046   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
   4047     return false;
   4048 
   4049   // The index should be aligned on a 128-bit boundary.
   4050   uint64_t Index =
   4051     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
   4052 
   4053   MVT VT = N->getValueType(0).getSimpleVT();
   4054   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
   4055   bool Result = (Index * ElSize) % 128 == 0;
   4056 
   4057   return Result;
   4058 }
   4059 
   4060 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
   4061 /// operand specifies a subvector insert that is suitable for input to
   4062 /// VINSERTF128.
   4063 bool X86::isVINSERTF128Index(SDNode *N) {
   4064   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
   4065     return false;
   4066 
   4067   // The index should be aligned on a 128-bit boundary.
   4068   uint64_t Index =
   4069     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
   4070 
   4071   MVT VT = N->getValueType(0).getSimpleVT();
   4072   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
   4073   bool Result = (Index * ElSize) % 128 == 0;
   4074 
   4075   return Result;
   4076 }
   4077 
   4078 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
   4079 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
   4080 /// Handles 128-bit and 256-bit.
   4081 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
   4082   MVT VT = N->getValueType(0).getSimpleVT();
   4083 
   4084   assert((VT.is128BitVector() || VT.is256BitVector()) &&
   4085          "Unsupported vector type for PSHUF/SHUFP");
   4086 
   4087   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
   4088   // independently on 128-bit lanes.
   4089   unsigned NumElts = VT.getVectorNumElements();
   4090   unsigned NumLanes = VT.getSizeInBits()/128;
   4091   unsigned NumLaneElts = NumElts/NumLanes;
   4092 
   4093   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
   4094          "Only supports 2 or 4 elements per lane");
   4095 
   4096   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
   4097   unsigned Mask = 0;
   4098   for (unsigned i = 0; i != NumElts; ++i) {
   4099     int Elt = N->getMaskElt(i);
   4100     if (Elt < 0) continue;
   4101     Elt &= NumLaneElts - 1;
   4102     unsigned ShAmt = (i << Shift) % 8;
   4103     Mask |= Elt << ShAmt;
   4104   }
   4105 
   4106   return Mask;
   4107 }
   4108 
   4109 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
   4110 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
   4111 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
   4112   MVT VT = N->getValueType(0).getSimpleVT();
   4113 
   4114   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
   4115          "Unsupported vector type for PSHUFHW");
   4116 
   4117   unsigned NumElts = VT.getVectorNumElements();
   4118 
   4119   unsigned Mask = 0;
   4120   for (unsigned l = 0; l != NumElts; l += 8) {
   4121     // 8 nodes per lane, but we only care about the last 4.
   4122     for (unsigned i = 0; i < 4; ++i) {
   4123       int Elt = N->getMaskElt(l+i+4);
   4124       if (Elt < 0) continue;
   4125       Elt &= 0x3; // only 2-bits.
   4126       Mask |= Elt << (i * 2);
   4127     }
   4128   }
   4129 
   4130   return Mask;
   4131 }
   4132 
   4133 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
   4134 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
   4135 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
   4136   MVT VT = N->getValueType(0).getSimpleVT();
   4137 
   4138   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
   4139          "Unsupported vector type for PSHUFHW");
   4140 
   4141   unsigned NumElts = VT.getVectorNumElements();
   4142 
   4143   unsigned Mask = 0;
   4144   for (unsigned l = 0; l != NumElts; l += 8) {
   4145     // 8 nodes per lane, but we only care about the first 4.
   4146     for (unsigned i = 0; i < 4; ++i) {
   4147       int Elt = N->getMaskElt(l+i);
   4148       if (Elt < 0) continue;
   4149       Elt &= 0x3; // only 2-bits
   4150       Mask |= Elt << (i * 2);
   4151     }
   4152   }
   4153 
   4154   return Mask;
   4155 }
   4156 
   4157 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
   4158 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
   4159 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
   4160   MVT VT = SVOp->getValueType(0).getSimpleVT();
   4161   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
   4162 
   4163   unsigned NumElts = VT.getVectorNumElements();
   4164   unsigned NumLanes = VT.getSizeInBits()/128;
   4165   unsigned NumLaneElts = NumElts/NumLanes;
   4166 
   4167   int Val = 0;
   4168   unsigned i;
   4169   for (i = 0; i != NumElts; ++i) {
   4170     Val = SVOp->getMaskElt(i);
   4171     if (Val >= 0)
   4172       break;
   4173   }
   4174   if (Val >= (int)NumElts)
   4175     Val -= NumElts - NumLaneElts;
   4176 
   4177   assert(Val - i > 0 && "PALIGNR imm should be positive");
   4178   return (Val - i) * EltSize;
   4179 }
   4180 
   4181 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
   4182 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
   4183 /// instructions.
   4184 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
   4185   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
   4186     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
   4187 
   4188   uint64_t Index =
   4189     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
   4190 
   4191   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
   4192   MVT ElVT = VecVT.getVectorElementType();
   4193 
   4194   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
   4195   return Index / NumElemsPerChunk;
   4196 }
   4197 
   4198 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
   4199 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
   4200 /// instructions.
   4201 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
   4202   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
   4203     llvm_unreachable("Illegal insert subvector for VINSERTF128");
   4204 
   4205   uint64_t Index =
   4206     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
   4207 
   4208   MVT VecVT = N->getValueType(0).getSimpleVT();
   4209   MVT ElVT = VecVT.getVectorElementType();
   4210 
   4211   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
   4212   return Index / NumElemsPerChunk;
   4213 }
   4214 
   4215 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
   4216 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
   4217 /// Handles 256-bit.
   4218 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
   4219   MVT VT = N->getValueType(0).getSimpleVT();
   4220 
   4221   unsigned NumElts = VT.getVectorNumElements();
   4222 
   4223   assert((VT.is256BitVector() && NumElts == 4) &&
   4224          "Unsupported vector type for VPERMQ/VPERMPD");
   4225 
   4226   unsigned Mask = 0;
   4227   for (unsigned i = 0; i != NumElts; ++i) {
   4228     int Elt = N->getMaskElt(i);
   4229     if (Elt < 0)
   4230       continue;
   4231     Mask |= Elt << (i*2);
   4232   }
   4233 
   4234   return Mask;
   4235 }
   4236 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
   4237 /// constant +0.0.
   4238 bool X86::isZeroNode(SDValue Elt) {
   4239   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
   4240     return CN->isNullValue();
   4241   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
   4242     return CFP->getValueAPF().isPosZero();
   4243   return false;
   4244 }
   4245 
   4246 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
   4247 /// their permute mask.
   4248 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
   4249                                     SelectionDAG &DAG) {
   4250   MVT VT = SVOp->getValueType(0).getSimpleVT();
   4251   unsigned NumElems = VT.getVectorNumElements();
   4252   SmallVector<int, 8> MaskVec;
   4253 
   4254   for (unsigned i = 0; i != NumElems; ++i) {
   4255     int Idx = SVOp->getMaskElt(i);
   4256     if (Idx >= 0) {
   4257       if (Idx < (int)NumElems)
   4258         Idx += NumElems;
   4259       else
   4260         Idx -= NumElems;
   4261     }
   4262     MaskVec.push_back(Idx);
   4263   }
   4264   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
   4265                               SVOp->getOperand(0), &MaskVec[0]);
   4266 }
   4267 
   4268 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
   4269 /// match movhlps. The lower half elements should come from upper half of
   4270 /// V1 (and in order), and the upper half elements should come from the upper
   4271 /// half of V2 (and in order).
   4272 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
   4273   if (!VT.is128BitVector())
   4274     return false;
   4275   if (VT.getVectorNumElements() != 4)
   4276     return false;
   4277   for (unsigned i = 0, e = 2; i != e; ++i)
   4278     if (!isUndefOrEqual(Mask[i], i+2))
   4279       return false;
   4280   for (unsigned i = 2; i != 4; ++i)
   4281     if (!isUndefOrEqual(Mask[i], i+4))
   4282       return false;
   4283   return true;
   4284 }
   4285 
   4286 /// isScalarLoadToVector - Returns true if the node is a scalar load that
   4287 /// is promoted to a vector. It also returns the LoadSDNode by reference if
   4288 /// required.
   4289 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
   4290   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
   4291     return false;
   4292   N = N->getOperand(0).getNode();
   4293   if (!ISD::isNON_EXTLoad(N))
   4294     return false;
   4295   if (LD)
   4296     *LD = cast<LoadSDNode>(N);
   4297   return true;
   4298 }
   4299 
   4300 // Test whether the given value is a vector value which will be legalized
   4301 // into a load.
   4302 static bool WillBeConstantPoolLoad(SDNode *N) {
   4303   if (N->getOpcode() != ISD::BUILD_VECTOR)
   4304     return false;
   4305 
   4306   // Check for any non-constant elements.
   4307   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
   4308     switch (N->getOperand(i).getNode()->getOpcode()) {
   4309     case ISD::UNDEF:
   4310     case ISD::ConstantFP:
   4311     case ISD::Constant:
   4312       break;
   4313     default:
   4314       return false;
   4315     }
   4316 
   4317   // Vectors of all-zeros and all-ones are materialized with special
   4318   // instructions rather than being loaded.
   4319   return !ISD::isBuildVectorAllZeros(N) &&
   4320          !ISD::isBuildVectorAllOnes(N);
   4321 }
   4322 
   4323 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
   4324 /// match movlp{s|d}. The lower half elements should come from lower half of
   4325 /// V1 (and in order), and the upper half elements should come from the upper
   4326 /// half of V2 (and in order). And since V1 will become the source of the
   4327 /// MOVLP, it must be either a vector load or a scalar load to vector.
   4328 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
   4329                                ArrayRef<int> Mask, EVT VT) {
   4330   if (!VT.is128BitVector())
   4331     return false;
   4332 
   4333   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
   4334     return false;
   4335   // Is V2 is a vector load, don't do this transformation. We will try to use
   4336   // load folding shufps op.
   4337   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
   4338     return false;
   4339 
   4340   unsigned NumElems = VT.getVectorNumElements();
   4341 
   4342   if (NumElems != 2 && NumElems != 4)
   4343     return false;
   4344   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
   4345     if (!isUndefOrEqual(Mask[i], i))
   4346       return false;
   4347   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
   4348     if (!isUndefOrEqual(Mask[i], i+NumElems))
   4349       return false;
   4350   return true;
   4351 }
   4352 
   4353 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
   4354 /// all the same.
   4355 static bool isSplatVector(SDNode *N) {
   4356   if (N->getOpcode() != ISD::BUILD_VECTOR)
   4357     return false;
   4358 
   4359   SDValue SplatValue = N->getOperand(0);
   4360   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
   4361     if (N->getOperand(i) != SplatValue)
   4362       return false;
   4363   return true;
   4364 }
   4365 
   4366 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
   4367 /// to an zero vector.
   4368 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
   4369 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
   4370   SDValue V1 = N->getOperand(0);
   4371   SDValue V2 = N->getOperand(1);
   4372   unsigned NumElems = N->getValueType(0).getVectorNumElements();
   4373   for (unsigned i = 0; i != NumElems; ++i) {
   4374     int Idx = N->getMaskElt(i);
   4375     if (Idx >= (int)NumElems) {
   4376       unsigned Opc = V2.getOpcode();
   4377       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
   4378         continue;
   4379       if (Opc != ISD::BUILD_VECTOR ||
   4380           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
   4381         return false;
   4382     } else if (Idx >= 0) {
   4383       unsigned Opc = V1.getOpcode();
   4384       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
   4385         continue;
   4386       if (Opc != ISD::BUILD_VECTOR ||
   4387           !X86::isZeroNode(V1.getOperand(Idx)))
   4388         return false;
   4389     }
   4390   }
   4391   return true;
   4392 }
   4393 
   4394 /// getZeroVector - Returns a vector of specified type with all zero elements.
   4395 ///
   4396 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
   4397                              SelectionDAG &DAG, DebugLoc dl) {
   4398   assert(VT.isVector() && "Expected a vector type");
   4399 
   4400   // Always build SSE zero vectors as <4 x i32> bitcasted
   4401   // to their dest type. This ensures they get CSE'd.
   4402   SDValue Vec;
   4403   if (VT.is128BitVector()) {  // SSE
   4404     if (Subtarget->hasSSE2()) {  // SSE2
   4405       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
   4406       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
   4407     } else { // SSE1
   4408       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
   4409       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
   4410     }
   4411   } else if (VT.is256BitVector()) { // AVX
   4412     if (Subtarget->hasInt256()) { // AVX2
   4413       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
   4414       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
   4415       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
   4416     } else {
   4417       // 256-bit logic and arithmetic instructions in AVX are all
   4418       // floating-point, no support for integer ops. Emit fp zeroed vectors.
   4419       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
   4420       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
   4421       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
   4422     }
   4423   } else
   4424     llvm_unreachable("Unexpected vector type");
   4425 
   4426   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
   4427 }
   4428 
   4429 /// getOnesVector - Returns a vector of specified type with all bits set.
   4430 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
   4431 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
   4432 /// Then bitcast to their original type, ensuring they get CSE'd.
   4433 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
   4434                              DebugLoc dl) {
   4435   assert(VT.isVector() && "Expected a vector type");
   4436 
   4437   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
   4438   SDValue Vec;
   4439   if (VT.is256BitVector()) {
   4440     if (HasInt256) { // AVX2
   4441       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
   4442       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
   4443     } else { // AVX
   4444       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
   4445       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
   4446     }
   4447   } else if (VT.is128BitVector()) {
   4448     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
   4449   } else
   4450     llvm_unreachable("Unexpected vector type");
   4451 
   4452   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
   4453 }
   4454 
   4455 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
   4456 /// that point to V2 points to its first element.
   4457 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
   4458   for (unsigned i = 0; i != NumElems; ++i) {
   4459     if (Mask[i] > (int)NumElems) {
   4460       Mask[i] = NumElems;
   4461     }
   4462   }
   4463 }
   4464 
   4465 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
   4466 /// operation of specified width.
   4467 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
   4468                        SDValue V2) {
   4469   unsigned NumElems = VT.getVectorNumElements();
   4470   SmallVector<int, 8> Mask;
   4471   Mask.push_back(NumElems);
   4472   for (unsigned i = 1; i != NumElems; ++i)
   4473     Mask.push_back(i);
   4474   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
   4475 }
   4476 
   4477 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
   4478 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
   4479                           SDValue V2) {
   4480   unsigned NumElems = VT.getVectorNumElements();
   4481   SmallVector<int, 8> Mask;
   4482   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
   4483     Mask.push_back(i);
   4484     Mask.push_back(i + NumElems);
   4485   }
   4486   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
   4487 }
   4488 
   4489 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
   4490 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
   4491                           SDValue V2) {
   4492   unsigned NumElems = VT.getVectorNumElements();
   4493   SmallVector<int, 8> Mask;
   4494   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
   4495     Mask.push_back(i + Half);
   4496     Mask.push_back(i + NumElems + Half);
   4497   }
   4498   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
   4499 }
   4500 
   4501 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
   4502 // a generic shuffle instruction because the target has no such instructions.
   4503 // Generate shuffles which repeat i16 and i8 several times until they can be
   4504 // represented by v4f32 and then be manipulated by target suported shuffles.
   4505 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
   4506   EVT VT = V.getValueType();
   4507   int NumElems = VT.getVectorNumElements();
   4508   DebugLoc dl = V.getDebugLoc();
   4509 
   4510   while (NumElems > 4) {
   4511     if (EltNo < NumElems/2) {
   4512       V = getUnpackl(DAG, dl, VT, V, V);
   4513     } else {
   4514       V = getUnpackh(DAG, dl, VT, V, V);
   4515       EltNo -= NumElems/2;
   4516     }
   4517     NumElems >>= 1;
   4518   }
   4519   return V;
   4520 }
   4521 
   4522 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
   4523 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
   4524   EVT VT = V.getValueType();
   4525   DebugLoc dl = V.getDebugLoc();
   4526 
   4527   if (VT.is128BitVector()) {
   4528     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
   4529     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
   4530     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
   4531                              &SplatMask[0]);
   4532   } else if (VT.is256BitVector()) {
   4533     // To use VPERMILPS to splat scalars, the second half of indicies must
   4534     // refer to the higher part, which is a duplication of the lower one,
   4535     // because VPERMILPS can only handle in-lane permutations.
   4536     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
   4537                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
   4538 
   4539     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
   4540     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
   4541                              &SplatMask[0]);
   4542   } else
   4543     llvm_unreachable("Vector size not supported");
   4544 
   4545   return DAG.getNode(ISD::BITCAST, dl, VT, V);
   4546 }
   4547 
   4548 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
   4549 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
   4550   EVT SrcVT = SV->getValueType(0);
   4551   SDValue V1 = SV->getOperand(0);
   4552   DebugLoc dl = SV->getDebugLoc();
   4553 
   4554   int EltNo = SV->getSplatIndex();
   4555   int NumElems = SrcVT.getVectorNumElements();
   4556   bool Is256BitVec = SrcVT.is256BitVector();
   4557 
   4558   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
   4559          "Unknown how to promote splat for type");
   4560 
   4561   // Extract the 128-bit part containing the splat element and update
   4562   // the splat element index when it refers to the higher register.
   4563   if (Is256BitVec) {
   4564     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
   4565     if (EltNo >= NumElems/2)
   4566       EltNo -= NumElems/2;
   4567   }
   4568 
   4569   // All i16 and i8 vector types can't be used directly by a generic shuffle
   4570   // instruction because the target has no such instruction. Generate shuffles
   4571   // which repeat i16 and i8 several times until they fit in i32, and then can
   4572   // be manipulated by target suported shuffles.
   4573   EVT EltVT = SrcVT.getVectorElementType();
   4574   if (EltVT == MVT::i8 || EltVT == MVT::i16)
   4575     V1 = PromoteSplati8i16(V1, DAG, EltNo);
   4576 
   4577   // Recreate the 256-bit vector and place the same 128-bit vector
   4578   // into the low and high part. This is necessary because we want
   4579   // to use VPERM* to shuffle the vectors
   4580   if (Is256BitVec) {
   4581     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
   4582   }
   4583 
   4584   return getLegalSplat(DAG, V1, EltNo);
   4585 }
   4586 
   4587 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
   4588 /// vector of zero or undef vector.  This produces a shuffle where the low
   4589 /// element of V2 is swizzled into the zero/undef vector, landing at element
   4590 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
   4591 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
   4592                                            bool IsZero,
   4593                                            const X86Subtarget *Subtarget,
   4594                                            SelectionDAG &DAG) {
   4595   EVT VT = V2.getValueType();
   4596   SDValue V1 = IsZero
   4597     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
   4598   unsigned NumElems = VT.getVectorNumElements();
   4599   SmallVector<int, 16> MaskVec;
   4600   for (unsigned i = 0; i != NumElems; ++i)
   4601     // If this is the insertion idx, put the low elt of V2 here.
   4602     MaskVec.push_back(i == Idx ? NumElems : i);
   4603   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
   4604 }
   4605 
   4606 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
   4607 /// target specific opcode. Returns true if the Mask could be calculated.
   4608 /// Sets IsUnary to true if only uses one source.
   4609 static bool getTargetShuffleMask(SDNode *N, MVT VT,
   4610                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
   4611   unsigned NumElems = VT.getVectorNumElements();
   4612   SDValue ImmN;
   4613 
   4614   IsUnary = false;
   4615   switch(N->getOpcode()) {
   4616   case X86ISD::SHUFP:
   4617     ImmN = N->getOperand(N->getNumOperands()-1);
   4618     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
   4619     break;
   4620   case X86ISD::UNPCKH:
   4621     DecodeUNPCKHMask(VT, Mask);
   4622     break;
   4623   case X86ISD::UNPCKL:
   4624     DecodeUNPCKLMask(VT, Mask);
   4625     break;
   4626   case X86ISD::MOVHLPS:
   4627     DecodeMOVHLPSMask(NumElems, Mask);
   4628     break;
   4629   case X86ISD::MOVLHPS:
   4630     DecodeMOVLHPSMask(NumElems, Mask);
   4631     break;
   4632   case X86ISD::PALIGNR:
   4633     ImmN = N->getOperand(N->getNumOperands()-1);
   4634     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
   4635     break;
   4636   case X86ISD::PSHUFD:
   4637   case X86ISD::VPERMILP:
   4638     ImmN = N->getOperand(N->getNumOperands()-1);
   4639     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
   4640     IsUnary = true;
   4641     break;
   4642   case X86ISD::PSHUFHW:
   4643     ImmN = N->getOperand(N->getNumOperands()-1);
   4644     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
   4645     IsUnary = true;
   4646     break;
   4647   case X86ISD::PSHUFLW:
   4648     ImmN = N->getOperand(N->getNumOperands()-1);
   4649     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
   4650     IsUnary = true;
   4651     break;
   4652   case X86ISD::VPERMI:
   4653     ImmN = N->getOperand(N->getNumOperands()-1);
   4654     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
   4655     IsUnary = true;
   4656     break;
   4657   case X86ISD::MOVSS:
   4658   case X86ISD::MOVSD: {
   4659     // The index 0 always comes from the first element of the second source,
   4660     // this is why MOVSS and MOVSD are used in the first place. The other
   4661     // elements come from the other positions of the first source vector
   4662     Mask.push_back(NumElems);
   4663     for (unsigned i = 1; i != NumElems; ++i) {
   4664       Mask.push_back(i);
   4665     }
   4666     break;
   4667   }
   4668   case X86ISD::VPERM2X128:
   4669     ImmN = N->getOperand(N->getNumOperands()-1);
   4670     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
   4671     if (Mask.empty()) return false;
   4672     break;
   4673   case X86ISD::MOVDDUP:
   4674   case X86ISD::MOVLHPD:
   4675   case X86ISD::MOVLPD:
   4676   case X86ISD::MOVLPS:
   4677   case X86ISD::MOVSHDUP:
   4678   case X86ISD::MOVSLDUP:
   4679     // Not yet implemented
   4680     return false;
   4681   default: llvm_unreachable("unknown target shuffle node");
   4682   }
   4683 
   4684   return true;
   4685 }
   4686 
   4687 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
   4688 /// element of the result of the vector shuffle.
   4689 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
   4690                                    unsigned Depth) {
   4691   if (Depth == 6)
   4692     return SDValue();  // Limit search depth.
   4693 
   4694   SDValue V = SDValue(N, 0);
   4695   EVT VT = V.getValueType();
   4696   unsigned Opcode = V.getOpcode();
   4697 
   4698   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
   4699   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
   4700     int Elt = SV->getMaskElt(Index);
   4701 
   4702     if (Elt < 0)
   4703       return DAG.getUNDEF(VT.getVectorElementType());
   4704 
   4705     unsigned NumElems = VT.getVectorNumElements();
   4706     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
   4707                                          : SV->getOperand(1);
   4708     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
   4709   }
   4710 
   4711   // Recurse into target specific vector shuffles to find scalars.
   4712   if (isTargetShuffle(Opcode)) {
   4713     MVT ShufVT = V.getValueType().getSimpleVT();
   4714     unsigned NumElems = ShufVT.getVectorNumElements();
   4715     SmallVector<int, 16> ShuffleMask;
   4716     bool IsUnary;
   4717 
   4718     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
   4719       return SDValue();
   4720 
   4721     int Elt = ShuffleMask[Index];
   4722     if (Elt < 0)
   4723       return DAG.getUNDEF(ShufVT.getVectorElementType());
   4724 
   4725     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
   4726                                          : N->getOperand(1);
   4727     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
   4728                                Depth+1);
   4729   }
   4730 
   4731   // Actual nodes that may contain scalar elements
   4732   if (Opcode == ISD::BITCAST) {
   4733     V = V.getOperand(0);
   4734     EVT SrcVT = V.getValueType();
   4735     unsigned NumElems = VT.getVectorNumElements();
   4736 
   4737     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
   4738       return SDValue();
   4739   }
   4740 
   4741   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
   4742     return (Index == 0) ? V.getOperand(0)
   4743                         : DAG.getUNDEF(VT.getVectorElementType());
   4744 
   4745   if (V.getOpcode() == ISD::BUILD_VECTOR)
   4746     return V.getOperand(Index);
   4747 
   4748   return SDValue();
   4749 }
   4750 
   4751 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
   4752 /// shuffle operation which come from a consecutively from a zero. The
   4753 /// search can start in two different directions, from left or right.
   4754 static
   4755 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
   4756                                   bool ZerosFromLeft, SelectionDAG &DAG) {
   4757   unsigned i;
   4758   for (i = 0; i != NumElems; ++i) {
   4759     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
   4760     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
   4761     if (!(Elt.getNode() &&
   4762          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
   4763       break;
   4764   }
   4765 
   4766   return i;
   4767 }
   4768 
   4769 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
   4770 /// correspond consecutively to elements from one of the vector operands,
   4771 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
   4772 static
   4773 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
   4774                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
   4775                               unsigned NumElems, unsigned &OpNum) {
   4776   bool SeenV1 = false;
   4777   bool SeenV2 = false;
   4778 
   4779   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
   4780     int Idx = SVOp->getMaskElt(i);
   4781     // Ignore undef indicies
   4782     if (Idx < 0)
   4783       continue;
   4784 
   4785     if (Idx < (int)NumElems)
   4786       SeenV1 = true;
   4787     else
   4788       SeenV2 = true;
   4789 
   4790     // Only accept consecutive elements from the same vector
   4791     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
   4792       return false;
   4793   }
   4794 
   4795   OpNum = SeenV1 ? 0 : 1;
   4796   return true;
   4797 }
   4798 
   4799 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
   4800 /// logical left shift of a vector.
   4801 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
   4802                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
   4803   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
   4804   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
   4805               false /* check zeros from right */, DAG);
   4806   unsigned OpSrc;
   4807 
   4808   if (!NumZeros)
   4809     return false;
   4810 
   4811   // Considering the elements in the mask that are not consecutive zeros,
   4812   // check if they consecutively come from only one of the source vectors.
   4813   //
   4814   //               V1 = {X, A, B, C}     0
   4815   //                         \  \  \    /
   4816   //   vector_shuffle V1, V2 <1, 2, 3, X>
   4817   //
   4818   if (!isShuffleMaskConsecutive(SVOp,
   4819             0,                   // Mask Start Index
   4820             NumElems-NumZeros,   // Mask End Index(exclusive)
   4821             NumZeros,            // Where to start looking in the src vector
   4822             NumElems,            // Number of elements in vector
   4823             OpSrc))              // Which source operand ?
   4824     return false;
   4825 
   4826   isLeft = false;
   4827   ShAmt = NumZeros;
   4828   ShVal = SVOp->getOperand(OpSrc);
   4829   return true;
   4830 }
   4831 
   4832 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
   4833 /// logical left shift of a vector.
   4834 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
   4835                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
   4836   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
   4837   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
   4838               true /* check zeros from left */, DAG);
   4839   unsigned OpSrc;
   4840 
   4841   if (!NumZeros)
   4842     return false;
   4843 
   4844   // Considering the elements in the mask that are not consecutive zeros,
   4845   // check if they consecutively come from only one of the source vectors.
   4846   //
   4847   //                           0    { A, B, X, X } = V2
   4848   //                          / \    /  /
   4849   //   vector_shuffle V1, V2 <X, X, 4, 5>
   4850   //
   4851   if (!isShuffleMaskConsecutive(SVOp,
   4852             NumZeros,     // Mask Start Index
   4853             NumElems,     // Mask End Index(exclusive)
   4854             0,            // Where to start looking in the src vector
   4855             NumElems,     // Number of elements in vector
   4856             OpSrc))       // Which source operand ?
   4857     return false;
   4858 
   4859   isLeft = true;
   4860   ShAmt = NumZeros;
   4861   ShVal = SVOp->getOperand(OpSrc);
   4862   return true;
   4863 }
   4864 
   4865 /// isVectorShift - Returns true if the shuffle can be implemented as a
   4866 /// logical left or right shift of a vector.
   4867 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
   4868                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
   4869   // Although the logic below support any bitwidth size, there are no
   4870   // shift instructions which handle more than 128-bit vectors.
   4871   if (!SVOp->getValueType(0).is128BitVector())
   4872     return false;
   4873 
   4874   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
   4875       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
   4876     return true;
   4877 
   4878   return false;
   4879 }
   4880 
   4881 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
   4882 ///
   4883 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
   4884                                        unsigned NumNonZero, unsigned NumZero,
   4885                                        SelectionDAG &DAG,
   4886                                        const X86Subtarget* Subtarget,
   4887                                        const TargetLowering &TLI) {
   4888   if (NumNonZero > 8)
   4889     return SDValue();
   4890 
   4891   DebugLoc dl = Op.getDebugLoc();
   4892   SDValue V(0, 0);
   4893   bool First = true;
   4894   for (unsigned i = 0; i < 16; ++i) {
   4895     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
   4896     if (ThisIsNonZero && First) {
   4897       if (NumZero)
   4898         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
   4899       else
   4900         V = DAG.getUNDEF(MVT::v8i16);
   4901       First = false;
   4902     }
   4903 
   4904     if ((i & 1) != 0) {
   4905       SDValue ThisElt(0, 0), LastElt(0, 0);
   4906       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
   4907       if (LastIsNonZero) {
   4908         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
   4909                               MVT::i16, Op.getOperand(i-1));
   4910       }
   4911       if (ThisIsNonZero) {
   4912         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
   4913         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
   4914                               ThisElt, DAG.getConstant(8, MVT::i8));
   4915         if (LastIsNonZero)
   4916           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
   4917       } else
   4918         ThisElt = LastElt;
   4919 
   4920       if (ThisElt.getNode())
   4921         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
   4922                         DAG.getIntPtrConstant(i/2));
   4923     }
   4924   }
   4925 
   4926   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
   4927 }
   4928 
   4929 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
   4930 ///
   4931 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
   4932                                      unsigned NumNonZero, unsigned NumZero,
   4933                                      SelectionDAG &DAG,
   4934                                      const X86Subtarget* Subtarget,
   4935                                      const TargetLowering &TLI) {
   4936   if (NumNonZero > 4)
   4937     return SDValue();
   4938 
   4939   DebugLoc dl = Op.getDebugLoc();
   4940   SDValue V(0, 0);
   4941   bool First = true;
   4942   for (unsigned i = 0; i < 8; ++i) {
   4943     bool isNonZero = (NonZeros & (1 << i)) != 0;
   4944     if (isNonZero) {
   4945       if (First) {
   4946         if (NumZero)
   4947           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
   4948         else
   4949           V = DAG.getUNDEF(MVT::v8i16);
   4950         First = false;
   4951       }
   4952       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
   4953                       MVT::v8i16, V, Op.getOperand(i),
   4954                       DAG.getIntPtrConstant(i));
   4955     }
   4956   }
   4957 
   4958   return V;
   4959 }
   4960 
   4961 /// getVShift - Return a vector logical shift node.
   4962 ///
   4963 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
   4964                          unsigned NumBits, SelectionDAG &DAG,
   4965                          const TargetLowering &TLI, DebugLoc dl) {
   4966   assert(VT.is128BitVector() && "Unknown type for VShift");
   4967   EVT ShVT = MVT::v2i64;
   4968   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
   4969   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
   4970   return DAG.getNode(ISD::BITCAST, dl, VT,
   4971                      DAG.getNode(Opc, dl, ShVT, SrcOp,
   4972                              DAG.getConstant(NumBits,
   4973                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
   4974 }
   4975 
   4976 SDValue
   4977 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
   4978                                           SelectionDAG &DAG) const {
   4979 
   4980   // Check if the scalar load can be widened into a vector load. And if
   4981   // the address is "base + cst" see if the cst can be "absorbed" into
   4982   // the shuffle mask.
   4983   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
   4984     SDValue Ptr = LD->getBasePtr();
   4985     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
   4986       return SDValue();
   4987     EVT PVT = LD->getValueType(0);
   4988     if (PVT != MVT::i32 && PVT != MVT::f32)
   4989       return SDValue();
   4990 
   4991     int FI = -1;
   4992     int64_t Offset = 0;
   4993     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
   4994       FI = FINode->getIndex();
   4995       Offset = 0;
   4996     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
   4997                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
   4998       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
   4999       Offset = Ptr.getConstantOperandVal(1);
   5000       Ptr = Ptr.getOperand(0);
   5001     } else {
   5002       return SDValue();
   5003     }
   5004 
   5005     // FIXME: 256-bit vector instructions don't require a strict alignment,
   5006     // improve this code to support it better.
   5007     unsigned RequiredAlign = VT.getSizeInBits()/8;
   5008     SDValue Chain = LD->getChain();
   5009     // Make sure the stack object alignment is at least 16 or 32.
   5010     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
   5011     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
   5012       if (MFI->isFixedObjectIndex(FI)) {
   5013         // Can't change the alignment. FIXME: It's possible to compute
   5014         // the exact stack offset and reference FI + adjust offset instead.
   5015         // If someone *really* cares about this. That's the way to implement it.
   5016         return SDValue();
   5017       } else {
   5018         MFI->setObjectAlignment(FI, RequiredAlign);
   5019       }
   5020     }
   5021 
   5022     // (Offset % 16 or 32) must be multiple of 4. Then address is then
   5023     // Ptr + (Offset & ~15).
   5024     if (Offset < 0)
   5025       return SDValue();
   5026     if ((Offset % RequiredAlign) & 3)
   5027       return SDValue();
   5028     int64_t StartOffset = Offset & ~(RequiredAlign-1);
   5029     if (StartOffset)
   5030       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
   5031                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
   5032 
   5033     int EltNo = (Offset - StartOffset) >> 2;
   5034     unsigned NumElems = VT.getVectorNumElements();
   5035 
   5036     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
   5037     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
   5038                              LD->getPointerInfo().getWithOffset(StartOffset),
   5039                              false, false, false, 0);
   5040 
   5041     SmallVector<int, 8> Mask;
   5042     for (unsigned i = 0; i != NumElems; ++i)
   5043       Mask.push_back(EltNo);
   5044 
   5045     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
   5046   }
   5047 
   5048   return SDValue();
   5049 }
   5050 
   5051 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
   5052 /// vector of type 'VT', see if the elements can be replaced by a single large
   5053 /// load which has the same value as a build_vector whose operands are 'elts'.
   5054 ///
   5055 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
   5056 ///
   5057 /// FIXME: we'd also like to handle the case where the last elements are zero
   5058 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
   5059 /// There's even a handy isZeroNode for that purpose.
   5060 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
   5061                                         DebugLoc &DL, SelectionDAG &DAG) {
   5062   EVT EltVT = VT.getVectorElementType();
   5063   unsigned NumElems = Elts.size();
   5064 
   5065   LoadSDNode *LDBase = NULL;
   5066   unsigned LastLoadedElt = -1U;
   5067 
   5068   // For each element in the initializer, see if we've found a load or an undef.
   5069   // If we don't find an initial load element, or later load elements are
   5070   // non-consecutive, bail out.
   5071   for (unsigned i = 0; i < NumElems; ++i) {
   5072     SDValue Elt = Elts[i];
   5073 
   5074     if (!Elt.getNode() ||
   5075         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
   5076       return SDValue();
   5077     if (!LDBase) {
   5078       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
   5079         return SDValue();
   5080       LDBase = cast<LoadSDNode>(Elt.getNode());
   5081       LastLoadedElt = i;
   5082       continue;
   5083     }
   5084     if (Elt.getOpcode() == ISD::UNDEF)
   5085       continue;
   5086 
   5087     LoadSDNode *LD = cast<LoadSDNode>(Elt);
   5088     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
   5089       return SDValue();
   5090     LastLoadedElt = i;
   5091   }
   5092 
   5093   // If we have found an entire vector of loads and undefs, then return a large
   5094   // load of the entire vector width starting at the base pointer.  If we found
   5095   // consecutive loads for the low half, generate a vzext_load node.
   5096   if (LastLoadedElt == NumElems - 1) {
   5097     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
   5098       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
   5099                          LDBase->getPointerInfo(),
   5100                          LDBase->isVolatile(), LDBase->isNonTemporal(),
   5101                          LDBase->isInvariant(), 0);
   5102     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
   5103                        LDBase->getPointerInfo(),
   5104                        LDBase->isVolatile(), LDBase->isNonTemporal(),
   5105                        LDBase->isInvariant(), LDBase->getAlignment());
   5106   }
   5107   if (NumElems == 4 && LastLoadedElt == 1 &&
   5108       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
   5109     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
   5110     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
   5111     SDValue ResNode =
   5112         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
   5113                                 LDBase->getPointerInfo(),
   5114                                 LDBase->getAlignment(),
   5115                                 false/*isVolatile*/, true/*ReadMem*/,
   5116                                 false/*WriteMem*/);
   5117 
   5118     // Make sure the newly-created LOAD is in the same position as LDBase in
   5119     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
   5120     // update uses of LDBase's output chain to use the TokenFactor.
   5121     if (LDBase->hasAnyUseOfValue(1)) {
   5122       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
   5123                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
   5124       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
   5125       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
   5126                              SDValue(ResNode.getNode(), 1));
   5127     }
   5128 
   5129     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
   5130   }
   5131   return SDValue();
   5132 }
   5133 
   5134 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
   5135 /// to generate a splat value for the following cases:
   5136 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
   5137 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
   5138 /// a scalar load, or a constant.
   5139 /// The VBROADCAST node is returned when a pattern is found,
   5140 /// or SDValue() otherwise.
   5141 SDValue
   5142 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
   5143   if (!Subtarget->hasFp256())
   5144     return SDValue();
   5145 
   5146   MVT VT = Op.getValueType().getSimpleVT();
   5147   DebugLoc dl = Op.getDebugLoc();
   5148 
   5149   assert((VT.is128BitVector() || VT.is256BitVector()) &&
   5150          "Unsupported vector type for broadcast.");
   5151 
   5152   SDValue Ld;
   5153   bool ConstSplatVal;
   5154 
   5155   switch (Op.getOpcode()) {
   5156     default:
   5157       // Unknown pattern found.
   5158       return SDValue();
   5159 
   5160     case ISD::BUILD_VECTOR: {
   5161       // The BUILD_VECTOR node must be a splat.
   5162       if (!isSplatVector(Op.getNode()))
   5163         return SDValue();
   5164 
   5165       Ld = Op.getOperand(0);
   5166       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
   5167                      Ld.getOpcode() == ISD::ConstantFP);
   5168 
   5169       // The suspected load node has several users. Make sure that all
   5170       // of its users are from the BUILD_VECTOR node.
   5171       // Constants may have multiple users.
   5172       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
   5173         return SDValue();
   5174       break;
   5175     }
   5176 
   5177     case ISD::VECTOR_SHUFFLE: {
   5178       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
   5179 
   5180       // Shuffles must have a splat mask where the first element is
   5181       // broadcasted.
   5182       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
   5183         return SDValue();
   5184 
   5185       SDValue Sc = Op.getOperand(0);
   5186       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
   5187           Sc.getOpcode() != ISD::BUILD_VECTOR) {
   5188 
   5189         if (!Subtarget->hasInt256())
   5190           return SDValue();
   5191 
   5192         // Use the register form of the broadcast instruction available on AVX2.
   5193         if (VT.is256BitVector())
   5194           Sc = Extract128BitVector(Sc, 0, DAG, dl);
   5195         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
   5196       }
   5197 
   5198       Ld = Sc.getOperand(0);
   5199       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
   5200                        Ld.getOpcode() == ISD::ConstantFP);
   5201 
   5202       // The scalar_to_vector node and the suspected
   5203       // load node must have exactly one user.
   5204       // Constants may have multiple users.
   5205       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
   5206         return SDValue();
   5207       break;
   5208     }
   5209   }
   5210 
   5211   bool Is256 = VT.is256BitVector();
   5212 
   5213   // Handle the broadcasting a single constant scalar from the constant pool
   5214   // into a vector. On Sandybridge it is still better to load a constant vector
   5215   // from the constant pool and not to broadcast it from a scalar.
   5216   if (ConstSplatVal && Subtarget->hasInt256()) {
   5217     EVT CVT = Ld.getValueType();
   5218     assert(!CVT.isVector() && "Must not broadcast a vector type");
   5219     unsigned ScalarSize = CVT.getSizeInBits();
   5220 
   5221     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
   5222       const Constant *C = 0;
   5223       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
   5224         C = CI->getConstantIntValue();
   5225       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
   5226         C = CF->getConstantFPValue();
   5227 
   5228       assert(C && "Invalid constant type");
   5229 
   5230       SDValue CP = DAG.getConstantPool(C, getPointerTy());
   5231       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
   5232       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
   5233                        MachinePointerInfo::getConstantPool(),
   5234                        false, false, false, Alignment);
   5235 
   5236       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
   5237     }
   5238   }
   5239 
   5240   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
   5241   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
   5242 
   5243   // Handle AVX2 in-register broadcasts.
   5244   if (!IsLoad && Subtarget->hasInt256() &&
   5245       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
   5246     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
   5247 
   5248   // The scalar source must be a normal load.
   5249   if (!IsLoad)
   5250     return SDValue();
   5251 
   5252   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
   5253     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
   5254 
   5255   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
   5256   // double since there is no vbroadcastsd xmm
   5257   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
   5258     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
   5259       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
   5260   }
   5261 
   5262   // Unsupported broadcast.
   5263   return SDValue();
   5264 }
   5265 
   5266 SDValue
   5267 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
   5268   EVT VT = Op.getValueType();
   5269 
   5270   // Skip if insert_vec_elt is not supported.
   5271   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
   5272     return SDValue();
   5273 
   5274   DebugLoc DL = Op.getDebugLoc();
   5275   unsigned NumElems = Op.getNumOperands();
   5276 
   5277   SDValue VecIn1;
   5278   SDValue VecIn2;
   5279   SmallVector<unsigned, 4> InsertIndices;
   5280   SmallVector<int, 8> Mask(NumElems, -1);
   5281 
   5282   for (unsigned i = 0; i != NumElems; ++i) {
   5283     unsigned Opc = Op.getOperand(i).getOpcode();
   5284 
   5285     if (Opc == ISD::UNDEF)
   5286       continue;
   5287 
   5288     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
   5289       // Quit if more than 1 elements need inserting.
   5290       if (InsertIndices.size() > 1)
   5291         return SDValue();
   5292 
   5293       InsertIndices.push_back(i);
   5294       continue;
   5295     }
   5296 
   5297     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
   5298     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
   5299 
   5300     // Quit if extracted from vector of different type.
   5301     if (ExtractedFromVec.getValueType() != VT)
   5302       return SDValue();
   5303 
   5304     // Quit if non-constant index.
   5305     if (!isa<ConstantSDNode>(ExtIdx))
   5306       return SDValue();
   5307 
   5308     if (VecIn1.getNode() == 0)
   5309       VecIn1 = ExtractedFromVec;
   5310     else if (VecIn1 != ExtractedFromVec) {
   5311       if (VecIn2.getNode() == 0)
   5312         VecIn2 = ExtractedFromVec;
   5313       else if (VecIn2 != ExtractedFromVec)
   5314         // Quit if more than 2 vectors to shuffle
   5315         return SDValue();
   5316     }
   5317 
   5318     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
   5319 
   5320     if (ExtractedFromVec == VecIn1)
   5321       Mask[i] = Idx;
   5322     else if (ExtractedFromVec == VecIn2)
   5323       Mask[i] = Idx + NumElems;
   5324   }
   5325 
   5326   if (VecIn1.getNode() == 0)
   5327     return SDValue();
   5328 
   5329   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
   5330   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
   5331   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
   5332     unsigned Idx = InsertIndices[i];
   5333     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
   5334                      DAG.getIntPtrConstant(Idx));
   5335   }
   5336 
   5337   return NV;
   5338 }
   5339 
   5340 SDValue
   5341 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
   5342   DebugLoc dl = Op.getDebugLoc();
   5343 
   5344   MVT VT = Op.getValueType().getSimpleVT();
   5345   MVT ExtVT = VT.getVectorElementType();
   5346   unsigned NumElems = Op.getNumOperands();
   5347 
   5348   // Vectors containing all zeros can be matched by pxor and xorps later
   5349   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
   5350     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
   5351     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
   5352     if (VT == MVT::v4i32 || VT == MVT::v8i32)
   5353       return Op;
   5354 
   5355     return getZeroVector(VT, Subtarget, DAG, dl);
   5356   }
   5357 
   5358   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
   5359   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
   5360   // vpcmpeqd on 256-bit vectors.
   5361   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
   5362     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
   5363       return Op;
   5364 
   5365     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
   5366   }
   5367 
   5368   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
   5369   if (Broadcast.getNode())
   5370     return Broadcast;
   5371 
   5372   unsigned EVTBits = ExtVT.getSizeInBits();
   5373 
   5374   unsigned NumZero  = 0;
   5375   unsigned NumNonZero = 0;
   5376   unsigned NonZeros = 0;
   5377   bool IsAllConstants = true;
   5378   SmallSet<SDValue, 8> Values;
   5379   for (unsigned i = 0; i < NumElems; ++i) {
   5380     SDValue Elt = Op.getOperand(i);
   5381     if (Elt.getOpcode() == ISD::UNDEF)
   5382       continue;
   5383     Values.insert(Elt);
   5384     if (Elt.getOpcode() != ISD::Constant &&
   5385         Elt.getOpcode() != ISD::ConstantFP)
   5386       IsAllConstants = false;
   5387     if (X86::isZeroNode(Elt))
   5388       NumZero++;
   5389     else {
   5390       NonZeros |= (1 << i);
   5391       NumNonZero++;
   5392     }
   5393   }
   5394 
   5395   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
   5396   if (NumNonZero == 0)
   5397     return DAG.getUNDEF(VT);
   5398 
   5399   // Special case for single non-zero, non-undef, element.
   5400   if (NumNonZero == 1) {
   5401     unsigned Idx = CountTrailingZeros_32(NonZeros);
   5402     SDValue Item = Op.getOperand(Idx);
   5403 
   5404     // If this is an insertion of an i64 value on x86-32, and if the top bits of
   5405     // the value are obviously zero, truncate the value to i32 and do the
   5406     // insertion that way.  Only do this if the value is non-constant or if the
   5407     // value is a constant being inserted into element 0.  It is cheaper to do
   5408     // a constant pool load than it is to do a movd + shuffle.
   5409     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
   5410         (!IsAllConstants || Idx == 0)) {
   5411       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
   5412         // Handle SSE only.
   5413         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
   5414         EVT VecVT = MVT::v4i32;
   5415         unsigned VecElts = 4;
   5416 
   5417         // Truncate the value (which may itself be a constant) to i32, and
   5418         // convert it to a vector with movd (S2V+shuffle to zero extend).
   5419         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
   5420         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
   5421         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
   5422 
   5423         // Now we have our 32-bit value zero extended in the low element of
   5424         // a vector.  If Idx != 0, swizzle it into place.
   5425         if (Idx != 0) {
   5426           SmallVector<int, 4> Mask;
   5427           Mask.push_back(Idx);
   5428           for (unsigned i = 1; i != VecElts; ++i)
   5429             Mask.push_back(i);
   5430           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
   5431                                       &Mask[0]);
   5432         }
   5433         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
   5434       }
   5435     }
   5436 
   5437     // If we have a constant or non-constant insertion into the low element of
   5438     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
   5439     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
   5440     // depending on what the source datatype is.
   5441     if (Idx == 0) {
   5442       if (NumZero == 0)
   5443         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
   5444 
   5445       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
   5446           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
   5447         if (VT.is256BitVector()) {
   5448           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
   5449           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
   5450                              Item, DAG.getIntPtrConstant(0));
   5451         }
   5452         assert(VT.is128BitVector() && "Expected an SSE value type!");
   5453         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
   5454         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
   5455         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
   5456       }
   5457 
   5458       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
   5459         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
   5460         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
   5461         if (VT.is256BitVector()) {
   5462           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
   5463           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
   5464         } else {
   5465           assert(VT.is128BitVector() && "Expected an SSE value type!");
   5466           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
   5467         }
   5468         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
   5469       }
   5470     }
   5471 
   5472     // Is it a vector logical left shift?
   5473     if (NumElems == 2 && Idx == 1 &&
   5474         X86::isZeroNode(Op.getOperand(0)) &&
   5475         !X86::isZeroNode(Op.getOperand(1))) {
   5476       unsigned NumBits = VT.getSizeInBits();
   5477       return getVShift(true, VT,
   5478                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
   5479                                    VT, Op.getOperand(1)),
   5480                        NumBits/2, DAG, *this, dl);
   5481     }
   5482 
   5483     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
   5484       return SDValue();
   5485 
   5486     // Otherwise, if this is a vector with i32 or f32 elements, and the element
   5487     // is a non-constant being inserted into an element other than the low one,
   5488     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
   5489     // movd/movss) to move this into the low element, then shuffle it into
   5490     // place.
   5491     if (EVTBits == 32) {
   5492       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
   5493 
   5494       // Turn it into a shuffle of zero and zero-extended scalar to vector.
   5495       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
   5496       SmallVector<int, 8> MaskVec;
   5497       for (unsigned i = 0; i != NumElems; ++i)
   5498         MaskVec.push_back(i == Idx ? 0 : 1);
   5499       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
   5500     }
   5501   }
   5502 
   5503   // Splat is obviously ok. Let legalizer expand it to a shuffle.
   5504   if (Values.size() == 1) {
   5505     if (EVTBits == 32) {
   5506       // Instead of a shuffle like this:
   5507       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
   5508       // Check if it's possible to issue this instead.
   5509       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
   5510       unsigned Idx = CountTrailingZeros_32(NonZeros);
   5511       SDValue Item = Op.getOperand(Idx);
   5512       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
   5513         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
   5514     }
   5515     return SDValue();
   5516   }
   5517 
   5518   // A vector full of immediates; various special cases are already
   5519   // handled, so this is best done with a single constant-pool load.
   5520   if (IsAllConstants)
   5521     return SDValue();
   5522 
   5523   // For AVX-length vectors, build the individual 128-bit pieces and use
   5524   // shuffles to put them in place.
   5525   if (VT.is256BitVector()) {
   5526     SmallVector<SDValue, 32> V;
   5527     for (unsigned i = 0; i != NumElems; ++i)
   5528       V.push_back(Op.getOperand(i));
   5529 
   5530     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
   5531 
   5532     // Build both the lower and upper subvector.
   5533     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
   5534     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
   5535                                 NumElems/2);
   5536 
   5537     // Recreate the wider vector with the lower and upper part.
   5538     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
   5539   }
   5540 
   5541   // Let legalizer expand 2-wide build_vectors.
   5542   if (EVTBits == 64) {
   5543     if (NumNonZero == 1) {
   5544       // One half is zero or undef.
   5545       unsigned Idx = CountTrailingZeros_32(NonZeros);
   5546       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
   5547                                  Op.getOperand(Idx));
   5548       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
   5549     }
   5550     return SDValue();
   5551   }
   5552 
   5553   // If element VT is < 32 bits, convert it to inserts into a zero vector.
   5554   if (EVTBits == 8 && NumElems == 16) {
   5555     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
   5556                                         Subtarget, *this);
   5557     if (V.getNode()) return V;
   5558   }
   5559 
   5560   if (EVTBits == 16 && NumElems == 8) {
   5561     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
   5562                                       Subtarget, *this);
   5563     if (V.getNode()) return V;
   5564   }
   5565 
   5566   // If element VT is == 32 bits, turn it into a number of shuffles.
   5567   SmallVector<SDValue, 8> V(NumElems);
   5568   if (NumElems == 4 && NumZero > 0) {
   5569     for (unsigned i = 0; i < 4; ++i) {
   5570       bool isZero = !(NonZeros & (1 << i));
   5571       if (isZero)
   5572         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
   5573       else
   5574         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
   5575     }
   5576 
   5577     for (unsigned i = 0; i < 2; ++i) {
   5578       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
   5579         default: break;
   5580         case 0:
   5581           V[i] = V[i*2];  // Must be a zero vector.
   5582           break;
   5583         case 1:
   5584           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
   5585           break;
   5586         case 2:
   5587           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
   5588           break;
   5589         case 3:
   5590           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
   5591           break;
   5592       }
   5593     }
   5594 
   5595     bool Reverse1 = (NonZeros & 0x3) == 2;
   5596     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
   5597     int MaskVec[] = {
   5598       Reverse1 ? 1 : 0,
   5599       Reverse1 ? 0 : 1,
   5600       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
   5601       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
   5602     };
   5603     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
   5604   }
   5605 
   5606   if (Values.size() > 1 && VT.is128BitVector()) {
   5607     // Check for a build vector of consecutive loads.
   5608     for (unsigned i = 0; i < NumElems; ++i)
   5609       V[i] = Op.getOperand(i);
   5610 
   5611     // Check for elements which are consecutive loads.
   5612     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
   5613     if (LD.getNode())
   5614       return LD;
   5615 
   5616     // Check for a build vector from mostly shuffle plus few inserting.
   5617     SDValue Sh = buildFromShuffleMostly(Op, DAG);
   5618     if (Sh.getNode())
   5619       return Sh;
   5620 
   5621     // For SSE 4.1, use insertps to put the high elements into the low element.
   5622     if (getSubtarget()->hasSSE41()) {
   5623       SDValue Result;
   5624       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
   5625         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
   5626       else
   5627         Result = DAG.getUNDEF(VT);
   5628 
   5629       for (unsigned i = 1; i < NumElems; ++i) {
   5630         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
   5631         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
   5632                              Op.getOperand(i), DAG.getIntPtrConstant(i));
   5633       }
   5634       return Result;
   5635     }
   5636 
   5637     // Otherwise, expand into a number of unpckl*, start by extending each of
   5638     // our (non-undef) elements to the full vector width with the element in the
   5639     // bottom slot of the vector (which generates no code for SSE).
   5640     for (unsigned i = 0; i < NumElems; ++i) {
   5641       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
   5642         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
   5643       else
   5644         V[i] = DAG.getUNDEF(VT);
   5645     }
   5646 
   5647     // Next, we iteratively mix elements, e.g. for v4f32:
   5648     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
   5649     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
   5650     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
   5651     unsigned EltStride = NumElems >> 1;
   5652     while (EltStride != 0) {
   5653       for (unsigned i = 0; i < EltStride; ++i) {
   5654         // If V[i+EltStride] is undef and this is the first round of mixing,
   5655         // then it is safe to just drop this shuffle: V[i] is already in the
   5656         // right place, the one element (since it's the first round) being
   5657         // inserted as undef can be dropped.  This isn't safe for successive
   5658         // rounds because they will permute elements within both vectors.
   5659         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
   5660             EltStride == NumElems/2)
   5661           continue;
   5662 
   5663         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
   5664       }
   5665       EltStride >>= 1;
   5666     }
   5667     return V[0];
   5668   }
   5669   return SDValue();
   5670 }
   5671 
   5672 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
   5673 // to create 256-bit vectors from two other 128-bit ones.
   5674 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
   5675   DebugLoc dl = Op.getDebugLoc();
   5676   MVT ResVT = Op.getValueType().getSimpleVT();
   5677 
   5678   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
   5679 
   5680   SDValue V1 = Op.getOperand(0);
   5681   SDValue V2 = Op.getOperand(1);
   5682   unsigned NumElems = ResVT.getVectorNumElements();
   5683 
   5684   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
   5685 }
   5686 
   5687 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
   5688   assert(Op.getNumOperands() == 2);
   5689 
   5690   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
   5691   // from two other 128-bit ones.
   5692   return LowerAVXCONCAT_VECTORS(Op, DAG);
   5693 }
   5694 
   5695 // Try to lower a shuffle node into a simple blend instruction.
   5696 static SDValue
   5697 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
   5698                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
   5699   SDValue V1 = SVOp->getOperand(0);
   5700   SDValue V2 = SVOp->getOperand(1);
   5701   DebugLoc dl = SVOp->getDebugLoc();
   5702   MVT VT = SVOp->getValueType(0).getSimpleVT();
   5703   MVT EltVT = VT.getVectorElementType();
   5704   unsigned NumElems = VT.getVectorNumElements();
   5705 
   5706   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
   5707     return SDValue();
   5708   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
   5709     return SDValue();
   5710 
   5711   // Check the mask for BLEND and build the value.
   5712   unsigned MaskValue = 0;
   5713   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
   5714   unsigned NumLanes = (NumElems-1)/8 + 1;
   5715   unsigned NumElemsInLane = NumElems / NumLanes;
   5716 
   5717   // Blend for v16i16 should be symetric for the both lanes.
   5718   for (unsigned i = 0; i < NumElemsInLane; ++i) {
   5719 
   5720     int SndLaneEltIdx = (NumLanes == 2) ?
   5721       SVOp->getMaskElt(i + NumElemsInLane) : -1;
   5722     int EltIdx = SVOp->getMaskElt(i);
   5723 
   5724     if ((EltIdx < 0 || EltIdx == (int)i) &&
   5725         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
   5726       continue;
   5727 
   5728     if (((unsigned)EltIdx == (i + NumElems)) &&
   5729         (SndLaneEltIdx < 0 ||
   5730          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
   5731       MaskValue |= (1<<i);
   5732     else
   5733       return SDValue();
   5734   }
   5735 
   5736   // Convert i32 vectors to floating point if it is not AVX2.
   5737   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
   5738   MVT BlendVT = VT;
   5739   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
   5740     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
   5741                                NumElems);
   5742     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
   5743     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
   5744   }
   5745 
   5746   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
   5747                             DAG.getConstant(MaskValue, MVT::i32));
   5748   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
   5749 }
   5750 
   5751 // v8i16 shuffles - Prefer shuffles in the following order:
   5752 // 1. [all]   pshuflw, pshufhw, optional move
   5753 // 2. [ssse3] 1 x pshufb
   5754 // 3. [ssse3] 2 x pshufb + 1 x por
   5755 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
   5756 static SDValue
   5757 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
   5758                          SelectionDAG &DAG) {
   5759   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
   5760   SDValue V1 = SVOp->getOperand(0);
   5761   SDValue V2 = SVOp->getOperand(1);
   5762   DebugLoc dl = SVOp->getDebugLoc();
   5763   SmallVector<int, 8> MaskVals;
   5764 
   5765   // Determine if more than 1 of the words in each of the low and high quadwords
   5766   // of the result come from the same quadword of one of the two inputs.  Undef
   5767   // mask values count as coming from any quadword, for better codegen.
   5768   unsigned LoQuad[] = { 0, 0, 0, 0 };
   5769   unsigned HiQuad[] = { 0, 0, 0, 0 };
   5770   std::bitset<4> InputQuads;
   5771   for (unsigned i = 0; i < 8; ++i) {
   5772     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
   5773     int EltIdx = SVOp->getMaskElt(i);
   5774     MaskVals.push_back(EltIdx);
   5775     if (EltIdx < 0) {
   5776       ++Quad[0];
   5777       ++Quad[1];
   5778       ++Quad[2];
   5779       ++Quad[3];
   5780       continue;
   5781     }
   5782     ++Quad[EltIdx / 4];
   5783     InputQuads.set(EltIdx / 4);
   5784   }
   5785 
   5786   int BestLoQuad = -1;
   5787   unsigned MaxQuad = 1;
   5788   for (unsigned i = 0; i < 4; ++i) {
   5789     if (LoQuad[i] > MaxQuad) {
   5790       BestLoQuad = i;
   5791       MaxQuad = LoQuad[i];
   5792     }
   5793   }
   5794 
   5795   int BestHiQuad = -1;
   5796   MaxQuad = 1;
   5797   for (unsigned i = 0; i < 4; ++i) {
   5798     if (HiQuad[i] > MaxQuad) {
   5799       BestHiQuad = i;
   5800       MaxQuad = HiQuad[i];
   5801     }
   5802   }
   5803 
   5804   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
   5805   // of the two input vectors, shuffle them into one input vector so only a
   5806   // single pshufb instruction is necessary. If There are more than 2 input
   5807   // quads, disable the next transformation since it does not help SSSE3.
   5808   bool V1Used = InputQuads[0] || InputQuads[1];
   5809   bool V2Used = InputQuads[2] || InputQuads[3];
   5810   if (Subtarget->hasSSSE3()) {
   5811     if (InputQuads.count() == 2 && V1Used && V2Used) {
   5812       BestLoQuad = InputQuads[0] ? 0 : 1;
   5813       BestHiQuad = InputQuads[2] ? 2 : 3;
   5814     }
   5815     if (InputQuads.count() > 2) {
   5816       BestLoQuad = -1;
   5817       BestHiQuad = -1;
   5818     }
   5819   }
   5820 
   5821   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
   5822   // the shuffle mask.  If a quad is scored as -1, that means that it contains
   5823   // words from all 4 input quadwords.
   5824   SDValue NewV;
   5825   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
   5826     int MaskV[] = {
   5827       BestLoQuad < 0 ? 0 : BestLoQuad,
   5828       BestHiQuad < 0 ? 1 : BestHiQuad
   5829     };
   5830     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
   5831                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
   5832                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
   5833     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
   5834 
   5835     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
   5836     // source words for the shuffle, to aid later transformations.
   5837     bool AllWordsInNewV = true;
   5838     bool InOrder[2] = { true, true };
   5839     for (unsigned i = 0; i != 8; ++i) {
   5840       int idx = MaskVals[i];
   5841       if (idx != (int)i)
   5842         InOrder[i/4] = false;
   5843       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
   5844         continue;
   5845       AllWordsInNewV = false;
   5846       break;
   5847     }
   5848 
   5849     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
   5850     if (AllWordsInNewV) {
   5851       for (int i = 0; i != 8; ++i) {
   5852         int idx = MaskVals[i];
   5853         if (idx < 0)
   5854           continue;
   5855         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
   5856         if ((idx != i) && idx < 4)
   5857           pshufhw = false;
   5858         if ((idx != i) && idx > 3)
   5859           pshuflw = false;
   5860       }
   5861       V1 = NewV;
   5862       V2Used = false;
   5863       BestLoQuad = 0;
   5864       BestHiQuad = 1;
   5865     }
   5866 
   5867     // If we've eliminated the use of V2, and the new mask is a pshuflw or
   5868     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
   5869     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
   5870       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
   5871       unsigned TargetMask = 0;
   5872       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
   5873                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
   5874       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
   5875       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
   5876                              getShufflePSHUFLWImmediate(SVOp);
   5877       V1 = NewV.getOperand(0);
   5878       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
   5879     }
   5880   }
   5881 
   5882   // Promote splats to a larger type which usually leads to more efficient code.
   5883   // FIXME: Is this true if pshufb is available?
   5884   if (SVOp->isSplat())
   5885     return PromoteSplat(SVOp, DAG);
   5886 
   5887   // If we have SSSE3, and all words of the result are from 1 input vector,
   5888   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
   5889   // is present, fall back to case 4.
   5890   if (Subtarget->hasSSSE3()) {
   5891     SmallVector<SDValue,16> pshufbMask;
   5892 
   5893     // If we have elements from both input vectors, set the high bit of the
   5894     // shuffle mask element to zero out elements that come from V2 in the V1
   5895     // mask, and elements that come from V1 in the V2 mask, so that the two
   5896     // results can be OR'd together.
   5897     bool TwoInputs = V1Used && V2Used;
   5898     for (unsigned i = 0; i != 8; ++i) {
   5899       int EltIdx = MaskVals[i] * 2;
   5900       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
   5901       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
   5902       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
   5903       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
   5904     }
   5905     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
   5906     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
   5907                      DAG.getNode(ISD::BUILD_VECTOR, dl,
   5908                                  MVT::v16i8, &pshufbMask[0], 16));
   5909     if (!TwoInputs)
   5910       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
   5911 
   5912     // Calculate the shuffle mask for the second input, shuffle it, and
   5913     // OR it with the first shuffled input.
   5914     pshufbMask.clear();
   5915     for (unsigned i = 0; i != 8; ++i) {
   5916       int EltIdx = MaskVals[i] * 2;
   5917       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
   5918       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
   5919       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
   5920       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
   5921     }
   5922     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
   5923     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
   5924                      DAG.getNode(ISD::BUILD_VECTOR, dl,
   5925                                  MVT::v16i8, &pshufbMask[0], 16));
   5926     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
   5927     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
   5928   }
   5929 
   5930   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
   5931   // and update MaskVals with new element order.
   5932   std::bitset<8> InOrder;
   5933   if (BestLoQuad >= 0) {
   5934     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
   5935     for (int i = 0; i != 4; ++i) {
   5936       int idx = MaskVals[i];
   5937       if (idx < 0) {
   5938         InOrder.set(i);
   5939       } else if ((idx / 4) == BestLoQuad) {
   5940         MaskV[i] = idx & 3;
   5941         InOrder.set(i);
   5942       }
   5943     }
   5944     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
   5945                                 &MaskV[0]);
   5946 
   5947     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
   5948       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
   5949       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
   5950                                   NewV.getOperand(0),
   5951                                   getShufflePSHUFLWImmediate(SVOp), DAG);
   5952     }
   5953   }
   5954 
   5955   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
   5956   // and update MaskVals with the new element order.
   5957   if (BestHiQuad >= 0) {
   5958     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
   5959     for (unsigned i = 4; i != 8; ++i) {
   5960       int idx = MaskVals[i];
   5961       if (idx < 0) {
   5962         InOrder.set(i);
   5963       } else if ((idx / 4) == BestHiQuad) {
   5964         MaskV[i] = (idx & 3) + 4;
   5965         InOrder.set(i);
   5966       }
   5967     }
   5968     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
   5969                                 &MaskV[0]);
   5970 
   5971     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
   5972       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
   5973       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
   5974                                   NewV.getOperand(0),
   5975                                   getShufflePSHUFHWImmediate(SVOp), DAG);
   5976     }
   5977   }
   5978 
   5979   // In case BestHi & BestLo were both -1, which means each quadword has a word
   5980   // from each of the four input quadwords, calculate the InOrder bitvector now
   5981   // before falling through to the insert/extract cleanup.
   5982   if (BestLoQuad == -1 && BestHiQuad == -1) {
   5983     NewV = V1;
   5984     for (int i = 0; i != 8; ++i)
   5985       if (MaskVals[i] < 0 || MaskVals[i] == i)
   5986         InOrder.set(i);
   5987   }
   5988 
   5989   // The other elements are put in the right place using pextrw and pinsrw.
   5990   for (unsigned i = 0; i != 8; ++i) {
   5991     if (InOrder[i])
   5992       continue;
   5993     int EltIdx = MaskVals[i];
   5994     if (EltIdx < 0)
   5995       continue;
   5996     SDValue ExtOp = (EltIdx < 8) ?
   5997       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
   5998                   DAG.getIntPtrConstant(EltIdx)) :
   5999       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
   6000                   DAG.getIntPtrConstant(EltIdx - 8));
   6001     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
   6002                        DAG.getIntPtrConstant(i));
   6003   }
   6004   return NewV;
   6005 }
   6006 
   6007 // v16i8 shuffles - Prefer shuffles in the following order:
   6008 // 1. [ssse3] 1 x pshufb
   6009 // 2. [ssse3] 2 x pshufb + 1 x por
   6010 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
   6011 static
   6012 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
   6013                                  SelectionDAG &DAG,
   6014                                  const X86TargetLowering &TLI) {
   6015   SDValue V1 = SVOp->getOperand(0);
   6016   SDValue V2 = SVOp->getOperand(1);
   6017   DebugLoc dl = SVOp->getDebugLoc();
   6018   ArrayRef<int> MaskVals = SVOp->getMask();
   6019 
   6020   // Promote splats to a larger type which usually leads to more efficient code.
   6021   // FIXME: Is this true if pshufb is available?
   6022   if (SVOp->isSplat())
   6023     return PromoteSplat(SVOp, DAG);
   6024 
   6025   // If we have SSSE3, case 1 is generated when all result bytes come from
   6026   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
   6027   // present, fall back to case 3.
   6028 
   6029   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
   6030   if (TLI.getSubtarget()->hasSSSE3()) {
   6031     SmallVector<SDValue,16> pshufbMask;
   6032 
   6033     // If all result elements are from one input vector, then only translate
   6034     // undef mask values to 0x80 (zero out result) in the pshufb mask.
   6035     //
   6036     // Otherwise, we have elements from both input vectors, and must zero out
   6037     // elements that come from V2 in the first mask, and V1 in the second mask
   6038     // so that we can OR them together.
   6039     for (unsigned i = 0; i != 16; ++i) {
   6040       int EltIdx = MaskVals[i];
   6041       if (EltIdx < 0 || EltIdx >= 16)
   6042         EltIdx = 0x80;
   6043       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
   6044     }
   6045     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
   6046                      DAG.getNode(ISD::BUILD_VECTOR, dl,
   6047                                  MVT::v16i8, &pshufbMask[0], 16));
   6048 
   6049     // As PSHUFB will zero elements with negative indices, it's safe to ignore
   6050     // the 2nd operand if it's undefined or zero.
   6051     if (V2.getOpcode() == ISD::UNDEF ||
   6052         ISD::isBuildVectorAllZeros(V2.getNode()))
   6053       return V1;
   6054 
   6055     // Calculate the shuffle mask for the second input, shuffle it, and
   6056     // OR it with the first shuffled input.
   6057     pshufbMask.clear();
   6058     for (unsigned i = 0; i != 16; ++i) {
   6059       int EltIdx = MaskVals[i];
   6060       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
   6061       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
   6062     }
   6063     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
   6064                      DAG.getNode(ISD::BUILD_VECTOR, dl,
   6065                                  MVT::v16i8, &pshufbMask[0], 16));
   6066     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
   6067   }
   6068 
   6069   // No SSSE3 - Calculate in place words and then fix all out of place words
   6070   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
   6071   // the 16 different words that comprise the two doublequadword input vectors.
   6072   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
   6073   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
   6074   SDValue NewV = V1;
   6075   for (int i = 0; i != 8; ++i) {
   6076     int Elt0 = MaskVals[i*2];
   6077     int Elt1 = MaskVals[i*2+1];
   6078 
   6079     // This word of the result is all undef, skip it.
   6080     if (Elt0 < 0 && Elt1 < 0)
   6081       continue;
   6082 
   6083     // This word of the result is already in the correct place, skip it.
   6084     if ((Elt0 == i*2) && (Elt1 == i*2+1))
   6085       continue;
   6086 
   6087     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
   6088     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
   6089     SDValue InsElt;
   6090 
   6091     // If Elt0 and Elt1 are defined, are consecutive, and can be load
   6092     // using a single extract together, load it and store it.
   6093     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
   6094       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
   6095                            DAG.getIntPtrConstant(Elt1 / 2));
   6096       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
   6097                         DAG.getIntPtrConstant(i));
   6098       continue;
   6099     }
   6100 
   6101     // If Elt1 is defined, extract it from the appropriate source.  If the
   6102     // source byte is not also odd, shift the extracted word left 8 bits
   6103     // otherwise clear the bottom 8 bits if we need to do an or.
   6104     if (Elt1 >= 0) {
   6105       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
   6106                            DAG.getIntPtrConstant(Elt1 / 2));
   6107       if ((Elt1 & 1) == 0)
   6108         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
   6109                              DAG.getConstant(8,
   6110                                   TLI.getShiftAmountTy(InsElt.getValueType())));
   6111       else if (Elt0 >= 0)
   6112         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
   6113                              DAG.getConstant(0xFF00, MVT::i16));
   6114     }
   6115     // If Elt0 is defined, extract it from the appropriate source.  If the
   6116     // source byte is not also even, shift the extracted word right 8 bits. If
   6117     // Elt1 was also defined, OR the extracted values together before
   6118     // inserting them in the result.
   6119     if (Elt0 >= 0) {
   6120       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
   6121                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
   6122       if ((Elt0 & 1) != 0)
   6123         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
   6124                               DAG.getConstant(8,
   6125                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
   6126       else if (Elt1 >= 0)
   6127         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
   6128                              DAG.getConstant(0x00FF, MVT::i16));
   6129       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
   6130                          : InsElt0;
   6131     }
   6132     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
   6133                        DAG.getIntPtrConstant(i));
   6134   }
   6135   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
   6136 }
   6137 
   6138 // v32i8 shuffles - Translate to VPSHUFB if possible.
   6139 static
   6140 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
   6141                                  const X86Subtarget *Subtarget,
   6142                                  SelectionDAG &DAG) {
   6143   MVT VT = SVOp->getValueType(0).getSimpleVT();
   6144   SDValue V1 = SVOp->getOperand(0);
   6145   SDValue V2 = SVOp->getOperand(1);
   6146   DebugLoc dl = SVOp->getDebugLoc();
   6147   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
   6148 
   6149   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
   6150   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
   6151   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
   6152 
   6153   // VPSHUFB may be generated if
   6154   // (1) one of input vector is undefined or zeroinitializer.
   6155   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
   6156   // And (2) the mask indexes don't cross the 128-bit lane.
   6157   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
   6158       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
   6159     return SDValue();
   6160 
   6161   if (V1IsAllZero && !V2IsAllZero) {
   6162     CommuteVectorShuffleMask(MaskVals, 32);
   6163     V1 = V2;
   6164   }
   6165   SmallVector<SDValue, 32> pshufbMask;
   6166   for (unsigned i = 0; i != 32; i++) {
   6167     int EltIdx = MaskVals[i];
   6168     if (EltIdx < 0 || EltIdx >= 32)
   6169       EltIdx = 0x80;
   6170     else {
   6171       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
   6172         // Cross lane is not allowed.
   6173         return SDValue();
   6174       EltIdx &= 0xf;
   6175     }
   6176     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
   6177   }
   6178   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
   6179                       DAG.getNode(ISD::BUILD_VECTOR, dl,
   6180                                   MVT::v32i8, &pshufbMask[0], 32));
   6181 }
   6182 
   6183 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
   6184 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
   6185 /// done when every pair / quad of shuffle mask elements point to elements in
   6186 /// the right sequence. e.g.
   6187 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
   6188 static
   6189 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
   6190                                  SelectionDAG &DAG) {
   6191   MVT VT = SVOp->getValueType(0).getSimpleVT();
   6192   DebugLoc dl = SVOp->getDebugLoc();
   6193   unsigned NumElems = VT.getVectorNumElements();
   6194   MVT NewVT;
   6195   unsigned Scale;
   6196   switch (VT.SimpleTy) {
   6197   default: llvm_unreachable("Unexpected!");
   6198   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
   6199   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
   6200   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
   6201   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
   6202   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
   6203   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
   6204   }
   6205 
   6206   SmallVector<int, 8> MaskVec;
   6207   for (unsigned i = 0; i != NumElems; i += Scale) {
   6208     int StartIdx = -1;
   6209     for (unsigned j = 0; j != Scale; ++j) {
   6210       int EltIdx = SVOp->getMaskElt(i+j);
   6211       if (EltIdx < 0)
   6212         continue;
   6213       if (StartIdx < 0)
   6214         StartIdx = (EltIdx / Scale);
   6215       if (EltIdx != (int)(StartIdx*Scale + j))
   6216         return SDValue();
   6217     }
   6218     MaskVec.push_back(StartIdx);
   6219   }
   6220 
   6221   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
   6222   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
   6223   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
   6224 }
   6225 
   6226 /// getVZextMovL - Return a zero-extending vector move low node.
   6227 ///
   6228 static SDValue getVZextMovL(MVT VT, EVT OpVT,
   6229                             SDValue SrcOp, SelectionDAG &DAG,
   6230                             const X86Subtarget *Subtarget, DebugLoc dl) {
   6231   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
   6232     LoadSDNode *LD = NULL;
   6233     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
   6234       LD = dyn_cast<LoadSDNode>(SrcOp);
   6235     if (!LD) {
   6236       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
   6237       // instead.
   6238       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
   6239       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
   6240           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
   6241           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
   6242           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
   6243         // PR2108
   6244         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
   6245         return DAG.getNode(ISD::BITCAST, dl, VT,
   6246                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
   6247                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
   6248                                                    OpVT,
   6249                                                    SrcOp.getOperand(0)
   6250                                                           .getOperand(0))));
   6251       }
   6252     }
   6253   }
   6254 
   6255   return DAG.getNode(ISD::BITCAST, dl, VT,
   6256                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
   6257                                  DAG.getNode(ISD::BITCAST, dl,
   6258                                              OpVT, SrcOp)));
   6259 }
   6260 
   6261 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
   6262 /// which could not be matched by any known target speficic shuffle
   6263 static SDValue
   6264 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
   6265 
   6266   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
   6267   if (NewOp.getNode())
   6268     return NewOp;
   6269 
   6270   MVT VT = SVOp->getValueType(0).getSimpleVT();
   6271 
   6272   unsigned NumElems = VT.getVectorNumElements();
   6273   unsigned NumLaneElems = NumElems / 2;
   6274 
   6275   DebugLoc dl = SVOp->getDebugLoc();
   6276   MVT EltVT = VT.getVectorElementType();
   6277   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
   6278   SDValue Output[2];
   6279 
   6280   SmallVector<int, 16> Mask;
   6281   for (unsigned l = 0; l < 2; ++l) {
   6282     // Build a shuffle mask for the output, discovering on the fly which
   6283     // input vectors to use as shuffle operands (recorded in InputUsed).
   6284     // If building a suitable shuffle vector proves too hard, then bail
   6285     // out with UseBuildVector set.
   6286     bool UseBuildVector = false;
   6287     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
   6288     unsigned LaneStart = l * NumLaneElems;
   6289     for (unsigned i = 0; i != NumLaneElems; ++i) {
   6290       // The mask element.  This indexes into the input.
   6291       int Idx = SVOp->getMaskElt(i+LaneStart);
   6292       if (Idx < 0) {
   6293         // the mask element does not index into any input vector.
   6294         Mask.push_back(-1);
   6295         continue;
   6296       }
   6297 
   6298       // The input vector this mask element indexes into.
   6299       int Input = Idx / NumLaneElems;
   6300 
   6301       // Turn the index into an offset from the start of the input vector.
   6302       Idx -= Input * NumLaneElems;
   6303 
   6304       // Find or create a shuffle vector operand to hold this input.
   6305       unsigned OpNo;
   6306       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
   6307         if (InputUsed[OpNo] == Input)
   6308           // This input vector is already an operand.
   6309           break;
   6310         if (InputUsed[OpNo] < 0) {
   6311           // Create a new operand for this input vector.
   6312           InputUsed[OpNo] = Input;
   6313           break;
   6314         }
   6315       }
   6316 
   6317       if (OpNo >= array_lengthof(InputUsed)) {
   6318         // More than two input vectors used!  Give up on trying to create a
   6319         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
   6320         UseBuildVector = true;
   6321         break;
   6322       }
   6323 
   6324       // Add the mask index for the new shuffle vector.
   6325       Mask.push_back(Idx + OpNo * NumLaneElems);
   6326     }
   6327 
   6328     if (UseBuildVector) {
   6329       SmallVector<SDValue, 16> SVOps;
   6330       for (unsigned i = 0; i != NumLaneElems; ++i) {
   6331         // The mask element.  This indexes into the input.
   6332         int Idx = SVOp->getMaskElt(i+LaneStart);
   6333         if (Idx < 0) {
   6334           SVOps.push_back(DAG.getUNDEF(EltVT));
   6335           continue;
   6336         }
   6337 
   6338         // The input vector this mask element indexes into.
   6339         int Input = Idx / NumElems;
   6340 
   6341         // Turn the index into an offset from the start of the input vector.
   6342         Idx -= Input * NumElems;
   6343 
   6344         // Extract the vector element by hand.
   6345         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
   6346                                     SVOp->getOperand(Input),
   6347                                     DAG.getIntPtrConstant(Idx)));
   6348       }
   6349 
   6350       // Construct the output using a BUILD_VECTOR.
   6351       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
   6352                               SVOps.size());
   6353     } else if (InputUsed[0] < 0) {
   6354       // No input vectors were used! The result is undefined.
   6355       Output[l] = DAG.getUNDEF(NVT);
   6356     } else {
   6357       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
   6358                                         (InputUsed[0] % 2) * NumLaneElems,
   6359                                         DAG, dl);
   6360       // If only one input was used, use an undefined vector for the other.
   6361       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
   6362         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
   6363                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
   6364       // At least one input vector was used. Create a new shuffle vector.
   6365       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
   6366     }
   6367 
   6368     Mask.clear();
   6369   }
   6370 
   6371   // Concatenate the result back
   6372   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
   6373 }
   6374 
   6375 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
   6376 /// 4 elements, and match them with several different shuffle types.
   6377 static SDValue
   6378 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
   6379   SDValue V1 = SVOp->getOperand(0);
   6380   SDValue V2 = SVOp->getOperand(1);
   6381   DebugLoc dl = SVOp->getDebugLoc();
   6382   MVT VT = SVOp->getValueType(0).getSimpleVT();
   6383 
   6384   assert(VT.is128BitVector() && "Unsupported vector size");
   6385 
   6386   std::pair<int, int> Locs[4];
   6387   int Mask1[] = { -1, -1, -1, -1 };
   6388   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
   6389 
   6390   unsigned NumHi = 0;
   6391   unsigned NumLo = 0;
   6392   for (unsigned i = 0; i != 4; ++i) {
   6393     int Idx = PermMask[i];
   6394     if (Idx < 0) {
   6395       Locs[i] = std::make_pair(-1, -1);
   6396     } else {
   6397       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
   6398       if (Idx < 4) {
   6399         Locs[i] = std::make_pair(0, NumLo);
   6400         Mask1[NumLo] = Idx;
   6401         NumLo++;
   6402       } else {
   6403         Locs[i] = std::make_pair(1, NumHi);
   6404         if (2+NumHi < 4)
   6405           Mask1[2+NumHi] = Idx;
   6406         NumHi++;
   6407       }
   6408     }
   6409   }
   6410 
   6411   if (NumLo <= 2 && NumHi <= 2) {
   6412     // If no more than two elements come from either vector. This can be
   6413     // implemented with two shuffles. First shuffle gather the elements.
   6414     // The second shuffle, which takes the first shuffle as both of its
   6415     // vector operands, put the elements into the right order.
   6416     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
   6417 
   6418     int Mask2[] = { -1, -1, -1, -1 };
   6419 
   6420     for (unsigned i = 0; i != 4; ++i)
   6421       if (Locs[i].first != -1) {
   6422         unsigned Idx = (i < 2) ? 0 : 4;
   6423         Idx += Locs[i].first * 2 + Locs[i].second;
   6424         Mask2[i] = Idx;
   6425       }
   6426 
   6427     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
   6428   }
   6429 
   6430   if (NumLo == 3 || NumHi == 3) {
   6431     // Otherwise, we must have three elements from one vector, call it X, and
   6432     // one element from the other, call it Y.  First, use a shufps to build an
   6433     // intermediate vector with the one element from Y and the element from X
   6434     // that will be in the same half in the final destination (the indexes don't
   6435     // matter). Then, use a shufps to build the final vector, taking the half
   6436     // containing the element from Y from the intermediate, and the other half
   6437     // from X.
   6438     if (NumHi == 3) {
   6439       // Normalize it so the 3 elements come from V1.
   6440       CommuteVectorShuffleMask(PermMask, 4);
   6441       std::swap(V1, V2);
   6442     }
   6443 
   6444     // Find the element from V2.
   6445     unsigned HiIndex;
   6446     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
   6447       int Val = PermMask[HiIndex];
   6448       if (Val < 0)
   6449         continue;
   6450       if (Val >= 4)
   6451         break;
   6452     }
   6453 
   6454     Mask1[0] = PermMask[HiIndex];
   6455     Mask1[1] = -1;
   6456     Mask1[2] = PermMask[HiIndex^1];
   6457     Mask1[3] = -1;
   6458     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
   6459 
   6460     if (HiIndex >= 2) {
   6461       Mask1[0] = PermMask[0];
   6462       Mask1[1] = PermMask[1];
   6463       Mask1[2] = HiIndex & 1 ? 6 : 4;
   6464       Mask1[3] = HiIndex & 1 ? 4 : 6;
   6465       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
   6466     }
   6467 
   6468     Mask1[0] = HiIndex & 1 ? 2 : 0;
   6469     Mask1[1] = HiIndex & 1 ? 0 : 2;
   6470     Mask1[2] = PermMask[2];
   6471     Mask1[3] = PermMask[3];
   6472     if (Mask1[2] >= 0)
   6473       Mask1[2] += 4;
   6474     if (Mask1[3] >= 0)
   6475       Mask1[3] += 4;
   6476     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
   6477   }
   6478 
   6479   // Break it into (shuffle shuffle_hi, shuffle_lo).
   6480   int LoMask[] = { -1, -1, -1, -1 };
   6481   int HiMask[] = { -1, -1, -1, -1 };
   6482 
   6483   int *MaskPtr = LoMask;
   6484   unsigned MaskIdx = 0;
   6485   unsigned LoIdx = 0;
   6486   unsigned HiIdx = 2;
   6487   for (unsigned i = 0; i != 4; ++i) {
   6488     if (i == 2) {
   6489       MaskPtr = HiMask;
   6490       MaskIdx = 1;
   6491       LoIdx = 0;
   6492       HiIdx = 2;
   6493     }
   6494     int Idx = PermMask[i];
   6495     if (Idx < 0) {
   6496       Locs[i] = std::make_pair(-1, -1);
   6497     } else if (Idx < 4) {
   6498       Locs[i] = std::make_pair(MaskIdx, LoIdx);
   6499       MaskPtr[LoIdx] = Idx;
   6500       LoIdx++;
   6501     } else {
   6502       Locs[i] = std::make_pair(MaskIdx, HiIdx);
   6503       MaskPtr[HiIdx] = Idx;
   6504       HiIdx++;
   6505     }
   6506   }
   6507 
   6508   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
   6509   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
   6510   int MaskOps[] = { -1, -1, -1, -1 };
   6511   for (unsigned i = 0; i != 4; ++i)
   6512     if (Locs[i].first != -1)
   6513       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
   6514   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
   6515 }
   6516 
   6517 static bool MayFoldVectorLoad(SDValue V) {
   6518   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
   6519     V = V.getOperand(0);
   6520 
   6521   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
   6522     V = V.getOperand(0);
   6523   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
   6524       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
   6525     // BUILD_VECTOR (load), undef
   6526     V = V.getOperand(0);
   6527 
   6528   return MayFoldLoad(V);
   6529 }
   6530 
   6531 static
   6532 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
   6533   EVT VT = Op.getValueType();
   6534 
   6535   // Canonizalize to v2f64.
   6536   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
   6537   return DAG.getNode(ISD::BITCAST, dl, VT,
   6538                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
   6539                                           V1, DAG));
   6540 }
   6541 
   6542 static
   6543 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
   6544                         bool HasSSE2) {
   6545   SDValue V1 = Op.getOperand(0);
   6546   SDValue V2 = Op.getOperand(1);
   6547   EVT VT = Op.getValueType();
   6548 
   6549   assert(VT != MVT::v2i64 && "unsupported shuffle type");
   6550 
   6551   if (HasSSE2 && VT == MVT::v2f64)
   6552     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
   6553 
   6554   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
   6555   return DAG.getNode(ISD::BITCAST, dl, VT,
   6556                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
   6557                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
   6558                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
   6559 }
   6560 
   6561 static
   6562 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
   6563   SDValue V1 = Op.getOperand(0);
   6564   SDValue V2 = Op.getOperand(1);
   6565   EVT VT = Op.getValueType();
   6566 
   6567   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
   6568          "unsupported shuffle type");
   6569 
   6570   if (V2.getOpcode() == ISD::UNDEF)
   6571     V2 = V1;
   6572 
   6573   // v4i32 or v4f32
   6574   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
   6575 }
   6576 
   6577 static
   6578 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
   6579   SDValue V1 = Op.getOperand(0);
   6580   SDValue V2 = Op.getOperand(1);
   6581   EVT VT = Op.getValueType();
   6582   unsigned NumElems = VT.getVectorNumElements();
   6583 
   6584   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
   6585   // operand of these instructions is only memory, so check if there's a
   6586   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
   6587   // same masks.
   6588   bool CanFoldLoad = false;
   6589 
   6590   // Trivial case, when V2 comes from a load.
   6591   if (MayFoldVectorLoad(V2))
   6592     CanFoldLoad = true;
   6593 
   6594   // When V1 is a load, it can be folded later into a store in isel, example:
   6595   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
   6596   //    turns into:
   6597   //  (MOVLPSmr addr:$src1, VR128:$src2)
   6598   // So, recognize this potential and also use MOVLPS or MOVLPD
   6599   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
   6600     CanFoldLoad = true;
   6601 
   6602   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
   6603   if (CanFoldLoad) {
   6604     if (HasSSE2 && NumElems == 2)
   6605       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
   6606 
   6607     if (NumElems == 4)
   6608       // If we don't care about the second element, proceed to use movss.
   6609       if (SVOp->getMaskElt(1) != -1)
   6610         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
   6611   }
   6612 
   6613   // movl and movlp will both match v2i64, but v2i64 is never matched by
   6614   // movl earlier because we make it strict to avoid messing with the movlp load
   6615   // folding logic (see the code above getMOVLP call). Match it here then,
   6616   // this is horrible, but will stay like this until we move all shuffle
   6617   // matching to x86 specific nodes. Note that for the 1st condition all
   6618   // types are matched with movsd.
   6619   if (HasSSE2) {
   6620     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
   6621     // as to remove this logic from here, as much as possible
   6622     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
   6623       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
   6624     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
   6625   }
   6626 
   6627   assert(VT != MVT::v4i32 && "unsupported shuffle type");
   6628 
   6629   // Invert the operand order and use SHUFPS to match it.
   6630   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
   6631                               getShuffleSHUFImmediate(SVOp), DAG);
   6632 }
   6633 
   6634 // Reduce a vector shuffle to zext.
   6635 SDValue
   6636 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
   6637   // PMOVZX is only available from SSE41.
   6638   if (!Subtarget->hasSSE41())
   6639     return SDValue();
   6640 
   6641   EVT VT = Op.getValueType();
   6642 
   6643   // Only AVX2 support 256-bit vector integer extending.
   6644   if (!Subtarget->hasInt256() && VT.is256BitVector())
   6645     return SDValue();
   6646 
   6647   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
   6648   DebugLoc DL = Op.getDebugLoc();
   6649   SDValue V1 = Op.getOperand(0);
   6650   SDValue V2 = Op.getOperand(1);
   6651   unsigned NumElems = VT.getVectorNumElements();
   6652 
   6653   // Extending is an unary operation and the element type of the source vector
   6654   // won't be equal to or larger than i64.
   6655   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
   6656       VT.getVectorElementType() == MVT::i64)
   6657     return SDValue();
   6658 
   6659   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
   6660   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
   6661   while ((1U << Shift) < NumElems) {
   6662     if (SVOp->getMaskElt(1U << Shift) == 1)
   6663       break;
   6664     Shift += 1;
   6665     // The maximal ratio is 8, i.e. from i8 to i64.
   6666     if (Shift > 3)
   6667       return SDValue();
   6668   }
   6669 
   6670   // Check the shuffle mask.
   6671   unsigned Mask = (1U << Shift) - 1;
   6672   for (unsigned i = 0; i != NumElems; ++i) {
   6673     int EltIdx = SVOp->getMaskElt(i);
   6674     if ((i & Mask) != 0 && EltIdx != -1)
   6675       return SDValue();
   6676     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
   6677       return SDValue();
   6678   }
   6679 
   6680   LLVMContext *Context = DAG.getContext();
   6681   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
   6682   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
   6683   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
   6684 
   6685   if (!isTypeLegal(NVT))
   6686     return SDValue();
   6687 
   6688   // Simplify the operand as it's prepared to be fed into shuffle.
   6689   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
   6690   if (V1.getOpcode() == ISD::BITCAST &&
   6691       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
   6692       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
   6693       V1.getOperand(0)
   6694         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
   6695     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
   6696     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
   6697     ConstantSDNode *CIdx =
   6698       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
   6699     // If it's foldable, i.e. normal load with single use, we will let code
   6700     // selection to fold it. Otherwise, we will short the conversion sequence.
   6701     if (CIdx && CIdx->getZExtValue() == 0 &&
   6702         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
   6703       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
   6704         // The "ext_vec_elt" node is wider than the result node.
   6705         // In this case we should extract subvector from V.
   6706         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
   6707         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
   6708         EVT FullVT = V.getValueType();
   6709         EVT SubVecVT = EVT::getVectorVT(*Context,
   6710                                         FullVT.getVectorElementType(),
   6711                                         FullVT.getVectorNumElements()/Ratio);
   6712         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
   6713                         DAG.getIntPtrConstant(0));
   6714       }
   6715       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
   6716     }
   6717   }
   6718 
   6719   return DAG.getNode(ISD::BITCAST, DL, VT,
   6720                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
   6721 }
   6722 
   6723 SDValue
   6724 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
   6725   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
   6726   MVT VT = Op.getValueType().getSimpleVT();
   6727   DebugLoc dl = Op.getDebugLoc();
   6728   SDValue V1 = Op.getOperand(0);
   6729   SDValue V2 = Op.getOperand(1);
   6730 
   6731   if (isZeroShuffle(SVOp))
   6732     return getZeroVector(VT, Subtarget, DAG, dl);
   6733 
   6734   // Handle splat operations
   6735   if (SVOp->isSplat()) {
   6736     // Use vbroadcast whenever the splat comes from a foldable load
   6737     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
   6738     if (Broadcast.getNode())
   6739       return Broadcast;
   6740   }
   6741 
   6742   // Check integer expanding shuffles.
   6743   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
   6744   if (NewOp.getNode())
   6745     return NewOp;
   6746 
   6747   // If the shuffle can be profitably rewritten as a narrower shuffle, then
   6748   // do it!
   6749   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
   6750       VT == MVT::v16i16 || VT == MVT::v32i8) {
   6751     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
   6752     if (NewOp.getNode())
   6753       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
   6754   } else if ((VT == MVT::v4i32 ||
   6755              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
   6756     // FIXME: Figure out a cleaner way to do this.
   6757     // Try to make use of movq to zero out the top part.
   6758     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
   6759       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
   6760       if (NewOp.getNode()) {
   6761         MVT NewVT = NewOp.getValueType().getSimpleVT();
   6762         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
   6763                                NewVT, true, false))
   6764           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
   6765                               DAG, Subtarget, dl);
   6766       }
   6767     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
   6768       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
   6769       if (NewOp.getNode()) {
   6770         MVT NewVT = NewOp.getValueType().getSimpleVT();
   6771         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
   6772           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
   6773                               DAG, Subtarget, dl);
   6774       }
   6775     }
   6776   }
   6777   return SDValue();
   6778 }
   6779 
   6780 SDValue
   6781 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
   6782   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
   6783   SDValue V1 = Op.getOperand(0);
   6784   SDValue V2 = Op.getOperand(1);
   6785   MVT VT = Op.getValueType().getSimpleVT();
   6786   DebugLoc dl = Op.getDebugLoc();
   6787   unsigned NumElems = VT.getVectorNumElements();
   6788   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
   6789   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
   6790   bool V1IsSplat = false;
   6791   bool V2IsSplat = false;
   6792   bool HasSSE2 = Subtarget->hasSSE2();
   6793   bool HasFp256    = Subtarget->hasFp256();
   6794   bool HasInt256   = Subtarget->hasInt256();
   6795   MachineFunction &MF = DAG.getMachineFunction();
   6796   bool OptForSize = MF.getFunction()->getAttributes().
   6797     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
   6798 
   6799   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
   6800 
   6801   if (V1IsUndef && V2IsUndef)
   6802     return DAG.getUNDEF(VT);
   6803 
   6804   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
   6805 
   6806   // Vector shuffle lowering takes 3 steps:
   6807   //
   6808   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
   6809   //    narrowing and commutation of operands should be handled.
   6810   // 2) Matching of shuffles with known shuffle masks to x86 target specific
   6811   //    shuffle nodes.
   6812   // 3) Rewriting of unmatched masks into new generic shuffle operations,
   6813   //    so the shuffle can be broken into other shuffles and the legalizer can
   6814   //    try the lowering again.
   6815   //
   6816   // The general idea is that no vector_shuffle operation should be left to
   6817   // be matched during isel, all of them must be converted to a target specific
   6818   // node here.
   6819 
   6820   // Normalize the input vectors. Here splats, zeroed vectors, profitable
   6821   // narrowing and commutation of operands should be handled. The actual code
   6822   // doesn't include all of those, work in progress...
   6823   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
   6824   if (NewOp.getNode())
   6825     return NewOp;
   6826 
   6827   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
   6828 
   6829   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
   6830   // unpckh_undef). Only use pshufd if speed is more important than size.
   6831   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
   6832     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
   6833   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
   6834     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
   6835 
   6836   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
   6837       V2IsUndef && MayFoldVectorLoad(V1))
   6838     return getMOVDDup(Op, dl, V1, DAG);
   6839 
   6840   if (isMOVHLPS_v_undef_Mask(M, VT))
   6841     return getMOVHighToLow(Op, dl, DAG);
   6842 
   6843   // Use to match splats
   6844   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
   6845       (VT == MVT::v2f64 || VT == MVT::v2i64))
   6846     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
   6847 
   6848   if (isPSHUFDMask(M, VT)) {
   6849     // The actual implementation will match the mask in the if above and then
   6850     // during isel it can match several different instructions, not only pshufd
   6851     // as its name says, sad but true, emulate the behavior for now...
   6852     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
   6853       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
   6854 
   6855     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
   6856 
   6857     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
   6858       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
   6859 
   6860     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
   6861       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
   6862                                   DAG);
   6863 
   6864     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
   6865                                 TargetMask, DAG);
   6866   }
   6867 
   6868   // Check if this can be converted into a logical shift.
   6869   bool isLeft = false;
   6870   unsigned ShAmt = 0;
   6871   SDValue ShVal;
   6872   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
   6873   if (isShift && ShVal.hasOneUse()) {
   6874     // If the shifted value has multiple uses, it may be cheaper to use
   6875     // v_set0 + movlhps or movhlps, etc.
   6876     MVT EltVT = VT.getVectorElementType();
   6877     ShAmt *= EltVT.getSizeInBits();
   6878     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
   6879   }
   6880 
   6881   if (isMOVLMask(M, VT)) {
   6882     if (ISD::isBuildVectorAllZeros(V1.getNode()))
   6883       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
   6884     if (!isMOVLPMask(M, VT)) {
   6885       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
   6886         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
   6887 
   6888       if (VT == MVT::v4i32 || VT == MVT::v4f32)
   6889         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
   6890     }
   6891   }
   6892 
   6893   // FIXME: fold these into legal mask.
   6894   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
   6895     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
   6896 
   6897   if (isMOVHLPSMask(M, VT))
   6898     return getMOVHighToLow(Op, dl, DAG);
   6899 
   6900   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
   6901     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
   6902 
   6903   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
   6904     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
   6905 
   6906   if (isMOVLPMask(M, VT))
   6907     return getMOVLP(Op, dl, DAG, HasSSE2);
   6908 
   6909   if (ShouldXformToMOVHLPS(M, VT) ||
   6910       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
   6911     return CommuteVectorShuffle(SVOp, DAG);
   6912 
   6913   if (isShift) {
   6914     // No better options. Use a vshldq / vsrldq.
   6915     MVT EltVT = VT.getVectorElementType();
   6916     ShAmt *= EltVT.getSizeInBits();
   6917     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
   6918   }
   6919 
   6920   bool Commuted = false;
   6921   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
   6922   // 1,1,1,1 -> v8i16 though.
   6923   V1IsSplat = isSplatVector(V1.getNode());
   6924   V2IsSplat = isSplatVector(V2.getNode());
   6925 
   6926   // Canonicalize the splat or undef, if present, to be on the RHS.
   6927   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
   6928     CommuteVectorShuffleMask(M, NumElems);
   6929     std::swap(V1, V2);
   6930     std::swap(V1IsSplat, V2IsSplat);
   6931     Commuted = true;
   6932   }
   6933 
   6934   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
   6935     // Shuffling low element of v1 into undef, just return v1.
   6936     if (V2IsUndef)
   6937       return V1;
   6938     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
   6939     // the instruction selector will not match, so get a canonical MOVL with
   6940     // swapped operands to undo the commute.
   6941     return getMOVL(DAG, dl, VT, V2, V1);
   6942   }
   6943 
   6944   if (isUNPCKLMask(M, VT, HasInt256))
   6945     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
   6946 
   6947   if (isUNPCKHMask(M, VT, HasInt256))
   6948     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
   6949 
   6950   if (V2IsSplat) {
   6951     // Normalize mask so all entries that point to V2 points to its first
   6952     // element then try to match unpck{h|l} again. If match, return a
   6953     // new vector_shuffle with the corrected mask.p
   6954     SmallVector<int, 8> NewMask(M.begin(), M.end());
   6955     NormalizeMask(NewMask, NumElems);
   6956     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
   6957       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
   6958     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
   6959       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
   6960   }
   6961 
   6962   if (Commuted) {
   6963     // Commute is back and try unpck* again.
   6964     // FIXME: this seems wrong.
   6965     CommuteVectorShuffleMask(M, NumElems);
   6966     std::swap(V1, V2);
   6967     std::swap(V1IsSplat, V2IsSplat);
   6968     Commuted = false;
   6969 
   6970     if (isUNPCKLMask(M, VT, HasInt256))
   6971       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
   6972 
   6973     if (isUNPCKHMask(M, VT, HasInt256))
   6974       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
   6975   }
   6976 
   6977   // Normalize the node to match x86 shuffle ops if needed
   6978   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
   6979     return CommuteVectorShuffle(SVOp, DAG);
   6980 
   6981   // The checks below are all present in isShuffleMaskLegal, but they are
   6982   // inlined here right now to enable us to directly emit target specific
   6983   // nodes, and remove one by one until they don't return Op anymore.
   6984 
   6985   if (isPALIGNRMask(M, VT, Subtarget))
   6986     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
   6987                                 getShufflePALIGNRImmediate(SVOp),
   6988                                 DAG);
   6989 
   6990   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
   6991       SVOp->getSplatIndex() == 0 && V2IsUndef) {
   6992     if (VT == MVT::v2f64 || VT == MVT::v2i64)
   6993       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
   6994   }
   6995 
   6996   if (isPSHUFHWMask(M, VT, HasInt256))
   6997     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
   6998                                 getShufflePSHUFHWImmediate(SVOp),
   6999                                 DAG);
   7000 
   7001   if (isPSHUFLWMask(M, VT, HasInt256))
   7002     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
   7003                                 getShufflePSHUFLWImmediate(SVOp),
   7004                                 DAG);
   7005 
   7006   if (isSHUFPMask(M, VT, HasFp256))
   7007     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
   7008                                 getShuffleSHUFImmediate(SVOp), DAG);
   7009 
   7010   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
   7011     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
   7012   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
   7013     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
   7014 
   7015   //===--------------------------------------------------------------------===//
   7016   // Generate target specific nodes for 128 or 256-bit shuffles only
   7017   // supported in the AVX instruction set.
   7018   //
   7019 
   7020   // Handle VMOVDDUPY permutations
   7021   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
   7022     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
   7023 
   7024   // Handle VPERMILPS/D* permutations
   7025   if (isVPERMILPMask(M, VT, HasFp256)) {
   7026     if (HasInt256 && VT == MVT::v8i32)
   7027       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
   7028                                   getShuffleSHUFImmediate(SVOp), DAG);
   7029     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
   7030                                 getShuffleSHUFImmediate(SVOp), DAG);
   7031   }
   7032 
   7033   // Handle VPERM2F128/VPERM2I128 permutations
   7034   if (isVPERM2X128Mask(M, VT, HasFp256))
   7035     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
   7036                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
   7037 
   7038   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
   7039   if (BlendOp.getNode())
   7040     return BlendOp;
   7041 
   7042   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
   7043     SmallVector<SDValue, 8> permclMask;
   7044     for (unsigned i = 0; i != 8; ++i) {
   7045       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
   7046     }
   7047     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
   7048                                &permclMask[0], 8);
   7049     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
   7050     return DAG.getNode(X86ISD::VPERMV, dl, VT,
   7051                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
   7052   }
   7053 
   7054   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
   7055     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
   7056                                 getShuffleCLImmediate(SVOp), DAG);
   7057 
   7058   //===--------------------------------------------------------------------===//
   7059   // Since no target specific shuffle was selected for this generic one,
   7060   // lower it into other known shuffles. FIXME: this isn't true yet, but
   7061   // this is the plan.
   7062   //
   7063 
   7064   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
   7065   if (VT == MVT::v8i16) {
   7066     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
   7067     if (NewOp.getNode())
   7068       return NewOp;
   7069   }
   7070 
   7071   if (VT == MVT::v16i8) {
   7072     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
   7073     if (NewOp.getNode())
   7074       return NewOp;
   7075   }
   7076 
   7077   if (VT == MVT::v32i8) {
   7078     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
   7079     if (NewOp.getNode())
   7080       return NewOp;
   7081   }
   7082 
   7083   // Handle all 128-bit wide vectors with 4 elements, and match them with
   7084   // several different shuffle types.
   7085   if (NumElems == 4 && VT.is128BitVector())
   7086     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
   7087 
   7088   // Handle general 256-bit shuffles
   7089   if (VT.is256BitVector())
   7090     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
   7091 
   7092   return SDValue();
   7093 }
   7094 
   7095 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
   7096   MVT VT = Op.getValueType().getSimpleVT();
   7097   DebugLoc dl = Op.getDebugLoc();
   7098 
   7099   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
   7100     return SDValue();
   7101 
   7102   if (VT.getSizeInBits() == 8) {
   7103     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
   7104                                   Op.getOperand(0), Op.getOperand(1));
   7105     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
   7106                                   DAG.getValueType(VT));
   7107     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
   7108   }
   7109 
   7110   if (VT.getSizeInBits() == 16) {
   7111     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
   7112     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
   7113     if (Idx == 0)
   7114       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
   7115                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
   7116                                      DAG.getNode(ISD::BITCAST, dl,
   7117                                                  MVT::v4i32,
   7118                                                  Op.getOperand(0)),
   7119                                      Op.getOperand(1)));
   7120     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
   7121                                   Op.getOperand(0), Op.getOperand(1));
   7122     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
   7123                                   DAG.getValueType(VT));
   7124     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
   7125   }
   7126 
   7127   if (VT == MVT::f32) {
   7128     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
   7129     // the result back to FR32 register. It's only worth matching if the
   7130     // result has a single use which is a store or a bitcast to i32.  And in
   7131     // the case of a store, it's not worth it if the index is a constant 0,
   7132     // because a MOVSSmr can be used instead, which is smaller and faster.
   7133     if (!Op.hasOneUse())
   7134       return SDValue();
   7135     SDNode *User = *Op.getNode()->use_begin();
   7136     if ((User->getOpcode() != ISD::STORE ||
   7137          (isa<ConstantSDNode>(Op.getOperand(1)) &&
   7138           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
   7139         (User->getOpcode() != ISD::BITCAST ||
   7140          User->getValueType(0) != MVT::i32))
   7141       return SDValue();
   7142     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
   7143                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
   7144                                               Op.getOperand(0)),
   7145                                               Op.getOperand(1));
   7146     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
   7147   }
   7148 
   7149   if (VT == MVT::i32 || VT == MVT::i64) {
   7150     // ExtractPS/pextrq works with constant index.
   7151     if (isa<ConstantSDNode>(Op.getOperand(1)))
   7152       return Op;
   7153   }
   7154   return SDValue();
   7155 }
   7156 
   7157 SDValue
   7158 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
   7159                                            SelectionDAG &DAG) const {
   7160   if (!isa<ConstantSDNode>(Op.getOperand(1)))
   7161     return SDValue();
   7162 
   7163   SDValue Vec = Op.getOperand(0);
   7164   MVT VecVT = Vec.getValueType().getSimpleVT();
   7165 
   7166   // If this is a 256-bit vector result, first extract the 128-bit vector and
   7167   // then extract the element from the 128-bit vector.
   7168   if (VecVT.is256BitVector()) {
   7169     DebugLoc dl = Op.getNode()->getDebugLoc();
   7170     unsigned NumElems = VecVT.getVectorNumElements();
   7171     SDValue Idx = Op.getOperand(1);
   7172     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
   7173 
   7174     // Get the 128-bit vector.
   7175     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
   7176 
   7177     if (IdxVal >= NumElems/2)
   7178       IdxVal -= NumElems/2;
   7179     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
   7180                        DAG.getConstant(IdxVal, MVT::i32));
   7181   }
   7182 
   7183   assert(VecVT.is128BitVector() && "Unexpected vector length");
   7184 
   7185   if (Subtarget->hasSSE41()) {
   7186     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
   7187     if (Res.getNode())
   7188       return Res;
   7189   }
   7190 
   7191   MVT VT = Op.getValueType().getSimpleVT();
   7192   DebugLoc dl = Op.getDebugLoc();
   7193   // TODO: handle v16i8.
   7194   if (VT.getSizeInBits() == 16) {
   7195     SDValue Vec = Op.getOperand(0);
   7196     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
   7197     if (Idx == 0)
   7198       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
   7199                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
   7200                                      DAG.getNode(ISD::BITCAST, dl,
   7201                                                  MVT::v4i32, Vec),
   7202                                      Op.getOperand(1)));
   7203     // Transform it so it match pextrw which produces a 32-bit result.
   7204     MVT EltVT = MVT::i32;
   7205     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
   7206                                   Op.getOperand(0), Op.getOperand(1));
   7207     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
   7208                                   DAG.getValueType(VT));
   7209     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
   7210   }
   7211 
   7212   if (VT.getSizeInBits() == 32) {
   7213     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
   7214     if (Idx == 0)
   7215       return Op;
   7216 
   7217     // SHUFPS the element to the lowest double word, then movss.
   7218     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
   7219     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
   7220     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
   7221                                        DAG.getUNDEF(VVT), Mask);
   7222     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
   7223                        DAG.getIntPtrConstant(0));
   7224   }
   7225 
   7226   if (VT.getSizeInBits() == 64) {
   7227     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
   7228     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
   7229     //        to match extract_elt for f64.
   7230     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
   7231     if (Idx == 0)
   7232       return Op;
   7233 
   7234     // UNPCKHPD the element to the lowest double word, then movsd.
   7235     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
   7236     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
   7237     int Mask[2] = { 1, -1 };
   7238     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
   7239     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
   7240                                        DAG.getUNDEF(VVT), Mask);
   7241     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
   7242                        DAG.getIntPtrConstant(0));
   7243   }
   7244 
   7245   return SDValue();
   7246 }
   7247 
   7248 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
   7249   MVT VT = Op.getValueType().getSimpleVT();
   7250   MVT EltVT = VT.getVectorElementType();
   7251   DebugLoc dl = Op.getDebugLoc();
   7252 
   7253   SDValue N0 = Op.getOperand(0);
   7254   SDValue N1 = Op.getOperand(1);
   7255   SDValue N2 = Op.getOperand(2);
   7256 
   7257   if (!VT.is128BitVector())
   7258     return SDValue();
   7259 
   7260   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
   7261       isa<ConstantSDNode>(N2)) {
   7262     unsigned Opc;
   7263     if (VT == MVT::v8i16)
   7264       Opc = X86ISD::PINSRW;
   7265     else if (VT == MVT::v16i8)
   7266       Opc = X86ISD::PINSRB;
   7267     else
   7268       Opc = X86ISD::PINSRB;
   7269 
   7270     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
   7271     // argument.
   7272     if (N1.getValueType() != MVT::i32)
   7273       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
   7274     if (N2.getValueType() != MVT::i32)
   7275       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
   7276     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
   7277   }
   7278 
   7279   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
   7280     // Bits [7:6] of the constant are the source select.  This will always be
   7281     //  zero here.  The DAG Combiner may combine an extract_elt index into these
   7282     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
   7283     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
   7284     // Bits [5:4] of the constant are the destination select.  This is the
   7285     //  value of the incoming immediate.
   7286     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
   7287     //   combine either bitwise AND or insert of float 0.0 to set these bits.
   7288     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
   7289     // Create this as a scalar to vector..
   7290     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
   7291     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
   7292   }
   7293 
   7294   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
   7295     // PINSR* works with constant index.
   7296     return Op;
   7297   }
   7298   return SDValue();
   7299 }
   7300 
   7301 SDValue
   7302 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
   7303   MVT VT = Op.getValueType().getSimpleVT();
   7304   MVT EltVT = VT.getVectorElementType();
   7305 
   7306   DebugLoc dl = Op.getDebugLoc();
   7307   SDValue N0 = Op.getOperand(0);
   7308   SDValue N1 = Op.getOperand(1);
   7309   SDValue N2 = Op.getOperand(2);
   7310 
   7311   // If this is a 256-bit vector result, first extract the 128-bit vector,
   7312   // insert the element into the extracted half and then place it back.
   7313   if (VT.is256BitVector()) {
   7314     if (!isa<ConstantSDNode>(N2))
   7315       return SDValue();
   7316 
   7317     // Get the desired 128-bit vector half.
   7318     unsigned NumElems = VT.getVectorNumElements();
   7319     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
   7320     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
   7321 
   7322     // Insert the element into the desired half.
   7323     bool Upper = IdxVal >= NumElems/2;
   7324     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
   7325                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
   7326 
   7327     // Insert the changed part back to the 256-bit vector
   7328     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
   7329   }
   7330 
   7331   if (Subtarget->hasSSE41())
   7332     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
   7333 
   7334   if (EltVT == MVT::i8)
   7335     return SDValue();
   7336 
   7337   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
   7338     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
   7339     // as its second argument.
   7340     if (N1.getValueType() != MVT::i32)
   7341       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
   7342     if (N2.getValueType() != MVT::i32)
   7343       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
   7344     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
   7345   }
   7346   return SDValue();
   7347 }
   7348 
   7349 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
   7350   LLVMContext *Context = DAG.getContext();
   7351   DebugLoc dl = Op.getDebugLoc();
   7352   MVT OpVT = Op.getValueType().getSimpleVT();
   7353 
   7354   // If this is a 256-bit vector result, first insert into a 128-bit
   7355   // vector and then insert into the 256-bit vector.
   7356   if (!OpVT.is128BitVector()) {
   7357     // Insert into a 128-bit vector.
   7358     EVT VT128 = EVT::getVectorVT(*Context,
   7359                                  OpVT.getVectorElementType(),
   7360                                  OpVT.getVectorNumElements() / 2);
   7361 
   7362     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
   7363 
   7364     // Insert the 128-bit vector.
   7365     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
   7366   }
   7367 
   7368   if (OpVT == MVT::v1i64 &&
   7369       Op.getOperand(0).getValueType() == MVT::i64)
   7370     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
   7371 
   7372   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
   7373   assert(OpVT.is128BitVector() && "Expected an SSE type!");
   7374   return DAG.getNode(ISD::BITCAST, dl, OpVT,
   7375                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
   7376 }
   7377 
   7378 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
   7379 // a simple subregister reference or explicit instructions to grab
   7380 // upper bits of a vector.
   7381 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
   7382                                       SelectionDAG &DAG) {
   7383   if (Subtarget->hasFp256()) {
   7384     DebugLoc dl = Op.getNode()->getDebugLoc();
   7385     SDValue Vec = Op.getNode()->getOperand(0);
   7386     SDValue Idx = Op.getNode()->getOperand(1);
   7387 
   7388     if (Op.getNode()->getValueType(0).is128BitVector() &&
   7389         Vec.getNode()->getValueType(0).is256BitVector() &&
   7390         isa<ConstantSDNode>(Idx)) {
   7391       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
   7392       return Extract128BitVector(Vec, IdxVal, DAG, dl);
   7393     }
   7394   }
   7395   return SDValue();
   7396 }
   7397 
   7398 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
   7399 // simple superregister reference or explicit instructions to insert
   7400 // the upper bits of a vector.
   7401 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
   7402                                      SelectionDAG &DAG) {
   7403   if (Subtarget->hasFp256()) {
   7404     DebugLoc dl = Op.getNode()->getDebugLoc();
   7405     SDValue Vec = Op.getNode()->getOperand(0);
   7406     SDValue SubVec = Op.getNode()->getOperand(1);
   7407     SDValue Idx = Op.getNode()->getOperand(2);
   7408 
   7409     if (Op.getNode()->getValueType(0).is256BitVector() &&
   7410         SubVec.getNode()->getValueType(0).is128BitVector() &&
   7411         isa<ConstantSDNode>(Idx)) {
   7412       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
   7413       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
   7414     }
   7415   }
   7416   return SDValue();
   7417 }
   7418 
   7419 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
   7420 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
   7421 // one of the above mentioned nodes. It has to be wrapped because otherwise
   7422 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
   7423 // be used to form addressing mode. These wrapped nodes will be selected
   7424 // into MOV32ri.
   7425 SDValue
   7426 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
   7427   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
   7428 
   7429   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
   7430   // global base reg.
   7431   unsigned char OpFlag = 0;
   7432   unsigned WrapperKind = X86ISD::Wrapper;
   7433   CodeModel::Model M = getTargetMachine().getCodeModel();
   7434 
   7435   if (Subtarget->isPICStyleRIPRel() &&
   7436       (M == CodeModel::Small || M == CodeModel::Kernel))
   7437     WrapperKind = X86ISD::WrapperRIP;
   7438   else if (Subtarget->isPICStyleGOT())
   7439     OpFlag = X86II::MO_GOTOFF;
   7440   else if (Subtarget->isPICStyleStubPIC())
   7441     OpFlag = X86II::MO_PIC_BASE_OFFSET;
   7442 
   7443   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
   7444                                              CP->getAlignment(),
   7445                                              CP->getOffset(), OpFlag);
   7446   DebugLoc DL = CP->getDebugLoc();
   7447   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
   7448   // With PIC, the address is actually $g + Offset.
   7449   if (OpFlag) {
   7450     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
   7451                          DAG.getNode(X86ISD::GlobalBaseReg,
   7452                                      DebugLoc(), getPointerTy()),
   7453                          Result);
   7454   }
   7455 
   7456   return Result;
   7457 }
   7458 
   7459 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
   7460   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
   7461 
   7462   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
   7463   // global base reg.
   7464   unsigned char OpFlag = 0;
   7465   unsigned WrapperKind = X86ISD::Wrapper;
   7466   CodeModel::Model M = getTargetMachine().getCodeModel();
   7467 
   7468   if (Subtarget->isPICStyleRIPRel() &&
   7469       (M == CodeModel::Small || M == CodeModel::Kernel))
   7470     WrapperKind = X86ISD::WrapperRIP;
   7471   else if (Subtarget->isPICStyleGOT())
   7472     OpFlag = X86II::MO_GOTOFF;
   7473   else if (Subtarget->isPICStyleStubPIC())
   7474     OpFlag = X86II::MO_PIC_BASE_OFFSET;
   7475 
   7476   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
   7477                                           OpFlag);
   7478   DebugLoc DL = JT->getDebugLoc();
   7479   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
   7480 
   7481   // With PIC, the address is actually $g + Offset.
   7482   if (OpFlag)
   7483     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
   7484                          DAG.getNode(X86ISD::GlobalBaseReg,
   7485                                      DebugLoc(), getPointerTy()),
   7486                          Result);
   7487 
   7488   return Result;
   7489 }
   7490 
   7491 SDValue
   7492 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
   7493   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
   7494 
   7495   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
   7496   // global base reg.
   7497   unsigned char OpFlag = 0;
   7498   unsigned WrapperKind = X86ISD::Wrapper;
   7499   CodeModel::Model M = getTargetMachine().getCodeModel();
   7500 
   7501   if (Subtarget->isPICStyleRIPRel() &&
   7502       (M == CodeModel::Small || M == CodeModel::Kernel)) {
   7503     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
   7504       OpFlag = X86II::MO_GOTPCREL;
   7505     WrapperKind = X86ISD::WrapperRIP;
   7506   } else if (Subtarget->isPICStyleGOT()) {
   7507     OpFlag = X86II::MO_GOT;
   7508   } else if (Subtarget->isPICStyleStubPIC()) {
   7509     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
   7510   } else if (Subtarget->isPICStyleStubNoDynamic()) {
   7511     OpFlag = X86II::MO_DARWIN_NONLAZY;
   7512   }
   7513 
   7514   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
   7515 
   7516   DebugLoc DL = Op.getDebugLoc();
   7517   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
   7518 
   7519   // With PIC, the address is actually $g + Offset.
   7520   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
   7521       !Subtarget->is64Bit()) {
   7522     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
   7523                          DAG.getNode(X86ISD::GlobalBaseReg,
   7524                                      DebugLoc(), getPointerTy()),
   7525                          Result);
   7526   }
   7527 
   7528   // For symbols that require a load from a stub to get the address, emit the
   7529   // load.
   7530   if (isGlobalStubReference(OpFlag))
   7531     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
   7532                          MachinePointerInfo::getGOT(), false, false, false, 0);
   7533 
   7534   return Result;
   7535 }
   7536 
   7537 SDValue
   7538 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
   7539   // Create the TargetBlockAddressAddress node.
   7540   unsigned char OpFlags =
   7541     Subtarget->ClassifyBlockAddressReference();
   7542   CodeModel::Model M = getTargetMachine().getCodeModel();
   7543   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
   7544   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
   7545   DebugLoc dl = Op.getDebugLoc();
   7546   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
   7547                                              OpFlags);
   7548 
   7549   if (Subtarget->isPICStyleRIPRel() &&
   7550       (M == CodeModel::Small || M == CodeModel::Kernel))
   7551     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
   7552   else
   7553     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
   7554 
   7555   // With PIC, the address is actually $g + Offset.
   7556   if (isGlobalRelativeToPICBase(OpFlags)) {
   7557     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
   7558                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
   7559                          Result);
   7560   }
   7561 
   7562   return Result;
   7563 }
   7564 
   7565 SDValue
   7566 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
   7567                                       int64_t Offset, SelectionDAG &DAG) const {
   7568   // Create the TargetGlobalAddress node, folding in the constant
   7569   // offset if it is legal.
   7570   unsigned char OpFlags =
   7571     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
   7572   CodeModel::Model M = getTargetMachine().getCodeModel();
   7573   SDValue Result;
   7574   if (OpFlags == X86II::MO_NO_FLAG &&
   7575       X86::isOffsetSuitableForCodeModel(Offset, M)) {
   7576     // A direct static reference to a global.
   7577     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
   7578     Offset = 0;
   7579   } else {
   7580     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
   7581   }
   7582 
   7583   if (Subtarget->isPICStyleRIPRel() &&
   7584       (M == CodeModel::Small || M == CodeModel::Kernel))
   7585     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
   7586   else
   7587     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
   7588 
   7589   // With PIC, the address is actually $g + Offset.
   7590   if (isGlobalRelativeToPICBase(OpFlags)) {
   7591     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
   7592                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
   7593                          Result);
   7594   }
   7595 
   7596   // For globals that require a load from a stub to get the address, emit the
   7597   // load.
   7598   if (isGlobalStubReference(OpFlags))
   7599     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
   7600                          MachinePointerInfo::getGOT(), false, false, false, 0);
   7601 
   7602   // If there was a non-zero offset that we didn't fold, create an explicit
   7603   // addition for it.
   7604   if (Offset != 0)
   7605     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
   7606                          DAG.getConstant(Offset, getPointerTy()));
   7607 
   7608   return Result;
   7609 }
   7610 
   7611 SDValue
   7612 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
   7613   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
   7614   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
   7615   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
   7616 }
   7617 
   7618 static SDValue
   7619 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
   7620            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
   7621            unsigned char OperandFlags, bool LocalDynamic = false) {
   7622   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
   7623   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
   7624   DebugLoc dl = GA->getDebugLoc();
   7625   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
   7626                                            GA->getValueType(0),
   7627                                            GA->getOffset(),
   7628                                            OperandFlags);
   7629 
   7630   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
   7631                                            : X86ISD::TLSADDR;
   7632 
   7633   if (InFlag) {
   7634     SDValue Ops[] = { Chain,  TGA, *InFlag };
   7635     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
   7636   } else {
   7637     SDValue Ops[]  = { Chain, TGA };
   7638     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
   7639   }
   7640 
   7641   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
   7642   MFI->setAdjustsStack(true);
   7643 
   7644   SDValue Flag = Chain.getValue(1);
   7645   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
   7646 }
   7647 
   7648 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
   7649 static SDValue
   7650 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
   7651                                 const EVT PtrVT) {
   7652   SDValue InFlag;
   7653   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
   7654   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
   7655                                    DAG.getNode(X86ISD::GlobalBaseReg,
   7656                                                DebugLoc(), PtrVT), InFlag);
   7657   InFlag = Chain.getValue(1);
   7658 
   7659   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
   7660 }
   7661 
   7662 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
   7663 static SDValue
   7664 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
   7665                                 const EVT PtrVT) {
   7666   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
   7667                     X86::RAX, X86II::MO_TLSGD);
   7668 }
   7669 
   7670 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
   7671                                            SelectionDAG &DAG,
   7672                                            const EVT PtrVT,
   7673                                            bool is64Bit) {
   7674   DebugLoc dl = GA->getDebugLoc();
   7675 
   7676   // Get the start address of the TLS block for this module.
   7677   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
   7678       .getInfo<X86MachineFunctionInfo>();
   7679   MFI->incNumLocalDynamicTLSAccesses();
   7680 
   7681   SDValue Base;
   7682   if (is64Bit) {
   7683     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
   7684                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
   7685   } else {
   7686     SDValue InFlag;
   7687     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
   7688         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
   7689     InFlag = Chain.getValue(1);
   7690     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
   7691                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
   7692   }
   7693 
   7694   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
   7695   // of Base.
   7696 
   7697   // Build x@dtpoff.
   7698   unsigned char OperandFlags = X86II::MO_DTPOFF;
   7699   unsigned WrapperKind = X86ISD::Wrapper;
   7700   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
   7701                                            GA->getValueType(0),
   7702                                            GA->getOffset(), OperandFlags);
   7703   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
   7704 
   7705   // Add x@dtpoff with the base.
   7706   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
   7707 }
   7708 
   7709 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
   7710 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
   7711                                    const EVT PtrVT, TLSModel::Model model,
   7712                                    bool is64Bit, bool isPIC) {
   7713   DebugLoc dl = GA->getDebugLoc();
   7714 
   7715   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
   7716   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
   7717                                                          is64Bit ? 257 : 256));
   7718 
   7719   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
   7720                                       DAG.getIntPtrConstant(0),
   7721                                       MachinePointerInfo(Ptr),
   7722                                       false, false, false, 0);
   7723 
   7724   unsigned char OperandFlags = 0;
   7725   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
   7726   // initialexec.
   7727   unsigned WrapperKind = X86ISD::Wrapper;
   7728   if (model == TLSModel::LocalExec) {
   7729     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
   7730   } else if (model == TLSModel::InitialExec) {
   7731     if (is64Bit) {
   7732       OperandFlags = X86II::MO_GOTTPOFF;
   7733       WrapperKind = X86ISD::WrapperRIP;
   7734     } else {
   7735       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
   7736     }
   7737   } else {
   7738     llvm_unreachable("Unexpected model");
   7739   }
   7740 
   7741   // emit "addl x@ntpoff,%eax" (local exec)
   7742   // or "addl x@indntpoff,%eax" (initial exec)
   7743   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
   7744   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
   7745                                            GA->getValueType(0),
   7746                                            GA->getOffset(), OperandFlags);
   7747   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
   7748 
   7749   if (model == TLSModel::InitialExec) {
   7750     if (isPIC && !is64Bit) {
   7751       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
   7752                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
   7753                            Offset);
   7754     }
   7755 
   7756     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
   7757                          MachinePointerInfo::getGOT(), false, false, false,
   7758                          0);
   7759   }
   7760 
   7761   // The address of the thread local variable is the add of the thread
   7762   // pointer with the offset of the variable.
   7763   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
   7764 }
   7765 
   7766 SDValue
   7767 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
   7768 
   7769   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
   7770   const GlobalValue *GV = GA->getGlobal();
   7771 
   7772   if (Subtarget->isTargetELF()) {
   7773     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
   7774 
   7775     switch (model) {
   7776       case TLSModel::GeneralDynamic:
   7777         if (Subtarget->is64Bit())
   7778           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
   7779         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
   7780       case TLSModel::LocalDynamic:
   7781         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
   7782                                            Subtarget->is64Bit());
   7783       case TLSModel::InitialExec:
   7784       case TLSModel::LocalExec:
   7785         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
   7786                                    Subtarget->is64Bit(),
   7787                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
   7788     }
   7789     llvm_unreachable("Unknown TLS model.");
   7790   }
   7791 
   7792   if (Subtarget->isTargetDarwin()) {
   7793     // Darwin only has one model of TLS.  Lower to that.
   7794     unsigned char OpFlag = 0;
   7795     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
   7796                            X86ISD::WrapperRIP : X86ISD::Wrapper;
   7797 
   7798     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
   7799     // global base reg.
   7800     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
   7801                   !Subtarget->is64Bit();
   7802     if (PIC32)
   7803       OpFlag = X86II::MO_TLVP_PIC_BASE;
   7804     else
   7805       OpFlag = X86II::MO_TLVP;
   7806     DebugLoc DL = Op.getDebugLoc();
   7807     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
   7808                                                 GA->getValueType(0),
   7809                                                 GA->getOffset(), OpFlag);
   7810     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
   7811 
   7812     // With PIC32, the address is actually $g + Offset.
   7813     if (PIC32)
   7814       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
   7815                            DAG.getNode(X86ISD::GlobalBaseReg,
   7816                                        DebugLoc(), getPointerTy()),
   7817                            Offset);
   7818 
   7819     // Lowering the machine isd will make sure everything is in the right
   7820     // location.
   7821     SDValue Chain = DAG.getEntryNode();
   7822     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
   7823     SDValue Args[] = { Chain, Offset };
   7824     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
   7825 
   7826     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
   7827     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
   7828     MFI->setAdjustsStack(true);
   7829 
   7830     // And our return value (tls address) is in the standard call return value
   7831     // location.
   7832     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
   7833     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
   7834                               Chain.getValue(1));
   7835   }
   7836 
   7837   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
   7838     // Just use the implicit TLS architecture
   7839     // Need to generate someting similar to:
   7840     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
   7841     //                                  ; from TEB
   7842     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
   7843     //   mov     rcx, qword [rdx+rcx*8]
   7844     //   mov     eax, .tls$:tlsvar
   7845     //   [rax+rcx] contains the address
   7846     // Windows 64bit: gs:0x58
   7847     // Windows 32bit: fs:__tls_array
   7848 
   7849     // If GV is an alias then use the aliasee for determining
   7850     // thread-localness.
   7851     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
   7852       GV = GA->resolveAliasedGlobal(false);
   7853     DebugLoc dl = GA->getDebugLoc();
   7854     SDValue Chain = DAG.getEntryNode();
   7855 
   7856     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
   7857     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
   7858     // use its literal value of 0x2C.
   7859     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
   7860                                         ? Type::getInt8PtrTy(*DAG.getContext(),
   7861                                                              256)
   7862                                         : Type::getInt32PtrTy(*DAG.getContext(),
   7863                                                               257));
   7864 
   7865     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
   7866       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
   7867         DAG.getExternalSymbol("_tls_array", getPointerTy()));
   7868 
   7869     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
   7870                                         MachinePointerInfo(Ptr),
   7871                                         false, false, false, 0);
   7872 
   7873     // Load the _tls_index variable
   7874     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
   7875     if (Subtarget->is64Bit())
   7876       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
   7877                            IDX, MachinePointerInfo(), MVT::i32,
   7878                            false, false, 0);
   7879     else
   7880       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
   7881                         false, false, false, 0);
   7882 
   7883     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
   7884                                     getPointerTy());
   7885     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
   7886 
   7887     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
   7888     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
   7889                       false, false, false, 0);
   7890 
   7891     // Get the offset of start of .tls section
   7892     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
   7893                                              GA->getValueType(0),
   7894                                              GA->getOffset(), X86II::MO_SECREL);
   7895     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
   7896 
   7897     // The address of the thread local variable is the add of the thread
   7898     // pointer with the offset of the variable.
   7899     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
   7900   }
   7901 
   7902   llvm_unreachable("TLS not implemented for this target.");
   7903 }
   7904 
   7905 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
   7906 /// and take a 2 x i32 value to shift plus a shift amount.
   7907 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
   7908   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
   7909   EVT VT = Op.getValueType();
   7910   unsigned VTBits = VT.getSizeInBits();
   7911   DebugLoc dl = Op.getDebugLoc();
   7912   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
   7913   SDValue ShOpLo = Op.getOperand(0);
   7914   SDValue ShOpHi = Op.getOperand(1);
   7915   SDValue ShAmt  = Op.getOperand(2);
   7916   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
   7917                                      DAG.getConstant(VTBits - 1, MVT::i8))
   7918                        : DAG.getConstant(0, VT);
   7919 
   7920   SDValue Tmp2, Tmp3;
   7921   if (Op.getOpcode() == ISD::SHL_PARTS) {
   7922     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
   7923     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
   7924   } else {
   7925     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
   7926     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
   7927   }
   7928 
   7929   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
   7930                                 DAG.getConstant(VTBits, MVT::i8));
   7931   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
   7932                              AndNode, DAG.getConstant(0, MVT::i8));
   7933 
   7934   SDValue Hi, Lo;
   7935   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
   7936   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
   7937   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
   7938 
   7939   if (Op.getOpcode() == ISD::SHL_PARTS) {
   7940     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
   7941     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
   7942   } else {
   7943     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
   7944     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
   7945   }
   7946 
   7947   SDValue Ops[2] = { Lo, Hi };
   7948   return DAG.getMergeValues(Ops, 2, dl);
   7949 }
   7950 
   7951 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
   7952                                            SelectionDAG &DAG) const {
   7953   EVT SrcVT = Op.getOperand(0).getValueType();
   7954 
   7955   if (SrcVT.isVector())
   7956     return SDValue();
   7957 
   7958   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
   7959          "Unknown SINT_TO_FP to lower!");
   7960 
   7961   // These are really Legal; return the operand so the caller accepts it as
   7962   // Legal.
   7963   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
   7964     return Op;
   7965   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
   7966       Subtarget->is64Bit()) {
   7967     return Op;
   7968   }
   7969 
   7970   DebugLoc dl = Op.getDebugLoc();
   7971   unsigned Size = SrcVT.getSizeInBits()/8;
   7972   MachineFunction &MF = DAG.getMachineFunction();
   7973   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
   7974   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
   7975   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
   7976                                StackSlot,
   7977                                MachinePointerInfo::getFixedStack(SSFI),
   7978                                false, false, 0);
   7979   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
   7980 }
   7981 
   7982 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
   7983                                      SDValue StackSlot,
   7984                                      SelectionDAG &DAG) const {
   7985   // Build the FILD
   7986   DebugLoc DL = Op.getDebugLoc();
   7987   SDVTList Tys;
   7988   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
   7989   if (useSSE)
   7990     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
   7991   else
   7992     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
   7993 
   7994   unsigned ByteSize = SrcVT.getSizeInBits()/8;
   7995 
   7996   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
   7997   MachineMemOperand *MMO;
   7998   if (FI) {
   7999     int SSFI = FI->getIndex();
   8000     MMO =
   8001       DAG.getMachineFunction()
   8002       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
   8003                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
   8004   } else {
   8005     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
   8006     StackSlot = StackSlot.getOperand(1);
   8007   }
   8008   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
   8009   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
   8010                                            X86ISD::FILD, DL,
   8011                                            Tys, Ops, array_lengthof(Ops),
   8012                                            SrcVT, MMO);
   8013 
   8014   if (useSSE) {
   8015     Chain = Result.getValue(1);
   8016     SDValue InFlag = Result.getValue(2);
   8017 
   8018     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
   8019     // shouldn't be necessary except that RFP cannot be live across
   8020     // multiple blocks. When stackifier is fixed, they can be uncoupled.
   8021     MachineFunction &MF = DAG.getMachineFunction();
   8022     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
   8023     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
   8024     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
   8025     Tys = DAG.getVTList(MVT::Other);
   8026     SDValue Ops[] = {
   8027       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
   8028     };
   8029     MachineMemOperand *MMO =
   8030       DAG.getMachineFunction()
   8031       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
   8032                             MachineMemOperand::MOStore, SSFISize, SSFISize);
   8033 
   8034     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
   8035                                     Ops, array_lengthof(Ops),
   8036                                     Op.getValueType(), MMO);
   8037     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
   8038                          MachinePointerInfo::getFixedStack(SSFI),
   8039                          false, false, false, 0);
   8040   }
   8041 
   8042   return Result;
   8043 }
   8044 
   8045 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
   8046 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
   8047                                                SelectionDAG &DAG) const {
   8048   // This algorithm is not obvious. Here it is what we're trying to output:
   8049   /*
   8050      movq       %rax,  %xmm0
   8051      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
   8052      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
   8053      #ifdef __SSE3__
   8054        haddpd   %xmm0, %xmm0
   8055      #else
   8056        pshufd   $0x4e, %xmm0, %xmm1
   8057        addpd    %xmm1, %xmm0
   8058      #endif
   8059   */
   8060 
   8061   DebugLoc dl = Op.getDebugLoc();
   8062   LLVMContext *Context = DAG.getContext();
   8063 
   8064   // Build some magic constants.
   8065   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
   8066   Constant *C0 = ConstantDataVector::get(*Context, CV0);
   8067   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
   8068 
   8069   SmallVector<Constant*,2> CV1;
   8070   CV1.push_back(
   8071     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
   8072                                       APInt(64, 0x4330000000000000ULL))));
   8073   CV1.push_back(
   8074     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
   8075                                       APInt(64, 0x4530000000000000ULL))));
   8076   Constant *C1 = ConstantVector::get(CV1);
   8077   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
   8078 
   8079   // Load the 64-bit value into an XMM register.
   8080   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
   8081                             Op.getOperand(0));
   8082   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
   8083                               MachinePointerInfo::getConstantPool(),
   8084                               false, false, false, 16);
   8085   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
   8086                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
   8087                               CLod0);
   8088 
   8089   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
   8090                               MachinePointerInfo::getConstantPool(),
   8091                               false, false, false, 16);
   8092   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
   8093   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
   8094   SDValue Result;
   8095 
   8096   if (Subtarget->hasSSE3()) {
   8097     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
   8098     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
   8099   } else {
   8100     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
   8101     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
   8102                                            S2F, 0x4E, DAG);
   8103     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
   8104                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
   8105                          Sub);
   8106   }
   8107 
   8108   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
   8109                      DAG.getIntPtrConstant(0));
   8110 }
   8111 
   8112 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
   8113 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
   8114                                                SelectionDAG &DAG) const {
   8115   DebugLoc dl = Op.getDebugLoc();
   8116   // FP constant to bias correct the final result.
   8117   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
   8118                                    MVT::f64);
   8119 
   8120   // Load the 32-bit value into an XMM register.
   8121   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
   8122                              Op.getOperand(0));
   8123 
   8124   // Zero out the upper parts of the register.
   8125   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
   8126 
   8127   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
   8128                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
   8129                      DAG.getIntPtrConstant(0));
   8130 
   8131   // Or the load with the bias.
   8132   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
   8133                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
   8134                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
   8135                                                    MVT::v2f64, Load)),
   8136                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
   8137                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
   8138                                                    MVT::v2f64, Bias)));
   8139   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
   8140                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
   8141                    DAG.getIntPtrConstant(0));
   8142 
   8143   // Subtract the bias.
   8144   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
   8145 
   8146   // Handle final rounding.
   8147   EVT DestVT = Op.getValueType();
   8148 
   8149   if (DestVT.bitsLT(MVT::f64))
   8150     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
   8151                        DAG.getIntPtrConstant(0));
   8152   if (DestVT.bitsGT(MVT::f64))
   8153     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
   8154 
   8155   // Handle final rounding.
   8156   return Sub;
   8157 }
   8158 
   8159 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
   8160                                                SelectionDAG &DAG) const {
   8161   SDValue N0 = Op.getOperand(0);
   8162   EVT SVT = N0.getValueType();
   8163   DebugLoc dl = Op.getDebugLoc();
   8164 
   8165   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
   8166           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
   8167          "Custom UINT_TO_FP is not supported!");
   8168 
   8169   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
   8170                              SVT.getVectorNumElements());
   8171   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
   8172                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
   8173 }
   8174 
   8175 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
   8176                                            SelectionDAG &DAG) const {
   8177   SDValue N0 = Op.getOperand(0);
   8178   DebugLoc dl = Op.getDebugLoc();
   8179 
   8180   if (Op.getValueType().isVector())
   8181     return lowerUINT_TO_FP_vec(Op, DAG);
   8182 
   8183   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
   8184   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
   8185   // the optimization here.
   8186   if (DAG.SignBitIsZero(N0))
   8187     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
   8188 
   8189   EVT SrcVT = N0.getValueType();
   8190   EVT DstVT = Op.getValueType();
   8191   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
   8192     return LowerUINT_TO_FP_i64(Op, DAG);
   8193   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
   8194     return LowerUINT_TO_FP_i32(Op, DAG);
   8195   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
   8196     return SDValue();
   8197 
   8198   // Make a 64-bit buffer, and use it to build an FILD.
   8199   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
   8200   if (SrcVT == MVT::i32) {
   8201     SDValue WordOff = DAG.getConstant(4, getPointerTy());
   8202     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
   8203                                      getPointerTy(), StackSlot, WordOff);
   8204     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
   8205                                   StackSlot, MachinePointerInfo(),
   8206                                   false, false, 0);
   8207     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
   8208                                   OffsetSlot, MachinePointerInfo(),
   8209                                   false, false, 0);
   8210     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
   8211     return Fild;
   8212   }
   8213 
   8214   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
   8215   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
   8216                                StackSlot, MachinePointerInfo(),
   8217                                false, false, 0);
   8218   // For i64 source, we need to add the appropriate power of 2 if the input
   8219   // was negative.  This is the same as the optimization in
   8220   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
   8221   // we must be careful to do the computation in x87 extended precision, not
   8222   // in SSE. (The generic code can't know it's OK to do this, or how to.)
   8223   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
   8224   MachineMemOperand *MMO =
   8225     DAG.getMachineFunction()
   8226     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
   8227                           MachineMemOperand::MOLoad, 8, 8);
   8228 
   8229   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
   8230   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
   8231   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
   8232                                          MVT::i64, MMO);
   8233 
   8234   APInt FF(32, 0x5F800000ULL);
   8235 
   8236   // Check whether the sign bit is set.
   8237   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
   8238                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
   8239                                  ISD::SETLT);
   8240 
   8241   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
   8242   SDValue FudgePtr = DAG.getConstantPool(
   8243                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
   8244                                          getPointerTy());
   8245 
   8246   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
   8247   SDValue Zero = DAG.getIntPtrConstant(0);
   8248   SDValue Four = DAG.getIntPtrConstant(4);
   8249   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
   8250                                Zero, Four);
   8251   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
   8252 
   8253   // Load the value out, extending it from f32 to f80.
   8254   // FIXME: Avoid the extend by constructing the right constant pool?
   8255   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
   8256                                  FudgePtr, MachinePointerInfo::getConstantPool(),
   8257                                  MVT::f32, false, false, 4);
   8258   // Extend everything to 80 bits to force it to be done on x87.
   8259   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
   8260   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
   8261 }
   8262 
   8263 std::pair<SDValue,SDValue>
   8264 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
   8265                                     bool IsSigned, bool IsReplace) const {
   8266   DebugLoc DL = Op.getDebugLoc();
   8267 
   8268   EVT DstTy = Op.getValueType();
   8269 
   8270   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
   8271     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
   8272     DstTy = MVT::i64;
   8273   }
   8274 
   8275   assert(DstTy.getSimpleVT() <= MVT::i64 &&
   8276          DstTy.getSimpleVT() >= MVT::i16 &&
   8277          "Unknown FP_TO_INT to lower!");
   8278 
   8279   // These are really Legal.
   8280   if (DstTy == MVT::i32 &&
   8281       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
   8282     return std::make_pair(SDValue(), SDValue());
   8283   if (Subtarget->is64Bit() &&
   8284       DstTy == MVT::i64 &&
   8285       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
   8286     return std::make_pair(SDValue(), SDValue());
   8287 
   8288   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
   8289   // stack slot, or into the FTOL runtime function.
   8290   MachineFunction &MF = DAG.getMachineFunction();
   8291   unsigned MemSize = DstTy.getSizeInBits()/8;
   8292   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
   8293   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
   8294 
   8295   unsigned Opc;
   8296   if (!IsSigned && isIntegerTypeFTOL(DstTy))
   8297     Opc = X86ISD::WIN_FTOL;
   8298   else
   8299     switch (DstTy.getSimpleVT().SimpleTy) {
   8300     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
   8301     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
   8302     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
   8303     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
   8304     }
   8305 
   8306   SDValue Chain = DAG.getEntryNode();
   8307   SDValue Value = Op.getOperand(0);
   8308   EVT TheVT = Op.getOperand(0).getValueType();
   8309   // FIXME This causes a redundant load/store if the SSE-class value is already
   8310   // in memory, such as if it is on the callstack.
   8311   if (isScalarFPTypeInSSEReg(TheVT)) {
   8312     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
   8313     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
   8314                          MachinePointerInfo::getFixedStack(SSFI),
   8315                          false, false, 0);
   8316     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
   8317     SDValue Ops[] = {
   8318       Chain, StackSlot, DAG.getValueType(TheVT)
   8319     };
   8320 
   8321     MachineMemOperand *MMO =
   8322       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
   8323                               MachineMemOperand::MOLoad, MemSize, MemSize);
   8324     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
   8325                                     DstTy, MMO);
   8326     Chain = Value.getValue(1);
   8327     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
   8328     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
   8329   }
   8330 
   8331   MachineMemOperand *MMO =
   8332     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
   8333                             MachineMemOperand::MOStore, MemSize, MemSize);
   8334 
   8335   if (Opc != X86ISD::WIN_FTOL) {
   8336     // Build the FP_TO_INT*_IN_MEM
   8337     SDValue Ops[] = { Chain, Value, StackSlot };
   8338     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
   8339                                            Ops, 3, DstTy, MMO);
   8340     return std::make_pair(FIST, StackSlot);
   8341   } else {
   8342     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
   8343       DAG.getVTList(MVT::Other, MVT::Glue),
   8344       Chain, Value);
   8345     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
   8346       MVT::i32, ftol.getValue(1));
   8347     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
   8348       MVT::i32, eax.getValue(2));
   8349     SDValue Ops[] = { eax, edx };
   8350     SDValue pair = IsReplace
   8351       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
   8352       : DAG.getMergeValues(Ops, 2, DL);
   8353     return std::make_pair(pair, SDValue());
   8354   }
   8355 }
   8356 
   8357 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
   8358                               const X86Subtarget *Subtarget) {
   8359   MVT VT = Op->getValueType(0).getSimpleVT();
   8360   SDValue In = Op->getOperand(0);
   8361   MVT InVT = In.getValueType().getSimpleVT();
   8362   DebugLoc dl = Op->getDebugLoc();
   8363 
   8364   // Optimize vectors in AVX mode:
   8365   //
   8366   //   v8i16 -> v8i32
   8367   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
   8368   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
   8369   //   Concat upper and lower parts.
   8370   //
   8371   //   v4i32 -> v4i64
   8372   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
   8373   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
   8374   //   Concat upper and lower parts.
   8375   //
   8376 
   8377   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
   8378       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
   8379     return SDValue();
   8380 
   8381   if (Subtarget->hasInt256())
   8382     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
   8383 
   8384   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
   8385   SDValue Undef = DAG.getUNDEF(InVT);
   8386   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
   8387   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
   8388   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
   8389 
   8390   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
   8391                              VT.getVectorNumElements()/2);
   8392 
   8393   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
   8394   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
   8395 
   8396   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
   8397 }
   8398 
   8399 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
   8400                                            SelectionDAG &DAG) const {
   8401   if (Subtarget->hasFp256()) {
   8402     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
   8403     if (Res.getNode())
   8404       return Res;
   8405   }
   8406 
   8407   return SDValue();
   8408 }
   8409 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
   8410                                             SelectionDAG &DAG) const {
   8411   DebugLoc DL = Op.getDebugLoc();
   8412   MVT VT = Op.getValueType().getSimpleVT();
   8413   SDValue In = Op.getOperand(0);
   8414   MVT SVT = In.getValueType().getSimpleVT();
   8415 
   8416   if (Subtarget->hasFp256()) {
   8417     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
   8418     if (Res.getNode())
   8419       return Res;
   8420   }
   8421 
   8422   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
   8423       VT.getVectorNumElements() != SVT.getVectorNumElements())
   8424     return SDValue();
   8425 
   8426   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
   8427 
   8428   // AVX2 has better support of integer extending.
   8429   if (Subtarget->hasInt256())
   8430     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
   8431 
   8432   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
   8433   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
   8434   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
   8435                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
   8436                                                 DAG.getUNDEF(MVT::v8i16),
   8437                                                 &Mask[0]));
   8438 
   8439   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
   8440 }
   8441 
   8442 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
   8443   DebugLoc DL = Op.getDebugLoc();
   8444   MVT VT = Op.getValueType().getSimpleVT();
   8445   SDValue In = Op.getOperand(0);
   8446   MVT SVT = In.getValueType().getSimpleVT();
   8447 
   8448   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
   8449     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
   8450     if (Subtarget->hasInt256()) {
   8451       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
   8452       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
   8453       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
   8454                                 ShufMask);
   8455       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
   8456                          DAG.getIntPtrConstant(0));
   8457     }
   8458 
   8459     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
   8460     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
   8461                                DAG.getIntPtrConstant(0));
   8462     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
   8463                                DAG.getIntPtrConstant(2));
   8464 
   8465     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
   8466     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
   8467 
   8468     // The PSHUFD mask:
   8469     static const int ShufMask1[] = {0, 2, 0, 0};
   8470     SDValue Undef = DAG.getUNDEF(VT);
   8471     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
   8472     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
   8473 
   8474     // The MOVLHPS mask:
   8475     static const int ShufMask2[] = {0, 1, 4, 5};
   8476     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
   8477   }
   8478 
   8479   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
   8480     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
   8481     if (Subtarget->hasInt256()) {
   8482       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
   8483 
   8484       SmallVector<SDValue,32> pshufbMask;
   8485       for (unsigned i = 0; i < 2; ++i) {
   8486         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
   8487         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
   8488         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
   8489         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
   8490         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
   8491         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
   8492         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
   8493         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
   8494         for (unsigned j = 0; j < 8; ++j)
   8495           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
   8496       }
   8497       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
   8498                                &pshufbMask[0], 32);
   8499       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
   8500       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
   8501 
   8502       static const int ShufMask[] = {0,  2,  -1,  -1};
   8503       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
   8504                                 &ShufMask[0]);
   8505       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
   8506                        DAG.getIntPtrConstant(0));
   8507       return DAG.getNode(ISD::BITCAST, DL, VT, In);
   8508     }
   8509 
   8510     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
   8511                                DAG.getIntPtrConstant(0));
   8512 
   8513     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
   8514                                DAG.getIntPtrConstant(4));
   8515 
   8516     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
   8517     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
   8518 
   8519     // The PSHUFB mask:
   8520     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
   8521                                    -1, -1, -1, -1, -1, -1, -1, -1};
   8522 
   8523     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
   8524     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
   8525     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
   8526 
   8527     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
   8528     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
   8529 
   8530     // The MOVLHPS Mask:
   8531     static const int ShufMask2[] = {0, 1, 4, 5};
   8532     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
   8533     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
   8534   }
   8535 
   8536   // Handle truncation of V256 to V128 using shuffles.
   8537   if (!VT.is128BitVector() || !SVT.is256BitVector())
   8538     return SDValue();
   8539 
   8540   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
   8541          "Invalid op");
   8542   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
   8543 
   8544   unsigned NumElems = VT.getVectorNumElements();
   8545   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
   8546                              NumElems * 2);
   8547 
   8548   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
   8549   // Prepare truncation shuffle mask
   8550   for (unsigned i = 0; i != NumElems; ++i)
   8551     MaskVec[i] = i * 2;
   8552   SDValue V = DAG.getVectorShuffle(NVT, DL,
   8553                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
   8554                                    DAG.getUNDEF(NVT), &MaskVec[0]);
   8555   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
   8556                      DAG.getIntPtrConstant(0));
   8557 }
   8558 
   8559 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
   8560                                            SelectionDAG &DAG) const {
   8561   MVT VT = Op.getValueType().getSimpleVT();
   8562   if (VT.isVector()) {
   8563     if (VT == MVT::v8i16)
   8564       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
   8565                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
   8566                                      MVT::v8i32, Op.getOperand(0)));
   8567     return SDValue();
   8568   }
   8569 
   8570   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
   8571     /*IsSigned=*/ true, /*IsReplace=*/ false);
   8572   SDValue FIST = Vals.first, StackSlot = Vals.second;
   8573   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
   8574   if (FIST.getNode() == 0) return Op;
   8575 
   8576   if (StackSlot.getNode())
   8577     // Load the result.
   8578     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
   8579                        FIST, StackSlot, MachinePointerInfo(),
   8580                        false, false, false, 0);
   8581 
   8582   // The node is the result.
   8583   return FIST;
   8584 }
   8585 
   8586 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
   8587                                            SelectionDAG &DAG) const {
   8588   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
   8589     /*IsSigned=*/ false, /*IsReplace=*/ false);
   8590   SDValue FIST = Vals.first, StackSlot = Vals.second;
   8591   assert(FIST.getNode() && "Unexpected failure");
   8592 
   8593   if (StackSlot.getNode())
   8594     // Load the result.
   8595     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
   8596                        FIST, StackSlot, MachinePointerInfo(),
   8597                        false, false, false, 0);
   8598 
   8599   // The node is the result.
   8600   return FIST;
   8601 }
   8602 
   8603 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
   8604   DebugLoc DL = Op.getDebugLoc();
   8605   MVT VT = Op.getValueType().getSimpleVT();
   8606   SDValue In = Op.getOperand(0);
   8607   MVT SVT = In.getValueType().getSimpleVT();
   8608 
   8609   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
   8610 
   8611   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
   8612                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
   8613                                  In, DAG.getUNDEF(SVT)));
   8614 }
   8615 
   8616 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
   8617   LLVMContext *Context = DAG.getContext();
   8618   DebugLoc dl = Op.getDebugLoc();
   8619   MVT VT = Op.getValueType().getSimpleVT();
   8620   MVT EltVT = VT;
   8621   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
   8622   if (VT.isVector()) {
   8623     EltVT = VT.getVectorElementType();
   8624     NumElts = VT.getVectorNumElements();
   8625   }
   8626   Constant *C;
   8627   if (EltVT == MVT::f64)
   8628     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
   8629                                           APInt(64, ~(1ULL << 63))));
   8630   else
   8631     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
   8632                                           APInt(32, ~(1U << 31))));
   8633   C = ConstantVector::getSplat(NumElts, C);
   8634   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
   8635   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
   8636   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
   8637                              MachinePointerInfo::getConstantPool(),
   8638                              false, false, false, Alignment);
   8639   if (VT.isVector()) {
   8640     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
   8641     return DAG.getNode(ISD::BITCAST, dl, VT,
   8642                        DAG.getNode(ISD::AND, dl, ANDVT,
   8643                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
   8644                                                Op.getOperand(0)),
   8645                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
   8646   }
   8647   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
   8648 }
   8649 
   8650 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
   8651   LLVMContext *Context = DAG.getContext();
   8652   DebugLoc dl = Op.getDebugLoc();
   8653   MVT VT = Op.getValueType().getSimpleVT();
   8654   MVT EltVT = VT;
   8655   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
   8656   if (VT.isVector()) {
   8657     EltVT = VT.getVectorElementType();
   8658     NumElts = VT.getVectorNumElements();
   8659   }
   8660   Constant *C;
   8661   if (EltVT == MVT::f64)
   8662     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
   8663                                           APInt(64, 1ULL << 63)));
   8664   else
   8665     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
   8666                                           APInt(32, 1U << 31)));
   8667   C = ConstantVector::getSplat(NumElts, C);
   8668   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
   8669   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
   8670   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
   8671                              MachinePointerInfo::getConstantPool(),
   8672                              false, false, false, Alignment);
   8673   if (VT.isVector()) {
   8674     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
   8675     return DAG.getNode(ISD::BITCAST, dl, VT,
   8676                        DAG.getNode(ISD::XOR, dl, XORVT,
   8677                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
   8678                                                Op.getOperand(0)),
   8679                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
   8680   }
   8681 
   8682   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
   8683 }
   8684 
   8685 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
   8686   LLVMContext *Context = DAG.getContext();
   8687   SDValue Op0 = Op.getOperand(0);
   8688   SDValue Op1 = Op.getOperand(1);
   8689   DebugLoc dl = Op.getDebugLoc();
   8690   MVT VT = Op.getValueType().getSimpleVT();
   8691   MVT SrcVT = Op1.getValueType().getSimpleVT();
   8692 
   8693   // If second operand is smaller, extend it first.
   8694   if (SrcVT.bitsLT(VT)) {
   8695     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
   8696     SrcVT = VT;
   8697   }
   8698   // And if it is bigger, shrink it first.
   8699   if (SrcVT.bitsGT(VT)) {
   8700     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
   8701     SrcVT = VT;
   8702   }
   8703 
   8704   // At this point the operands and the result should have the same
   8705   // type, and that won't be f80 since that is not custom lowered.
   8706 
   8707   // First get the sign bit of second operand.
   8708   SmallVector<Constant*,4> CV;
   8709   if (SrcVT == MVT::f64) {
   8710     const fltSemantics &Sem = APFloat::IEEEdouble;
   8711     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
   8712     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
   8713   } else {
   8714     const fltSemantics &Sem = APFloat::IEEEsingle;
   8715     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
   8716     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
   8717     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
   8718     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
   8719   }
   8720   Constant *C = ConstantVector::get(CV);
   8721   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
   8722   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
   8723                               MachinePointerInfo::getConstantPool(),
   8724                               false, false, false, 16);
   8725   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
   8726 
   8727   // Shift sign bit right or left if the two operands have different types.
   8728   if (SrcVT.bitsGT(VT)) {
   8729     // Op0 is MVT::f32, Op1 is MVT::f64.
   8730     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
   8731     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
   8732                           DAG.getConstant(32, MVT::i32));
   8733     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
   8734     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
   8735                           DAG.getIntPtrConstant(0));
   8736   }
   8737 
   8738   // Clear first operand sign bit.
   8739   CV.clear();
   8740   if (VT == MVT::f64) {
   8741     const fltSemantics &Sem = APFloat::IEEEdouble;
   8742     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
   8743                                                    APInt(64, ~(1ULL << 63)))));
   8744     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
   8745   } else {
   8746     const fltSemantics &Sem = APFloat::IEEEsingle;
   8747     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
   8748                                                    APInt(32, ~(1U << 31)))));
   8749     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
   8750     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
   8751     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
   8752   }
   8753   C = ConstantVector::get(CV);
   8754   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
   8755   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
   8756                               MachinePointerInfo::getConstantPool(),
   8757                               false, false, false, 16);
   8758   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
   8759 
   8760   // Or the value with the sign bit.
   8761   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
   8762 }
   8763 
   8764 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
   8765   SDValue N0 = Op.getOperand(0);
   8766   DebugLoc dl = Op.getDebugLoc();
   8767   MVT VT = Op.getValueType().getSimpleVT();
   8768 
   8769   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
   8770   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
   8771                                   DAG.getConstant(1, VT));
   8772   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
   8773 }
   8774 
   8775 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
   8776 //
   8777 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
   8778                                                   SelectionDAG &DAG) const {
   8779   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
   8780 
   8781   if (!Subtarget->hasSSE41())
   8782     return SDValue();
   8783 
   8784   if (!Op->hasOneUse())
   8785     return SDValue();
   8786 
   8787   SDNode *N = Op.getNode();
   8788   DebugLoc DL = N->getDebugLoc();
   8789 
   8790   SmallVector<SDValue, 8> Opnds;
   8791   DenseMap<SDValue, unsigned> VecInMap;
   8792   EVT VT = MVT::Other;
   8793 
   8794   // Recognize a special case where a vector is casted into wide integer to
   8795   // test all 0s.
   8796   Opnds.push_back(N->getOperand(0));
   8797   Opnds.push_back(N->getOperand(1));
   8798 
   8799   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
   8800     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
   8801     // BFS traverse all OR'd operands.
   8802     if (I->getOpcode() == ISD::OR) {
   8803       Opnds.push_back(I->getOperand(0));
   8804       Opnds.push_back(I->getOperand(1));
   8805       // Re-evaluate the number of nodes to be traversed.
   8806       e += 2; // 2 more nodes (LHS and RHS) are pushed.
   8807       continue;
   8808     }
   8809 
   8810     // Quit if a non-EXTRACT_VECTOR_ELT
   8811     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
   8812       return SDValue();
   8813 
   8814     // Quit if without a constant index.
   8815     SDValue Idx = I->getOperand(1);
   8816     if (!isa<ConstantSDNode>(Idx))
   8817       return SDValue();
   8818 
   8819     SDValue ExtractedFromVec = I->getOperand(0);
   8820     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
   8821     if (M == VecInMap.end()) {
   8822       VT = ExtractedFromVec.getValueType();
   8823       // Quit if not 128/256-bit vector.
   8824       if (!VT.is128BitVector() && !VT.is256BitVector())
   8825         return SDValue();
   8826       // Quit if not the same type.
   8827       if (VecInMap.begin() != VecInMap.end() &&
   8828           VT != VecInMap.begin()->first.getValueType())
   8829         return SDValue();
   8830       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
   8831     }
   8832     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
   8833   }
   8834 
   8835   assert((VT.is128BitVector() || VT.is256BitVector()) &&
   8836          "Not extracted from 128-/256-bit vector.");
   8837 
   8838   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
   8839   SmallVector<SDValue, 8> VecIns;
   8840 
   8841   for (DenseMap<SDValue, unsigned>::const_iterator
   8842         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
   8843     // Quit if not all elements are used.
   8844     if (I->second != FullMask)
   8845       return SDValue();
   8846     VecIns.push_back(I->first);
   8847   }
   8848 
   8849   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
   8850 
   8851   // Cast all vectors into TestVT for PTEST.
   8852   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
   8853     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
   8854 
   8855   // If more than one full vectors are evaluated, OR them first before PTEST.
   8856   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
   8857     // Each iteration will OR 2 nodes and append the result until there is only
   8858     // 1 node left, i.e. the final OR'd value of all vectors.
   8859     SDValue LHS = VecIns[Slot];
   8860     SDValue RHS = VecIns[Slot + 1];
   8861     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
   8862   }
   8863 
   8864   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
   8865                      VecIns.back(), VecIns.back());
   8866 }
   8867 
   8868 /// Emit nodes that will be selected as "test Op0,Op0", or something
   8869 /// equivalent.
   8870 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
   8871                                     SelectionDAG &DAG) const {
   8872   DebugLoc dl = Op.getDebugLoc();
   8873 
   8874   // CF and OF aren't always set the way we want. Determine which
   8875   // of these we need.
   8876   bool NeedCF = false;
   8877   bool NeedOF = false;
   8878   switch (X86CC) {
   8879   default: break;
   8880   case X86::COND_A: case X86::COND_AE:
   8881   case X86::COND_B: case X86::COND_BE:
   8882     NeedCF = true;
   8883     break;
   8884   case X86::COND_G: case X86::COND_GE:
   8885   case X86::COND_L: case X86::COND_LE:
   8886   case X86::COND_O: case X86::COND_NO:
   8887     NeedOF = true;
   8888     break;
   8889   }
   8890 
   8891   // See if we can use the EFLAGS value from the operand instead of
   8892   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
   8893   // we prove that the arithmetic won't overflow, we can't use OF or CF.
   8894   if (Op.getResNo() != 0 || NeedOF || NeedCF)
   8895     // Emit a CMP with 0, which is the TEST pattern.
   8896     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
   8897                        DAG.getConstant(0, Op.getValueType()));
   8898 
   8899   unsigned Opcode = 0;
   8900   unsigned NumOperands = 0;
   8901 
   8902   // Truncate operations may prevent the merge of the SETCC instruction
   8903   // and the arithmetic intruction before it. Attempt to truncate the operands
   8904   // of the arithmetic instruction and use a reduced bit-width instruction.
   8905   bool NeedTruncation = false;
   8906   SDValue ArithOp = Op;
   8907   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
   8908     SDValue Arith = Op->getOperand(0);
   8909     // Both the trunc and the arithmetic op need to have one user each.
   8910     if (Arith->hasOneUse())
   8911       switch (Arith.getOpcode()) {
   8912         default: break;
   8913         case ISD::ADD:
   8914         case ISD::SUB:
   8915         case ISD::AND:
   8916         case ISD::OR:
   8917         case ISD::XOR: {
   8918           NeedTruncation = true;
   8919           ArithOp = Arith;
   8920         }
   8921       }
   8922   }
   8923 
   8924   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
   8925   // which may be the result of a CAST.  We use the variable 'Op', which is the
   8926   // non-casted variable when we check for possible users.
   8927   switch (ArithOp.getOpcode()) {
   8928   case ISD::ADD:
   8929     // Due to an isel shortcoming, be conservative if this add is likely to be
   8930     // selected as part of a load-modify-store instruction. When the root node
   8931     // in a match is a store, isel doesn't know how to remap non-chain non-flag
   8932     // uses of other nodes in the match, such as the ADD in this case. This
   8933     // leads to the ADD being left around and reselected, with the result being
   8934     // two adds in the output.  Alas, even if none our users are stores, that
   8935     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
   8936     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
   8937     // climbing the DAG back to the root, and it doesn't seem to be worth the
   8938     // effort.
   8939     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
   8940          UE = Op.getNode()->use_end(); UI != UE; ++UI)
   8941       if (UI->getOpcode() != ISD::CopyToReg &&
   8942           UI->getOpcode() != ISD::SETCC &&
   8943           UI->getOpcode() != ISD::STORE)
   8944         goto default_case;
   8945 
   8946     if (ConstantSDNode *C =
   8947         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
   8948       // An add of one will be selected as an INC.
   8949       if (C->getAPIntValue() == 1) {
   8950         Opcode = X86ISD::INC;
   8951         NumOperands = 1;
   8952         break;
   8953       }
   8954 
   8955       // An add of negative one (subtract of one) will be selected as a DEC.
   8956       if (C->getAPIntValue().isAllOnesValue()) {
   8957         Opcode = X86ISD::DEC;
   8958         NumOperands = 1;
   8959         break;
   8960       }
   8961     }
   8962 
   8963     // Otherwise use a regular EFLAGS-setting add.
   8964     Opcode = X86ISD::ADD;
   8965     NumOperands = 2;
   8966     break;
   8967   case ISD::AND: {
   8968     // If the primary and result isn't used, don't bother using X86ISD::AND,
   8969     // because a TEST instruction will be better.
   8970     bool NonFlagUse = false;
   8971     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
   8972            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
   8973       SDNode *User = *UI;
   8974       unsigned UOpNo = UI.getOperandNo();
   8975       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
   8976         // Look pass truncate.
   8977         UOpNo = User->use_begin().getOperandNo();
   8978         User = *User->use_begin();
   8979       }
   8980 
   8981       if (User->getOpcode() != ISD::BRCOND &&
   8982           User->getOpcode() != ISD::SETCC &&
   8983           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
   8984         NonFlagUse = true;
   8985         break;
   8986       }
   8987     }
   8988 
   8989     if (!NonFlagUse)
   8990       break;
   8991   }
   8992     // FALL THROUGH
   8993   case ISD::SUB:
   8994   case ISD::OR:
   8995   case ISD::XOR:
   8996     // Due to the ISEL shortcoming noted above, be conservative if this op is
   8997     // likely to be selected as part of a load-modify-store instruction.
   8998     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
   8999            UE = Op.getNode()->use_end(); UI != UE; ++UI)
   9000       if (UI->getOpcode() == ISD::STORE)
   9001         goto default_case;
   9002 
   9003     // Otherwise use a regular EFLAGS-setting instruction.
   9004     switch (ArithOp.getOpcode()) {
   9005     default: llvm_unreachable("unexpected operator!");
   9006     case ISD::SUB: Opcode = X86ISD::SUB; break;
   9007     case ISD::XOR: Opcode = X86ISD::XOR; break;
   9008     case ISD::AND: Opcode = X86ISD::AND; break;
   9009     case ISD::OR: {
   9010       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
   9011         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
   9012         if (EFLAGS.getNode())
   9013           return EFLAGS;
   9014       }
   9015       Opcode = X86ISD::OR;
   9016       break;
   9017     }
   9018     }
   9019 
   9020     NumOperands = 2;
   9021     break;
   9022   case X86ISD::ADD:
   9023   case X86ISD::SUB:
   9024   case X86ISD::INC:
   9025   case X86ISD::DEC:
   9026   case X86ISD::OR:
   9027   case X86ISD::XOR:
   9028   case X86ISD::AND:
   9029     return SDValue(Op.getNode(), 1);
   9030   default:
   9031   default_case:
   9032     break;
   9033   }
   9034 
   9035   // If we found that truncation is beneficial, perform the truncation and
   9036   // update 'Op'.
   9037   if (NeedTruncation) {
   9038     EVT VT = Op.getValueType();
   9039     SDValue WideVal = Op->getOperand(0);
   9040     EVT WideVT = WideVal.getValueType();
   9041     unsigned ConvertedOp = 0;
   9042     // Use a target machine opcode to prevent further DAGCombine
   9043     // optimizations that may separate the arithmetic operations
   9044     // from the setcc node.
   9045     switch (WideVal.getOpcode()) {
   9046       default: break;
   9047       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
   9048       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
   9049       case ISD::AND: ConvertedOp = X86ISD::AND; break;
   9050       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
   9051       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
   9052     }
   9053 
   9054     if (ConvertedOp) {
   9055       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   9056       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
   9057         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
   9058         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
   9059         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
   9060       }
   9061     }
   9062   }
   9063 
   9064   if (Opcode == 0)
   9065     // Emit a CMP with 0, which is the TEST pattern.
   9066     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
   9067                        DAG.getConstant(0, Op.getValueType()));
   9068 
   9069   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
   9070   SmallVector<SDValue, 4> Ops;
   9071   for (unsigned i = 0; i != NumOperands; ++i)
   9072     Ops.push_back(Op.getOperand(i));
   9073 
   9074   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
   9075   DAG.ReplaceAllUsesWith(Op, New);
   9076   return SDValue(New.getNode(), 1);
   9077 }
   9078 
   9079 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
   9080 /// equivalent.
   9081 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
   9082                                    SelectionDAG &DAG) const {
   9083   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
   9084     if (C->getAPIntValue() == 0)
   9085       return EmitTest(Op0, X86CC, DAG);
   9086 
   9087   DebugLoc dl = Op0.getDebugLoc();
   9088   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
   9089        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
   9090     // Use SUB instead of CMP to enable CSE between SUB and CMP.
   9091     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
   9092     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
   9093                               Op0, Op1);
   9094     return SDValue(Sub.getNode(), 1);
   9095   }
   9096   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
   9097 }
   9098 
   9099 /// Convert a comparison if required by the subtarget.
   9100 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
   9101                                                  SelectionDAG &DAG) const {
   9102   // If the subtarget does not support the FUCOMI instruction, floating-point
   9103   // comparisons have to be converted.
   9104   if (Subtarget->hasCMov() ||
   9105       Cmp.getOpcode() != X86ISD::CMP ||
   9106       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
   9107       !Cmp.getOperand(1).getValueType().isFloatingPoint())
   9108     return Cmp;
   9109 
   9110   // The instruction selector will select an FUCOM instruction instead of
   9111   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
   9112   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
   9113   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
   9114   DebugLoc dl = Cmp.getDebugLoc();
   9115   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
   9116   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
   9117   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
   9118                             DAG.getConstant(8, MVT::i8));
   9119   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
   9120   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
   9121 }
   9122 
   9123 static bool isAllOnes(SDValue V) {
   9124   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
   9125   return C && C->isAllOnesValue();
   9126 }
   9127 
   9128 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
   9129 /// if it's possible.
   9130 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
   9131                                      DebugLoc dl, SelectionDAG &DAG) const {
   9132   SDValue Op0 = And.getOperand(0);
   9133   SDValue Op1 = And.getOperand(1);
   9134   if (Op0.getOpcode() == ISD::TRUNCATE)
   9135     Op0 = Op0.getOperand(0);
   9136   if (Op1.getOpcode() == ISD::TRUNCATE)
   9137     Op1 = Op1.getOperand(0);
   9138 
   9139   SDValue LHS, RHS;
   9140   if (Op1.getOpcode() == ISD::SHL)
   9141     std::swap(Op0, Op1);
   9142   if (Op0.getOpcode() == ISD::SHL) {
   9143     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
   9144       if (And00C->getZExtValue() == 1) {
   9145         // If we looked past a truncate, check that it's only truncating away
   9146         // known zeros.
   9147         unsigned BitWidth = Op0.getValueSizeInBits();
   9148         unsigned AndBitWidth = And.getValueSizeInBits();
   9149         if (BitWidth > AndBitWidth) {
   9150           APInt Zeros, Ones;
   9151           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
   9152           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
   9153             return SDValue();
   9154         }
   9155         LHS = Op1;
   9156         RHS = Op0.getOperand(1);
   9157       }
   9158   } else if (Op1.getOpcode() == ISD::Constant) {
   9159     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
   9160     uint64_t AndRHSVal = AndRHS->getZExtValue();
   9161     SDValue AndLHS = Op0;
   9162 
   9163     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
   9164       LHS = AndLHS.getOperand(0);
   9165       RHS = AndLHS.getOperand(1);
   9166     }
   9167 
   9168     // Use BT if the immediate can't be encoded in a TEST instruction.
   9169     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
   9170       LHS = AndLHS;
   9171       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
   9172     }
   9173   }
   9174 
   9175   if (LHS.getNode()) {
   9176     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
   9177     // the condition code later.
   9178     bool Invert = false;
   9179     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
   9180       Invert = true;
   9181       LHS = LHS.getOperand(0);
   9182     }
   9183 
   9184     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
   9185     // instruction.  Since the shift amount is in-range-or-undefined, we know
   9186     // that doing a bittest on the i32 value is ok.  We extend to i32 because
   9187     // the encoding for the i16 version is larger than the i32 version.
   9188     // Also promote i16 to i32 for performance / code size reason.
   9189     if (LHS.getValueType() == MVT::i8 ||
   9190         LHS.getValueType() == MVT::i16)
   9191       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
   9192 
   9193     // If the operand types disagree, extend the shift amount to match.  Since
   9194     // BT ignores high bits (like shifts) we can use anyextend.
   9195     if (LHS.getValueType() != RHS.getValueType())
   9196       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
   9197 
   9198     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
   9199     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
   9200     // Flip the condition if the LHS was a not instruction
   9201     if (Invert)
   9202       Cond = X86::GetOppositeBranchCondition(Cond);
   9203     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
   9204                        DAG.getConstant(Cond, MVT::i8), BT);
   9205   }
   9206 
   9207   return SDValue();
   9208 }
   9209 
   9210 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
   9211 // ones, and then concatenate the result back.
   9212 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
   9213   MVT VT = Op.getValueType().getSimpleVT();
   9214 
   9215   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
   9216          "Unsupported value type for operation");
   9217 
   9218   unsigned NumElems = VT.getVectorNumElements();
   9219   DebugLoc dl = Op.getDebugLoc();
   9220   SDValue CC = Op.getOperand(2);
   9221 
   9222   // Extract the LHS vectors
   9223   SDValue LHS = Op.getOperand(0);
   9224   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
   9225   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
   9226 
   9227   // Extract the RHS vectors
   9228   SDValue RHS = Op.getOperand(1);
   9229   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
   9230   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
   9231 
   9232   // Issue the operation on the smaller types and concatenate the result back
   9233   MVT EltVT = VT.getVectorElementType();
   9234   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
   9235   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
   9236                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
   9237                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
   9238 }
   9239 
   9240 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
   9241                            SelectionDAG &DAG) {
   9242   SDValue Cond;
   9243   SDValue Op0 = Op.getOperand(0);
   9244   SDValue Op1 = Op.getOperand(1);
   9245   SDValue CC = Op.getOperand(2);
   9246   MVT VT = Op.getValueType().getSimpleVT();
   9247   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
   9248   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
   9249   DebugLoc dl = Op.getDebugLoc();
   9250 
   9251   if (isFP) {
   9252 #ifndef NDEBUG
   9253     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
   9254     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
   9255 #endif
   9256 
   9257     unsigned SSECC;
   9258     bool Swap = false;
   9259 
   9260     // SSE Condition code mapping:
   9261     //  0 - EQ
   9262     //  1 - LT
   9263     //  2 - LE
   9264     //  3 - UNORD
   9265     //  4 - NEQ
   9266     //  5 - NLT
   9267     //  6 - NLE
   9268     //  7 - ORD
   9269     switch (SetCCOpcode) {
   9270     default: llvm_unreachable("Unexpected SETCC condition");
   9271     case ISD::SETOEQ:
   9272     case ISD::SETEQ:  SSECC = 0; break;
   9273     case ISD::SETOGT:
   9274     case ISD::SETGT: Swap = true; // Fallthrough
   9275     case ISD::SETLT:
   9276     case ISD::SETOLT: SSECC = 1; break;
   9277     case ISD::SETOGE:
   9278     case ISD::SETGE: Swap = true; // Fallthrough
   9279     case ISD::SETLE:
   9280     case ISD::SETOLE: SSECC = 2; break;
   9281     case ISD::SETUO:  SSECC = 3; break;
   9282     case ISD::SETUNE:
   9283     case ISD::SETNE:  SSECC = 4; break;
   9284     case ISD::SETULE: Swap = true; // Fallthrough
   9285     case ISD::SETUGE: SSECC = 5; break;
   9286     case ISD::SETULT: Swap = true; // Fallthrough
   9287     case ISD::SETUGT: SSECC = 6; break;
   9288     case ISD::SETO:   SSECC = 7; break;
   9289     case ISD::SETUEQ:
   9290     case ISD::SETONE: SSECC = 8; break;
   9291     }
   9292     if (Swap)
   9293       std::swap(Op0, Op1);
   9294 
   9295     // In the two special cases we can't handle, emit two comparisons.
   9296     if (SSECC == 8) {
   9297       unsigned CC0, CC1;
   9298       unsigned CombineOpc;
   9299       if (SetCCOpcode == ISD::SETUEQ) {
   9300         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
   9301       } else {
   9302         assert(SetCCOpcode == ISD::SETONE);
   9303         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
   9304       }
   9305 
   9306       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
   9307                                  DAG.getConstant(CC0, MVT::i8));
   9308       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
   9309                                  DAG.getConstant(CC1, MVT::i8));
   9310       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
   9311     }
   9312     // Handle all other FP comparisons here.
   9313     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
   9314                        DAG.getConstant(SSECC, MVT::i8));
   9315   }
   9316 
   9317   // Break 256-bit integer vector compare into smaller ones.
   9318   if (VT.is256BitVector() && !Subtarget->hasInt256())
   9319     return Lower256IntVSETCC(Op, DAG);
   9320 
   9321   // We are handling one of the integer comparisons here.  Since SSE only has
   9322   // GT and EQ comparisons for integer, swapping operands and multiple
   9323   // operations may be required for some comparisons.
   9324   unsigned Opc;
   9325   bool Swap = false, Invert = false, FlipSigns = false;
   9326 
   9327   switch (SetCCOpcode) {
   9328   default: llvm_unreachable("Unexpected SETCC condition");
   9329   case ISD::SETNE:  Invert = true;
   9330   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
   9331   case ISD::SETLT:  Swap = true;
   9332   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
   9333   case ISD::SETGE:  Swap = true;
   9334   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
   9335   case ISD::SETULT: Swap = true;
   9336   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
   9337   case ISD::SETUGE: Swap = true;
   9338   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
   9339   }
   9340   if (Swap)
   9341     std::swap(Op0, Op1);
   9342 
   9343   // Check that the operation in question is available (most are plain SSE2,
   9344   // but PCMPGTQ and PCMPEQQ have different requirements).
   9345   if (VT == MVT::v2i64) {
   9346     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
   9347       return SDValue();
   9348     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
   9349       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
   9350       // pcmpeqd + pshufd + pand.
   9351       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
   9352 
   9353       // First cast everything to the right type,
   9354       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
   9355       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
   9356 
   9357       // Do the compare.
   9358       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
   9359 
   9360       // Make sure the lower and upper halves are both all-ones.
   9361       const int Mask[] = { 1, 0, 3, 2 };
   9362       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
   9363       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
   9364 
   9365       if (Invert)
   9366         Result = DAG.getNOT(dl, Result, MVT::v4i32);
   9367 
   9368       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
   9369     }
   9370   }
   9371 
   9372   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
   9373   // bits of the inputs before performing those operations.
   9374   if (FlipSigns) {
   9375     EVT EltVT = VT.getVectorElementType();
   9376     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
   9377                                       EltVT);
   9378     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
   9379     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
   9380                                     SignBits.size());
   9381     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
   9382     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
   9383   }
   9384 
   9385   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
   9386 
   9387   // If the logical-not of the result is required, perform that now.
   9388   if (Invert)
   9389     Result = DAG.getNOT(dl, Result, VT);
   9390 
   9391   return Result;
   9392 }
   9393 
   9394 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
   9395 
   9396   MVT VT = Op.getValueType().getSimpleVT();
   9397 
   9398   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
   9399 
   9400   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
   9401   SDValue Op0 = Op.getOperand(0);
   9402   SDValue Op1 = Op.getOperand(1);
   9403   DebugLoc dl = Op.getDebugLoc();
   9404   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
   9405 
   9406   // Optimize to BT if possible.
   9407   // Lower (X & (1 << N)) == 0 to BT(X, N).
   9408   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
   9409   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
   9410   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
   9411       Op1.getOpcode() == ISD::Constant &&
   9412       cast<ConstantSDNode>(Op1)->isNullValue() &&
   9413       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
   9414     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
   9415     if (NewSetCC.getNode())
   9416       return NewSetCC;
   9417   }
   9418 
   9419   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
   9420   // these.
   9421   if (Op1.getOpcode() == ISD::Constant &&
   9422       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
   9423        cast<ConstantSDNode>(Op1)->isNullValue()) &&
   9424       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
   9425 
   9426     // If the input is a setcc, then reuse the input setcc or use a new one with
   9427     // the inverted condition.
   9428     if (Op0.getOpcode() == X86ISD::SETCC) {
   9429       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
   9430       bool Invert = (CC == ISD::SETNE) ^
   9431         cast<ConstantSDNode>(Op1)->isNullValue();
   9432       if (!Invert) return Op0;
   9433 
   9434       CCode = X86::GetOppositeBranchCondition(CCode);
   9435       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
   9436                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
   9437     }
   9438   }
   9439 
   9440   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
   9441   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
   9442   if (X86CC == X86::COND_INVALID)
   9443     return SDValue();
   9444 
   9445   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
   9446   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
   9447   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
   9448                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
   9449 }
   9450 
   9451 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
   9452 static bool isX86LogicalCmp(SDValue Op) {
   9453   unsigned Opc = Op.getNode()->getOpcode();
   9454   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
   9455       Opc == X86ISD::SAHF)
   9456     return true;
   9457   if (Op.getResNo() == 1 &&
   9458       (Opc == X86ISD::ADD ||
   9459        Opc == X86ISD::SUB ||
   9460        Opc == X86ISD::ADC ||
   9461        Opc == X86ISD::SBB ||
   9462        Opc == X86ISD::SMUL ||
   9463        Opc == X86ISD::UMUL ||
   9464        Opc == X86ISD::INC ||
   9465        Opc == X86ISD::DEC ||
   9466        Opc == X86ISD::OR ||
   9467        Opc == X86ISD::XOR ||
   9468        Opc == X86ISD::AND))
   9469     return true;
   9470 
   9471   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
   9472     return true;
   9473 
   9474   return false;
   9475 }
   9476 
   9477 static bool isZero(SDValue V) {
   9478   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
   9479   return C && C->isNullValue();
   9480 }
   9481 
   9482 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
   9483   if (V.getOpcode() != ISD::TRUNCATE)
   9484     return false;
   9485 
   9486   SDValue VOp0 = V.getOperand(0);
   9487   unsigned InBits = VOp0.getValueSizeInBits();
   9488   unsigned Bits = V.getValueSizeInBits();
   9489   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
   9490 }
   9491 
   9492 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
   9493   bool addTest = true;
   9494   SDValue Cond  = Op.getOperand(0);
   9495   SDValue Op1 = Op.getOperand(1);
   9496   SDValue Op2 = Op.getOperand(2);
   9497   DebugLoc DL = Op.getDebugLoc();
   9498   SDValue CC;
   9499 
   9500   if (Cond.getOpcode() == ISD::SETCC) {
   9501     SDValue NewCond = LowerSETCC(Cond, DAG);
   9502     if (NewCond.getNode())
   9503       Cond = NewCond;
   9504   }
   9505 
   9506   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
   9507   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
   9508   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
   9509   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
   9510   if (Cond.getOpcode() == X86ISD::SETCC &&
   9511       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
   9512       isZero(Cond.getOperand(1).getOperand(1))) {
   9513     SDValue Cmp = Cond.getOperand(1);
   9514 
   9515     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
   9516 
   9517     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
   9518         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
   9519       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
   9520 
   9521       SDValue CmpOp0 = Cmp.getOperand(0);
   9522       // Apply further optimizations for special cases
   9523       // (select (x != 0), -1, 0) -> neg & sbb
   9524       // (select (x == 0), 0, -1) -> neg & sbb
   9525       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
   9526         if (YC->isNullValue() &&
   9527             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
   9528           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
   9529           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
   9530                                     DAG.getConstant(0, CmpOp0.getValueType()),
   9531                                     CmpOp0);
   9532           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
   9533                                     DAG.getConstant(X86::COND_B, MVT::i8),
   9534                                     SDValue(Neg.getNode(), 1));
   9535           return Res;
   9536         }
   9537 
   9538       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
   9539                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
   9540       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
   9541 
   9542       SDValue Res =   // Res = 0 or -1.
   9543         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
   9544                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
   9545 
   9546       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
   9547         Res = DAG.getNOT(DL, Res, Res.getValueType());
   9548 
   9549       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
   9550       if (N2C == 0 || !N2C->isNullValue())
   9551         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
   9552       return Res;
   9553     }
   9554   }
   9555 
   9556   // Look past (and (setcc_carry (cmp ...)), 1).
   9557   if (Cond.getOpcode() == ISD::AND &&
   9558       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
   9559     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
   9560     if (C && C->getAPIntValue() == 1)
   9561       Cond = Cond.getOperand(0);
   9562   }
   9563 
   9564   // If condition flag is set by a X86ISD::CMP, then use it as the condition
   9565   // setting operand in place of the X86ISD::SETCC.
   9566   unsigned CondOpcode = Cond.getOpcode();
   9567   if (CondOpcode == X86ISD::SETCC ||
   9568       CondOpcode == X86ISD::SETCC_CARRY) {
   9569     CC = Cond.getOperand(0);
   9570 
   9571     SDValue Cmp = Cond.getOperand(1);
   9572     unsigned Opc = Cmp.getOpcode();
   9573     MVT VT = Op.getValueType().getSimpleVT();
   9574 
   9575     bool IllegalFPCMov = false;
   9576     if (VT.isFloatingPoint() && !VT.isVector() &&
   9577         !isScalarFPTypeInSSEReg(VT))  // FPStack?
   9578       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
   9579 
   9580     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
   9581         Opc == X86ISD::BT) { // FIXME
   9582       Cond = Cmp;
   9583       addTest = false;
   9584     }
   9585   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
   9586              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
   9587              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
   9588               Cond.getOperand(0).getValueType() != MVT::i8)) {
   9589     SDValue LHS = Cond.getOperand(0);
   9590     SDValue RHS = Cond.getOperand(1);
   9591     unsigned X86Opcode;
   9592     unsigned X86Cond;
   9593     SDVTList VTs;
   9594     switch (CondOpcode) {
   9595     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
   9596     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
   9597     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
   9598     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
   9599     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
   9600     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
   9601     default: llvm_unreachable("unexpected overflowing operator");
   9602     }
   9603     if (CondOpcode == ISD::UMULO)
   9604       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
   9605                           MVT::i32);
   9606     else
   9607       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
   9608 
   9609     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
   9610 
   9611     if (CondOpcode == ISD::UMULO)
   9612       Cond = X86Op.getValue(2);
   9613     else
   9614       Cond = X86Op.getValue(1);
   9615 
   9616     CC = DAG.getConstant(X86Cond, MVT::i8);
   9617     addTest = false;
   9618   }
   9619 
   9620   if (addTest) {
   9621     // Look pass the truncate if the high bits are known zero.
   9622     if (isTruncWithZeroHighBitsInput(Cond, DAG))
   9623         Cond = Cond.getOperand(0);
   9624 
   9625     // We know the result of AND is compared against zero. Try to match
   9626     // it to BT.
   9627     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
   9628       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
   9629       if (NewSetCC.getNode()) {
   9630         CC = NewSetCC.getOperand(0);
   9631         Cond = NewSetCC.getOperand(1);
   9632         addTest = false;
   9633       }
   9634     }
   9635   }
   9636 
   9637   if (addTest) {
   9638     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
   9639     Cond = EmitTest(Cond, X86::COND_NE, DAG);
   9640   }
   9641 
   9642   // a <  b ? -1 :  0 -> RES = ~setcc_carry
   9643   // a <  b ?  0 : -1 -> RES = setcc_carry
   9644   // a >= b ? -1 :  0 -> RES = setcc_carry
   9645   // a >= b ?  0 : -1 -> RES = ~setcc_carry
   9646   if (Cond.getOpcode() == X86ISD::SUB) {
   9647     Cond = ConvertCmpIfNecessary(Cond, DAG);
   9648     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
   9649 
   9650     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
   9651         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
   9652       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
   9653                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
   9654       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
   9655         return DAG.getNOT(DL, Res, Res.getValueType());
   9656       return Res;
   9657     }
   9658   }
   9659 
   9660   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
   9661   // widen the cmov and push the truncate through. This avoids introducing a new
   9662   // branch during isel and doesn't add any extensions.
   9663   if (Op.getValueType() == MVT::i8 &&
   9664       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
   9665     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
   9666     if (T1.getValueType() == T2.getValueType() &&
   9667         // Blacklist CopyFromReg to avoid partial register stalls.
   9668         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
   9669       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
   9670       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
   9671       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
   9672     }
   9673   }
   9674 
   9675   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
   9676   // condition is true.
   9677   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
   9678   SDValue Ops[] = { Op2, Op1, CC, Cond };
   9679   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
   9680 }
   9681 
   9682 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
   9683                                             SelectionDAG &DAG) const {
   9684   MVT VT = Op->getValueType(0).getSimpleVT();
   9685   SDValue In = Op->getOperand(0);
   9686   MVT InVT = In.getValueType().getSimpleVT();
   9687   DebugLoc dl = Op->getDebugLoc();
   9688 
   9689   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
   9690       (VT != MVT::v8i32 || InVT != MVT::v8i16))
   9691     return SDValue();
   9692 
   9693   if (Subtarget->hasInt256())
   9694     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
   9695 
   9696   // Optimize vectors in AVX mode
   9697   // Sign extend  v8i16 to v8i32 and
   9698   //              v4i32 to v4i64
   9699   //
   9700   // Divide input vector into two parts
   9701   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
   9702   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
   9703   // concat the vectors to original VT
   9704 
   9705   unsigned NumElems = InVT.getVectorNumElements();
   9706   SDValue Undef = DAG.getUNDEF(InVT);
   9707 
   9708   SmallVector<int,8> ShufMask1(NumElems, -1);
   9709   for (unsigned i = 0; i != NumElems/2; ++i)
   9710     ShufMask1[i] = i;
   9711 
   9712   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
   9713 
   9714   SmallVector<int,8> ShufMask2(NumElems, -1);
   9715   for (unsigned i = 0; i != NumElems/2; ++i)
   9716     ShufMask2[i] = i + NumElems/2;
   9717 
   9718   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
   9719 
   9720   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
   9721                                 VT.getVectorNumElements()/2);
   9722 
   9723   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
   9724   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
   9725 
   9726   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
   9727 }
   9728 
   9729 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
   9730 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
   9731 // from the AND / OR.
   9732 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
   9733   Opc = Op.getOpcode();
   9734   if (Opc != ISD::OR && Opc != ISD::AND)
   9735     return false;
   9736   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
   9737           Op.getOperand(0).hasOneUse() &&
   9738           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
   9739           Op.getOperand(1).hasOneUse());
   9740 }
   9741 
   9742 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
   9743 // 1 and that the SETCC node has a single use.
   9744 static bool isXor1OfSetCC(SDValue Op) {
   9745   if (Op.getOpcode() != ISD::XOR)
   9746     return false;
   9747   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
   9748   if (N1C && N1C->getAPIntValue() == 1) {
   9749     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
   9750       Op.getOperand(0).hasOneUse();
   9751   }
   9752   return false;
   9753 }
   9754 
   9755 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
   9756   bool addTest = true;
   9757   SDValue Chain = Op.getOperand(0);
   9758   SDValue Cond  = Op.getOperand(1);
   9759   SDValue Dest  = Op.getOperand(2);
   9760   DebugLoc dl = Op.getDebugLoc();
   9761   SDValue CC;
   9762   bool Inverted = false;
   9763 
   9764   if (Cond.getOpcode() == ISD::SETCC) {
   9765     // Check for setcc([su]{add,sub,mul}o == 0).
   9766     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
   9767         isa<ConstantSDNode>(Cond.getOperand(1)) &&
   9768         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
   9769         Cond.getOperand(0).getResNo() == 1 &&
   9770         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
   9771          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
   9772          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
   9773          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
   9774          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
   9775          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
   9776       Inverted = true;
   9777       Cond = Cond.getOperand(0);
   9778     } else {
   9779       SDValue NewCond = LowerSETCC(Cond, DAG);
   9780       if (NewCond.getNode())
   9781         Cond = NewCond;
   9782     }
   9783   }
   9784 #if 0
   9785   // FIXME: LowerXALUO doesn't handle these!!
   9786   else if (Cond.getOpcode() == X86ISD::ADD  ||
   9787            Cond.getOpcode() == X86ISD::SUB  ||
   9788            Cond.getOpcode() == X86ISD::SMUL ||
   9789            Cond.getOpcode() == X86ISD::UMUL)
   9790     Cond = LowerXALUO(Cond, DAG);
   9791 #endif
   9792 
   9793   // Look pass (and (setcc_carry (cmp ...)), 1).
   9794   if (Cond.getOpcode() == ISD::AND &&
   9795       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
   9796     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
   9797     if (C && C->getAPIntValue() == 1)
   9798       Cond = Cond.getOperand(0);
   9799   }
   9800 
   9801   // If condition flag is set by a X86ISD::CMP, then use it as the condition
   9802   // setting operand in place of the X86ISD::SETCC.
   9803   unsigned CondOpcode = Cond.getOpcode();
   9804   if (CondOpcode == X86ISD::SETCC ||
   9805       CondOpcode == X86ISD::SETCC_CARRY) {
   9806     CC = Cond.getOperand(0);
   9807 
   9808     SDValue Cmp = Cond.getOperand(1);
   9809     unsigned Opc = Cmp.getOpcode();
   9810     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
   9811     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
   9812       Cond = Cmp;
   9813       addTest = false;
   9814     } else {
   9815       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
   9816       default: break;
   9817       case X86::COND_O:
   9818       case X86::COND_B:
   9819         // These can only come from an arithmetic instruction with overflow,
   9820         // e.g. SADDO, UADDO.
   9821         Cond = Cond.getNode()->getOperand(1);
   9822         addTest = false;
   9823         break;
   9824       }
   9825     }
   9826   }
   9827   CondOpcode = Cond.getOpcode();
   9828   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
   9829       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
   9830       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
   9831        Cond.getOperand(0).getValueType() != MVT::i8)) {
   9832     SDValue LHS = Cond.getOperand(0);
   9833     SDValue RHS = Cond.getOperand(1);
   9834     unsigned X86Opcode;
   9835     unsigned X86Cond;
   9836     SDVTList VTs;
   9837     switch (CondOpcode) {
   9838     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
   9839     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
   9840     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
   9841     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
   9842     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
   9843     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
   9844     default: llvm_unreachable("unexpected overflowing operator");
   9845     }
   9846     if (Inverted)
   9847       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
   9848     if (CondOpcode == ISD::UMULO)
   9849       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
   9850                           MVT::i32);
   9851     else
   9852       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
   9853 
   9854     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
   9855 
   9856     if (CondOpcode == ISD::UMULO)
   9857       Cond = X86Op.getValue(2);
   9858     else
   9859       Cond = X86Op.getValue(1);
   9860 
   9861     CC = DAG.getConstant(X86Cond, MVT::i8);
   9862     addTest = false;
   9863   } else {
   9864     unsigned CondOpc;
   9865     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
   9866       SDValue Cmp = Cond.getOperand(0).getOperand(1);
   9867       if (CondOpc == ISD::OR) {
   9868         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
   9869         // two branches instead of an explicit OR instruction with a
   9870         // separate test.
   9871         if (Cmp == Cond.getOperand(1).getOperand(1) &&
   9872             isX86LogicalCmp(Cmp)) {
   9873           CC = Cond.getOperand(0).getOperand(0);
   9874           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
   9875                               Chain, Dest, CC, Cmp);
   9876           CC = Cond.getOperand(1).getOperand(0);
   9877           Cond = Cmp;
   9878           addTest = false;
   9879         }
   9880       } else { // ISD::AND
   9881         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
   9882         // two branches instead of an explicit AND instruction with a
   9883         // separate test. However, we only do this if this block doesn't
   9884         // have a fall-through edge, because this requires an explicit
   9885         // jmp when the condition is false.
   9886         if (Cmp == Cond.getOperand(1).getOperand(1) &&
   9887             isX86LogicalCmp(Cmp) &&
   9888             Op.getNode()->hasOneUse()) {
   9889           X86::CondCode CCode =
   9890             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
   9891           CCode = X86::GetOppositeBranchCondition(CCode);
   9892           CC = DAG.getConstant(CCode, MVT::i8);
   9893           SDNode *User = *Op.getNode()->use_begin();
   9894           // Look for an unconditional branch following this conditional branch.
   9895           // We need this because we need to reverse the successors in order
   9896           // to implement FCMP_OEQ.
   9897           if (User->getOpcode() == ISD::BR) {
   9898             SDValue FalseBB = User->getOperand(1);
   9899             SDNode *NewBR =
   9900               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
   9901             assert(NewBR == User);
   9902             (void)NewBR;
   9903             Dest = FalseBB;
   9904 
   9905             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
   9906                                 Chain, Dest, CC, Cmp);
   9907             X86::CondCode CCode =
   9908               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
   9909             CCode = X86::GetOppositeBranchCondition(CCode);
   9910             CC = DAG.getConstant(CCode, MVT::i8);
   9911             Cond = Cmp;
   9912             addTest = false;
   9913           }
   9914         }
   9915       }
   9916     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
   9917       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
   9918       // It should be transformed during dag combiner except when the condition
   9919       // is set by a arithmetics with overflow node.
   9920       X86::CondCode CCode =
   9921         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
   9922       CCode = X86::GetOppositeBranchCondition(CCode);
   9923       CC = DAG.getConstant(CCode, MVT::i8);
   9924       Cond = Cond.getOperand(0).getOperand(1);
   9925       addTest = false;
   9926     } else if (Cond.getOpcode() == ISD::SETCC &&
   9927                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
   9928       // For FCMP_OEQ, we can emit
   9929       // two branches instead of an explicit AND instruction with a
   9930       // separate test. However, we only do this if this block doesn't
   9931       // have a fall-through edge, because this requires an explicit
   9932       // jmp when the condition is false.
   9933       if (Op.getNode()->hasOneUse()) {
   9934         SDNode *User = *Op.getNode()->use_begin();
   9935         // Look for an unconditional branch following this conditional branch.
   9936         // We need this because we need to reverse the successors in order
   9937         // to implement FCMP_OEQ.
   9938         if (User->getOpcode() == ISD::BR) {
   9939           SDValue FalseBB = User->getOperand(1);
   9940           SDNode *NewBR =
   9941             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
   9942           assert(NewBR == User);
   9943           (void)NewBR;
   9944           Dest = FalseBB;
   9945 
   9946           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
   9947                                     Cond.getOperand(0), Cond.getOperand(1));
   9948           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
   9949           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
   9950           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
   9951                               Chain, Dest, CC, Cmp);
   9952           CC = DAG.getConstant(X86::COND_P, MVT::i8);
   9953           Cond = Cmp;
   9954           addTest = false;
   9955         }
   9956       }
   9957     } else if (Cond.getOpcode() == ISD::SETCC &&
   9958                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
   9959       // For FCMP_UNE, we can emit
   9960       // two branches instead of an explicit AND instruction with a
   9961       // separate test. However, we only do this if this block doesn't
   9962       // have a fall-through edge, because this requires an explicit
   9963       // jmp when the condition is false.
   9964       if (Op.getNode()->hasOneUse()) {
   9965         SDNode *User = *Op.getNode()->use_begin();
   9966         // Look for an unconditional branch following this conditional branch.
   9967         // We need this because we need to reverse the successors in order
   9968         // to implement FCMP_UNE.
   9969         if (User->getOpcode() == ISD::BR) {
   9970           SDValue FalseBB = User->getOperand(1);
   9971           SDNode *NewBR =
   9972             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
   9973           assert(NewBR == User);
   9974           (void)NewBR;
   9975 
   9976           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
   9977                                     Cond.getOperand(0), Cond.getOperand(1));
   9978           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
   9979           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
   9980           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
   9981                               Chain, Dest, CC, Cmp);
   9982           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
   9983           Cond = Cmp;
   9984           addTest = false;
   9985           Dest = FalseBB;
   9986         }
   9987       }
   9988     }
   9989   }
   9990 
   9991   if (addTest) {
   9992     // Look pass the truncate if the high bits are known zero.
   9993     if (isTruncWithZeroHighBitsInput(Cond, DAG))
   9994         Cond = Cond.getOperand(0);
   9995 
   9996     // We know the result of AND is compared against zero. Try to match
   9997     // it to BT.
   9998     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
   9999       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
   10000       if (NewSetCC.getNode()) {
   10001         CC = NewSetCC.getOperand(0);
   10002         Cond = NewSetCC.getOperand(1);
   10003         addTest = false;
   10004       }
   10005     }
   10006   }
   10007 
   10008   if (addTest) {
   10009     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
   10010     Cond = EmitTest(Cond, X86::COND_NE, DAG);
   10011   }
   10012   Cond = ConvertCmpIfNecessary(Cond, DAG);
   10013   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
   10014                      Chain, Dest, CC, Cond);
   10015 }
   10016 
   10017 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
   10018 // Calls to _alloca is needed to probe the stack when allocating more than 4k
   10019 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
   10020 // that the guard pages used by the OS virtual memory manager are allocated in
   10021 // correct sequence.
   10022 SDValue
   10023 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
   10024                                            SelectionDAG &DAG) const {
   10025   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
   10026           getTargetMachine().Options.EnableSegmentedStacks) &&
   10027          "This should be used only on Windows targets or when segmented stacks "
   10028          "are being used");
   10029   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
   10030   DebugLoc dl = Op.getDebugLoc();
   10031 
   10032   // Get the inputs.
   10033   SDValue Chain = Op.getOperand(0);
   10034   SDValue Size  = Op.getOperand(1);
   10035   // FIXME: Ensure alignment here
   10036 
   10037   bool Is64Bit = Subtarget->is64Bit();
   10038   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
   10039 
   10040   if (getTargetMachine().Options.EnableSegmentedStacks) {
   10041     MachineFunction &MF = DAG.getMachineFunction();
   10042     MachineRegisterInfo &MRI = MF.getRegInfo();
   10043 
   10044     if (Is64Bit) {
   10045       // The 64 bit implementation of segmented stacks needs to clobber both r10
   10046       // r11. This makes it impossible to use it along with nested parameters.
   10047       const Function *F = MF.getFunction();
   10048 
   10049       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
   10050            I != E; ++I)
   10051         if (I->hasNestAttr())
   10052           report_fatal_error("Cannot use segmented stacks with functions that "
   10053                              "have nested arguments.");
   10054     }
   10055 
   10056     const TargetRegisterClass *AddrRegClass =
   10057       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
   10058     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
   10059     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
   10060     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
   10061                                 DAG.getRegister(Vreg, SPTy));
   10062     SDValue Ops1[2] = { Value, Chain };
   10063     return DAG.getMergeValues(Ops1, 2, dl);
   10064   } else {
   10065     SDValue Flag;
   10066     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
   10067 
   10068     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
   10069     Flag = Chain.getValue(1);
   10070     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
   10071 
   10072     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
   10073     Flag = Chain.getValue(1);
   10074 
   10075     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
   10076                                SPTy).getValue(1);
   10077 
   10078     SDValue Ops1[2] = { Chain.getValue(0), Chain };
   10079     return DAG.getMergeValues(Ops1, 2, dl);
   10080   }
   10081 }
   10082 
   10083 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
   10084   MachineFunction &MF = DAG.getMachineFunction();
   10085   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
   10086 
   10087   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
   10088   DebugLoc DL = Op.getDebugLoc();
   10089 
   10090   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
   10091     // vastart just stores the address of the VarArgsFrameIndex slot into the
   10092     // memory location argument.
   10093     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
   10094                                    getPointerTy());
   10095     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
   10096                         MachinePointerInfo(SV), false, false, 0);
   10097   }
   10098 
   10099   // __va_list_tag:
   10100   //   gp_offset         (0 - 6 * 8)
   10101   //   fp_offset         (48 - 48 + 8 * 16)
   10102   //   overflow_arg_area (point to parameters coming in memory).
   10103   //   reg_save_area
   10104   SmallVector<SDValue, 8> MemOps;
   10105   SDValue FIN = Op.getOperand(1);
   10106   // Store gp_offset
   10107   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
   10108                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
   10109                                                MVT::i32),
   10110                                FIN, MachinePointerInfo(SV), false, false, 0);
   10111   MemOps.push_back(Store);
   10112 
   10113   // Store fp_offset
   10114   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
   10115                     FIN, DAG.getIntPtrConstant(4));
   10116   Store = DAG.getStore(Op.getOperand(0), DL,
   10117                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
   10118                                        MVT::i32),
   10119                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
   10120   MemOps.push_back(Store);
   10121 
   10122   // Store ptr to overflow_arg_area
   10123   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
   10124                     FIN, DAG.getIntPtrConstant(4));
   10125   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
   10126                                     getPointerTy());
   10127   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
   10128                        MachinePointerInfo(SV, 8),
   10129                        false, false, 0);
   10130   MemOps.push_back(Store);
   10131 
   10132   // Store ptr to reg_save_area.
   10133   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
   10134                     FIN, DAG.getIntPtrConstant(8));
   10135   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
   10136                                     getPointerTy());
   10137   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
   10138                        MachinePointerInfo(SV, 16), false, false, 0);
   10139   MemOps.push_back(Store);
   10140   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
   10141                      &MemOps[0], MemOps.size());
   10142 }
   10143 
   10144 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
   10145   assert(Subtarget->is64Bit() &&
   10146          "LowerVAARG only handles 64-bit va_arg!");
   10147   assert((Subtarget->isTargetLinux() ||
   10148           Subtarget->isTargetDarwin()) &&
   10149           "Unhandled target in LowerVAARG");
   10150   assert(Op.getNode()->getNumOperands() == 4);
   10151   SDValue Chain = Op.getOperand(0);
   10152   SDValue SrcPtr = Op.getOperand(1);
   10153   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
   10154   unsigned Align = Op.getConstantOperandVal(3);
   10155   DebugLoc dl = Op.getDebugLoc();
   10156 
   10157   EVT ArgVT = Op.getNode()->getValueType(0);
   10158   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
   10159   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
   10160   uint8_t ArgMode;
   10161 
   10162   // Decide which area this value should be read from.
   10163   // TODO: Implement the AMD64 ABI in its entirety. This simple
   10164   // selection mechanism works only for the basic types.
   10165   if (ArgVT == MVT::f80) {
   10166     llvm_unreachable("va_arg for f80 not yet implemented");
   10167   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
   10168     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
   10169   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
   10170     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
   10171   } else {
   10172     llvm_unreachable("Unhandled argument type in LowerVAARG");
   10173   }
   10174 
   10175   if (ArgMode == 2) {
   10176     // Sanity Check: Make sure using fp_offset makes sense.
   10177     assert(!getTargetMachine().Options.UseSoftFloat &&
   10178            !(DAG.getMachineFunction()
   10179                 .getFunction()->getAttributes()
   10180                 .hasAttribute(AttributeSet::FunctionIndex,
   10181                               Attribute::NoImplicitFloat)) &&
   10182            Subtarget->hasSSE1());
   10183   }
   10184 
   10185   // Insert VAARG_64 node into the DAG
   10186   // VAARG_64 returns two values: Variable Argument Address, Chain
   10187   SmallVector<SDValue, 11> InstOps;
   10188   InstOps.push_back(Chain);
   10189   InstOps.push_back(SrcPtr);
   10190   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
   10191   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
   10192   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
   10193   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
   10194   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
   10195                                           VTs, &InstOps[0], InstOps.size(),
   10196                                           MVT::i64,
   10197                                           MachinePointerInfo(SV),
   10198                                           /*Align=*/0,
   10199                                           /*Volatile=*/false,
   10200                                           /*ReadMem=*/true,
   10201                                           /*WriteMem=*/true);
   10202   Chain = VAARG.getValue(1);
   10203 
   10204   // Load the next argument and return it
   10205   return DAG.getLoad(ArgVT, dl,
   10206                      Chain,
   10207                      VAARG,
   10208                      MachinePointerInfo(),
   10209                      false, false, false, 0);
   10210 }
   10211 
   10212 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
   10213                            SelectionDAG &DAG) {
   10214   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
   10215   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
   10216   SDValue Chain = Op.getOperand(0);
   10217   SDValue DstPtr = Op.getOperand(1);
   10218   SDValue SrcPtr = Op.getOperand(2);
   10219   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
   10220   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
   10221   DebugLoc DL = Op.getDebugLoc();
   10222 
   10223   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
   10224                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
   10225                        false,
   10226                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
   10227 }
   10228 
   10229 // getTargetVShiftNode - Handle vector element shifts where the shift amount
   10230 // may or may not be a constant. Takes immediate version of shift as input.
   10231 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
   10232                                    SDValue SrcOp, SDValue ShAmt,
   10233                                    SelectionDAG &DAG) {
   10234   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
   10235 
   10236   if (isa<ConstantSDNode>(ShAmt)) {
   10237     // Constant may be a TargetConstant. Use a regular constant.
   10238     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
   10239     switch (Opc) {
   10240       default: llvm_unreachable("Unknown target vector shift node");
   10241       case X86ISD::VSHLI:
   10242       case X86ISD::VSRLI:
   10243       case X86ISD::VSRAI:
   10244         return DAG.getNode(Opc, dl, VT, SrcOp,
   10245                            DAG.getConstant(ShiftAmt, MVT::i32));
   10246     }
   10247   }
   10248 
   10249   // Change opcode to non-immediate version
   10250   switch (Opc) {
   10251     default: llvm_unreachable("Unknown target vector shift node");
   10252     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
   10253     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
   10254     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
   10255   }
   10256 
   10257   // Need to build a vector containing shift amount
   10258   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
   10259   SDValue ShOps[4];
   10260   ShOps[0] = ShAmt;
   10261   ShOps[1] = DAG.getConstant(0, MVT::i32);
   10262   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
   10263   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
   10264 
   10265   // The return type has to be a 128-bit type with the same element
   10266   // type as the input type.
   10267   MVT EltVT = VT.getVectorElementType().getSimpleVT();
   10268   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
   10269 
   10270   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
   10271   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
   10272 }
   10273 
   10274 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
   10275   DebugLoc dl = Op.getDebugLoc();
   10276   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   10277   switch (IntNo) {
   10278   default: return SDValue();    // Don't custom lower most intrinsics.
   10279   // Comparison intrinsics.
   10280   case Intrinsic::x86_sse_comieq_ss:
   10281   case Intrinsic::x86_sse_comilt_ss:
   10282   case Intrinsic::x86_sse_comile_ss:
   10283   case Intrinsic::x86_sse_comigt_ss:
   10284   case Intrinsic::x86_sse_comige_ss:
   10285   case Intrinsic::x86_sse_comineq_ss:
   10286   case Intrinsic::x86_sse_ucomieq_ss:
   10287   case Intrinsic::x86_sse_ucomilt_ss:
   10288   case Intrinsic::x86_sse_ucomile_ss:
   10289   case Intrinsic::x86_sse_ucomigt_ss:
   10290   case Intrinsic::x86_sse_ucomige_ss:
   10291   case Intrinsic::x86_sse_ucomineq_ss:
   10292   case Intrinsic::x86_sse2_comieq_sd:
   10293   case Intrinsic::x86_sse2_comilt_sd:
   10294   case Intrinsic::x86_sse2_comile_sd:
   10295   case Intrinsic::x86_sse2_comigt_sd:
   10296   case Intrinsic::x86_sse2_comige_sd:
   10297   case Intrinsic::x86_sse2_comineq_sd:
   10298   case Intrinsic::x86_sse2_ucomieq_sd:
   10299   case Intrinsic::x86_sse2_ucomilt_sd:
   10300   case Intrinsic::x86_sse2_ucomile_sd:
   10301   case Intrinsic::x86_sse2_ucomigt_sd:
   10302   case Intrinsic::x86_sse2_ucomige_sd:
   10303   case Intrinsic::x86_sse2_ucomineq_sd: {
   10304     unsigned Opc;
   10305     ISD::CondCode CC;
   10306     switch (IntNo) {
   10307     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10308     case Intrinsic::x86_sse_comieq_ss:
   10309     case Intrinsic::x86_sse2_comieq_sd:
   10310       Opc = X86ISD::COMI;
   10311       CC = ISD::SETEQ;
   10312       break;
   10313     case Intrinsic::x86_sse_comilt_ss:
   10314     case Intrinsic::x86_sse2_comilt_sd:
   10315       Opc = X86ISD::COMI;
   10316       CC = ISD::SETLT;
   10317       break;
   10318     case Intrinsic::x86_sse_comile_ss:
   10319     case Intrinsic::x86_sse2_comile_sd:
   10320       Opc = X86ISD::COMI;
   10321       CC = ISD::SETLE;
   10322       break;
   10323     case Intrinsic::x86_sse_comigt_ss:
   10324     case Intrinsic::x86_sse2_comigt_sd:
   10325       Opc = X86ISD::COMI;
   10326       CC = ISD::SETGT;
   10327       break;
   10328     case Intrinsic::x86_sse_comige_ss:
   10329     case Intrinsic::x86_sse2_comige_sd:
   10330       Opc = X86ISD::COMI;
   10331       CC = ISD::SETGE;
   10332       break;
   10333     case Intrinsic::x86_sse_comineq_ss:
   10334     case Intrinsic::x86_sse2_comineq_sd:
   10335       Opc = X86ISD::COMI;
   10336       CC = ISD::SETNE;
   10337       break;
   10338     case Intrinsic::x86_sse_ucomieq_ss:
   10339     case Intrinsic::x86_sse2_ucomieq_sd:
   10340       Opc = X86ISD::UCOMI;
   10341       CC = ISD::SETEQ;
   10342       break;
   10343     case Intrinsic::x86_sse_ucomilt_ss:
   10344     case Intrinsic::x86_sse2_ucomilt_sd:
   10345       Opc = X86ISD::UCOMI;
   10346       CC = ISD::SETLT;
   10347       break;
   10348     case Intrinsic::x86_sse_ucomile_ss:
   10349     case Intrinsic::x86_sse2_ucomile_sd:
   10350       Opc = X86ISD::UCOMI;
   10351       CC = ISD::SETLE;
   10352       break;
   10353     case Intrinsic::x86_sse_ucomigt_ss:
   10354     case Intrinsic::x86_sse2_ucomigt_sd:
   10355       Opc = X86ISD::UCOMI;
   10356       CC = ISD::SETGT;
   10357       break;
   10358     case Intrinsic::x86_sse_ucomige_ss:
   10359     case Intrinsic::x86_sse2_ucomige_sd:
   10360       Opc = X86ISD::UCOMI;
   10361       CC = ISD::SETGE;
   10362       break;
   10363     case Intrinsic::x86_sse_ucomineq_ss:
   10364     case Intrinsic::x86_sse2_ucomineq_sd:
   10365       Opc = X86ISD::UCOMI;
   10366       CC = ISD::SETNE;
   10367       break;
   10368     }
   10369 
   10370     SDValue LHS = Op.getOperand(1);
   10371     SDValue RHS = Op.getOperand(2);
   10372     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
   10373     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
   10374     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
   10375     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
   10376                                 DAG.getConstant(X86CC, MVT::i8), Cond);
   10377     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
   10378   }
   10379 
   10380   // Arithmetic intrinsics.
   10381   case Intrinsic::x86_sse2_pmulu_dq:
   10382   case Intrinsic::x86_avx2_pmulu_dq:
   10383     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
   10384                        Op.getOperand(1), Op.getOperand(2));
   10385 
   10386   // SSE2/AVX2 sub with unsigned saturation intrinsics
   10387   case Intrinsic::x86_sse2_psubus_b:
   10388   case Intrinsic::x86_sse2_psubus_w:
   10389   case Intrinsic::x86_avx2_psubus_b:
   10390   case Intrinsic::x86_avx2_psubus_w:
   10391     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
   10392                        Op.getOperand(1), Op.getOperand(2));
   10393 
   10394   // SSE3/AVX horizontal add/sub intrinsics
   10395   case Intrinsic::x86_sse3_hadd_ps:
   10396   case Intrinsic::x86_sse3_hadd_pd:
   10397   case Intrinsic::x86_avx_hadd_ps_256:
   10398   case Intrinsic::x86_avx_hadd_pd_256:
   10399   case Intrinsic::x86_sse3_hsub_ps:
   10400   case Intrinsic::x86_sse3_hsub_pd:
   10401   case Intrinsic::x86_avx_hsub_ps_256:
   10402   case Intrinsic::x86_avx_hsub_pd_256:
   10403   case Intrinsic::x86_ssse3_phadd_w_128:
   10404   case Intrinsic::x86_ssse3_phadd_d_128:
   10405   case Intrinsic::x86_avx2_phadd_w:
   10406   case Intrinsic::x86_avx2_phadd_d:
   10407   case Intrinsic::x86_ssse3_phsub_w_128:
   10408   case Intrinsic::x86_ssse3_phsub_d_128:
   10409   case Intrinsic::x86_avx2_phsub_w:
   10410   case Intrinsic::x86_avx2_phsub_d: {
   10411     unsigned Opcode;
   10412     switch (IntNo) {
   10413     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10414     case Intrinsic::x86_sse3_hadd_ps:
   10415     case Intrinsic::x86_sse3_hadd_pd:
   10416     case Intrinsic::x86_avx_hadd_ps_256:
   10417     case Intrinsic::x86_avx_hadd_pd_256:
   10418       Opcode = X86ISD::FHADD;
   10419       break;
   10420     case Intrinsic::x86_sse3_hsub_ps:
   10421     case Intrinsic::x86_sse3_hsub_pd:
   10422     case Intrinsic::x86_avx_hsub_ps_256:
   10423     case Intrinsic::x86_avx_hsub_pd_256:
   10424       Opcode = X86ISD::FHSUB;
   10425       break;
   10426     case Intrinsic::x86_ssse3_phadd_w_128:
   10427     case Intrinsic::x86_ssse3_phadd_d_128:
   10428     case Intrinsic::x86_avx2_phadd_w:
   10429     case Intrinsic::x86_avx2_phadd_d:
   10430       Opcode = X86ISD::HADD;
   10431       break;
   10432     case Intrinsic::x86_ssse3_phsub_w_128:
   10433     case Intrinsic::x86_ssse3_phsub_d_128:
   10434     case Intrinsic::x86_avx2_phsub_w:
   10435     case Intrinsic::x86_avx2_phsub_d:
   10436       Opcode = X86ISD::HSUB;
   10437       break;
   10438     }
   10439     return DAG.getNode(Opcode, dl, Op.getValueType(),
   10440                        Op.getOperand(1), Op.getOperand(2));
   10441   }
   10442 
   10443   // SSE2/SSE41/AVX2 integer max/min intrinsics.
   10444   case Intrinsic::x86_sse2_pmaxu_b:
   10445   case Intrinsic::x86_sse41_pmaxuw:
   10446   case Intrinsic::x86_sse41_pmaxud:
   10447   case Intrinsic::x86_avx2_pmaxu_b:
   10448   case Intrinsic::x86_avx2_pmaxu_w:
   10449   case Intrinsic::x86_avx2_pmaxu_d:
   10450   case Intrinsic::x86_sse2_pminu_b:
   10451   case Intrinsic::x86_sse41_pminuw:
   10452   case Intrinsic::x86_sse41_pminud:
   10453   case Intrinsic::x86_avx2_pminu_b:
   10454   case Intrinsic::x86_avx2_pminu_w:
   10455   case Intrinsic::x86_avx2_pminu_d:
   10456   case Intrinsic::x86_sse41_pmaxsb:
   10457   case Intrinsic::x86_sse2_pmaxs_w:
   10458   case Intrinsic::x86_sse41_pmaxsd:
   10459   case Intrinsic::x86_avx2_pmaxs_b:
   10460   case Intrinsic::x86_avx2_pmaxs_w:
   10461   case Intrinsic::x86_avx2_pmaxs_d:
   10462   case Intrinsic::x86_sse41_pminsb:
   10463   case Intrinsic::x86_sse2_pmins_w:
   10464   case Intrinsic::x86_sse41_pminsd:
   10465   case Intrinsic::x86_avx2_pmins_b:
   10466   case Intrinsic::x86_avx2_pmins_w:
   10467   case Intrinsic::x86_avx2_pmins_d: {
   10468     unsigned Opcode;
   10469     switch (IntNo) {
   10470     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10471     case Intrinsic::x86_sse2_pmaxu_b:
   10472     case Intrinsic::x86_sse41_pmaxuw:
   10473     case Intrinsic::x86_sse41_pmaxud:
   10474     case Intrinsic::x86_avx2_pmaxu_b:
   10475     case Intrinsic::x86_avx2_pmaxu_w:
   10476     case Intrinsic::x86_avx2_pmaxu_d:
   10477       Opcode = X86ISD::UMAX;
   10478       break;
   10479     case Intrinsic::x86_sse2_pminu_b:
   10480     case Intrinsic::x86_sse41_pminuw:
   10481     case Intrinsic::x86_sse41_pminud:
   10482     case Intrinsic::x86_avx2_pminu_b:
   10483     case Intrinsic::x86_avx2_pminu_w:
   10484     case Intrinsic::x86_avx2_pminu_d:
   10485       Opcode = X86ISD::UMIN;
   10486       break;
   10487     case Intrinsic::x86_sse41_pmaxsb:
   10488     case Intrinsic::x86_sse2_pmaxs_w:
   10489     case Intrinsic::x86_sse41_pmaxsd:
   10490     case Intrinsic::x86_avx2_pmaxs_b:
   10491     case Intrinsic::x86_avx2_pmaxs_w:
   10492     case Intrinsic::x86_avx2_pmaxs_d:
   10493       Opcode = X86ISD::SMAX;
   10494       break;
   10495     case Intrinsic::x86_sse41_pminsb:
   10496     case Intrinsic::x86_sse2_pmins_w:
   10497     case Intrinsic::x86_sse41_pminsd:
   10498     case Intrinsic::x86_avx2_pmins_b:
   10499     case Intrinsic::x86_avx2_pmins_w:
   10500     case Intrinsic::x86_avx2_pmins_d:
   10501       Opcode = X86ISD::SMIN;
   10502       break;
   10503     }
   10504     return DAG.getNode(Opcode, dl, Op.getValueType(),
   10505                        Op.getOperand(1), Op.getOperand(2));
   10506   }
   10507 
   10508   // SSE/SSE2/AVX floating point max/min intrinsics.
   10509   case Intrinsic::x86_sse_max_ps:
   10510   case Intrinsic::x86_sse2_max_pd:
   10511   case Intrinsic::x86_avx_max_ps_256:
   10512   case Intrinsic::x86_avx_max_pd_256:
   10513   case Intrinsic::x86_sse_min_ps:
   10514   case Intrinsic::x86_sse2_min_pd:
   10515   case Intrinsic::x86_avx_min_ps_256:
   10516   case Intrinsic::x86_avx_min_pd_256: {
   10517     unsigned Opcode;
   10518     switch (IntNo) {
   10519     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10520     case Intrinsic::x86_sse_max_ps:
   10521     case Intrinsic::x86_sse2_max_pd:
   10522     case Intrinsic::x86_avx_max_ps_256:
   10523     case Intrinsic::x86_avx_max_pd_256:
   10524       Opcode = X86ISD::FMAX;
   10525       break;
   10526     case Intrinsic::x86_sse_min_ps:
   10527     case Intrinsic::x86_sse2_min_pd:
   10528     case Intrinsic::x86_avx_min_ps_256:
   10529     case Intrinsic::x86_avx_min_pd_256:
   10530       Opcode = X86ISD::FMIN;
   10531       break;
   10532     }
   10533     return DAG.getNode(Opcode, dl, Op.getValueType(),
   10534                        Op.getOperand(1), Op.getOperand(2));
   10535   }
   10536 
   10537   // AVX2 variable shift intrinsics
   10538   case Intrinsic::x86_avx2_psllv_d:
   10539   case Intrinsic::x86_avx2_psllv_q:
   10540   case Intrinsic::x86_avx2_psllv_d_256:
   10541   case Intrinsic::x86_avx2_psllv_q_256:
   10542   case Intrinsic::x86_avx2_psrlv_d:
   10543   case Intrinsic::x86_avx2_psrlv_q:
   10544   case Intrinsic::x86_avx2_psrlv_d_256:
   10545   case Intrinsic::x86_avx2_psrlv_q_256:
   10546   case Intrinsic::x86_avx2_psrav_d:
   10547   case Intrinsic::x86_avx2_psrav_d_256: {
   10548     unsigned Opcode;
   10549     switch (IntNo) {
   10550     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10551     case Intrinsic::x86_avx2_psllv_d:
   10552     case Intrinsic::x86_avx2_psllv_q:
   10553     case Intrinsic::x86_avx2_psllv_d_256:
   10554     case Intrinsic::x86_avx2_psllv_q_256:
   10555       Opcode = ISD::SHL;
   10556       break;
   10557     case Intrinsic::x86_avx2_psrlv_d:
   10558     case Intrinsic::x86_avx2_psrlv_q:
   10559     case Intrinsic::x86_avx2_psrlv_d_256:
   10560     case Intrinsic::x86_avx2_psrlv_q_256:
   10561       Opcode = ISD::SRL;
   10562       break;
   10563     case Intrinsic::x86_avx2_psrav_d:
   10564     case Intrinsic::x86_avx2_psrav_d_256:
   10565       Opcode = ISD::SRA;
   10566       break;
   10567     }
   10568     return DAG.getNode(Opcode, dl, Op.getValueType(),
   10569                        Op.getOperand(1), Op.getOperand(2));
   10570   }
   10571 
   10572   case Intrinsic::x86_ssse3_pshuf_b_128:
   10573   case Intrinsic::x86_avx2_pshuf_b:
   10574     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
   10575                        Op.getOperand(1), Op.getOperand(2));
   10576 
   10577   case Intrinsic::x86_ssse3_psign_b_128:
   10578   case Intrinsic::x86_ssse3_psign_w_128:
   10579   case Intrinsic::x86_ssse3_psign_d_128:
   10580   case Intrinsic::x86_avx2_psign_b:
   10581   case Intrinsic::x86_avx2_psign_w:
   10582   case Intrinsic::x86_avx2_psign_d:
   10583     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
   10584                        Op.getOperand(1), Op.getOperand(2));
   10585 
   10586   case Intrinsic::x86_sse41_insertps:
   10587     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
   10588                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
   10589 
   10590   case Intrinsic::x86_avx_vperm2f128_ps_256:
   10591   case Intrinsic::x86_avx_vperm2f128_pd_256:
   10592   case Intrinsic::x86_avx_vperm2f128_si_256:
   10593   case Intrinsic::x86_avx2_vperm2i128:
   10594     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
   10595                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
   10596 
   10597   case Intrinsic::x86_avx2_permd:
   10598   case Intrinsic::x86_avx2_permps:
   10599     // Operands intentionally swapped. Mask is last operand to intrinsic,
   10600     // but second operand for node/intruction.
   10601     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
   10602                        Op.getOperand(2), Op.getOperand(1));
   10603 
   10604   case Intrinsic::x86_sse_sqrt_ps:
   10605   case Intrinsic::x86_sse2_sqrt_pd:
   10606   case Intrinsic::x86_avx_sqrt_ps_256:
   10607   case Intrinsic::x86_avx_sqrt_pd_256:
   10608     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
   10609 
   10610   // ptest and testp intrinsics. The intrinsic these come from are designed to
   10611   // return an integer value, not just an instruction so lower it to the ptest
   10612   // or testp pattern and a setcc for the result.
   10613   case Intrinsic::x86_sse41_ptestz:
   10614   case Intrinsic::x86_sse41_ptestc:
   10615   case Intrinsic::x86_sse41_ptestnzc:
   10616   case Intrinsic::x86_avx_ptestz_256:
   10617   case Intrinsic::x86_avx_ptestc_256:
   10618   case Intrinsic::x86_avx_ptestnzc_256:
   10619   case Intrinsic::x86_avx_vtestz_ps:
   10620   case Intrinsic::x86_avx_vtestc_ps:
   10621   case Intrinsic::x86_avx_vtestnzc_ps:
   10622   case Intrinsic::x86_avx_vtestz_pd:
   10623   case Intrinsic::x86_avx_vtestc_pd:
   10624   case Intrinsic::x86_avx_vtestnzc_pd:
   10625   case Intrinsic::x86_avx_vtestz_ps_256:
   10626   case Intrinsic::x86_avx_vtestc_ps_256:
   10627   case Intrinsic::x86_avx_vtestnzc_ps_256:
   10628   case Intrinsic::x86_avx_vtestz_pd_256:
   10629   case Intrinsic::x86_avx_vtestc_pd_256:
   10630   case Intrinsic::x86_avx_vtestnzc_pd_256: {
   10631     bool IsTestPacked = false;
   10632     unsigned X86CC;
   10633     switch (IntNo) {
   10634     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
   10635     case Intrinsic::x86_avx_vtestz_ps:
   10636     case Intrinsic::x86_avx_vtestz_pd:
   10637     case Intrinsic::x86_avx_vtestz_ps_256:
   10638     case Intrinsic::x86_avx_vtestz_pd_256:
   10639       IsTestPacked = true; // Fallthrough
   10640     case Intrinsic::x86_sse41_ptestz:
   10641     case Intrinsic::x86_avx_ptestz_256:
   10642       // ZF = 1
   10643       X86CC = X86::COND_E;
   10644       break;
   10645     case Intrinsic::x86_avx_vtestc_ps:
   10646     case Intrinsic::x86_avx_vtestc_pd:
   10647     case Intrinsic::x86_avx_vtestc_ps_256:
   10648     case Intrinsic::x86_avx_vtestc_pd_256:
   10649       IsTestPacked = true; // Fallthrough
   10650     case Intrinsic::x86_sse41_ptestc:
   10651     case Intrinsic::x86_avx_ptestc_256:
   10652       // CF = 1
   10653       X86CC = X86::COND_B;
   10654       break;
   10655     case Intrinsic::x86_avx_vtestnzc_ps:
   10656     case Intrinsic::x86_avx_vtestnzc_pd:
   10657     case Intrinsic::x86_avx_vtestnzc_ps_256:
   10658     case Intrinsic::x86_avx_vtestnzc_pd_256:
   10659       IsTestPacked = true; // Fallthrough
   10660     case Intrinsic::x86_sse41_ptestnzc:
   10661     case Intrinsic::x86_avx_ptestnzc_256:
   10662       // ZF and CF = 0
   10663       X86CC = X86::COND_A;
   10664       break;
   10665     }
   10666 
   10667     SDValue LHS = Op.getOperand(1);
   10668     SDValue RHS = Op.getOperand(2);
   10669     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
   10670     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
   10671     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
   10672     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
   10673     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
   10674   }
   10675 
   10676   // SSE/AVX shift intrinsics
   10677   case Intrinsic::x86_sse2_psll_w:
   10678   case Intrinsic::x86_sse2_psll_d:
   10679   case Intrinsic::x86_sse2_psll_q:
   10680   case Intrinsic::x86_avx2_psll_w:
   10681   case Intrinsic::x86_avx2_psll_d:
   10682   case Intrinsic::x86_avx2_psll_q:
   10683   case Intrinsic::x86_sse2_psrl_w:
   10684   case Intrinsic::x86_sse2_psrl_d:
   10685   case Intrinsic::x86_sse2_psrl_q:
   10686   case Intrinsic::x86_avx2_psrl_w:
   10687   case Intrinsic::x86_avx2_psrl_d:
   10688   case Intrinsic::x86_avx2_psrl_q:
   10689   case Intrinsic::x86_sse2_psra_w:
   10690   case Intrinsic::x86_sse2_psra_d:
   10691   case Intrinsic::x86_avx2_psra_w:
   10692   case Intrinsic::x86_avx2_psra_d: {
   10693     unsigned Opcode;
   10694     switch (IntNo) {
   10695     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10696     case Intrinsic::x86_sse2_psll_w:
   10697     case Intrinsic::x86_sse2_psll_d:
   10698     case Intrinsic::x86_sse2_psll_q:
   10699     case Intrinsic::x86_avx2_psll_w:
   10700     case Intrinsic::x86_avx2_psll_d:
   10701     case Intrinsic::x86_avx2_psll_q:
   10702       Opcode = X86ISD::VSHL;
   10703       break;
   10704     case Intrinsic::x86_sse2_psrl_w:
   10705     case Intrinsic::x86_sse2_psrl_d:
   10706     case Intrinsic::x86_sse2_psrl_q:
   10707     case Intrinsic::x86_avx2_psrl_w:
   10708     case Intrinsic::x86_avx2_psrl_d:
   10709     case Intrinsic::x86_avx2_psrl_q:
   10710       Opcode = X86ISD::VSRL;
   10711       break;
   10712     case Intrinsic::x86_sse2_psra_w:
   10713     case Intrinsic::x86_sse2_psra_d:
   10714     case Intrinsic::x86_avx2_psra_w:
   10715     case Intrinsic::x86_avx2_psra_d:
   10716       Opcode = X86ISD::VSRA;
   10717       break;
   10718     }
   10719     return DAG.getNode(Opcode, dl, Op.getValueType(),
   10720                        Op.getOperand(1), Op.getOperand(2));
   10721   }
   10722 
   10723   // SSE/AVX immediate shift intrinsics
   10724   case Intrinsic::x86_sse2_pslli_w:
   10725   case Intrinsic::x86_sse2_pslli_d:
   10726   case Intrinsic::x86_sse2_pslli_q:
   10727   case Intrinsic::x86_avx2_pslli_w:
   10728   case Intrinsic::x86_avx2_pslli_d:
   10729   case Intrinsic::x86_avx2_pslli_q:
   10730   case Intrinsic::x86_sse2_psrli_w:
   10731   case Intrinsic::x86_sse2_psrli_d:
   10732   case Intrinsic::x86_sse2_psrli_q:
   10733   case Intrinsic::x86_avx2_psrli_w:
   10734   case Intrinsic::x86_avx2_psrli_d:
   10735   case Intrinsic::x86_avx2_psrli_q:
   10736   case Intrinsic::x86_sse2_psrai_w:
   10737   case Intrinsic::x86_sse2_psrai_d:
   10738   case Intrinsic::x86_avx2_psrai_w:
   10739   case Intrinsic::x86_avx2_psrai_d: {
   10740     unsigned Opcode;
   10741     switch (IntNo) {
   10742     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10743     case Intrinsic::x86_sse2_pslli_w:
   10744     case Intrinsic::x86_sse2_pslli_d:
   10745     case Intrinsic::x86_sse2_pslli_q:
   10746     case Intrinsic::x86_avx2_pslli_w:
   10747     case Intrinsic::x86_avx2_pslli_d:
   10748     case Intrinsic::x86_avx2_pslli_q:
   10749       Opcode = X86ISD::VSHLI;
   10750       break;
   10751     case Intrinsic::x86_sse2_psrli_w:
   10752     case Intrinsic::x86_sse2_psrli_d:
   10753     case Intrinsic::x86_sse2_psrli_q:
   10754     case Intrinsic::x86_avx2_psrli_w:
   10755     case Intrinsic::x86_avx2_psrli_d:
   10756     case Intrinsic::x86_avx2_psrli_q:
   10757       Opcode = X86ISD::VSRLI;
   10758       break;
   10759     case Intrinsic::x86_sse2_psrai_w:
   10760     case Intrinsic::x86_sse2_psrai_d:
   10761     case Intrinsic::x86_avx2_psrai_w:
   10762     case Intrinsic::x86_avx2_psrai_d:
   10763       Opcode = X86ISD::VSRAI;
   10764       break;
   10765     }
   10766     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
   10767                                Op.getOperand(1), Op.getOperand(2), DAG);
   10768   }
   10769 
   10770   case Intrinsic::x86_sse42_pcmpistria128:
   10771   case Intrinsic::x86_sse42_pcmpestria128:
   10772   case Intrinsic::x86_sse42_pcmpistric128:
   10773   case Intrinsic::x86_sse42_pcmpestric128:
   10774   case Intrinsic::x86_sse42_pcmpistrio128:
   10775   case Intrinsic::x86_sse42_pcmpestrio128:
   10776   case Intrinsic::x86_sse42_pcmpistris128:
   10777   case Intrinsic::x86_sse42_pcmpestris128:
   10778   case Intrinsic::x86_sse42_pcmpistriz128:
   10779   case Intrinsic::x86_sse42_pcmpestriz128: {
   10780     unsigned Opcode;
   10781     unsigned X86CC;
   10782     switch (IntNo) {
   10783     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10784     case Intrinsic::x86_sse42_pcmpistria128:
   10785       Opcode = X86ISD::PCMPISTRI;
   10786       X86CC = X86::COND_A;
   10787       break;
   10788     case Intrinsic::x86_sse42_pcmpestria128:
   10789       Opcode = X86ISD::PCMPESTRI;
   10790       X86CC = X86::COND_A;
   10791       break;
   10792     case Intrinsic::x86_sse42_pcmpistric128:
   10793       Opcode = X86ISD::PCMPISTRI;
   10794       X86CC = X86::COND_B;
   10795       break;
   10796     case Intrinsic::x86_sse42_pcmpestric128:
   10797       Opcode = X86ISD::PCMPESTRI;
   10798       X86CC = X86::COND_B;
   10799       break;
   10800     case Intrinsic::x86_sse42_pcmpistrio128:
   10801       Opcode = X86ISD::PCMPISTRI;
   10802       X86CC = X86::COND_O;
   10803       break;
   10804     case Intrinsic::x86_sse42_pcmpestrio128:
   10805       Opcode = X86ISD::PCMPESTRI;
   10806       X86CC = X86::COND_O;
   10807       break;
   10808     case Intrinsic::x86_sse42_pcmpistris128:
   10809       Opcode = X86ISD::PCMPISTRI;
   10810       X86CC = X86::COND_S;
   10811       break;
   10812     case Intrinsic::x86_sse42_pcmpestris128:
   10813       Opcode = X86ISD::PCMPESTRI;
   10814       X86CC = X86::COND_S;
   10815       break;
   10816     case Intrinsic::x86_sse42_pcmpistriz128:
   10817       Opcode = X86ISD::PCMPISTRI;
   10818       X86CC = X86::COND_E;
   10819       break;
   10820     case Intrinsic::x86_sse42_pcmpestriz128:
   10821       Opcode = X86ISD::PCMPESTRI;
   10822       X86CC = X86::COND_E;
   10823       break;
   10824     }
   10825     SmallVector<SDValue, 5> NewOps;
   10826     NewOps.append(Op->op_begin()+1, Op->op_end());
   10827     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
   10828     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
   10829     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
   10830                                 DAG.getConstant(X86CC, MVT::i8),
   10831                                 SDValue(PCMP.getNode(), 1));
   10832     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
   10833   }
   10834 
   10835   case Intrinsic::x86_sse42_pcmpistri128:
   10836   case Intrinsic::x86_sse42_pcmpestri128: {
   10837     unsigned Opcode;
   10838     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
   10839       Opcode = X86ISD::PCMPISTRI;
   10840     else
   10841       Opcode = X86ISD::PCMPESTRI;
   10842 
   10843     SmallVector<SDValue, 5> NewOps;
   10844     NewOps.append(Op->op_begin()+1, Op->op_end());
   10845     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
   10846     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
   10847   }
   10848   case Intrinsic::x86_fma_vfmadd_ps:
   10849   case Intrinsic::x86_fma_vfmadd_pd:
   10850   case Intrinsic::x86_fma_vfmsub_ps:
   10851   case Intrinsic::x86_fma_vfmsub_pd:
   10852   case Intrinsic::x86_fma_vfnmadd_ps:
   10853   case Intrinsic::x86_fma_vfnmadd_pd:
   10854   case Intrinsic::x86_fma_vfnmsub_ps:
   10855   case Intrinsic::x86_fma_vfnmsub_pd:
   10856   case Intrinsic::x86_fma_vfmaddsub_ps:
   10857   case Intrinsic::x86_fma_vfmaddsub_pd:
   10858   case Intrinsic::x86_fma_vfmsubadd_ps:
   10859   case Intrinsic::x86_fma_vfmsubadd_pd:
   10860   case Intrinsic::x86_fma_vfmadd_ps_256:
   10861   case Intrinsic::x86_fma_vfmadd_pd_256:
   10862   case Intrinsic::x86_fma_vfmsub_ps_256:
   10863   case Intrinsic::x86_fma_vfmsub_pd_256:
   10864   case Intrinsic::x86_fma_vfnmadd_ps_256:
   10865   case Intrinsic::x86_fma_vfnmadd_pd_256:
   10866   case Intrinsic::x86_fma_vfnmsub_ps_256:
   10867   case Intrinsic::x86_fma_vfnmsub_pd_256:
   10868   case Intrinsic::x86_fma_vfmaddsub_ps_256:
   10869   case Intrinsic::x86_fma_vfmaddsub_pd_256:
   10870   case Intrinsic::x86_fma_vfmsubadd_ps_256:
   10871   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
   10872     unsigned Opc;
   10873     switch (IntNo) {
   10874     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   10875     case Intrinsic::x86_fma_vfmadd_ps:
   10876     case Intrinsic::x86_fma_vfmadd_pd:
   10877     case Intrinsic::x86_fma_vfmadd_ps_256:
   10878     case Intrinsic::x86_fma_vfmadd_pd_256:
   10879       Opc = X86ISD::FMADD;
   10880       break;
   10881     case Intrinsic::x86_fma_vfmsub_ps:
   10882     case Intrinsic::x86_fma_vfmsub_pd:
   10883     case Intrinsic::x86_fma_vfmsub_ps_256:
   10884     case Intrinsic::x86_fma_vfmsub_pd_256:
   10885       Opc = X86ISD::FMSUB;
   10886       break;
   10887     case Intrinsic::x86_fma_vfnmadd_ps:
   10888     case Intrinsic::x86_fma_vfnmadd_pd:
   10889     case Intrinsic::x86_fma_vfnmadd_ps_256:
   10890     case Intrinsic::x86_fma_vfnmadd_pd_256:
   10891       Opc = X86ISD::FNMADD;
   10892       break;
   10893     case Intrinsic::x86_fma_vfnmsub_ps:
   10894     case Intrinsic::x86_fma_vfnmsub_pd:
   10895     case Intrinsic::x86_fma_vfnmsub_ps_256:
   10896     case Intrinsic::x86_fma_vfnmsub_pd_256:
   10897       Opc = X86ISD::FNMSUB;
   10898       break;
   10899     case Intrinsic::x86_fma_vfmaddsub_ps:
   10900     case Intrinsic::x86_fma_vfmaddsub_pd:
   10901     case Intrinsic::x86_fma_vfmaddsub_ps_256:
   10902     case Intrinsic::x86_fma_vfmaddsub_pd_256:
   10903       Opc = X86ISD::FMADDSUB;
   10904       break;
   10905     case Intrinsic::x86_fma_vfmsubadd_ps:
   10906     case Intrinsic::x86_fma_vfmsubadd_pd:
   10907     case Intrinsic::x86_fma_vfmsubadd_ps_256:
   10908     case Intrinsic::x86_fma_vfmsubadd_pd_256:
   10909       Opc = X86ISD::FMSUBADD;
   10910       break;
   10911     }
   10912 
   10913     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
   10914                        Op.getOperand(2), Op.getOperand(3));
   10915   }
   10916   }
   10917 }
   10918 
   10919 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
   10920   DebugLoc dl = Op.getDebugLoc();
   10921   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
   10922   switch (IntNo) {
   10923   default: return SDValue();    // Don't custom lower most intrinsics.
   10924 
   10925   // RDRAND intrinsics.
   10926   case Intrinsic::x86_rdrand_16:
   10927   case Intrinsic::x86_rdrand_32:
   10928   case Intrinsic::x86_rdrand_64: {
   10929     // Emit the node with the right value type.
   10930     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
   10931     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
   10932 
   10933     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
   10934     // return the value from Rand, which is always 0, casted to i32.
   10935     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
   10936                       DAG.getConstant(1, Op->getValueType(1)),
   10937                       DAG.getConstant(X86::COND_B, MVT::i32),
   10938                       SDValue(Result.getNode(), 1) };
   10939     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
   10940                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
   10941                                   Ops, 4);
   10942 
   10943     // Return { result, isValid, chain }.
   10944     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
   10945                        SDValue(Result.getNode(), 2));
   10946   }
   10947   }
   10948 }
   10949 
   10950 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
   10951                                            SelectionDAG &DAG) const {
   10952   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
   10953   MFI->setReturnAddressIsTaken(true);
   10954 
   10955   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   10956   DebugLoc dl = Op.getDebugLoc();
   10957   EVT PtrVT = getPointerTy();
   10958 
   10959   if (Depth > 0) {
   10960     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
   10961     SDValue Offset =
   10962       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
   10963     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
   10964                        DAG.getNode(ISD::ADD, dl, PtrVT,
   10965                                    FrameAddr, Offset),
   10966                        MachinePointerInfo(), false, false, false, 0);
   10967   }
   10968 
   10969   // Just load the return address.
   10970   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
   10971   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
   10972                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
   10973 }
   10974 
   10975 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
   10976   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
   10977   MFI->setFrameAddressIsTaken(true);
   10978 
   10979   EVT VT = Op.getValueType();
   10980   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
   10981   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   10982   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
   10983   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
   10984   while (Depth--)
   10985     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
   10986                             MachinePointerInfo(),
   10987                             false, false, false, 0);
   10988   return FrameAddr;
   10989 }
   10990 
   10991 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
   10992                                                      SelectionDAG &DAG) const {
   10993   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
   10994 }
   10995 
   10996 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
   10997   SDValue Chain     = Op.getOperand(0);
   10998   SDValue Offset    = Op.getOperand(1);
   10999   SDValue Handler   = Op.getOperand(2);
   11000   DebugLoc dl       = Op.getDebugLoc();
   11001 
   11002   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
   11003                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
   11004                                      getPointerTy());
   11005   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
   11006 
   11007   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
   11008                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
   11009   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
   11010   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
   11011                        false, false, 0);
   11012   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
   11013 
   11014   return DAG.getNode(X86ISD::EH_RETURN, dl,
   11015                      MVT::Other,
   11016                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
   11017 }
   11018 
   11019 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
   11020                                                SelectionDAG &DAG) const {
   11021   DebugLoc DL = Op.getDebugLoc();
   11022   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
   11023                      DAG.getVTList(MVT::i32, MVT::Other),
   11024                      Op.getOperand(0), Op.getOperand(1));
   11025 }
   11026 
   11027 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
   11028                                                 SelectionDAG &DAG) const {
   11029   DebugLoc DL = Op.getDebugLoc();
   11030   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
   11031                      Op.getOperand(0), Op.getOperand(1));
   11032 }
   11033 
   11034 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
   11035   return Op.getOperand(0);
   11036 }
   11037 
   11038 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
   11039                                                 SelectionDAG &DAG) const {
   11040   SDValue Root = Op.getOperand(0);
   11041   SDValue Trmp = Op.getOperand(1); // trampoline
   11042   SDValue FPtr = Op.getOperand(2); // nested function
   11043   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
   11044   DebugLoc dl  = Op.getDebugLoc();
   11045 
   11046   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
   11047   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
   11048 
   11049   if (Subtarget->is64Bit()) {
   11050     SDValue OutChains[6];
   11051 
   11052     // Large code-model.
   11053     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
   11054     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
   11055 
   11056     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
   11057     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
   11058 
   11059     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
   11060 
   11061     // Load the pointer to the nested function into R11.
   11062     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
   11063     SDValue Addr = Trmp;
   11064     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
   11065                                 Addr, MachinePointerInfo(TrmpAddr),
   11066                                 false, false, 0);
   11067 
   11068     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
   11069                        DAG.getConstant(2, MVT::i64));
   11070     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
   11071                                 MachinePointerInfo(TrmpAddr, 2),
   11072                                 false, false, 2);
   11073 
   11074     // Load the 'nest' parameter value into R10.
   11075     // R10 is specified in X86CallingConv.td
   11076     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
   11077     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
   11078                        DAG.getConstant(10, MVT::i64));
   11079     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
   11080                                 Addr, MachinePointerInfo(TrmpAddr, 10),
   11081                                 false, false, 0);
   11082 
   11083     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
   11084                        DAG.getConstant(12, MVT::i64));
   11085     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
   11086                                 MachinePointerInfo(TrmpAddr, 12),
   11087                                 false, false, 2);
   11088 
   11089     // Jump to the nested function.
   11090     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
   11091     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
   11092                        DAG.getConstant(20, MVT::i64));
   11093     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
   11094                                 Addr, MachinePointerInfo(TrmpAddr, 20),
   11095                                 false, false, 0);
   11096 
   11097     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
   11098     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
   11099                        DAG.getConstant(22, MVT::i64));
   11100     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
   11101                                 MachinePointerInfo(TrmpAddr, 22),
   11102                                 false, false, 0);
   11103 
   11104     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
   11105   } else {
   11106     const Function *Func =
   11107       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
   11108     CallingConv::ID CC = Func->getCallingConv();
   11109     unsigned NestReg;
   11110 
   11111     switch (CC) {
   11112     default:
   11113       llvm_unreachable("Unsupported calling convention");
   11114     case CallingConv::C:
   11115     case CallingConv::X86_StdCall: {
   11116       // Pass 'nest' parameter in ECX.
   11117       // Must be kept in sync with X86CallingConv.td
   11118       NestReg = X86::ECX;
   11119 
   11120       // Check that ECX wasn't needed by an 'inreg' parameter.
   11121       FunctionType *FTy = Func->getFunctionType();
   11122       const AttributeSet &Attrs = Func->getAttributes();
   11123 
   11124       if (!Attrs.isEmpty() && !Func->isVarArg()) {
   11125         unsigned InRegCount = 0;
   11126         unsigned Idx = 1;
   11127 
   11128         for (FunctionType::param_iterator I = FTy->param_begin(),
   11129              E = FTy->param_end(); I != E; ++I, ++Idx)
   11130           if (Attrs.hasAttribute(Idx, Attribute::InReg))
   11131             // FIXME: should only count parameters that are lowered to integers.
   11132             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
   11133 
   11134         if (InRegCount > 2) {
   11135           report_fatal_error("Nest register in use - reduce number of inreg"
   11136                              " parameters!");
   11137         }
   11138       }
   11139       break;
   11140     }
   11141     case CallingConv::X86_FastCall:
   11142     case CallingConv::X86_ThisCall:
   11143     case CallingConv::Fast:
   11144       // Pass 'nest' parameter in EAX.
   11145       // Must be kept in sync with X86CallingConv.td
   11146       NestReg = X86::EAX;
   11147       break;
   11148     }
   11149 
   11150     SDValue OutChains[4];
   11151     SDValue Addr, Disp;
   11152 
   11153     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
   11154                        DAG.getConstant(10, MVT::i32));
   11155     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
   11156 
   11157     // This is storing the opcode for MOV32ri.
   11158     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
   11159     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
   11160     OutChains[0] = DAG.getStore(Root, dl,
   11161                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
   11162                                 Trmp, MachinePointerInfo(TrmpAddr),
   11163                                 false, false, 0);
   11164 
   11165     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
   11166                        DAG.getConstant(1, MVT::i32));
   11167     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
   11168                                 MachinePointerInfo(TrmpAddr, 1),
   11169                                 false, false, 1);
   11170 
   11171     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
   11172     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
   11173                        DAG.getConstant(5, MVT::i32));
   11174     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
   11175                                 MachinePointerInfo(TrmpAddr, 5),
   11176                                 false, false, 1);
   11177 
   11178     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
   11179                        DAG.getConstant(6, MVT::i32));
   11180     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
   11181                                 MachinePointerInfo(TrmpAddr, 6),
   11182                                 false, false, 1);
   11183 
   11184     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
   11185   }
   11186 }
   11187 
   11188 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
   11189                                             SelectionDAG &DAG) const {
   11190   /*
   11191    The rounding mode is in bits 11:10 of FPSR, and has the following
   11192    settings:
   11193      00 Round to nearest
   11194      01 Round to -inf
   11195      10 Round to +inf
   11196      11 Round to 0
   11197 
   11198   FLT_ROUNDS, on the other hand, expects the following:
   11199     -1 Undefined
   11200      0 Round to 0
   11201      1 Round to nearest
   11202      2 Round to +inf
   11203      3 Round to -inf
   11204 
   11205   To perform the conversion, we do:
   11206     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
   11207   */
   11208 
   11209   MachineFunction &MF = DAG.getMachineFunction();
   11210   const TargetMachine &TM = MF.getTarget();
   11211   const TargetFrameLowering &TFI = *TM.getFrameLowering();
   11212   unsigned StackAlignment = TFI.getStackAlignment();
   11213   EVT VT = Op.getValueType();
   11214   DebugLoc DL = Op.getDebugLoc();
   11215 
   11216   // Save FP Control Word to stack slot
   11217   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
   11218   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
   11219 
   11220   MachineMemOperand *MMO =
   11221    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
   11222                            MachineMemOperand::MOStore, 2, 2);
   11223 
   11224   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
   11225   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
   11226                                           DAG.getVTList(MVT::Other),
   11227                                           Ops, 2, MVT::i16, MMO);
   11228 
   11229   // Load FP Control Word from stack slot
   11230   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
   11231                             MachinePointerInfo(), false, false, false, 0);
   11232 
   11233   // Transform as necessary
   11234   SDValue CWD1 =
   11235     DAG.getNode(ISD::SRL, DL, MVT::i16,
   11236                 DAG.getNode(ISD::AND, DL, MVT::i16,
   11237                             CWD, DAG.getConstant(0x800, MVT::i16)),
   11238                 DAG.getConstant(11, MVT::i8));
   11239   SDValue CWD2 =
   11240     DAG.getNode(ISD::SRL, DL, MVT::i16,
   11241                 DAG.getNode(ISD::AND, DL, MVT::i16,
   11242                             CWD, DAG.getConstant(0x400, MVT::i16)),
   11243                 DAG.getConstant(9, MVT::i8));
   11244 
   11245   SDValue RetVal =
   11246     DAG.getNode(ISD::AND, DL, MVT::i16,
   11247                 DAG.getNode(ISD::ADD, DL, MVT::i16,
   11248                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
   11249                             DAG.getConstant(1, MVT::i16)),
   11250                 DAG.getConstant(3, MVT::i16));
   11251 
   11252   return DAG.getNode((VT.getSizeInBits() < 16 ?
   11253                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
   11254 }
   11255 
   11256 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
   11257   EVT VT = Op.getValueType();
   11258   EVT OpVT = VT;
   11259   unsigned NumBits = VT.getSizeInBits();
   11260   DebugLoc dl = Op.getDebugLoc();
   11261 
   11262   Op = Op.getOperand(0);
   11263   if (VT == MVT::i8) {
   11264     // Zero extend to i32 since there is not an i8 bsr.
   11265     OpVT = MVT::i32;
   11266     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
   11267   }
   11268 
   11269   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
   11270   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
   11271   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
   11272 
   11273   // If src is zero (i.e. bsr sets ZF), returns NumBits.
   11274   SDValue Ops[] = {
   11275     Op,
   11276     DAG.getConstant(NumBits+NumBits-1, OpVT),
   11277     DAG.getConstant(X86::COND_E, MVT::i8),
   11278     Op.getValue(1)
   11279   };
   11280   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
   11281 
   11282   // Finally xor with NumBits-1.
   11283   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
   11284 
   11285   if (VT == MVT::i8)
   11286     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
   11287   return Op;
   11288 }
   11289 
   11290 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
   11291   EVT VT = Op.getValueType();
   11292   EVT OpVT = VT;
   11293   unsigned NumBits = VT.getSizeInBits();
   11294   DebugLoc dl = Op.getDebugLoc();
   11295 
   11296   Op = Op.getOperand(0);
   11297   if (VT == MVT::i8) {
   11298     // Zero extend to i32 since there is not an i8 bsr.
   11299     OpVT = MVT::i32;
   11300     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
   11301   }
   11302 
   11303   // Issue a bsr (scan bits in reverse).
   11304   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
   11305   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
   11306 
   11307   // And xor with NumBits-1.
   11308   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
   11309 
   11310   if (VT == MVT::i8)
   11311     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
   11312   return Op;
   11313 }
   11314 
   11315 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
   11316   EVT VT = Op.getValueType();
   11317   unsigned NumBits = VT.getSizeInBits();
   11318   DebugLoc dl = Op.getDebugLoc();
   11319   Op = Op.getOperand(0);
   11320 
   11321   // Issue a bsf (scan bits forward) which also sets EFLAGS.
   11322   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
   11323   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
   11324 
   11325   // If src is zero (i.e. bsf sets ZF), returns NumBits.
   11326   SDValue Ops[] = {
   11327     Op,
   11328     DAG.getConstant(NumBits, VT),
   11329     DAG.getConstant(X86::COND_E, MVT::i8),
   11330     Op.getValue(1)
   11331   };
   11332   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
   11333 }
   11334 
   11335 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
   11336 // ones, and then concatenate the result back.
   11337 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
   11338   EVT VT = Op.getValueType();
   11339 
   11340   assert(VT.is256BitVector() && VT.isInteger() &&
   11341          "Unsupported value type for operation");
   11342 
   11343   unsigned NumElems = VT.getVectorNumElements();
   11344   DebugLoc dl = Op.getDebugLoc();
   11345 
   11346   // Extract the LHS vectors
   11347   SDValue LHS = Op.getOperand(0);
   11348   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
   11349   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
   11350 
   11351   // Extract the RHS vectors
   11352   SDValue RHS = Op.getOperand(1);
   11353   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
   11354   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
   11355 
   11356   MVT EltVT = VT.getVectorElementType().getSimpleVT();
   11357   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
   11358 
   11359   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
   11360                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
   11361                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
   11362 }
   11363 
   11364 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
   11365   assert(Op.getValueType().is256BitVector() &&
   11366          Op.getValueType().isInteger() &&
   11367          "Only handle AVX 256-bit vector integer operation");
   11368   return Lower256IntArith(Op, DAG);
   11369 }
   11370 
   11371 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
   11372   assert(Op.getValueType().is256BitVector() &&
   11373          Op.getValueType().isInteger() &&
   11374          "Only handle AVX 256-bit vector integer operation");
   11375   return Lower256IntArith(Op, DAG);
   11376 }
   11377 
   11378 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
   11379                         SelectionDAG &DAG) {
   11380   DebugLoc dl = Op.getDebugLoc();
   11381   EVT VT = Op.getValueType();
   11382 
   11383   // Decompose 256-bit ops into smaller 128-bit ops.
   11384   if (VT.is256BitVector() && !Subtarget->hasInt256())
   11385     return Lower256IntArith(Op, DAG);
   11386 
   11387   SDValue A = Op.getOperand(0);
   11388   SDValue B = Op.getOperand(1);
   11389 
   11390   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
   11391   if (VT == MVT::v4i32) {
   11392     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
   11393            "Should not custom lower when pmuldq is available!");
   11394 
   11395     // Extract the odd parts.
   11396     const int UnpackMask[] = { 1, -1, 3, -1 };
   11397     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
   11398     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
   11399 
   11400     // Multiply the even parts.
   11401     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
   11402     // Now multiply odd parts.
   11403     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
   11404 
   11405     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
   11406     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
   11407 
   11408     // Merge the two vectors back together with a shuffle. This expands into 2
   11409     // shuffles.
   11410     const int ShufMask[] = { 0, 4, 2, 6 };
   11411     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
   11412   }
   11413 
   11414   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
   11415          "Only know how to lower V2I64/V4I64 multiply");
   11416 
   11417   //  Ahi = psrlqi(a, 32);
   11418   //  Bhi = psrlqi(b, 32);
   11419   //
   11420   //  AloBlo = pmuludq(a, b);
   11421   //  AloBhi = pmuludq(a, Bhi);
   11422   //  AhiBlo = pmuludq(Ahi, b);
   11423 
   11424   //  AloBhi = psllqi(AloBhi, 32);
   11425   //  AhiBlo = psllqi(AhiBlo, 32);
   11426   //  return AloBlo + AloBhi + AhiBlo;
   11427 
   11428   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
   11429 
   11430   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
   11431   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
   11432 
   11433   // Bit cast to 32-bit vectors for MULUDQ
   11434   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
   11435   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
   11436   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
   11437   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
   11438   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
   11439 
   11440   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
   11441   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
   11442   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
   11443 
   11444   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
   11445   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
   11446 
   11447   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
   11448   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
   11449 }
   11450 
   11451 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
   11452   EVT VT = Op.getValueType();
   11453   EVT EltTy = VT.getVectorElementType();
   11454   unsigned NumElts = VT.getVectorNumElements();
   11455   SDValue N0 = Op.getOperand(0);
   11456   DebugLoc dl = Op.getDebugLoc();
   11457 
   11458   // Lower sdiv X, pow2-const.
   11459   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
   11460   if (!C)
   11461     return SDValue();
   11462 
   11463   APInt SplatValue, SplatUndef;
   11464   unsigned MinSplatBits;
   11465   bool HasAnyUndefs;
   11466   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
   11467     return SDValue();
   11468 
   11469   if ((SplatValue != 0) &&
   11470       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
   11471     unsigned lg2 = SplatValue.countTrailingZeros();
   11472     // Splat the sign bit.
   11473     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
   11474     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
   11475     // Add (N0 < 0) ? abs2 - 1 : 0;
   11476     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
   11477     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
   11478     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
   11479     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
   11480     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
   11481 
   11482     // If we're dividing by a positive value, we're done.  Otherwise, we must
   11483     // negate the result.
   11484     if (SplatValue.isNonNegative())
   11485       return SRA;
   11486 
   11487     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
   11488     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
   11489     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
   11490   }
   11491   return SDValue();
   11492 }
   11493 
   11494 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
   11495 
   11496   EVT VT = Op.getValueType();
   11497   DebugLoc dl = Op.getDebugLoc();
   11498   SDValue R = Op.getOperand(0);
   11499   SDValue Amt = Op.getOperand(1);
   11500 
   11501   if (!Subtarget->hasSSE2())
   11502     return SDValue();
   11503 
   11504   // Optimize shl/srl/sra with constant shift amount.
   11505   if (isSplatVector(Amt.getNode())) {
   11506     SDValue SclrAmt = Amt->getOperand(0);
   11507     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
   11508       uint64_t ShiftAmt = C->getZExtValue();
   11509 
   11510       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
   11511           (Subtarget->hasInt256() &&
   11512            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
   11513         if (Op.getOpcode() == ISD::SHL)
   11514           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
   11515                              DAG.getConstant(ShiftAmt, MVT::i32));
   11516         if (Op.getOpcode() == ISD::SRL)
   11517           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
   11518                              DAG.getConstant(ShiftAmt, MVT::i32));
   11519         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
   11520           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
   11521                              DAG.getConstant(ShiftAmt, MVT::i32));
   11522       }
   11523 
   11524       if (VT == MVT::v16i8) {
   11525         if (Op.getOpcode() == ISD::SHL) {
   11526           // Make a large shift.
   11527           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
   11528                                     DAG.getConstant(ShiftAmt, MVT::i32));
   11529           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
   11530           // Zero out the rightmost bits.
   11531           SmallVector<SDValue, 16> V(16,
   11532                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
   11533                                                      MVT::i8));
   11534           return DAG.getNode(ISD::AND, dl, VT, SHL,
   11535                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
   11536         }
   11537         if (Op.getOpcode() == ISD::SRL) {
   11538           // Make a large shift.
   11539           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
   11540                                     DAG.getConstant(ShiftAmt, MVT::i32));
   11541           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
   11542           // Zero out the leftmost bits.
   11543           SmallVector<SDValue, 16> V(16,
   11544                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
   11545                                                      MVT::i8));
   11546           return DAG.getNode(ISD::AND, dl, VT, SRL,
   11547                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
   11548         }
   11549         if (Op.getOpcode() == ISD::SRA) {
   11550           if (ShiftAmt == 7) {
   11551             // R s>> 7  ===  R s< 0
   11552             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
   11553             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
   11554           }
   11555 
   11556           // R s>> a === ((R u>> a) ^ m) - m
   11557           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
   11558           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
   11559                                                          MVT::i8));
   11560           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
   11561           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
   11562           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
   11563           return Res;
   11564         }
   11565         llvm_unreachable("Unknown shift opcode.");
   11566       }
   11567 
   11568       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
   11569         if (Op.getOpcode() == ISD::SHL) {
   11570           // Make a large shift.
   11571           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
   11572                                     DAG.getConstant(ShiftAmt, MVT::i32));
   11573           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
   11574           // Zero out the rightmost bits.
   11575           SmallVector<SDValue, 32> V(32,
   11576                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
   11577                                                      MVT::i8));
   11578           return DAG.getNode(ISD::AND, dl, VT, SHL,
   11579                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
   11580         }
   11581         if (Op.getOpcode() == ISD::SRL) {
   11582           // Make a large shift.
   11583           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
   11584                                     DAG.getConstant(ShiftAmt, MVT::i32));
   11585           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
   11586           // Zero out the leftmost bits.
   11587           SmallVector<SDValue, 32> V(32,
   11588                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
   11589                                                      MVT::i8));
   11590           return DAG.getNode(ISD::AND, dl, VT, SRL,
   11591                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
   11592         }
   11593         if (Op.getOpcode() == ISD::SRA) {
   11594           if (ShiftAmt == 7) {
   11595             // R s>> 7  ===  R s< 0
   11596             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
   11597             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
   11598           }
   11599 
   11600           // R s>> a === ((R u>> a) ^ m) - m
   11601           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
   11602           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
   11603                                                          MVT::i8));
   11604           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
   11605           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
   11606           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
   11607           return Res;
   11608         }
   11609         llvm_unreachable("Unknown shift opcode.");
   11610       }
   11611     }
   11612   }
   11613 
   11614   // Lower SHL with variable shift amount.
   11615   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
   11616     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
   11617 
   11618     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
   11619     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
   11620     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
   11621     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
   11622   }
   11623   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
   11624     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
   11625 
   11626     // a = a << 5;
   11627     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
   11628     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
   11629 
   11630     // Turn 'a' into a mask suitable for VSELECT
   11631     SDValue VSelM = DAG.getConstant(0x80, VT);
   11632     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
   11633     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
   11634 
   11635     SDValue CM1 = DAG.getConstant(0x0f, VT);
   11636     SDValue CM2 = DAG.getConstant(0x3f, VT);
   11637 
   11638     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
   11639     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
   11640     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
   11641                             DAG.getConstant(4, MVT::i32), DAG);
   11642     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
   11643     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
   11644 
   11645     // a += a
   11646     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
   11647     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
   11648     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
   11649 
   11650     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
   11651     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
   11652     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
   11653                             DAG.getConstant(2, MVT::i32), DAG);
   11654     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
   11655     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
   11656 
   11657     // a += a
   11658     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
   11659     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
   11660     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
   11661 
   11662     // return VSELECT(r, r+r, a);
   11663     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
   11664                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
   11665     return R;
   11666   }
   11667 
   11668   // Decompose 256-bit shifts into smaller 128-bit shifts.
   11669   if (VT.is256BitVector()) {
   11670     unsigned NumElems = VT.getVectorNumElements();
   11671     MVT EltVT = VT.getVectorElementType().getSimpleVT();
   11672     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
   11673 
   11674     // Extract the two vectors
   11675     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
   11676     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
   11677 
   11678     // Recreate the shift amount vectors
   11679     SDValue Amt1, Amt2;
   11680     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
   11681       // Constant shift amount
   11682       SmallVector<SDValue, 4> Amt1Csts;
   11683       SmallVector<SDValue, 4> Amt2Csts;
   11684       for (unsigned i = 0; i != NumElems/2; ++i)
   11685         Amt1Csts.push_back(Amt->getOperand(i));
   11686       for (unsigned i = NumElems/2; i != NumElems; ++i)
   11687         Amt2Csts.push_back(Amt->getOperand(i));
   11688 
   11689       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
   11690                                  &Amt1Csts[0], NumElems/2);
   11691       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
   11692                                  &Amt2Csts[0], NumElems/2);
   11693     } else {
   11694       // Variable shift amount
   11695       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
   11696       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
   11697     }
   11698 
   11699     // Issue new vector shifts for the smaller types
   11700     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
   11701     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
   11702 
   11703     // Concatenate the result back
   11704     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
   11705   }
   11706 
   11707   return SDValue();
   11708 }
   11709 
   11710 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
   11711   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
   11712   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
   11713   // looks for this combo and may remove the "setcc" instruction if the "setcc"
   11714   // has only one use.
   11715   SDNode *N = Op.getNode();
   11716   SDValue LHS = N->getOperand(0);
   11717   SDValue RHS = N->getOperand(1);
   11718   unsigned BaseOp = 0;
   11719   unsigned Cond = 0;
   11720   DebugLoc DL = Op.getDebugLoc();
   11721   switch (Op.getOpcode()) {
   11722   default: llvm_unreachable("Unknown ovf instruction!");
   11723   case ISD::SADDO:
   11724     // A subtract of one will be selected as a INC. Note that INC doesn't
   11725     // set CF, so we can't do this for UADDO.
   11726     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
   11727       if (C->isOne()) {
   11728         BaseOp = X86ISD::INC;
   11729         Cond = X86::COND_O;
   11730         break;
   11731       }
   11732     BaseOp = X86ISD::ADD;
   11733     Cond = X86::COND_O;
   11734     break;
   11735   case ISD::UADDO:
   11736     BaseOp = X86ISD::ADD;
   11737     Cond = X86::COND_B;
   11738     break;
   11739   case ISD::SSUBO:
   11740     // A subtract of one will be selected as a DEC. Note that DEC doesn't
   11741     // set CF, so we can't do this for USUBO.
   11742     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
   11743       if (C->isOne()) {
   11744         BaseOp = X86ISD::DEC;
   11745         Cond = X86::COND_O;
   11746         break;
   11747       }
   11748     BaseOp = X86ISD::SUB;
   11749     Cond = X86::COND_O;
   11750     break;
   11751   case ISD::USUBO:
   11752     BaseOp = X86ISD::SUB;
   11753     Cond = X86::COND_B;
   11754     break;
   11755   case ISD::SMULO:
   11756     BaseOp = X86ISD::SMUL;
   11757     Cond = X86::COND_O;
   11758     break;
   11759   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
   11760     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
   11761                                  MVT::i32);
   11762     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
   11763 
   11764     SDValue SetCC =
   11765       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
   11766                   DAG.getConstant(X86::COND_O, MVT::i32),
   11767                   SDValue(Sum.getNode(), 2));
   11768 
   11769     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
   11770   }
   11771   }
   11772 
   11773   // Also sets EFLAGS.
   11774   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
   11775   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
   11776 
   11777   SDValue SetCC =
   11778     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
   11779                 DAG.getConstant(Cond, MVT::i32),
   11780                 SDValue(Sum.getNode(), 1));
   11781 
   11782   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
   11783 }
   11784 
   11785 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
   11786                                                   SelectionDAG &DAG) const {
   11787   DebugLoc dl = Op.getDebugLoc();
   11788   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
   11789   EVT VT = Op.getValueType();
   11790 
   11791   if (!Subtarget->hasSSE2() || !VT.isVector())
   11792     return SDValue();
   11793 
   11794   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
   11795                       ExtraVT.getScalarType().getSizeInBits();
   11796   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
   11797 
   11798   switch (VT.getSimpleVT().SimpleTy) {
   11799     default: return SDValue();
   11800     case MVT::v8i32:
   11801     case MVT::v16i16:
   11802       if (!Subtarget->hasFp256())
   11803         return SDValue();
   11804       if (!Subtarget->hasInt256()) {
   11805         // needs to be split
   11806         unsigned NumElems = VT.getVectorNumElements();
   11807 
   11808         // Extract the LHS vectors
   11809         SDValue LHS = Op.getOperand(0);
   11810         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
   11811         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
   11812 
   11813         MVT EltVT = VT.getVectorElementType().getSimpleVT();
   11814         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
   11815 
   11816         EVT ExtraEltVT = ExtraVT.getVectorElementType();
   11817         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
   11818         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
   11819                                    ExtraNumElems/2);
   11820         SDValue Extra = DAG.getValueType(ExtraVT);
   11821 
   11822         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
   11823         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
   11824 
   11825         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
   11826       }
   11827       // fall through
   11828     case MVT::v4i32:
   11829     case MVT::v8i16: {
   11830       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
   11831                                          Op.getOperand(0), ShAmt, DAG);
   11832       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
   11833     }
   11834   }
   11835 }
   11836 
   11837 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
   11838                               SelectionDAG &DAG) {
   11839   DebugLoc dl = Op.getDebugLoc();
   11840 
   11841   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
   11842   // There isn't any reason to disable it if the target processor supports it.
   11843   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
   11844     SDValue Chain = Op.getOperand(0);
   11845     SDValue Zero = DAG.getConstant(0, MVT::i32);
   11846     SDValue Ops[] = {
   11847       DAG.getRegister(X86::ESP, MVT::i32), // Base
   11848       DAG.getTargetConstant(1, MVT::i8),   // Scale
   11849       DAG.getRegister(0, MVT::i32),        // Index
   11850       DAG.getTargetConstant(0, MVT::i32),  // Disp
   11851       DAG.getRegister(0, MVT::i32),        // Segment.
   11852       Zero,
   11853       Chain
   11854     };
   11855     SDNode *Res =
   11856       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
   11857                           array_lengthof(Ops));
   11858     return SDValue(Res, 0);
   11859   }
   11860 
   11861   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
   11862   if (!isDev)
   11863     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
   11864 
   11865   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
   11866   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
   11867   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
   11868   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
   11869 
   11870   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
   11871   if (!Op1 && !Op2 && !Op3 && Op4)
   11872     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
   11873 
   11874   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
   11875   if (Op1 && !Op2 && !Op3 && !Op4)
   11876     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
   11877 
   11878   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
   11879   //           (MFENCE)>;
   11880   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
   11881 }
   11882 
   11883 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
   11884                                  SelectionDAG &DAG) {
   11885   DebugLoc dl = Op.getDebugLoc();
   11886   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
   11887     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
   11888   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
   11889     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
   11890 
   11891   // The only fence that needs an instruction is a sequentially-consistent
   11892   // cross-thread fence.
   11893   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
   11894     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
   11895     // no-sse2). There isn't any reason to disable it if the target processor
   11896     // supports it.
   11897     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
   11898       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
   11899 
   11900     SDValue Chain = Op.getOperand(0);
   11901     SDValue Zero = DAG.getConstant(0, MVT::i32);
   11902     SDValue Ops[] = {
   11903       DAG.getRegister(X86::ESP, MVT::i32), // Base
   11904       DAG.getTargetConstant(1, MVT::i8),   // Scale
   11905       DAG.getRegister(0, MVT::i32),        // Index
   11906       DAG.getTargetConstant(0, MVT::i32),  // Disp
   11907       DAG.getRegister(0, MVT::i32),        // Segment.
   11908       Zero,
   11909       Chain
   11910     };
   11911     SDNode *Res =
   11912       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
   11913                          array_lengthof(Ops));
   11914     return SDValue(Res, 0);
   11915   }
   11916 
   11917   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
   11918   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
   11919 }
   11920 
   11921 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
   11922                              SelectionDAG &DAG) {
   11923   EVT T = Op.getValueType();
   11924   DebugLoc DL = Op.getDebugLoc();
   11925   unsigned Reg = 0;
   11926   unsigned size = 0;
   11927   switch(T.getSimpleVT().SimpleTy) {
   11928   default: llvm_unreachable("Invalid value type!");
   11929   case MVT::i8:  Reg = X86::AL;  size = 1; break;
   11930   case MVT::i16: Reg = X86::AX;  size = 2; break;
   11931   case MVT::i32: Reg = X86::EAX; size = 4; break;
   11932   case MVT::i64:
   11933     assert(Subtarget->is64Bit() && "Node not type legal!");
   11934     Reg = X86::RAX; size = 8;
   11935     break;
   11936   }
   11937   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
   11938                                     Op.getOperand(2), SDValue());
   11939   SDValue Ops[] = { cpIn.getValue(0),
   11940                     Op.getOperand(1),
   11941                     Op.getOperand(3),
   11942                     DAG.getTargetConstant(size, MVT::i8),
   11943                     cpIn.getValue(1) };
   11944   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
   11945   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
   11946   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
   11947                                            Ops, 5, T, MMO);
   11948   SDValue cpOut =
   11949     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
   11950   return cpOut;
   11951 }
   11952 
   11953 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
   11954                                      SelectionDAG &DAG) {
   11955   assert(Subtarget->is64Bit() && "Result not type legalized?");
   11956   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
   11957   SDValue TheChain = Op.getOperand(0);
   11958   DebugLoc dl = Op.getDebugLoc();
   11959   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
   11960   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
   11961   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
   11962                                    rax.getValue(2));
   11963   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
   11964                             DAG.getConstant(32, MVT::i8));
   11965   SDValue Ops[] = {
   11966     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
   11967     rdx.getValue(1)
   11968   };
   11969   return DAG.getMergeValues(Ops, 2, dl);
   11970 }
   11971 
   11972 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
   11973   EVT SrcVT = Op.getOperand(0).getValueType();
   11974   EVT DstVT = Op.getValueType();
   11975   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
   11976          Subtarget->hasMMX() && "Unexpected custom BITCAST");
   11977   assert((DstVT == MVT::i64 ||
   11978           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
   11979          "Unexpected custom BITCAST");
   11980   // i64 <=> MMX conversions are Legal.
   11981   if (SrcVT==MVT::i64 && DstVT.isVector())
   11982     return Op;
   11983   if (DstVT==MVT::i64 && SrcVT.isVector())
   11984     return Op;
   11985   // MMX <=> MMX conversions are Legal.
   11986   if (SrcVT.isVector() && DstVT.isVector())
   11987     return Op;
   11988   // All other conversions need to be expanded.
   11989   return SDValue();
   11990 }
   11991 
   11992 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
   11993   SDNode *Node = Op.getNode();
   11994   DebugLoc dl = Node->getDebugLoc();
   11995   EVT T = Node->getValueType(0);
   11996   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
   11997                               DAG.getConstant(0, T), Node->getOperand(2));
   11998   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
   11999                        cast<AtomicSDNode>(Node)->getMemoryVT(),
   12000                        Node->getOperand(0),
   12001                        Node->getOperand(1), negOp,
   12002                        cast<AtomicSDNode>(Node)->getSrcValue(),
   12003                        cast<AtomicSDNode>(Node)->getAlignment(),
   12004                        cast<AtomicSDNode>(Node)->getOrdering(),
   12005                        cast<AtomicSDNode>(Node)->getSynchScope());
   12006 }
   12007 
   12008 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
   12009   SDNode *Node = Op.getNode();
   12010   DebugLoc dl = Node->getDebugLoc();
   12011   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
   12012 
   12013   // Convert seq_cst store -> xchg
   12014   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
   12015   // FIXME: On 32-bit, store -> fist or movq would be more efficient
   12016   //        (The only way to get a 16-byte store is cmpxchg16b)
   12017   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
   12018   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
   12019       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
   12020     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
   12021                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
   12022                                  Node->getOperand(0),
   12023                                  Node->getOperand(1), Node->getOperand(2),
   12024                                  cast<AtomicSDNode>(Node)->getMemOperand(),
   12025                                  cast<AtomicSDNode>(Node)->getOrdering(),
   12026                                  cast<AtomicSDNode>(Node)->getSynchScope());
   12027     return Swap.getValue(1);
   12028   }
   12029   // Other atomic stores have a simple pattern.
   12030   return Op;
   12031 }
   12032 
   12033 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
   12034   EVT VT = Op.getNode()->getValueType(0);
   12035 
   12036   // Let legalize expand this if it isn't a legal type yet.
   12037   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
   12038     return SDValue();
   12039 
   12040   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
   12041 
   12042   unsigned Opc;
   12043   bool ExtraOp = false;
   12044   switch (Op.getOpcode()) {
   12045   default: llvm_unreachable("Invalid code");
   12046   case ISD::ADDC: Opc = X86ISD::ADD; break;
   12047   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
   12048   case ISD::SUBC: Opc = X86ISD::SUB; break;
   12049   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
   12050   }
   12051 
   12052   if (!ExtraOp)
   12053     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
   12054                        Op.getOperand(1));
   12055   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
   12056                      Op.getOperand(1), Op.getOperand(2));
   12057 }
   12058 
   12059 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
   12060   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
   12061 
   12062   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
   12063   // which returns the values in two XMM registers.
   12064   DebugLoc dl = Op.getDebugLoc();
   12065   SDValue Arg = Op.getOperand(0);
   12066   EVT ArgVT = Arg.getValueType();
   12067   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
   12068 
   12069   ArgListTy Args;
   12070   ArgListEntry Entry;
   12071 
   12072   Entry.Node = Arg;
   12073   Entry.Ty = ArgTy;
   12074   Entry.isSExt = false;
   12075   Entry.isZExt = false;
   12076   Args.push_back(Entry);
   12077 
   12078   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
   12079   // the small struct {f32, f32} is returned in (eax, edx). For f64,
   12080   // the results are returned via SRet in memory.
   12081   const char *LibcallName = (ArgVT == MVT::f64)
   12082     ? "__sincos_stret" : "__sincosf_stret";
   12083   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
   12084 
   12085   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
   12086   TargetLowering::
   12087     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
   12088                          false, false, false, false, 0,
   12089                          CallingConv::C, /*isTaillCall=*/false,
   12090                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
   12091                          Callee, Args, DAG, dl);
   12092   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
   12093   return CallResult.first;
   12094 }
   12095 
   12096 /// LowerOperation - Provide custom lowering hooks for some operations.
   12097 ///
   12098 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
   12099   switch (Op.getOpcode()) {
   12100   default: llvm_unreachable("Should not custom lower this!");
   12101   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
   12102   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
   12103   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
   12104   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
   12105   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
   12106   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
   12107   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
   12108   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
   12109   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
   12110   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
   12111   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
   12112   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
   12113   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
   12114   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
   12115   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
   12116   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
   12117   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
   12118   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
   12119   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
   12120   case ISD::SHL_PARTS:
   12121   case ISD::SRA_PARTS:
   12122   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
   12123   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
   12124   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
   12125   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
   12126   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
   12127   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
   12128   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
   12129   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
   12130   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
   12131   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
   12132   case ISD::FABS:               return LowerFABS(Op, DAG);
   12133   case ISD::FNEG:               return LowerFNEG(Op, DAG);
   12134   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
   12135   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
   12136   case ISD::SETCC:              return LowerSETCC(Op, DAG);
   12137   case ISD::SELECT:             return LowerSELECT(Op, DAG);
   12138   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
   12139   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
   12140   case ISD::VASTART:            return LowerVASTART(Op, DAG);
   12141   case ISD::VAARG:              return LowerVAARG(Op, DAG);
   12142   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
   12143   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
   12144   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
   12145   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
   12146   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
   12147   case ISD::FRAME_TO_ARGS_OFFSET:
   12148                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
   12149   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
   12150   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
   12151   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
   12152   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
   12153   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
   12154   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
   12155   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
   12156   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
   12157   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
   12158   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
   12159   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
   12160   case ISD::SRA:
   12161   case ISD::SRL:
   12162   case ISD::SHL:                return LowerShift(Op, DAG);
   12163   case ISD::SADDO:
   12164   case ISD::UADDO:
   12165   case ISD::SSUBO:
   12166   case ISD::USUBO:
   12167   case ISD::SMULO:
   12168   case ISD::UMULO:              return LowerXALUO(Op, DAG);
   12169   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
   12170   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
   12171   case ISD::ADDC:
   12172   case ISD::ADDE:
   12173   case ISD::SUBC:
   12174   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
   12175   case ISD::ADD:                return LowerADD(Op, DAG);
   12176   case ISD::SUB:                return LowerSUB(Op, DAG);
   12177   case ISD::SDIV:               return LowerSDIV(Op, DAG);
   12178   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
   12179   }
   12180 }
   12181 
   12182 static void ReplaceATOMIC_LOAD(SDNode *Node,
   12183                                   SmallVectorImpl<SDValue> &Results,
   12184                                   SelectionDAG &DAG) {
   12185   DebugLoc dl = Node->getDebugLoc();
   12186   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
   12187 
   12188   // Convert wide load -> cmpxchg8b/cmpxchg16b
   12189   // FIXME: On 32-bit, load -> fild or movq would be more efficient
   12190   //        (The only way to get a 16-byte load is cmpxchg16b)
   12191   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
   12192   SDValue Zero = DAG.getConstant(0, VT);
   12193   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
   12194                                Node->getOperand(0),
   12195                                Node->getOperand(1), Zero, Zero,
   12196                                cast<AtomicSDNode>(Node)->getMemOperand(),
   12197                                cast<AtomicSDNode>(Node)->getOrdering(),
   12198                                cast<AtomicSDNode>(Node)->getSynchScope());
   12199   Results.push_back(Swap.getValue(0));
   12200   Results.push_back(Swap.getValue(1));
   12201 }
   12202 
   12203 static void
   12204 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
   12205                         SelectionDAG &DAG, unsigned NewOp) {
   12206   DebugLoc dl = Node->getDebugLoc();
   12207   assert (Node->getValueType(0) == MVT::i64 &&
   12208           "Only know how to expand i64 atomics");
   12209 
   12210   SDValue Chain = Node->getOperand(0);
   12211   SDValue In1 = Node->getOperand(1);
   12212   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   12213                              Node->getOperand(2), DAG.getIntPtrConstant(0));
   12214   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
   12215                              Node->getOperand(2), DAG.getIntPtrConstant(1));
   12216   SDValue Ops[] = { Chain, In1, In2L, In2H };
   12217   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
   12218   SDValue Result =
   12219     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
   12220                             cast<MemSDNode>(Node)->getMemOperand());
   12221   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
   12222   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
   12223   Results.push_back(Result.getValue(2));
   12224 }
   12225 
   12226 /// ReplaceNodeResults - Replace a node with an illegal result type
   12227 /// with a new node built out of custom code.
   12228 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
   12229                                            SmallVectorImpl<SDValue>&Results,
   12230                                            SelectionDAG &DAG) const {
   12231   DebugLoc dl = N->getDebugLoc();
   12232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   12233   switch (N->getOpcode()) {
   12234   default:
   12235     llvm_unreachable("Do not know how to custom type legalize this operation!");
   12236   case ISD::SIGN_EXTEND_INREG:
   12237   case ISD::ADDC:
   12238   case ISD::ADDE:
   12239   case ISD::SUBC:
   12240   case ISD::SUBE:
   12241     // We don't want to expand or promote these.
   12242     return;
   12243   case ISD::FP_TO_SINT:
   12244   case ISD::FP_TO_UINT: {
   12245     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
   12246 
   12247     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
   12248       return;
   12249 
   12250     std::pair<SDValue,SDValue> Vals =
   12251         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
   12252     SDValue FIST = Vals.first, StackSlot = Vals.second;
   12253     if (FIST.getNode() != 0) {
   12254       EVT VT = N->getValueType(0);
   12255       // Return a load from the stack slot.
   12256       if (StackSlot.getNode() != 0)
   12257         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
   12258                                       MachinePointerInfo(),
   12259                                       false, false, false, 0));
   12260       else
   12261         Results.push_back(FIST);
   12262     }
   12263     return;
   12264   }
   12265   case ISD::UINT_TO_FP: {
   12266     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
   12267     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
   12268         N->getValueType(0) != MVT::v2f32)
   12269       return;
   12270     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
   12271                                  N->getOperand(0));
   12272     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
   12273                                      MVT::f64);
   12274     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
   12275     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
   12276                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
   12277     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
   12278     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
   12279     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
   12280     return;
   12281   }
   12282   case ISD::FP_ROUND: {
   12283     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
   12284         return;
   12285     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
   12286     Results.push_back(V);
   12287     return;
   12288   }
   12289   case ISD::READCYCLECOUNTER: {
   12290     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
   12291     SDValue TheChain = N->getOperand(0);
   12292     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
   12293     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
   12294                                      rd.getValue(1));
   12295     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
   12296                                      eax.getValue(2));
   12297     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
   12298     SDValue Ops[] = { eax, edx };
   12299     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
   12300     Results.push_back(edx.getValue(1));
   12301     return;
   12302   }
   12303   case ISD::ATOMIC_CMP_SWAP: {
   12304     EVT T = N->getValueType(0);
   12305     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
   12306     bool Regs64bit = T == MVT::i128;
   12307     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
   12308     SDValue cpInL, cpInH;
   12309     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
   12310                         DAG.getConstant(0, HalfT));
   12311     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
   12312                         DAG.getConstant(1, HalfT));
   12313     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
   12314                              Regs64bit ? X86::RAX : X86::EAX,
   12315                              cpInL, SDValue());
   12316     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
   12317                              Regs64bit ? X86::RDX : X86::EDX,
   12318                              cpInH, cpInL.getValue(1));
   12319     SDValue swapInL, swapInH;
   12320     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
   12321                           DAG.getConstant(0, HalfT));
   12322     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
   12323                           DAG.getConstant(1, HalfT));
   12324     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
   12325                                Regs64bit ? X86::RBX : X86::EBX,
   12326                                swapInL, cpInH.getValue(1));
   12327     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
   12328                                Regs64bit ? X86::RCX : X86::ECX,
   12329                                swapInH, swapInL.getValue(1));
   12330     SDValue Ops[] = { swapInH.getValue(0),
   12331                       N->getOperand(1),
   12332                       swapInH.getValue(1) };
   12333     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
   12334     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
   12335     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
   12336                                   X86ISD::LCMPXCHG8_DAG;
   12337     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
   12338                                              Ops, 3, T, MMO);
   12339     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
   12340                                         Regs64bit ? X86::RAX : X86::EAX,
   12341                                         HalfT, Result.getValue(1));
   12342     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
   12343                                         Regs64bit ? X86::RDX : X86::EDX,
   12344                                         HalfT, cpOutL.getValue(2));
   12345     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
   12346     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
   12347     Results.push_back(cpOutH.getValue(1));
   12348     return;
   12349   }
   12350   case ISD::ATOMIC_LOAD_ADD:
   12351   case ISD::ATOMIC_LOAD_AND:
   12352   case ISD::ATOMIC_LOAD_NAND:
   12353   case ISD::ATOMIC_LOAD_OR:
   12354   case ISD::ATOMIC_LOAD_SUB:
   12355   case ISD::ATOMIC_LOAD_XOR:
   12356   case ISD::ATOMIC_LOAD_MAX:
   12357   case ISD::ATOMIC_LOAD_MIN:
   12358   case ISD::ATOMIC_LOAD_UMAX:
   12359   case ISD::ATOMIC_LOAD_UMIN:
   12360   case ISD::ATOMIC_SWAP: {
   12361     unsigned Opc;
   12362     switch (N->getOpcode()) {
   12363     default: llvm_unreachable("Unexpected opcode");
   12364     case ISD::ATOMIC_LOAD_ADD:
   12365       Opc = X86ISD::ATOMADD64_DAG;
   12366       break;
   12367     case ISD::ATOMIC_LOAD_AND:
   12368       Opc = X86ISD::ATOMAND64_DAG;
   12369       break;
   12370     case ISD::ATOMIC_LOAD_NAND:
   12371       Opc = X86ISD::ATOMNAND64_DAG;
   12372       break;
   12373     case ISD::ATOMIC_LOAD_OR:
   12374       Opc = X86ISD::ATOMOR64_DAG;
   12375       break;
   12376     case ISD::ATOMIC_LOAD_SUB:
   12377       Opc = X86ISD::ATOMSUB64_DAG;
   12378       break;
   12379     case ISD::ATOMIC_LOAD_XOR:
   12380       Opc = X86ISD::ATOMXOR64_DAG;
   12381       break;
   12382     case ISD::ATOMIC_LOAD_MAX:
   12383       Opc = X86ISD::ATOMMAX64_DAG;
   12384       break;
   12385     case ISD::ATOMIC_LOAD_MIN:
   12386       Opc = X86ISD::ATOMMIN64_DAG;
   12387       break;
   12388     case ISD::ATOMIC_LOAD_UMAX:
   12389       Opc = X86ISD::ATOMUMAX64_DAG;
   12390       break;
   12391     case ISD::ATOMIC_LOAD_UMIN:
   12392       Opc = X86ISD::ATOMUMIN64_DAG;
   12393       break;
   12394     case ISD::ATOMIC_SWAP:
   12395       Opc = X86ISD::ATOMSWAP64_DAG;
   12396       break;
   12397     }
   12398     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
   12399     return;
   12400   }
   12401   case ISD::ATOMIC_LOAD:
   12402     ReplaceATOMIC_LOAD(N, Results, DAG);
   12403   }
   12404 }
   12405 
   12406 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
   12407   switch (Opcode) {
   12408   default: return NULL;
   12409   case X86ISD::BSF:                return "X86ISD::BSF";
   12410   case X86ISD::BSR:                return "X86ISD::BSR";
   12411   case X86ISD::SHLD:               return "X86ISD::SHLD";
   12412   case X86ISD::SHRD:               return "X86ISD::SHRD";
   12413   case X86ISD::FAND:               return "X86ISD::FAND";
   12414   case X86ISD::FOR:                return "X86ISD::FOR";
   12415   case X86ISD::FXOR:               return "X86ISD::FXOR";
   12416   case X86ISD::FSRL:               return "X86ISD::FSRL";
   12417   case X86ISD::FILD:               return "X86ISD::FILD";
   12418   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
   12419   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
   12420   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
   12421   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
   12422   case X86ISD::FLD:                return "X86ISD::FLD";
   12423   case X86ISD::FST:                return "X86ISD::FST";
   12424   case X86ISD::CALL:               return "X86ISD::CALL";
   12425   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
   12426   case X86ISD::BT:                 return "X86ISD::BT";
   12427   case X86ISD::CMP:                return "X86ISD::CMP";
   12428   case X86ISD::COMI:               return "X86ISD::COMI";
   12429   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
   12430   case X86ISD::SETCC:              return "X86ISD::SETCC";
   12431   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
   12432   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
   12433   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
   12434   case X86ISD::CMOV:               return "X86ISD::CMOV";
   12435   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
   12436   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
   12437   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
   12438   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
   12439   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
   12440   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
   12441   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
   12442   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
   12443   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
   12444   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
   12445   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
   12446   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
   12447   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
   12448   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
   12449   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
   12450   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
   12451   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
   12452   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
   12453   case X86ISD::HADD:               return "X86ISD::HADD";
   12454   case X86ISD::HSUB:               return "X86ISD::HSUB";
   12455   case X86ISD::FHADD:              return "X86ISD::FHADD";
   12456   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
   12457   case X86ISD::UMAX:               return "X86ISD::UMAX";
   12458   case X86ISD::UMIN:               return "X86ISD::UMIN";
   12459   case X86ISD::SMAX:               return "X86ISD::SMAX";
   12460   case X86ISD::SMIN:               return "X86ISD::SMIN";
   12461   case X86ISD::FMAX:               return "X86ISD::FMAX";
   12462   case X86ISD::FMIN:               return "X86ISD::FMIN";
   12463   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
   12464   case X86ISD::FMINC:              return "X86ISD::FMINC";
   12465   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
   12466   case X86ISD::FRCP:               return "X86ISD::FRCP";
   12467   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
   12468   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
   12469   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
   12470   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
   12471   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
   12472   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
   12473   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
   12474   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
   12475   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
   12476   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
   12477   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
   12478   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
   12479   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
   12480   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
   12481   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
   12482   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
   12483   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
   12484   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
   12485   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
   12486   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
   12487   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
   12488   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
   12489   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
   12490   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
   12491   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
   12492   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
   12493   case X86ISD::VSHL:               return "X86ISD::VSHL";
   12494   case X86ISD::VSRL:               return "X86ISD::VSRL";
   12495   case X86ISD::VSRA:               return "X86ISD::VSRA";
   12496   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
   12497   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
   12498   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
   12499   case X86ISD::CMPP:               return "X86ISD::CMPP";
   12500   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
   12501   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
   12502   case X86ISD::ADD:                return "X86ISD::ADD";
   12503   case X86ISD::SUB:                return "X86ISD::SUB";
   12504   case X86ISD::ADC:                return "X86ISD::ADC";
   12505   case X86ISD::SBB:                return "X86ISD::SBB";
   12506   case X86ISD::SMUL:               return "X86ISD::SMUL";
   12507   case X86ISD::UMUL:               return "X86ISD::UMUL";
   12508   case X86ISD::INC:                return "X86ISD::INC";
   12509   case X86ISD::DEC:                return "X86ISD::DEC";
   12510   case X86ISD::OR:                 return "X86ISD::OR";
   12511   case X86ISD::XOR:                return "X86ISD::XOR";
   12512   case X86ISD::AND:                return "X86ISD::AND";
   12513   case X86ISD::BLSI:               return "X86ISD::BLSI";
   12514   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
   12515   case X86ISD::BLSR:               return "X86ISD::BLSR";
   12516   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
   12517   case X86ISD::PTEST:              return "X86ISD::PTEST";
   12518   case X86ISD::TESTP:              return "X86ISD::TESTP";
   12519   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
   12520   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
   12521   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
   12522   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
   12523   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
   12524   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
   12525   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
   12526   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
   12527   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
   12528   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
   12529   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
   12530   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
   12531   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
   12532   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
   12533   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
   12534   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
   12535   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
   12536   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
   12537   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
   12538   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
   12539   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
   12540   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
   12541   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
   12542   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
   12543   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
   12544   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
   12545   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
   12546   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
   12547   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
   12548   case X86ISD::SAHF:               return "X86ISD::SAHF";
   12549   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
   12550   case X86ISD::FMADD:              return "X86ISD::FMADD";
   12551   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
   12552   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
   12553   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
   12554   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
   12555   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
   12556   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
   12557   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
   12558   }
   12559 }
   12560 
   12561 // isLegalAddressingMode - Return true if the addressing mode represented
   12562 // by AM is legal for this target, for a load/store of the specified type.
   12563 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
   12564                                               Type *Ty) const {
   12565   // X86 supports extremely general addressing modes.
   12566   CodeModel::Model M = getTargetMachine().getCodeModel();
   12567   Reloc::Model R = getTargetMachine().getRelocationModel();
   12568 
   12569   // X86 allows a sign-extended 32-bit immediate field as a displacement.
   12570   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
   12571     return false;
   12572 
   12573   if (AM.BaseGV) {
   12574     unsigned GVFlags =
   12575       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
   12576 
   12577     // If a reference to this global requires an extra load, we can't fold it.
   12578     if (isGlobalStubReference(GVFlags))
   12579       return false;
   12580 
   12581     // If BaseGV requires a register for the PIC base, we cannot also have a
   12582     // BaseReg specified.
   12583     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
   12584       return false;
   12585 
   12586     // If lower 4G is not available, then we must use rip-relative addressing.
   12587     if ((M != CodeModel::Small || R != Reloc::Static) &&
   12588         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
   12589       return false;
   12590   }
   12591 
   12592   switch (AM.Scale) {
   12593   case 0:
   12594   case 1:
   12595   case 2:
   12596   case 4:
   12597   case 8:
   12598     // These scales always work.
   12599     break;
   12600   case 3:
   12601   case 5:
   12602   case 9:
   12603     // These scales are formed with basereg+scalereg.  Only accept if there is
   12604     // no basereg yet.
   12605     if (AM.HasBaseReg)
   12606       return false;
   12607     break;
   12608   default:  // Other stuff never works.
   12609     return false;
   12610   }
   12611 
   12612   return true;
   12613 }
   12614 
   12615 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
   12616   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
   12617     return false;
   12618   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
   12619   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
   12620   return NumBits1 > NumBits2;
   12621 }
   12622 
   12623 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
   12624   return isInt<32>(Imm);
   12625 }
   12626 
   12627 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
   12628   // Can also use sub to handle negated immediates.
   12629   return isInt<32>(Imm);
   12630 }
   12631 
   12632 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
   12633   if (!VT1.isInteger() || !VT2.isInteger())
   12634     return false;
   12635   unsigned NumBits1 = VT1.getSizeInBits();
   12636   unsigned NumBits2 = VT2.getSizeInBits();
   12637   return NumBits1 > NumBits2;
   12638 }
   12639 
   12640 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
   12641   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
   12642   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
   12643 }
   12644 
   12645 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
   12646   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
   12647   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
   12648 }
   12649 
   12650 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
   12651   EVT VT1 = Val.getValueType();
   12652   if (isZExtFree(VT1, VT2))
   12653     return true;
   12654 
   12655   if (Val.getOpcode() != ISD::LOAD)
   12656     return false;
   12657 
   12658   if (!VT1.isSimple() || !VT1.isInteger() ||
   12659       !VT2.isSimple() || !VT2.isInteger())
   12660     return false;
   12661 
   12662   switch (VT1.getSimpleVT().SimpleTy) {
   12663   default: break;
   12664   case MVT::i8:
   12665   case MVT::i16:
   12666   case MVT::i32:
   12667     // X86 has 8, 16, and 32-bit zero-extending loads.
   12668     return true;
   12669   }
   12670 
   12671   return false;
   12672 }
   12673 
   12674 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
   12675   // i16 instructions are longer (0x66 prefix) and potentially slower.
   12676   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
   12677 }
   12678 
   12679 /// isShuffleMaskLegal - Targets can use this to indicate that they only
   12680 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
   12681 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
   12682 /// are assumed to be legal.
   12683 bool
   12684 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
   12685                                       EVT VT) const {
   12686   // Very little shuffling can be done for 64-bit vectors right now.
   12687   if (VT.getSizeInBits() == 64)
   12688     return false;
   12689 
   12690   // FIXME: pshufb, blends, shifts.
   12691   return (VT.getVectorNumElements() == 2 ||
   12692           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
   12693           isMOVLMask(M, VT) ||
   12694           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
   12695           isPSHUFDMask(M, VT) ||
   12696           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
   12697           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
   12698           isPALIGNRMask(M, VT, Subtarget) ||
   12699           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
   12700           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
   12701           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
   12702           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
   12703 }
   12704 
   12705 bool
   12706 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
   12707                                           EVT VT) const {
   12708   unsigned NumElts = VT.getVectorNumElements();
   12709   // FIXME: This collection of masks seems suspect.
   12710   if (NumElts == 2)
   12711     return true;
   12712   if (NumElts == 4 && VT.is128BitVector()) {
   12713     return (isMOVLMask(Mask, VT)  ||
   12714             isCommutedMOVLMask(Mask, VT, true) ||
   12715             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
   12716             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
   12717   }
   12718   return false;
   12719 }
   12720 
   12721 //===----------------------------------------------------------------------===//
   12722 //                           X86 Scheduler Hooks
   12723 //===----------------------------------------------------------------------===//
   12724 
   12725 /// Utility function to emit xbegin specifying the start of an RTM region.
   12726 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
   12727                                      const TargetInstrInfo *TII) {
   12728   DebugLoc DL = MI->getDebugLoc();
   12729 
   12730   const BasicBlock *BB = MBB->getBasicBlock();
   12731   MachineFunction::iterator I = MBB;
   12732   ++I;
   12733 
   12734   // For the v = xbegin(), we generate
   12735   //
   12736   // thisMBB:
   12737   //  xbegin sinkMBB
   12738   //
   12739   // mainMBB:
   12740   //  eax = -1
   12741   //
   12742   // sinkMBB:
   12743   //  v = eax
   12744 
   12745   MachineBasicBlock *thisMBB = MBB;
   12746   MachineFunction *MF = MBB->getParent();
   12747   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
   12748   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
   12749   MF->insert(I, mainMBB);
   12750   MF->insert(I, sinkMBB);
   12751 
   12752   // Transfer the remainder of BB and its successor edges to sinkMBB.
   12753   sinkMBB->splice(sinkMBB->begin(), MBB,
   12754                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
   12755   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
   12756 
   12757   // thisMBB:
   12758   //  xbegin sinkMBB
   12759   //  # fallthrough to mainMBB
   12760   //  # abortion to sinkMBB
   12761   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
   12762   thisMBB->addSuccessor(mainMBB);
   12763   thisMBB->addSuccessor(sinkMBB);
   12764 
   12765   // mainMBB:
   12766   //  EAX = -1
   12767   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
   12768   mainMBB->addSuccessor(sinkMBB);
   12769 
   12770   // sinkMBB:
   12771   // EAX is live into the sinkMBB
   12772   sinkMBB->addLiveIn(X86::EAX);
   12773   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
   12774           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
   12775     .addReg(X86::EAX);
   12776 
   12777   MI->eraseFromParent();
   12778   return sinkMBB;
   12779 }
   12780 
   12781 // Get CMPXCHG opcode for the specified data type.
   12782 static unsigned getCmpXChgOpcode(EVT VT) {
   12783   switch (VT.getSimpleVT().SimpleTy) {
   12784   case MVT::i8:  return X86::LCMPXCHG8;
   12785   case MVT::i16: return X86::LCMPXCHG16;
   12786   case MVT::i32: return X86::LCMPXCHG32;
   12787   case MVT::i64: return X86::LCMPXCHG64;
   12788   default:
   12789     break;
   12790   }
   12791   llvm_unreachable("Invalid operand size!");
   12792 }
   12793 
   12794 // Get LOAD opcode for the specified data type.
   12795 static unsigned getLoadOpcode(EVT VT) {
   12796   switch (VT.getSimpleVT().SimpleTy) {
   12797   case MVT::i8:  return X86::MOV8rm;
   12798   case MVT::i16: return X86::MOV16rm;
   12799   case MVT::i32: return X86::MOV32rm;
   12800   case MVT::i64: return X86::MOV64rm;
   12801   default:
   12802     break;
   12803   }
   12804   llvm_unreachable("Invalid operand size!");
   12805 }
   12806 
   12807 // Get opcode of the non-atomic one from the specified atomic instruction.
   12808 static unsigned getNonAtomicOpcode(unsigned Opc) {
   12809   switch (Opc) {
   12810   case X86::ATOMAND8:  return X86::AND8rr;
   12811   case X86::ATOMAND16: return X86::AND16rr;
   12812   case X86::ATOMAND32: return X86::AND32rr;
   12813   case X86::ATOMAND64: return X86::AND64rr;
   12814   case X86::ATOMOR8:   return X86::OR8rr;
   12815   case X86::ATOMOR16:  return X86::OR16rr;
   12816   case X86::ATOMOR32:  return X86::OR32rr;
   12817   case X86::ATOMOR64:  return X86::OR64rr;
   12818   case X86::ATOMXOR8:  return X86::XOR8rr;
   12819   case X86::ATOMXOR16: return X86::XOR16rr;
   12820   case X86::ATOMXOR32: return X86::XOR32rr;
   12821   case X86::ATOMXOR64: return X86::XOR64rr;
   12822   }
   12823   llvm_unreachable("Unhandled atomic-load-op opcode!");
   12824 }
   12825 
   12826 // Get opcode of the non-atomic one from the specified atomic instruction with
   12827 // extra opcode.
   12828 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
   12829                                                unsigned &ExtraOpc) {
   12830   switch (Opc) {
   12831   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
   12832   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
   12833   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
   12834   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
   12835   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
   12836   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
   12837   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
   12838   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
   12839   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
   12840   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
   12841   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
   12842   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
   12843   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
   12844   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
   12845   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
   12846   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
   12847   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
   12848   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
   12849   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
   12850   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
   12851   }
   12852   llvm_unreachable("Unhandled atomic-load-op opcode!");
   12853 }
   12854 
   12855 // Get opcode of the non-atomic one from the specified atomic instruction for
   12856 // 64-bit data type on 32-bit target.
   12857 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
   12858   switch (Opc) {
   12859   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
   12860   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
   12861   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
   12862   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
   12863   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
   12864   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
   12865   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
   12866   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
   12867   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
   12868   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
   12869   }
   12870   llvm_unreachable("Unhandled atomic-load-op opcode!");
   12871 }
   12872 
   12873 // Get opcode of the non-atomic one from the specified atomic instruction for
   12874 // 64-bit data type on 32-bit target with extra opcode.
   12875 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
   12876                                                    unsigned &HiOpc,
   12877                                                    unsigned &ExtraOpc) {
   12878   switch (Opc) {
   12879   case X86::ATOMNAND6432:
   12880     ExtraOpc = X86::NOT32r;
   12881     HiOpc = X86::AND32rr;
   12882     return X86::AND32rr;
   12883   }
   12884   llvm_unreachable("Unhandled atomic-load-op opcode!");
   12885 }
   12886 
   12887 // Get pseudo CMOV opcode from the specified data type.
   12888 static unsigned getPseudoCMOVOpc(EVT VT) {
   12889   switch (VT.getSimpleVT().SimpleTy) {
   12890   case MVT::i8:  return X86::CMOV_GR8;
   12891   case MVT::i16: return X86::CMOV_GR16;
   12892   case MVT::i32: return X86::CMOV_GR32;
   12893   default:
   12894     break;
   12895   }
   12896   llvm_unreachable("Unknown CMOV opcode!");
   12897 }
   12898 
   12899 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
   12900 // They will be translated into a spin-loop or compare-exchange loop from
   12901 //
   12902 //    ...
   12903 //    dst = atomic-fetch-op MI.addr, MI.val
   12904 //    ...
   12905 //
   12906 // to
   12907 //
   12908 //    ...
   12909 //    t1 = LOAD MI.addr
   12910 // loop:
   12911 //    t4 = phi(t1, t3 / loop)
   12912 //    t2 = OP MI.val, t4
   12913 //    EAX = t4
   12914 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
   12915 //    t3 = EAX
   12916 //    JNE loop
   12917 // sink:
   12918 //    dst = t3
   12919 //    ...
   12920 MachineBasicBlock *
   12921 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
   12922                                        MachineBasicBlock *MBB) const {
   12923   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   12924   DebugLoc DL = MI->getDebugLoc();
   12925 
   12926   MachineFunction *MF = MBB->getParent();
   12927   MachineRegisterInfo &MRI = MF->getRegInfo();
   12928 
   12929   const BasicBlock *BB = MBB->getBasicBlock();
   12930   MachineFunction::iterator I = MBB;
   12931   ++I;
   12932 
   12933   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
   12934          "Unexpected number of operands");
   12935 
   12936   assert(MI->hasOneMemOperand() &&
   12937          "Expected atomic-load-op to have one memoperand");
   12938 
   12939   // Memory Reference
   12940   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
   12941   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
   12942 
   12943   unsigned DstReg, SrcReg;
   12944   unsigned MemOpndSlot;
   12945 
   12946   unsigned CurOp = 0;
   12947 
   12948   DstReg = MI->getOperand(CurOp++).getReg();
   12949   MemOpndSlot = CurOp;
   12950   CurOp += X86::AddrNumOperands;
   12951   SrcReg = MI->getOperand(CurOp++).getReg();
   12952 
   12953   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
   12954   MVT::SimpleValueType VT = *RC->vt_begin();
   12955   unsigned t1 = MRI.createVirtualRegister(RC);
   12956   unsigned t2 = MRI.createVirtualRegister(RC);
   12957   unsigned t3 = MRI.createVirtualRegister(RC);
   12958   unsigned t4 = MRI.createVirtualRegister(RC);
   12959   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
   12960 
   12961   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
   12962   unsigned LOADOpc = getLoadOpcode(VT);
   12963 
   12964   // For the atomic load-arith operator, we generate
   12965   //
   12966   //  thisMBB:
   12967   //    t1 = LOAD [MI.addr]
   12968   //  mainMBB:
   12969   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
   12970   //    t1 = OP MI.val, EAX
   12971   //    EAX = t4
   12972   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
   12973   //    t3 = EAX
   12974   //    JNE mainMBB
   12975   //  sinkMBB:
   12976   //    dst = t3
   12977 
   12978   MachineBasicBlock *thisMBB = MBB;
   12979   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
   12980   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
   12981   MF->insert(I, mainMBB);
   12982   MF->insert(I, sinkMBB);
   12983 
   12984   MachineInstrBuilder MIB;
   12985 
   12986   // Transfer the remainder of BB and its successor edges to sinkMBB.
   12987   sinkMBB->splice(sinkMBB->begin(), MBB,
   12988                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
   12989   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
   12990 
   12991   // thisMBB:
   12992   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
   12993   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
   12994     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
   12995     if (NewMO.isReg())
   12996       NewMO.setIsKill(false);
   12997     MIB.addOperand(NewMO);
   12998   }
   12999   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
   13000     unsigned flags = (*MMOI)->getFlags();
   13001     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
   13002     MachineMemOperand *MMO =
   13003       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
   13004                                (*MMOI)->getSize(),
   13005                                (*MMOI)->getBaseAlignment(),
   13006                                (*MMOI)->getTBAAInfo(),
   13007                                (*MMOI)->getRanges());
   13008     MIB.addMemOperand(MMO);
   13009   }
   13010 
   13011   thisMBB->addSuccessor(mainMBB);
   13012 
   13013   // mainMBB:
   13014   MachineBasicBlock *origMainMBB = mainMBB;
   13015 
   13016   // Add a PHI.
   13017   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
   13018                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
   13019 
   13020   unsigned Opc = MI->getOpcode();
   13021   switch (Opc) {
   13022   default:
   13023     llvm_unreachable("Unhandled atomic-load-op opcode!");
   13024   case X86::ATOMAND8:
   13025   case X86::ATOMAND16:
   13026   case X86::ATOMAND32:
   13027   case X86::ATOMAND64:
   13028   case X86::ATOMOR8:
   13029   case X86::ATOMOR16:
   13030   case X86::ATOMOR32:
   13031   case X86::ATOMOR64:
   13032   case X86::ATOMXOR8:
   13033   case X86::ATOMXOR16:
   13034   case X86::ATOMXOR32:
   13035   case X86::ATOMXOR64: {
   13036     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
   13037     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
   13038       .addReg(t4);
   13039     break;
   13040   }
   13041   case X86::ATOMNAND8:
   13042   case X86::ATOMNAND16:
   13043   case X86::ATOMNAND32:
   13044   case X86::ATOMNAND64: {
   13045     unsigned Tmp = MRI.createVirtualRegister(RC);
   13046     unsigned NOTOpc;
   13047     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
   13048     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
   13049       .addReg(t4);
   13050     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
   13051     break;
   13052   }
   13053   case X86::ATOMMAX8:
   13054   case X86::ATOMMAX16:
   13055   case X86::ATOMMAX32:
   13056   case X86::ATOMMAX64:
   13057   case X86::ATOMMIN8:
   13058   case X86::ATOMMIN16:
   13059   case X86::ATOMMIN32:
   13060   case X86::ATOMMIN64:
   13061   case X86::ATOMUMAX8:
   13062   case X86::ATOMUMAX16:
   13063   case X86::ATOMUMAX32:
   13064   case X86::ATOMUMAX64:
   13065   case X86::ATOMUMIN8:
   13066   case X86::ATOMUMIN16:
   13067   case X86::ATOMUMIN32:
   13068   case X86::ATOMUMIN64: {
   13069     unsigned CMPOpc;
   13070     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
   13071 
   13072     BuildMI(mainMBB, DL, TII->get(CMPOpc))
   13073       .addReg(SrcReg)
   13074       .addReg(t4);
   13075 
   13076     if (Subtarget->hasCMov()) {
   13077       if (VT != MVT::i8) {
   13078         // Native support
   13079         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
   13080           .addReg(SrcReg)
   13081           .addReg(t4);
   13082       } else {
   13083         // Promote i8 to i32 to use CMOV32
   13084         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
   13085         const TargetRegisterClass *RC32 =
   13086           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
   13087         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
   13088         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
   13089         unsigned Tmp = MRI.createVirtualRegister(RC32);
   13090 
   13091         unsigned Undef = MRI.createVirtualRegister(RC32);
   13092         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
   13093 
   13094         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
   13095           .addReg(Undef)
   13096           .addReg(SrcReg)
   13097           .addImm(X86::sub_8bit);
   13098         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
   13099           .addReg(Undef)
   13100           .addReg(t4)
   13101           .addImm(X86::sub_8bit);
   13102 
   13103         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
   13104           .addReg(SrcReg32)
   13105           .addReg(AccReg32);
   13106 
   13107         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
   13108           .addReg(Tmp, 0, X86::sub_8bit);
   13109       }
   13110     } else {
   13111       // Use pseudo select and lower them.
   13112       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
   13113              "Invalid atomic-load-op transformation!");
   13114       unsigned SelOpc = getPseudoCMOVOpc(VT);
   13115       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
   13116       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
   13117       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
   13118               .addReg(SrcReg).addReg(t4)
   13119               .addImm(CC);
   13120       mainMBB = EmitLoweredSelect(MIB, mainMBB);
   13121       // Replace the original PHI node as mainMBB is changed after CMOV
   13122       // lowering.
   13123       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
   13124         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
   13125       Phi->eraseFromParent();
   13126     }
   13127     break;
   13128   }
   13129   }
   13130 
   13131   // Copy PhyReg back from virtual register.
   13132   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
   13133     .addReg(t4);
   13134 
   13135   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
   13136   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
   13137     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
   13138     if (NewMO.isReg())
   13139       NewMO.setIsKill(false);
   13140     MIB.addOperand(NewMO);
   13141   }
   13142   MIB.addReg(t2);
   13143   MIB.setMemRefs(MMOBegin, MMOEnd);
   13144 
   13145   // Copy PhyReg back to virtual register.
   13146   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
   13147     .addReg(PhyReg);
   13148 
   13149   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
   13150 
   13151   mainMBB->addSuccessor(origMainMBB);
   13152   mainMBB->addSuccessor(sinkMBB);
   13153 
   13154   // sinkMBB:
   13155   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
   13156           TII->get(TargetOpcode::COPY), DstReg)
   13157     .addReg(t3);
   13158 
   13159   MI->eraseFromParent();
   13160   return sinkMBB;
   13161 }
   13162 
   13163 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
   13164 // instructions. They will be translated into a spin-loop or compare-exchange
   13165 // loop from
   13166 //
   13167 //    ...
   13168 //    dst = atomic-fetch-op MI.addr, MI.val
   13169 //    ...
   13170 //
   13171 // to
   13172 //
   13173 //    ...
   13174 //    t1L = LOAD [MI.addr + 0]
   13175 //    t1H = LOAD [MI.addr + 4]
   13176 // loop:
   13177 //    t4L = phi(t1L, t3L / loop)
   13178 //    t4H = phi(t1H, t3H / loop)
   13179 //    t2L = OP MI.val.lo, t4L
   13180 //    t2H = OP MI.val.hi, t4H
   13181 //    EAX = t4L
   13182 //    EDX = t4H
   13183 //    EBX = t2L
   13184 //    ECX = t2H
   13185 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
   13186 //    t3L = EAX
   13187 //    t3H = EDX
   13188 //    JNE loop
   13189 // sink:
   13190 //    dstL = t3L
   13191 //    dstH = t3H
   13192 //    ...
   13193 MachineBasicBlock *
   13194 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
   13195                                            MachineBasicBlock *MBB) const {
   13196   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   13197   DebugLoc DL = MI->getDebugLoc();
   13198 
   13199   MachineFunction *MF = MBB->getParent();
   13200   MachineRegisterInfo &MRI = MF->getRegInfo();
   13201 
   13202   const BasicBlock *BB = MBB->getBasicBlock();
   13203   MachineFunction::iterator I = MBB;
   13204   ++I;
   13205 
   13206   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
   13207          "Unexpected number of operands");
   13208 
   13209   assert(MI->hasOneMemOperand() &&
   13210          "Expected atomic-load-op32 to have one memoperand");
   13211 
   13212   // Memory Reference
   13213   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
   13214   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
   13215 
   13216   unsigned DstLoReg, DstHiReg;
   13217   unsigned SrcLoReg, SrcHiReg;
   13218   unsigned MemOpndSlot;
   13219 
   13220   unsigned CurOp = 0;
   13221 
   13222   DstLoReg = MI->getOperand(CurOp++).getReg();
   13223   DstHiReg = MI->getOperand(CurOp++).getReg();
   13224   MemOpndSlot = CurOp;
   13225   CurOp += X86::AddrNumOperands;
   13226   SrcLoReg = MI->getOperand(CurOp++).getReg();
   13227   SrcHiReg = MI->getOperand(CurOp++).getReg();
   13228 
   13229   const TargetRegisterClass *RC = &X86::GR32RegClass;
   13230   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
   13231 
   13232   unsigned t1L = MRI.createVirtualRegister(RC);
   13233   unsigned t1H = MRI.createVirtualRegister(RC);
   13234   unsigned t2L = MRI.createVirtualRegister(RC);
   13235   unsigned t2H = MRI.createVirtualRegister(RC);
   13236   unsigned t3L = MRI.createVirtualRegister(RC);
   13237   unsigned t3H = MRI.createVirtualRegister(RC);
   13238   unsigned t4L = MRI.createVirtualRegister(RC);
   13239   unsigned t4H = MRI.createVirtualRegister(RC);
   13240 
   13241   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
   13242   unsigned LOADOpc = X86::MOV32rm;
   13243 
   13244   // For the atomic load-arith operator, we generate
   13245   //
   13246   //  thisMBB:
   13247   //    t1L = LOAD [MI.addr + 0]
   13248   //    t1H = LOAD [MI.addr + 4]
   13249   //  mainMBB:
   13250   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
   13251   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
   13252   //    t2L = OP MI.val.lo, t4L
   13253   //    t2H = OP MI.val.hi, t4H
   13254   //    EBX = t2L
   13255   //    ECX = t2H
   13256   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
   13257   //    t3L = EAX
   13258   //    t3H = EDX
   13259   //    JNE loop
   13260   //  sinkMBB:
   13261   //    dstL = t3L
   13262   //    dstH = t3H
   13263 
   13264   MachineBasicBlock *thisMBB = MBB;
   13265   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
   13266   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
   13267   MF->insert(I, mainMBB);
   13268   MF->insert(I, sinkMBB);
   13269 
   13270   MachineInstrBuilder MIB;
   13271 
   13272   // Transfer the remainder of BB and its successor edges to sinkMBB.
   13273   sinkMBB->splice(sinkMBB->begin(), MBB,
   13274                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
   13275   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
   13276 
   13277   // thisMBB:
   13278   // Lo
   13279   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
   13280   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
   13281     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
   13282     if (NewMO.isReg())
   13283       NewMO.setIsKill(false);
   13284     MIB.addOperand(NewMO);
   13285   }
   13286   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
   13287     unsigned flags = (*MMOI)->getFlags();
   13288     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
   13289     MachineMemOperand *MMO =
   13290       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
   13291                                (*MMOI)->getSize(),
   13292                                (*MMOI)->getBaseAlignment(),
   13293                                (*MMOI)->getTBAAInfo(),
   13294                                (*MMOI)->getRanges());
   13295     MIB.addMemOperand(MMO);
   13296   };
   13297   MachineInstr *LowMI = MIB;
   13298 
   13299   // Hi
   13300   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
   13301   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
   13302     if (i == X86::AddrDisp) {
   13303       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
   13304     } else {
   13305       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
   13306       if (NewMO.isReg())
   13307         NewMO.setIsKill(false);
   13308       MIB.addOperand(NewMO);
   13309     }
   13310   }
   13311   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
   13312 
   13313   thisMBB->addSuccessor(mainMBB);
   13314 
   13315   // mainMBB:
   13316   MachineBasicBlock *origMainMBB = mainMBB;
   13317 
   13318   // Add PHIs.
   13319   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
   13320                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
   13321   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
   13322                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
   13323 
   13324   unsigned Opc = MI->getOpcode();
   13325   switch (Opc) {
   13326   default:
   13327     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
   13328   case X86::ATOMAND6432:
   13329   case X86::ATOMOR6432:
   13330   case X86::ATOMXOR6432:
   13331   case X86::ATOMADD6432:
   13332   case X86::ATOMSUB6432: {
   13333     unsigned HiOpc;
   13334     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
   13335     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
   13336       .addReg(SrcLoReg);
   13337     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
   13338       .addReg(SrcHiReg);
   13339     break;
   13340   }
   13341   case X86::ATOMNAND6432: {
   13342     unsigned HiOpc, NOTOpc;
   13343     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
   13344     unsigned TmpL = MRI.createVirtualRegister(RC);
   13345     unsigned TmpH = MRI.createVirtualRegister(RC);
   13346     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
   13347       .addReg(t4L);
   13348     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
   13349       .addReg(t4H);
   13350     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
   13351     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
   13352     break;
   13353   }
   13354   case X86::ATOMMAX6432:
   13355   case X86::ATOMMIN6432:
   13356   case X86::ATOMUMAX6432:
   13357   case X86::ATOMUMIN6432: {
   13358     unsigned HiOpc;
   13359     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
   13360     unsigned cL = MRI.createVirtualRegister(RC8);
   13361     unsigned cH = MRI.createVirtualRegister(RC8);
   13362     unsigned cL32 = MRI.createVirtualRegister(RC);
   13363     unsigned cH32 = MRI.createVirtualRegister(RC);
   13364     unsigned cc = MRI.createVirtualRegister(RC);
   13365     // cl := cmp src_lo, lo
   13366     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
   13367       .addReg(SrcLoReg).addReg(t4L);
   13368     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
   13369     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
   13370     // ch := cmp src_hi, hi
   13371     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
   13372       .addReg(SrcHiReg).addReg(t4H);
   13373     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
   13374     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
   13375     // cc := if (src_hi == hi) ? cl : ch;
   13376     if (Subtarget->hasCMov()) {
   13377       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
   13378         .addReg(cH32).addReg(cL32);
   13379     } else {
   13380       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
   13381               .addReg(cH32).addReg(cL32)
   13382               .addImm(X86::COND_E);
   13383       mainMBB = EmitLoweredSelect(MIB, mainMBB);
   13384     }
   13385     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
   13386     if (Subtarget->hasCMov()) {
   13387       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
   13388         .addReg(SrcLoReg).addReg(t4L);
   13389       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
   13390         .addReg(SrcHiReg).addReg(t4H);
   13391     } else {
   13392       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
   13393               .addReg(SrcLoReg).addReg(t4L)
   13394               .addImm(X86::COND_NE);
   13395       mainMBB = EmitLoweredSelect(MIB, mainMBB);
   13396       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
   13397       // 2nd CMOV lowering.
   13398       mainMBB->addLiveIn(X86::EFLAGS);
   13399       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
   13400               .addReg(SrcHiReg).addReg(t4H)
   13401               .addImm(X86::COND_NE);
   13402       mainMBB = EmitLoweredSelect(MIB, mainMBB);
   13403       // Replace the original PHI node as mainMBB is changed after CMOV
   13404       // lowering.
   13405       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
   13406         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
   13407       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
   13408         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
   13409       PhiL->eraseFromParent();
   13410       PhiH->eraseFromParent();
   13411     }
   13412     break;
   13413   }
   13414   case X86::ATOMSWAP6432: {
   13415     unsigned HiOpc;
   13416     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
   13417     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
   13418     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
   13419     break;
   13420   }
   13421   }
   13422 
   13423   // Copy EDX:EAX back from HiReg:LoReg
   13424   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
   13425   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
   13426   // Copy ECX:EBX from t1H:t1L
   13427   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
   13428   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
   13429 
   13430   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
   13431   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
   13432     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
   13433     if (NewMO.isReg())
   13434       NewMO.setIsKill(false);
   13435     MIB.addOperand(NewMO);
   13436   }
   13437   MIB.setMemRefs(MMOBegin, MMOEnd);
   13438 
   13439   // Copy EDX:EAX back to t3H:t3L
   13440   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
   13441   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
   13442 
   13443   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
   13444 
   13445   mainMBB->addSuccessor(origMainMBB);
   13446   mainMBB->addSuccessor(sinkMBB);
   13447 
   13448   // sinkMBB:
   13449   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
   13450           TII->get(TargetOpcode::COPY), DstLoReg)
   13451     .addReg(t3L);
   13452   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
   13453           TII->get(TargetOpcode::COPY), DstHiReg)
   13454     .addReg(t3H);
   13455 
   13456   MI->eraseFromParent();
   13457   return sinkMBB;
   13458 }
   13459 
   13460 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
   13461 // or XMM0_V32I8 in AVX all of this code can be replaced with that
   13462 // in the .td file.
   13463 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
   13464                                        const TargetInstrInfo *TII) {
   13465   unsigned Opc;
   13466   switch (MI->getOpcode()) {
   13467   default: llvm_unreachable("illegal opcode!");
   13468   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
   13469   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
   13470   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
   13471   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
   13472   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
   13473   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
   13474   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
   13475   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
   13476   }
   13477 
   13478   DebugLoc dl = MI->getDebugLoc();
   13479   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
   13480 
   13481   unsigned NumArgs = MI->getNumOperands();
   13482   for (unsigned i = 1; i < NumArgs; ++i) {
   13483     MachineOperand &Op = MI->getOperand(i);
   13484     if (!(Op.isReg() && Op.isImplicit()))
   13485       MIB.addOperand(Op);
   13486   }
   13487   if (MI->hasOneMemOperand())
   13488     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
   13489 
   13490   BuildMI(*BB, MI, dl,
   13491     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
   13492     .addReg(X86::XMM0);
   13493 
   13494   MI->eraseFromParent();
   13495   return BB;
   13496 }
   13497 
   13498 // FIXME: Custom handling because TableGen doesn't support multiple implicit
   13499 // defs in an instruction pattern
   13500 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
   13501                                        const TargetInstrInfo *TII) {
   13502   unsigned Opc;
   13503   switch (MI->getOpcode()) {
   13504   default: llvm_unreachable("illegal opcode!");
   13505   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
   13506   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
   13507   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
   13508   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
   13509   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
   13510   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
   13511   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
   13512   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
   13513   }
   13514 
   13515   DebugLoc dl = MI->getDebugLoc();
   13516   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
   13517 
   13518   unsigned NumArgs = MI->getNumOperands(); // remove the results
   13519   for (unsigned i = 1; i < NumArgs; ++i) {
   13520     MachineOperand &Op = MI->getOperand(i);
   13521     if (!(Op.isReg() && Op.isImplicit()))
   13522       MIB.addOperand(Op);
   13523   }
   13524   if (MI->hasOneMemOperand())
   13525     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
   13526 
   13527   BuildMI(*BB, MI, dl,
   13528     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
   13529     .addReg(X86::ECX);
   13530 
   13531   MI->eraseFromParent();
   13532   return BB;
   13533 }
   13534 
   13535 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
   13536                                        const TargetInstrInfo *TII,
   13537                                        const X86Subtarget* Subtarget) {
   13538   DebugLoc dl = MI->getDebugLoc();
   13539 
   13540   // Address into RAX/EAX, other two args into ECX, EDX.
   13541   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
   13542   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
   13543   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
   13544   for (int i = 0; i < X86::AddrNumOperands; ++i)
   13545     MIB.addOperand(MI->getOperand(i));
   13546 
   13547   unsigned ValOps = X86::AddrNumOperands;
   13548   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
   13549     .addReg(MI->getOperand(ValOps).getReg());
   13550   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
   13551     .addReg(MI->getOperand(ValOps+1).getReg());
   13552 
   13553   // The instruction doesn't actually take any operands though.
   13554   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
   13555 
   13556   MI->eraseFromParent(); // The pseudo is gone now.
   13557   return BB;
   13558 }
   13559 
   13560 MachineBasicBlock *
   13561 X86TargetLowering::EmitVAARG64WithCustomInserter(
   13562                    MachineInstr *MI,
   13563                    MachineBasicBlock *MBB) const {
   13564   // Emit va_arg instruction on X86-64.
   13565 
   13566   // Operands to this pseudo-instruction:
   13567   // 0  ) Output        : destination address (reg)
   13568   // 1-5) Input         : va_list address (addr, i64mem)
   13569   // 6  ) ArgSize       : Size (in bytes) of vararg type
   13570   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
   13571   // 8  ) Align         : Alignment of type
   13572   // 9  ) EFLAGS (implicit-def)
   13573 
   13574   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
   13575   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
   13576 
   13577   unsigned DestReg = MI->getOperand(0).getReg();
   13578   MachineOperand &Base = MI->getOperand(1);
   13579   MachineOperand &Scale = MI->getOperand(2);
   13580   MachineOperand &Index = MI->getOperand(3);
   13581   MachineOperand &Disp = MI->getOperand(4);
   13582   MachineOperand &Segment = MI->getOperand(5);
   13583   unsigned ArgSize = MI->getOperand(6).getImm();
   13584   unsigned ArgMode = MI->getOperand(7).getImm();
   13585   unsigned Align = MI->getOperand(8).getImm();
   13586 
   13587   // Memory Reference
   13588   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
   13589   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
   13590   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
   13591 
   13592   // Machine Information
   13593   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   13594   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
   13595   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
   13596   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
   13597   DebugLoc DL = MI->getDebugLoc();
   13598 
   13599   // struct va_list {
   13600   //   i32   gp_offset
   13601   //   i32   fp_offset
   13602   //   i64   overflow_area (address)
   13603   //   i64   reg_save_area (address)
   13604   // }
   13605   // sizeof(va_list) = 24
   13606   // alignment(va_list) = 8
   13607 
   13608   unsigned TotalNumIntRegs = 6;
   13609   unsigned TotalNumXMMRegs = 8;
   13610   bool UseGPOffset = (ArgMode == 1);
   13611   bool UseFPOffset = (ArgMode == 2);
   13612   unsigned MaxOffset = TotalNumIntRegs * 8 +
   13613                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
   13614 
   13615   /* Align ArgSize to a multiple of 8 */
   13616   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
   13617   bool NeedsAlign = (Align > 8);
   13618 
   13619   MachineBasicBlock *thisMBB = MBB;
   13620   MachineBasicBlock *overflowMBB;
   13621   MachineBasicBlock *offsetMBB;
   13622   MachineBasicBlock *endMBB;
   13623 
   13624   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
   13625   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
   13626   unsigned OffsetReg = 0;
   13627 
   13628   if (!UseGPOffset && !UseFPOffset) {
   13629     // If we only pull from the overflow region, we don't create a branch.
   13630     // We don't need to alter control flow.
   13631     OffsetDestReg = 0; // unused
   13632     OverflowDestReg = DestReg;
   13633 
   13634     offsetMBB = NULL;
   13635     overflowMBB = thisMBB;
   13636     endMBB = thisMBB;
   13637   } else {
   13638     // First emit code to check if gp_offset (or fp_offset) is below the bound.
   13639     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
   13640     // If not, pull from overflow_area. (branch to overflowMBB)
   13641     //
   13642     //       thisMBB
   13643     //         |     .
   13644     //         |        .
   13645     //     offsetMBB   overflowMBB
   13646     //         |        .
   13647     //         |     .
   13648     //        endMBB
   13649 
   13650     // Registers for the PHI in endMBB
   13651     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
   13652     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
   13653 
   13654     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
   13655     MachineFunction *MF = MBB->getParent();
   13656     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   13657     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   13658     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   13659 
   13660     MachineFunction::iterator MBBIter = MBB;
   13661     ++MBBIter;
   13662 
   13663     // Insert the new basic blocks
   13664     MF->insert(MBBIter, offsetMBB);
   13665     MF->insert(MBBIter, overflowMBB);
   13666     MF->insert(MBBIter, endMBB);
   13667 
   13668     // Transfer the remainder of MBB and its successor edges to endMBB.
   13669     endMBB->splice(endMBB->begin(), thisMBB,
   13670                     llvm::next(MachineBasicBlock::iterator(MI)),
   13671                     thisMBB->end());
   13672     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
   13673 
   13674     // Make offsetMBB and overflowMBB successors of thisMBB
   13675     thisMBB->addSuccessor(offsetMBB);
   13676     thisMBB->addSuccessor(overflowMBB);
   13677 
   13678     // endMBB is a successor of both offsetMBB and overflowMBB
   13679     offsetMBB->addSuccessor(endMBB);
   13680     overflowMBB->addSuccessor(endMBB);
   13681 
   13682     // Load the offset value into a register
   13683     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
   13684     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
   13685       .addOperand(Base)
   13686       .addOperand(Scale)
   13687       .addOperand(Index)
   13688       .addDisp(Disp, UseFPOffset ? 4 : 0)
   13689       .addOperand(Segment)
   13690       .setMemRefs(MMOBegin, MMOEnd);
   13691 
   13692     // Check if there is enough room left to pull this argument.
   13693     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
   13694       .addReg(OffsetReg)
   13695       .addImm(MaxOffset + 8 - ArgSizeA8);
   13696 
   13697     // Branch to "overflowMBB" if offset >= max
   13698     // Fall through to "offsetMBB" otherwise
   13699     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
   13700       .addMBB(overflowMBB);
   13701   }
   13702 
   13703   // In offsetMBB, emit code to use the reg_save_area.
   13704   if (offsetMBB) {
   13705     assert(OffsetReg != 0);
   13706 
   13707     // Read the reg_save_area address.
   13708     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
   13709     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
   13710       .addOperand(Base)
   13711       .addOperand(Scale)
   13712       .addOperand(Index)
   13713       .addDisp(Disp, 16)
   13714       .addOperand(Segment)
   13715       .setMemRefs(MMOBegin, MMOEnd);
   13716 
   13717     // Zero-extend the offset
   13718     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
   13719       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
   13720         .addImm(0)
   13721         .addReg(OffsetReg)
   13722         .addImm(X86::sub_32bit);
   13723 
   13724     // Add the offset to the reg_save_area to get the final address.
   13725     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
   13726       .addReg(OffsetReg64)
   13727       .addReg(RegSaveReg);
   13728 
   13729     // Compute the offset for the next argument
   13730     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
   13731     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
   13732       .addReg(OffsetReg)
   13733       .addImm(UseFPOffset ? 16 : 8);
   13734 
   13735     // Store it back into the va_list.
   13736     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
   13737       .addOperand(Base)
   13738       .addOperand(Scale)
   13739       .addOperand(Index)
   13740       .addDisp(Disp, UseFPOffset ? 4 : 0)
   13741       .addOperand(Segment)
   13742       .addReg(NextOffsetReg)
   13743       .setMemRefs(MMOBegin, MMOEnd);
   13744 
   13745     // Jump to endMBB
   13746     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
   13747       .addMBB(endMBB);
   13748   }
   13749 
   13750   //
   13751   // Emit code to use overflow area
   13752   //
   13753 
   13754   // Load the overflow_area address into a register.
   13755   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
   13756   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
   13757     .addOperand(Base)
   13758     .addOperand(Scale)
   13759     .addOperand(Index)
   13760     .addDisp(Disp, 8)
   13761     .addOperand(Segment)
   13762     .setMemRefs(MMOBegin, MMOEnd);
   13763 
   13764   // If we need to align it, do so. Otherwise, just copy the address
   13765   // to OverflowDestReg.
   13766   if (NeedsAlign) {
   13767     // Align the overflow address
   13768     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
   13769     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
   13770 
   13771     // aligned_addr = (addr + (align-1)) & ~(align-1)
   13772     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
   13773       .addReg(OverflowAddrReg)
   13774       .addImm(Align-1);
   13775 
   13776     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
   13777       .addReg(TmpReg)
   13778       .addImm(~(uint64_t)(Align-1));
   13779   } else {
   13780     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
   13781       .addReg(OverflowAddrReg);
   13782   }
   13783 
   13784   // Compute the next overflow address after this argument.
   13785   // (the overflow address should be kept 8-byte aligned)
   13786   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
   13787   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
   13788     .addReg(OverflowDestReg)
   13789     .addImm(ArgSizeA8);
   13790 
   13791   // Store the new overflow address.
   13792   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
   13793     .addOperand(Base)
   13794     .addOperand(Scale)
   13795     .addOperand(Index)
   13796     .addDisp(Disp, 8)
   13797     .addOperand(Segment)
   13798     .addReg(NextAddrReg)
   13799     .setMemRefs(MMOBegin, MMOEnd);
   13800 
   13801   // If we branched, emit the PHI to the front of endMBB.
   13802   if (offsetMBB) {
   13803     BuildMI(*endMBB, endMBB->begin(), DL,
   13804             TII->get(X86::PHI), DestReg)
   13805       .addReg(OffsetDestReg).addMBB(offsetMBB)
   13806       .addReg(OverflowDestReg).addMBB(overflowMBB);
   13807   }
   13808 
   13809   // Erase the pseudo instruction
   13810   MI->eraseFromParent();
   13811 
   13812   return endMBB;
   13813 }
   13814 
   13815 MachineBasicBlock *
   13816 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
   13817                                                  MachineInstr *MI,
   13818                                                  MachineBasicBlock *MBB) const {
   13819   // Emit code to save XMM registers to the stack. The ABI says that the
   13820   // number of registers to save is given in %al, so it's theoretically
   13821   // possible to do an indirect jump trick to avoid saving all of them,
   13822   // however this code takes a simpler approach and just executes all
   13823   // of the stores if %al is non-zero. It's less code, and it's probably
   13824   // easier on the hardware branch predictor, and stores aren't all that
   13825   // expensive anyway.
   13826 
   13827   // Create the new basic blocks. One block contains all the XMM stores,
   13828   // and one block is the final destination regardless of whether any
   13829   // stores were performed.
   13830   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
   13831   MachineFunction *F = MBB->getParent();
   13832   MachineFunction::iterator MBBIter = MBB;
   13833   ++MBBIter;
   13834   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
   13835   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
   13836   F->insert(MBBIter, XMMSaveMBB);
   13837   F->insert(MBBIter, EndMBB);
   13838 
   13839   // Transfer the remainder of MBB and its successor edges to EndMBB.
   13840   EndMBB->splice(EndMBB->begin(), MBB,
   13841                  llvm::next(MachineBasicBlock::iterator(MI)),
   13842                  MBB->end());
   13843   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
   13844 
   13845   // The original block will now fall through to the XMM save block.
   13846   MBB->addSuccessor(XMMSaveMBB);
   13847   // The XMMSaveMBB will fall through to the end block.
   13848   XMMSaveMBB->addSuccessor(EndMBB);
   13849 
   13850   // Now add the instructions.
   13851   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   13852   DebugLoc DL = MI->getDebugLoc();
   13853 
   13854   unsigned CountReg = MI->getOperand(0).getReg();
   13855   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
   13856   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
   13857 
   13858   if (!Subtarget->isTargetWin64()) {
   13859     // If %al is 0, branch around the XMM save block.
   13860     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
   13861     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
   13862     MBB->addSuccessor(EndMBB);
   13863   }
   13864 
   13865   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
   13866   // In the XMM save block, save all the XMM argument registers.
   13867   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
   13868     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
   13869     MachineMemOperand *MMO =
   13870       F->getMachineMemOperand(
   13871           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
   13872         MachineMemOperand::MOStore,
   13873         /*Size=*/16, /*Align=*/16);
   13874     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
   13875       .addFrameIndex(RegSaveFrameIndex)
   13876       .addImm(/*Scale=*/1)
   13877       .addReg(/*IndexReg=*/0)
   13878       .addImm(/*Disp=*/Offset)
   13879       .addReg(/*Segment=*/0)
   13880       .addReg(MI->getOperand(i).getReg())
   13881       .addMemOperand(MMO);
   13882   }
   13883 
   13884   MI->eraseFromParent();   // The pseudo instruction is gone now.
   13885 
   13886   return EndMBB;
   13887 }
   13888 
   13889 // The EFLAGS operand of SelectItr might be missing a kill marker
   13890 // because there were multiple uses of EFLAGS, and ISel didn't know
   13891 // which to mark. Figure out whether SelectItr should have had a
   13892 // kill marker, and set it if it should. Returns the correct kill
   13893 // marker value.
   13894 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
   13895                                      MachineBasicBlock* BB,
   13896                                      const TargetRegisterInfo* TRI) {
   13897   // Scan forward through BB for a use/def of EFLAGS.
   13898   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
   13899   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
   13900     const MachineInstr& mi = *miI;
   13901     if (mi.readsRegister(X86::EFLAGS))
   13902       return false;
   13903     if (mi.definesRegister(X86::EFLAGS))
   13904       break; // Should have kill-flag - update below.
   13905   }
   13906 
   13907   // If we hit the end of the block, check whether EFLAGS is live into a
   13908   // successor.
   13909   if (miI == BB->end()) {
   13910     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
   13911                                           sEnd = BB->succ_end();
   13912          sItr != sEnd; ++sItr) {
   13913       MachineBasicBlock* succ = *sItr;
   13914       if (succ->isLiveIn(X86::EFLAGS))
   13915         return false;
   13916     }
   13917   }
   13918 
   13919   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
   13920   // out. SelectMI should have a kill flag on EFLAGS.
   13921   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
   13922   return true;
   13923 }
   13924 
   13925 MachineBasicBlock *
   13926 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
   13927                                      MachineBasicBlock *BB) const {
   13928   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   13929   DebugLoc DL = MI->getDebugLoc();
   13930 
   13931   // To "insert" a SELECT_CC instruction, we actually have to insert the
   13932   // diamond control-flow pattern.  The incoming instruction knows the
   13933   // destination vreg to set, the condition code register to branch on, the
   13934   // true/false values to select between, and a branch opcode to use.
   13935   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   13936   MachineFunction::iterator It = BB;
   13937   ++It;
   13938 
   13939   //  thisMBB:
   13940   //  ...
   13941   //   TrueVal = ...
   13942   //   cmpTY ccX, r1, r2
   13943   //   bCC copy1MBB
   13944   //   fallthrough --> copy0MBB
   13945   MachineBasicBlock *thisMBB = BB;
   13946   MachineFunction *F = BB->getParent();
   13947   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
   13948   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
   13949   F->insert(It, copy0MBB);
   13950   F->insert(It, sinkMBB);
   13951 
   13952   // If the EFLAGS register isn't dead in the terminator, then claim that it's
   13953   // live into the sink and copy blocks.
   13954   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
   13955   if (!MI->killsRegister(X86::EFLAGS) &&
   13956       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
   13957     copy0MBB->addLiveIn(X86::EFLAGS);
   13958     sinkMBB->addLiveIn(X86::EFLAGS);
   13959   }
   13960 
   13961   // Transfer the remainder of BB and its successor edges to sinkMBB.
   13962   sinkMBB->splice(sinkMBB->begin(), BB,
   13963                   llvm::next(MachineBasicBlock::iterator(MI)),
   13964                   BB->end());
   13965   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
   13966 
   13967   // Add the true and fallthrough blocks as its successors.
   13968   BB->addSuccessor(copy0MBB);
   13969   BB->addSuccessor(sinkMBB);
   13970 
   13971   // Create the conditional branch instruction.
   13972   unsigned Opc =
   13973     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
   13974   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
   13975 
   13976   //  copy0MBB:
   13977   //   %FalseValue = ...
   13978   //   # fallthrough to sinkMBB
   13979   copy0MBB->addSuccessor(sinkMBB);
   13980 
   13981   //  sinkMBB:
   13982   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
   13983   //  ...
   13984   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
   13985           TII->get(X86::PHI), MI->getOperand(0).getReg())
   13986     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
   13987     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
   13988 
   13989   MI->eraseFromParent();   // The pseudo instruction is gone now.
   13990   return sinkMBB;
   13991 }
   13992 
   13993 MachineBasicBlock *
   13994 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
   13995                                         bool Is64Bit) const {
   13996   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   13997   DebugLoc DL = MI->getDebugLoc();
   13998   MachineFunction *MF = BB->getParent();
   13999   const BasicBlock *LLVM_BB = BB->getBasicBlock();
   14000 
   14001   assert(getTargetMachine().Options.EnableSegmentedStacks);
   14002 
   14003   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
   14004   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
   14005 
   14006   // BB:
   14007   //  ... [Till the alloca]
   14008   // If stacklet is not large enough, jump to mallocMBB
   14009   //
   14010   // bumpMBB:
   14011   //  Allocate by subtracting from RSP
   14012   //  Jump to continueMBB
   14013   //
   14014   // mallocMBB:
   14015   //  Allocate by call to runtime
   14016   //
   14017   // continueMBB:
   14018   //  ...
   14019   //  [rest of original BB]
   14020   //
   14021 
   14022   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   14023   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   14024   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
   14025 
   14026   MachineRegisterInfo &MRI = MF->getRegInfo();
   14027   const TargetRegisterClass *AddrRegClass =
   14028     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
   14029 
   14030   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
   14031     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
   14032     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
   14033     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
   14034     sizeVReg = MI->getOperand(1).getReg(),
   14035     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
   14036 
   14037   MachineFunction::iterator MBBIter = BB;
   14038   ++MBBIter;
   14039 
   14040   MF->insert(MBBIter, bumpMBB);
   14041   MF->insert(MBBIter, mallocMBB);
   14042   MF->insert(MBBIter, continueMBB);
   14043 
   14044   continueMBB->splice(continueMBB->begin(), BB, llvm::next
   14045                       (MachineBasicBlock::iterator(MI)), BB->end());
   14046   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
   14047 
   14048   // Add code to the main basic block to check if the stack limit has been hit,
   14049   // and if so, jump to mallocMBB otherwise to bumpMBB.
   14050   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
   14051   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
   14052     .addReg(tmpSPVReg).addReg(sizeVReg);
   14053   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
   14054     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
   14055     .addReg(SPLimitVReg);
   14056   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
   14057 
   14058   // bumpMBB simply decreases the stack pointer, since we know the current
   14059   // stacklet has enough space.
   14060   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
   14061     .addReg(SPLimitVReg);
   14062   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
   14063     .addReg(SPLimitVReg);
   14064   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
   14065 
   14066   // Calls into a routine in libgcc to allocate more space from the heap.
   14067   const uint32_t *RegMask =
   14068     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
   14069   if (Is64Bit) {
   14070     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
   14071       .addReg(sizeVReg);
   14072     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
   14073       .addExternalSymbol("__morestack_allocate_stack_space")
   14074       .addRegMask(RegMask)
   14075       .addReg(X86::RDI, RegState::Implicit)
   14076       .addReg(X86::RAX, RegState::ImplicitDefine);
   14077   } else {
   14078     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
   14079       .addImm(12);
   14080     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
   14081     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
   14082       .addExternalSymbol("__morestack_allocate_stack_space")
   14083       .addRegMask(RegMask)
   14084       .addReg(X86::EAX, RegState::ImplicitDefine);
   14085   }
   14086 
   14087   if (!Is64Bit)
   14088     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
   14089       .addImm(16);
   14090 
   14091   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
   14092     .addReg(Is64Bit ? X86::RAX : X86::EAX);
   14093   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
   14094 
   14095   // Set up the CFG correctly.
   14096   BB->addSuccessor(bumpMBB);
   14097   BB->addSuccessor(mallocMBB);
   14098   mallocMBB->addSuccessor(continueMBB);
   14099   bumpMBB->addSuccessor(continueMBB);
   14100 
   14101   // Take care of the PHI nodes.
   14102   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
   14103           MI->getOperand(0).getReg())
   14104     .addReg(mallocPtrVReg).addMBB(mallocMBB)
   14105     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
   14106 
   14107   // Delete the original pseudo instruction.
   14108   MI->eraseFromParent();
   14109 
   14110   // And we're done.
   14111   return continueMBB;
   14112 }
   14113 
   14114 MachineBasicBlock *
   14115 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
   14116                                           MachineBasicBlock *BB) const {
   14117   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   14118   DebugLoc DL = MI->getDebugLoc();
   14119 
   14120   assert(!Subtarget->isTargetEnvMacho());
   14121 
   14122   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
   14123   // non-trivial part is impdef of ESP.
   14124 
   14125   if (Subtarget->isTargetWin64()) {
   14126     if (Subtarget->isTargetCygMing()) {
   14127       // ___chkstk(Mingw64):
   14128       // Clobbers R10, R11, RAX and EFLAGS.
   14129       // Updates RSP.
   14130       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
   14131         .addExternalSymbol("___chkstk")
   14132         .addReg(X86::RAX, RegState::Implicit)
   14133         .addReg(X86::RSP, RegState::Implicit)
   14134         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
   14135         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
   14136         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
   14137     } else {
   14138       // __chkstk(MSVCRT): does not update stack pointer.
   14139       // Clobbers R10, R11 and EFLAGS.
   14140       // FIXME: RAX(allocated size) might be reused and not killed.
   14141       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
   14142         .addExternalSymbol("__chkstk")
   14143         .addReg(X86::RAX, RegState::Implicit)
   14144         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
   14145       // RAX has the offset to subtracted from RSP.
   14146       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
   14147         .addReg(X86::RSP)
   14148         .addReg(X86::RAX);
   14149     }
   14150   } else {
   14151     const char *StackProbeSymbol =
   14152       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
   14153 
   14154     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
   14155       .addExternalSymbol(StackProbeSymbol)
   14156       .addReg(X86::EAX, RegState::Implicit)
   14157       .addReg(X86::ESP, RegState::Implicit)
   14158       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
   14159       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
   14160       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
   14161   }
   14162 
   14163   MI->eraseFromParent();   // The pseudo instruction is gone now.
   14164   return BB;
   14165 }
   14166 
   14167 MachineBasicBlock *
   14168 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
   14169                                       MachineBasicBlock *BB) const {
   14170   // This is pretty easy.  We're taking the value that we received from
   14171   // our load from the relocation, sticking it in either RDI (x86-64)
   14172   // or EAX and doing an indirect call.  The return value will then
   14173   // be in the normal return register.
   14174   const X86InstrInfo *TII
   14175     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
   14176   DebugLoc DL = MI->getDebugLoc();
   14177   MachineFunction *F = BB->getParent();
   14178 
   14179   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
   14180   assert(MI->getOperand(3).isGlobal() && "This should be a global");
   14181 
   14182   // Get a register mask for the lowered call.
   14183   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
   14184   // proper register mask.
   14185   const uint32_t *RegMask =
   14186     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
   14187   if (Subtarget->is64Bit()) {
   14188     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
   14189                                       TII->get(X86::MOV64rm), X86::RDI)
   14190     .addReg(X86::RIP)
   14191     .addImm(0).addReg(0)
   14192     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
   14193                       MI->getOperand(3).getTargetFlags())
   14194     .addReg(0);
   14195     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
   14196     addDirectMem(MIB, X86::RDI);
   14197     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
   14198   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
   14199     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
   14200                                       TII->get(X86::MOV32rm), X86::EAX)
   14201     .addReg(0)
   14202     .addImm(0).addReg(0)
   14203     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
   14204                       MI->getOperand(3).getTargetFlags())
   14205     .addReg(0);
   14206     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
   14207     addDirectMem(MIB, X86::EAX);
   14208     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
   14209   } else {
   14210     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
   14211                                       TII->get(X86::MOV32rm), X86::EAX)
   14212     .addReg(TII->getGlobalBaseReg(F))
   14213     .addImm(0).addReg(0)
   14214     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
   14215                       MI->getOperand(3).getTargetFlags())
   14216     .addReg(0);
   14217     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
   14218     addDirectMem(MIB, X86::EAX);
   14219     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
   14220   }
   14221 
   14222   MI->eraseFromParent(); // The pseudo instruction is gone now.
   14223   return BB;
   14224 }
   14225 
   14226 MachineBasicBlock *
   14227 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
   14228                                     MachineBasicBlock *MBB) const {
   14229   DebugLoc DL = MI->getDebugLoc();
   14230   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   14231 
   14232   MachineFunction *MF = MBB->getParent();
   14233   MachineRegisterInfo &MRI = MF->getRegInfo();
   14234 
   14235   const BasicBlock *BB = MBB->getBasicBlock();
   14236   MachineFunction::iterator I = MBB;
   14237   ++I;
   14238 
   14239   // Memory Reference
   14240   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
   14241   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
   14242 
   14243   unsigned DstReg;
   14244   unsigned MemOpndSlot = 0;
   14245 
   14246   unsigned CurOp = 0;
   14247 
   14248   DstReg = MI->getOperand(CurOp++).getReg();
   14249   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
   14250   assert(RC->hasType(MVT::i32) && "Invalid destination!");
   14251   unsigned mainDstReg = MRI.createVirtualRegister(RC);
   14252   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
   14253 
   14254   MemOpndSlot = CurOp;
   14255 
   14256   MVT PVT = getPointerTy();
   14257   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
   14258          "Invalid Pointer Size!");
   14259 
   14260   // For v = setjmp(buf), we generate
   14261   //
   14262   // thisMBB:
   14263   //  buf[LabelOffset] = restoreMBB
   14264   //  SjLjSetup restoreMBB
   14265   //
   14266   // mainMBB:
   14267   //  v_main = 0
   14268   //
   14269   // sinkMBB:
   14270   //  v = phi(main, restore)
   14271   //
   14272   // restoreMBB:
   14273   //  v_restore = 1
   14274 
   14275   MachineBasicBlock *thisMBB = MBB;
   14276   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
   14277   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
   14278   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
   14279   MF->insert(I, mainMBB);
   14280   MF->insert(I, sinkMBB);
   14281   MF->push_back(restoreMBB);
   14282 
   14283   MachineInstrBuilder MIB;
   14284 
   14285   // Transfer the remainder of BB and its successor edges to sinkMBB.
   14286   sinkMBB->splice(sinkMBB->begin(), MBB,
   14287                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
   14288   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
   14289 
   14290   // thisMBB:
   14291   unsigned PtrStoreOpc = 0;
   14292   unsigned LabelReg = 0;
   14293   const int64_t LabelOffset = 1 * PVT.getStoreSize();
   14294   Reloc::Model RM = getTargetMachine().getRelocationModel();
   14295   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
   14296                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
   14297 
   14298   // Prepare IP either in reg or imm.
   14299   if (!UseImmLabel) {
   14300     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
   14301     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
   14302     LabelReg = MRI.createVirtualRegister(PtrRC);
   14303     if (Subtarget->is64Bit()) {
   14304       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
   14305               .addReg(X86::RIP)
   14306               .addImm(0)
   14307               .addReg(0)
   14308               .addMBB(restoreMBB)
   14309               .addReg(0);
   14310     } else {
   14311       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
   14312       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
   14313               .addReg(XII->getGlobalBaseReg(MF))
   14314               .addImm(0)
   14315               .addReg(0)
   14316               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
   14317               .addReg(0);
   14318     }
   14319   } else
   14320     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
   14321   // Store IP
   14322   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
   14323   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
   14324     if (i == X86::AddrDisp)
   14325       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
   14326     else
   14327       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
   14328   }
   14329   if (!UseImmLabel)
   14330     MIB.addReg(LabelReg);
   14331   else
   14332     MIB.addMBB(restoreMBB);
   14333   MIB.setMemRefs(MMOBegin, MMOEnd);
   14334   // Setup
   14335   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
   14336           .addMBB(restoreMBB);
   14337   MIB.addRegMask(RegInfo->getNoPreservedMask());
   14338   thisMBB->addSuccessor(mainMBB);
   14339   thisMBB->addSuccessor(restoreMBB);
   14340 
   14341   // mainMBB:
   14342   //  EAX = 0
   14343   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
   14344   mainMBB->addSuccessor(sinkMBB);
   14345 
   14346   // sinkMBB:
   14347   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
   14348           TII->get(X86::PHI), DstReg)
   14349     .addReg(mainDstReg).addMBB(mainMBB)
   14350     .addReg(restoreDstReg).addMBB(restoreMBB);
   14351 
   14352   // restoreMBB:
   14353   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
   14354   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
   14355   restoreMBB->addSuccessor(sinkMBB);
   14356 
   14357   MI->eraseFromParent();
   14358   return sinkMBB;
   14359 }
   14360 
   14361 MachineBasicBlock *
   14362 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
   14363                                      MachineBasicBlock *MBB) const {
   14364   DebugLoc DL = MI->getDebugLoc();
   14365   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   14366 
   14367   MachineFunction *MF = MBB->getParent();
   14368   MachineRegisterInfo &MRI = MF->getRegInfo();
   14369 
   14370   // Memory Reference
   14371   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
   14372   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
   14373 
   14374   MVT PVT = getPointerTy();
   14375   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
   14376          "Invalid Pointer Size!");
   14377 
   14378   const TargetRegisterClass *RC =
   14379     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
   14380   unsigned Tmp = MRI.createVirtualRegister(RC);
   14381   // Since FP is only updated here but NOT referenced, it's treated as GPR.
   14382   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
   14383   unsigned SP = RegInfo->getStackRegister();
   14384 
   14385   MachineInstrBuilder MIB;
   14386 
   14387   const int64_t LabelOffset = 1 * PVT.getStoreSize();
   14388   const int64_t SPOffset = 2 * PVT.getStoreSize();
   14389 
   14390   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
   14391   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
   14392 
   14393   // Reload FP
   14394   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
   14395   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
   14396     MIB.addOperand(MI->getOperand(i));
   14397   MIB.setMemRefs(MMOBegin, MMOEnd);
   14398   // Reload IP
   14399   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
   14400   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
   14401     if (i == X86::AddrDisp)
   14402       MIB.addDisp(MI->getOperand(i), LabelOffset);
   14403     else
   14404       MIB.addOperand(MI->getOperand(i));
   14405   }
   14406   MIB.setMemRefs(MMOBegin, MMOEnd);
   14407   // Reload SP
   14408   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
   14409   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
   14410     if (i == X86::AddrDisp)
   14411       MIB.addDisp(MI->getOperand(i), SPOffset);
   14412     else
   14413       MIB.addOperand(MI->getOperand(i));
   14414   }
   14415   MIB.setMemRefs(MMOBegin, MMOEnd);
   14416   // Jump
   14417   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
   14418 
   14419   MI->eraseFromParent();
   14420   return MBB;
   14421 }
   14422 
   14423 MachineBasicBlock *
   14424 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
   14425                                                MachineBasicBlock *BB) const {
   14426   switch (MI->getOpcode()) {
   14427   default: llvm_unreachable("Unexpected instr type to insert");
   14428   case X86::TAILJMPd64:
   14429   case X86::TAILJMPr64:
   14430   case X86::TAILJMPm64:
   14431     llvm_unreachable("TAILJMP64 would not be touched here.");
   14432   case X86::TCRETURNdi64:
   14433   case X86::TCRETURNri64:
   14434   case X86::TCRETURNmi64:
   14435     return BB;
   14436   case X86::WIN_ALLOCA:
   14437     return EmitLoweredWinAlloca(MI, BB);
   14438   case X86::SEG_ALLOCA_32:
   14439     return EmitLoweredSegAlloca(MI, BB, false);
   14440   case X86::SEG_ALLOCA_64:
   14441     return EmitLoweredSegAlloca(MI, BB, true);
   14442   case X86::TLSCall_32:
   14443   case X86::TLSCall_64:
   14444     return EmitLoweredTLSCall(MI, BB);
   14445   case X86::CMOV_GR8:
   14446   case X86::CMOV_FR32:
   14447   case X86::CMOV_FR64:
   14448   case X86::CMOV_V4F32:
   14449   case X86::CMOV_V2F64:
   14450   case X86::CMOV_V2I64:
   14451   case X86::CMOV_V8F32:
   14452   case X86::CMOV_V4F64:
   14453   case X86::CMOV_V4I64:
   14454   case X86::CMOV_GR16:
   14455   case X86::CMOV_GR32:
   14456   case X86::CMOV_RFP32:
   14457   case X86::CMOV_RFP64:
   14458   case X86::CMOV_RFP80:
   14459     return EmitLoweredSelect(MI, BB);
   14460 
   14461   case X86::FP32_TO_INT16_IN_MEM:
   14462   case X86::FP32_TO_INT32_IN_MEM:
   14463   case X86::FP32_TO_INT64_IN_MEM:
   14464   case X86::FP64_TO_INT16_IN_MEM:
   14465   case X86::FP64_TO_INT32_IN_MEM:
   14466   case X86::FP64_TO_INT64_IN_MEM:
   14467   case X86::FP80_TO_INT16_IN_MEM:
   14468   case X86::FP80_TO_INT32_IN_MEM:
   14469   case X86::FP80_TO_INT64_IN_MEM: {
   14470     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
   14471     DebugLoc DL = MI->getDebugLoc();
   14472 
   14473     // Change the floating point control register to use "round towards zero"
   14474     // mode when truncating to an integer value.
   14475     MachineFunction *F = BB->getParent();
   14476     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
   14477     addFrameReference(BuildMI(*BB, MI, DL,
   14478                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
   14479 
   14480     // Load the old value of the high byte of the control word...
   14481     unsigned OldCW =
   14482       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
   14483     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
   14484                       CWFrameIdx);
   14485 
   14486     // Set the high part to be round to zero...
   14487     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
   14488       .addImm(0xC7F);
   14489 
   14490     // Reload the modified control word now...
   14491     addFrameReference(BuildMI(*BB, MI, DL,
   14492                               TII->get(X86::FLDCW16m)), CWFrameIdx);
   14493 
   14494     // Restore the memory image of control word to original value
   14495     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
   14496       .addReg(OldCW);
   14497 
   14498     // Get the X86 opcode to use.
   14499     unsigned Opc;
   14500     switch (MI->getOpcode()) {
   14501     default: llvm_unreachable("illegal opcode!");
   14502     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
   14503     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
   14504     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
   14505     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
   14506     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
   14507     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
   14508     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
   14509     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
   14510     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
   14511     }
   14512 
   14513     X86AddressMode AM;
   14514     MachineOperand &Op = MI->getOperand(0);
   14515     if (Op.isReg()) {
   14516       AM.BaseType = X86AddressMode::RegBase;
   14517       AM.Base.Reg = Op.getReg();
   14518     } else {
   14519       AM.BaseType = X86AddressMode::FrameIndexBase;
   14520       AM.Base.FrameIndex = Op.getIndex();
   14521     }
   14522     Op = MI->getOperand(1);
   14523     if (Op.isImm())
   14524       AM.Scale = Op.getImm();
   14525     Op = MI->getOperand(2);
   14526     if (Op.isImm())
   14527       AM.IndexReg = Op.getImm();
   14528     Op = MI->getOperand(3);
   14529     if (Op.isGlobal()) {
   14530       AM.GV = Op.getGlobal();
   14531     } else {
   14532       AM.Disp = Op.getImm();
   14533     }
   14534     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
   14535                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
   14536 
   14537     // Reload the original control word now.
   14538     addFrameReference(BuildMI(*BB, MI, DL,
   14539                               TII->get(X86::FLDCW16m)), CWFrameIdx);
   14540 
   14541     MI->eraseFromParent();   // The pseudo instruction is gone now.
   14542     return BB;
   14543   }
   14544     // String/text processing lowering.
   14545   case X86::PCMPISTRM128REG:
   14546   case X86::VPCMPISTRM128REG:
   14547   case X86::PCMPISTRM128MEM:
   14548   case X86::VPCMPISTRM128MEM:
   14549   case X86::PCMPESTRM128REG:
   14550   case X86::VPCMPESTRM128REG:
   14551   case X86::PCMPESTRM128MEM:
   14552   case X86::VPCMPESTRM128MEM:
   14553     assert(Subtarget->hasSSE42() &&
   14554            "Target must have SSE4.2 or AVX features enabled");
   14555     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
   14556 
   14557   // String/text processing lowering.
   14558   case X86::PCMPISTRIREG:
   14559   case X86::VPCMPISTRIREG:
   14560   case X86::PCMPISTRIMEM:
   14561   case X86::VPCMPISTRIMEM:
   14562   case X86::PCMPESTRIREG:
   14563   case X86::VPCMPESTRIREG:
   14564   case X86::PCMPESTRIMEM:
   14565   case X86::VPCMPESTRIMEM:
   14566     assert(Subtarget->hasSSE42() &&
   14567            "Target must have SSE4.2 or AVX features enabled");
   14568     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
   14569 
   14570   // Thread synchronization.
   14571   case X86::MONITOR:
   14572     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
   14573 
   14574   // xbegin
   14575   case X86::XBEGIN:
   14576     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
   14577 
   14578   // Atomic Lowering.
   14579   case X86::ATOMAND8:
   14580   case X86::ATOMAND16:
   14581   case X86::ATOMAND32:
   14582   case X86::ATOMAND64:
   14583     // Fall through
   14584   case X86::ATOMOR8:
   14585   case X86::ATOMOR16:
   14586   case X86::ATOMOR32:
   14587   case X86::ATOMOR64:
   14588     // Fall through
   14589   case X86::ATOMXOR16:
   14590   case X86::ATOMXOR8:
   14591   case X86::ATOMXOR32:
   14592   case X86::ATOMXOR64:
   14593     // Fall through
   14594   case X86::ATOMNAND8:
   14595   case X86::ATOMNAND16:
   14596   case X86::ATOMNAND32:
   14597   case X86::ATOMNAND64:
   14598     // Fall through
   14599   case X86::ATOMMAX8:
   14600   case X86::ATOMMAX16:
   14601   case X86::ATOMMAX32:
   14602   case X86::ATOMMAX64:
   14603     // Fall through
   14604   case X86::ATOMMIN8:
   14605   case X86::ATOMMIN16:
   14606   case X86::ATOMMIN32:
   14607   case X86::ATOMMIN64:
   14608     // Fall through
   14609   case X86::ATOMUMAX8:
   14610   case X86::ATOMUMAX16:
   14611   case X86::ATOMUMAX32:
   14612   case X86::ATOMUMAX64:
   14613     // Fall through
   14614   case X86::ATOMUMIN8:
   14615   case X86::ATOMUMIN16:
   14616   case X86::ATOMUMIN32:
   14617   case X86::ATOMUMIN64:
   14618     return EmitAtomicLoadArith(MI, BB);
   14619 
   14620   // This group does 64-bit operations on a 32-bit host.
   14621   case X86::ATOMAND6432:
   14622   case X86::ATOMOR6432:
   14623   case X86::ATOMXOR6432:
   14624   case X86::ATOMNAND6432:
   14625   case X86::ATOMADD6432:
   14626   case X86::ATOMSUB6432:
   14627   case X86::ATOMMAX6432:
   14628   case X86::ATOMMIN6432:
   14629   case X86::ATOMUMAX6432:
   14630   case X86::ATOMUMIN6432:
   14631   case X86::ATOMSWAP6432:
   14632     return EmitAtomicLoadArith6432(MI, BB);
   14633 
   14634   case X86::VASTART_SAVE_XMM_REGS:
   14635     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
   14636 
   14637   case X86::VAARG_64:
   14638     return EmitVAARG64WithCustomInserter(MI, BB);
   14639 
   14640   case X86::EH_SjLj_SetJmp32:
   14641   case X86::EH_SjLj_SetJmp64:
   14642     return emitEHSjLjSetJmp(MI, BB);
   14643 
   14644   case X86::EH_SjLj_LongJmp32:
   14645   case X86::EH_SjLj_LongJmp64:
   14646     return emitEHSjLjLongJmp(MI, BB);
   14647   }
   14648 }
   14649 
   14650 //===----------------------------------------------------------------------===//
   14651 //                           X86 Optimization Hooks
   14652 //===----------------------------------------------------------------------===//
   14653 
   14654 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
   14655                                                        APInt &KnownZero,
   14656                                                        APInt &KnownOne,
   14657                                                        const SelectionDAG &DAG,
   14658                                                        unsigned Depth) const {
   14659   unsigned BitWidth = KnownZero.getBitWidth();
   14660   unsigned Opc = Op.getOpcode();
   14661   assert((Opc >= ISD::BUILTIN_OP_END ||
   14662           Opc == ISD::INTRINSIC_WO_CHAIN ||
   14663           Opc == ISD::INTRINSIC_W_CHAIN ||
   14664           Opc == ISD::INTRINSIC_VOID) &&
   14665          "Should use MaskedValueIsZero if you don't know whether Op"
   14666          " is a target node!");
   14667 
   14668   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
   14669   switch (Opc) {
   14670   default: break;
   14671   case X86ISD::ADD:
   14672   case X86ISD::SUB:
   14673   case X86ISD::ADC:
   14674   case X86ISD::SBB:
   14675   case X86ISD::SMUL:
   14676   case X86ISD::UMUL:
   14677   case X86ISD::INC:
   14678   case X86ISD::DEC:
   14679   case X86ISD::OR:
   14680   case X86ISD::XOR:
   14681   case X86ISD::AND:
   14682     // These nodes' second result is a boolean.
   14683     if (Op.getResNo() == 0)
   14684       break;
   14685     // Fallthrough
   14686   case X86ISD::SETCC:
   14687     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
   14688     break;
   14689   case ISD::INTRINSIC_WO_CHAIN: {
   14690     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
   14691     unsigned NumLoBits = 0;
   14692     switch (IntId) {
   14693     default: break;
   14694     case Intrinsic::x86_sse_movmsk_ps:
   14695     case Intrinsic::x86_avx_movmsk_ps_256:
   14696     case Intrinsic::x86_sse2_movmsk_pd:
   14697     case Intrinsic::x86_avx_movmsk_pd_256:
   14698     case Intrinsic::x86_mmx_pmovmskb:
   14699     case Intrinsic::x86_sse2_pmovmskb_128:
   14700     case Intrinsic::x86_avx2_pmovmskb: {
   14701       // High bits of movmskp{s|d}, pmovmskb are known zero.
   14702       switch (IntId) {
   14703         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
   14704         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
   14705         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
   14706         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
   14707         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
   14708         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
   14709         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
   14710         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
   14711       }
   14712       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
   14713       break;
   14714     }
   14715     }
   14716     break;
   14717   }
   14718   }
   14719 }
   14720 
   14721 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
   14722                                                          unsigned Depth) const {
   14723   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
   14724   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
   14725     return Op.getValueType().getScalarType().getSizeInBits();
   14726 
   14727   // Fallback case.
   14728   return 1;
   14729 }
   14730 
   14731 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
   14732 /// node is a GlobalAddress + offset.
   14733 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
   14734                                        const GlobalValue* &GA,
   14735                                        int64_t &Offset) const {
   14736   if (N->getOpcode() == X86ISD::Wrapper) {
   14737     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
   14738       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
   14739       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
   14740       return true;
   14741     }
   14742   }
   14743   return TargetLowering::isGAPlusOffset(N, GA, Offset);
   14744 }
   14745 
   14746 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
   14747 /// same as extracting the high 128-bit part of 256-bit vector and then
   14748 /// inserting the result into the low part of a new 256-bit vector
   14749 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
   14750   EVT VT = SVOp->getValueType(0);
   14751   unsigned NumElems = VT.getVectorNumElements();
   14752 
   14753   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
   14754   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
   14755     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
   14756         SVOp->getMaskElt(j) >= 0)
   14757       return false;
   14758 
   14759   return true;
   14760 }
   14761 
   14762 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
   14763 /// same as extracting the low 128-bit part of 256-bit vector and then
   14764 /// inserting the result into the high part of a new 256-bit vector
   14765 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
   14766   EVT VT = SVOp->getValueType(0);
   14767   unsigned NumElems = VT.getVectorNumElements();
   14768 
   14769   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
   14770   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
   14771     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
   14772         SVOp->getMaskElt(j) >= 0)
   14773       return false;
   14774 
   14775   return true;
   14776 }
   14777 
   14778 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
   14779 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
   14780                                         TargetLowering::DAGCombinerInfo &DCI,
   14781                                         const X86Subtarget* Subtarget) {
   14782   DebugLoc dl = N->getDebugLoc();
   14783   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
   14784   SDValue V1 = SVOp->getOperand(0);
   14785   SDValue V2 = SVOp->getOperand(1);
   14786   EVT VT = SVOp->getValueType(0);
   14787   unsigned NumElems = VT.getVectorNumElements();
   14788 
   14789   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
   14790       V2.getOpcode() == ISD::CONCAT_VECTORS) {
   14791     //
   14792     //                   0,0,0,...
   14793     //                      |
   14794     //    V      UNDEF    BUILD_VECTOR    UNDEF
   14795     //     \      /           \           /
   14796     //  CONCAT_VECTOR         CONCAT_VECTOR
   14797     //         \                  /
   14798     //          \                /
   14799     //          RESULT: V + zero extended
   14800     //
   14801     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
   14802         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
   14803         V1.getOperand(1).getOpcode() != ISD::UNDEF)
   14804       return SDValue();
   14805 
   14806     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
   14807       return SDValue();
   14808 
   14809     // To match the shuffle mask, the first half of the mask should
   14810     // be exactly the first vector, and all the rest a splat with the
   14811     // first element of the second one.
   14812     for (unsigned i = 0; i != NumElems/2; ++i)
   14813       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
   14814           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
   14815         return SDValue();
   14816 
   14817     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
   14818     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
   14819       if (Ld->hasNUsesOfValue(1, 0)) {
   14820         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
   14821         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
   14822         SDValue ResNode =
   14823           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
   14824                                   Ld->getMemoryVT(),
   14825                                   Ld->getPointerInfo(),
   14826                                   Ld->getAlignment(),
   14827                                   false/*isVolatile*/, true/*ReadMem*/,
   14828                                   false/*WriteMem*/);
   14829 
   14830         // Make sure the newly-created LOAD is in the same position as Ld in
   14831         // terms of dependency. We create a TokenFactor for Ld and ResNode,
   14832         // and update uses of Ld's output chain to use the TokenFactor.
   14833         if (Ld->hasAnyUseOfValue(1)) {
   14834           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
   14835                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
   14836           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
   14837           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
   14838                                  SDValue(ResNode.getNode(), 1));
   14839         }
   14840 
   14841         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
   14842       }
   14843     }
   14844 
   14845     // Emit a zeroed vector and insert the desired subvector on its
   14846     // first half.
   14847     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
   14848     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
   14849     return DCI.CombineTo(N, InsV);
   14850   }
   14851 
   14852   //===--------------------------------------------------------------------===//
   14853   // Combine some shuffles into subvector extracts and inserts:
   14854   //
   14855 
   14856   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
   14857   if (isShuffleHigh128VectorInsertLow(SVOp)) {
   14858     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
   14859     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
   14860     return DCI.CombineTo(N, InsV);
   14861   }
   14862 
   14863   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
   14864   if (isShuffleLow128VectorInsertHigh(SVOp)) {
   14865     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
   14866     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
   14867     return DCI.CombineTo(N, InsV);
   14868   }
   14869 
   14870   return SDValue();
   14871 }
   14872 
   14873 /// PerformShuffleCombine - Performs several different shuffle combines.
   14874 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
   14875                                      TargetLowering::DAGCombinerInfo &DCI,
   14876                                      const X86Subtarget *Subtarget) {
   14877   DebugLoc dl = N->getDebugLoc();
   14878   EVT VT = N->getValueType(0);
   14879 
   14880   // Don't create instructions with illegal types after legalize types has run.
   14881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   14882   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
   14883     return SDValue();
   14884 
   14885   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
   14886   if (Subtarget->hasFp256() && VT.is256BitVector() &&
   14887       N->getOpcode() == ISD::VECTOR_SHUFFLE)
   14888     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
   14889 
   14890   // Only handle 128 wide vector from here on.
   14891   if (!VT.is128BitVector())
   14892     return SDValue();
   14893 
   14894   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
   14895   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
   14896   // consecutive, non-overlapping, and in the right order.
   14897   SmallVector<SDValue, 16> Elts;
   14898   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
   14899     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
   14900 
   14901   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
   14902 }
   14903 
   14904 /// PerformTruncateCombine - Converts truncate operation to
   14905 /// a sequence of vector shuffle operations.
   14906 /// It is possible when we truncate 256-bit vector to 128-bit vector
   14907 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
   14908                                       TargetLowering::DAGCombinerInfo &DCI,
   14909                                       const X86Subtarget *Subtarget)  {
   14910   return SDValue();
   14911 }
   14912 
   14913 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
   14914 /// specific shuffle of a load can be folded into a single element load.
   14915 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
   14916 /// shuffles have been customed lowered so we need to handle those here.
   14917 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
   14918                                          TargetLowering::DAGCombinerInfo &DCI) {
   14919   if (DCI.isBeforeLegalizeOps())
   14920     return SDValue();
   14921 
   14922   SDValue InVec = N->getOperand(0);
   14923   SDValue EltNo = N->getOperand(1);
   14924 
   14925   if (!isa<ConstantSDNode>(EltNo))
   14926     return SDValue();
   14927 
   14928   EVT VT = InVec.getValueType();
   14929 
   14930   bool HasShuffleIntoBitcast = false;
   14931   if (InVec.getOpcode() == ISD::BITCAST) {
   14932     // Don't duplicate a load with other uses.
   14933     if (!InVec.hasOneUse())
   14934       return SDValue();
   14935     EVT BCVT = InVec.getOperand(0).getValueType();
   14936     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
   14937       return SDValue();
   14938     InVec = InVec.getOperand(0);
   14939     HasShuffleIntoBitcast = true;
   14940   }
   14941 
   14942   if (!isTargetShuffle(InVec.getOpcode()))
   14943     return SDValue();
   14944 
   14945   // Don't duplicate a load with other uses.
   14946   if (!InVec.hasOneUse())
   14947     return SDValue();
   14948 
   14949   SmallVector<int, 16> ShuffleMask;
   14950   bool UnaryShuffle;
   14951   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
   14952                             UnaryShuffle))
   14953     return SDValue();
   14954 
   14955   // Select the input vector, guarding against out of range extract vector.
   14956   unsigned NumElems = VT.getVectorNumElements();
   14957   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
   14958   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
   14959   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
   14960                                          : InVec.getOperand(1);
   14961 
   14962   // If inputs to shuffle are the same for both ops, then allow 2 uses
   14963   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
   14964 
   14965   if (LdNode.getOpcode() == ISD::BITCAST) {
   14966     // Don't duplicate a load with other uses.
   14967     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
   14968       return SDValue();
   14969 
   14970     AllowedUses = 1; // only allow 1 load use if we have a bitcast
   14971     LdNode = LdNode.getOperand(0);
   14972   }
   14973 
   14974   if (!ISD::isNormalLoad(LdNode.getNode()))
   14975     return SDValue();
   14976 
   14977   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
   14978 
   14979   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
   14980     return SDValue();
   14981 
   14982   if (HasShuffleIntoBitcast) {
   14983     // If there's a bitcast before the shuffle, check if the load type and
   14984     // alignment is valid.
   14985     unsigned Align = LN0->getAlignment();
   14986     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   14987     unsigned NewAlign = TLI.getDataLayout()->
   14988       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
   14989 
   14990     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
   14991       return SDValue();
   14992   }
   14993 
   14994   // All checks match so transform back to vector_shuffle so that DAG combiner
   14995   // can finish the job
   14996   DebugLoc dl = N->getDebugLoc();
   14997 
   14998   // Create shuffle node taking into account the case that its a unary shuffle
   14999   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
   15000   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
   15001                                  InVec.getOperand(0), Shuffle,
   15002                                  &ShuffleMask[0]);
   15003   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
   15004   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
   15005                      EltNo);
   15006 }
   15007 
   15008 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
   15009 /// generation and convert it from being a bunch of shuffles and extracts
   15010 /// to a simple store and scalar loads to extract the elements.
   15011 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
   15012                                          TargetLowering::DAGCombinerInfo &DCI) {
   15013   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
   15014   if (NewOp.getNode())
   15015     return NewOp;
   15016 
   15017   SDValue InputVector = N->getOperand(0);
   15018   // Detect whether we are trying to convert from mmx to i32 and the bitcast
   15019   // from mmx to v2i32 has a single usage.
   15020   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
   15021       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
   15022       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
   15023     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
   15024                        N->getValueType(0),
   15025                        InputVector.getNode()->getOperand(0));
   15026 
   15027   // Only operate on vectors of 4 elements, where the alternative shuffling
   15028   // gets to be more expensive.
   15029   if (InputVector.getValueType() != MVT::v4i32)
   15030     return SDValue();
   15031 
   15032   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
   15033   // single use which is a sign-extend or zero-extend, and all elements are
   15034   // used.
   15035   SmallVector<SDNode *, 4> Uses;
   15036   unsigned ExtractedElements = 0;
   15037   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
   15038        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
   15039     if (UI.getUse().getResNo() != InputVector.getResNo())
   15040       return SDValue();
   15041 
   15042     SDNode *Extract = *UI;
   15043     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
   15044       return SDValue();
   15045 
   15046     if (Extract->getValueType(0) != MVT::i32)
   15047       return SDValue();
   15048     if (!Extract->hasOneUse())
   15049       return SDValue();
   15050     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
   15051         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
   15052       return SDValue();
   15053     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
   15054       return SDValue();
   15055 
   15056     // Record which element was extracted.
   15057     ExtractedElements |=
   15058       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
   15059 
   15060     Uses.push_back(Extract);
   15061   }
   15062 
   15063   // If not all the elements were used, this may not be worthwhile.
   15064   if (ExtractedElements != 15)
   15065     return SDValue();
   15066 
   15067   // Ok, we've now decided to do the transformation.
   15068   DebugLoc dl = InputVector.getDebugLoc();
   15069 
   15070   // Store the value to a temporary stack slot.
   15071   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
   15072   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
   15073                             MachinePointerInfo(), false, false, 0);
   15074 
   15075   // Replace each use (extract) with a load of the appropriate element.
   15076   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
   15077        UE = Uses.end(); UI != UE; ++UI) {
   15078     SDNode *Extract = *UI;
   15079 
   15080     // cOMpute the element's address.
   15081     SDValue Idx = Extract->getOperand(1);
   15082     unsigned EltSize =
   15083         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
   15084     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
   15085     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   15086     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
   15087 
   15088     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
   15089                                      StackPtr, OffsetVal);
   15090 
   15091     // Load the scalar.
   15092     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
   15093                                      ScalarAddr, MachinePointerInfo(),
   15094                                      false, false, false, 0);
   15095 
   15096     // Replace the exact with the load.
   15097     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
   15098   }
   15099 
   15100   // The replacement was made in place; don't return anything.
   15101   return SDValue();
   15102 }
   15103 
   15104 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
   15105 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
   15106                                    SDValue RHS, SelectionDAG &DAG,
   15107                                    const X86Subtarget *Subtarget) {
   15108   if (!VT.isVector())
   15109     return 0;
   15110 
   15111   switch (VT.getSimpleVT().SimpleTy) {
   15112   default: return 0;
   15113   case MVT::v32i8:
   15114   case MVT::v16i16:
   15115   case MVT::v8i32:
   15116     if (!Subtarget->hasAVX2())
   15117       return 0;
   15118   case MVT::v16i8:
   15119   case MVT::v8i16:
   15120   case MVT::v4i32:
   15121     if (!Subtarget->hasSSE2())
   15122       return 0;
   15123   }
   15124 
   15125   // SSE2 has only a small subset of the operations.
   15126   bool hasUnsigned = Subtarget->hasSSE41() ||
   15127                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
   15128   bool hasSigned = Subtarget->hasSSE41() ||
   15129                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
   15130 
   15131   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
   15132 
   15133   // Check for x CC y ? x : y.
   15134   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
   15135       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
   15136     switch (CC) {
   15137     default: break;
   15138     case ISD::SETULT:
   15139     case ISD::SETULE:
   15140       return hasUnsigned ? X86ISD::UMIN : 0;
   15141     case ISD::SETUGT:
   15142     case ISD::SETUGE:
   15143       return hasUnsigned ? X86ISD::UMAX : 0;
   15144     case ISD::SETLT:
   15145     case ISD::SETLE:
   15146       return hasSigned ? X86ISD::SMIN : 0;
   15147     case ISD::SETGT:
   15148     case ISD::SETGE:
   15149       return hasSigned ? X86ISD::SMAX : 0;
   15150     }
   15151   // Check for x CC y ? y : x -- a min/max with reversed arms.
   15152   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
   15153              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
   15154     switch (CC) {
   15155     default: break;
   15156     case ISD::SETULT:
   15157     case ISD::SETULE:
   15158       return hasUnsigned ? X86ISD::UMAX : 0;
   15159     case ISD::SETUGT:
   15160     case ISD::SETUGE:
   15161       return hasUnsigned ? X86ISD::UMIN : 0;
   15162     case ISD::SETLT:
   15163     case ISD::SETLE:
   15164       return hasSigned ? X86ISD::SMAX : 0;
   15165     case ISD::SETGT:
   15166     case ISD::SETGE:
   15167       return hasSigned ? X86ISD::SMIN : 0;
   15168     }
   15169   }
   15170 
   15171   return 0;
   15172 }
   15173 
   15174 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
   15175 /// nodes.
   15176 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
   15177                                     TargetLowering::DAGCombinerInfo &DCI,
   15178                                     const X86Subtarget *Subtarget) {
   15179   DebugLoc DL = N->getDebugLoc();
   15180   SDValue Cond = N->getOperand(0);
   15181   // Get the LHS/RHS of the select.
   15182   SDValue LHS = N->getOperand(1);
   15183   SDValue RHS = N->getOperand(2);
   15184   EVT VT = LHS.getValueType();
   15185 
   15186   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
   15187   // instructions match the semantics of the common C idiom x<y?x:y but not
   15188   // x<=y?x:y, because of how they handle negative zero (which can be
   15189   // ignored in unsafe-math mode).
   15190   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
   15191       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
   15192       (Subtarget->hasSSE2() ||
   15193        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
   15194     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
   15195 
   15196     unsigned Opcode = 0;
   15197     // Check for x CC y ? x : y.
   15198     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
   15199         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
   15200       switch (CC) {
   15201       default: break;
   15202       case ISD::SETULT:
   15203         // Converting this to a min would handle NaNs incorrectly, and swapping
   15204         // the operands would cause it to handle comparisons between positive
   15205         // and negative zero incorrectly.
   15206         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
   15207           if (!DAG.getTarget().Options.UnsafeFPMath &&
   15208               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
   15209             break;
   15210           std::swap(LHS, RHS);
   15211         }
   15212         Opcode = X86ISD::FMIN;
   15213         break;
   15214       case ISD::SETOLE:
   15215         // Converting this to a min would handle comparisons between positive
   15216         // and negative zero incorrectly.
   15217         if (!DAG.getTarget().Options.UnsafeFPMath &&
   15218             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
   15219           break;
   15220         Opcode = X86ISD::FMIN;
   15221         break;
   15222       case ISD::SETULE:
   15223         // Converting this to a min would handle both negative zeros and NaNs
   15224         // incorrectly, but we can swap the operands to fix both.
   15225         std::swap(LHS, RHS);
   15226       case ISD::SETOLT:
   15227       case ISD::SETLT:
   15228       case ISD::SETLE:
   15229         Opcode = X86ISD::FMIN;
   15230         break;
   15231 
   15232       case ISD::SETOGE:
   15233         // Converting this to a max would handle comparisons between positive
   15234         // and negative zero incorrectly.
   15235         if (!DAG.getTarget().Options.UnsafeFPMath &&
   15236             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
   15237           break;
   15238         Opcode = X86ISD::FMAX;
   15239         break;
   15240       case ISD::SETUGT:
   15241         // Converting this to a max would handle NaNs incorrectly, and swapping
   15242         // the operands would cause it to handle comparisons between positive
   15243         // and negative zero incorrectly.
   15244         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
   15245           if (!DAG.getTarget().Options.UnsafeFPMath &&
   15246               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
   15247             break;
   15248           std::swap(LHS, RHS);
   15249         }
   15250         Opcode = X86ISD::FMAX;
   15251         break;
   15252       case ISD::SETUGE:
   15253         // Converting this to a max would handle both negative zeros and NaNs
   15254         // incorrectly, but we can swap the operands to fix both.
   15255         std::swap(LHS, RHS);
   15256       case ISD::SETOGT:
   15257       case ISD::SETGT:
   15258       case ISD::SETGE:
   15259         Opcode = X86ISD::FMAX;
   15260         break;
   15261       }
   15262     // Check for x CC y ? y : x -- a min/max with reversed arms.
   15263     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
   15264                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
   15265       switch (CC) {
   15266       default: break;
   15267       case ISD::SETOGE:
   15268         // Converting this to a min would handle comparisons between positive
   15269         // and negative zero incorrectly, and swapping the operands would
   15270         // cause it to handle NaNs incorrectly.
   15271         if (!DAG.getTarget().Options.UnsafeFPMath &&
   15272             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
   15273           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
   15274             break;
   15275           std::swap(LHS, RHS);
   15276         }
   15277         Opcode = X86ISD::FMIN;
   15278         break;
   15279       case ISD::SETUGT:
   15280         // Converting this to a min would handle NaNs incorrectly.
   15281         if (!DAG.getTarget().Options.UnsafeFPMath &&
   15282             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
   15283           break;
   15284         Opcode = X86ISD::FMIN;
   15285         break;
   15286       case ISD::SETUGE:
   15287         // Converting this to a min would handle both negative zeros and NaNs
   15288         // incorrectly, but we can swap the operands to fix both.
   15289         std::swap(LHS, RHS);
   15290       case ISD::SETOGT:
   15291       case ISD::SETGT:
   15292       case ISD::SETGE:
   15293         Opcode = X86ISD::FMIN;
   15294         break;
   15295 
   15296       case ISD::SETULT:
   15297         // Converting this to a max would handle NaNs incorrectly.
   15298         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
   15299           break;
   15300         Opcode = X86ISD::FMAX;
   15301         break;
   15302       case ISD::SETOLE:
   15303         // Converting this to a max would handle comparisons between positive
   15304         // and negative zero incorrectly, and swapping the operands would
   15305         // cause it to handle NaNs incorrectly.
   15306         if (!DAG.getTarget().Options.UnsafeFPMath &&
   15307             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
   15308           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
   15309             break;
   15310           std::swap(LHS, RHS);
   15311         }
   15312         Opcode = X86ISD::FMAX;
   15313         break;
   15314       case ISD::SETULE:
   15315         // Converting this to a max would handle both negative zeros and NaNs
   15316         // incorrectly, but we can swap the operands to fix both.
   15317         std::swap(LHS, RHS);
   15318       case ISD::SETOLT:
   15319       case ISD::SETLT:
   15320       case ISD::SETLE:
   15321         Opcode = X86ISD::FMAX;
   15322         break;
   15323       }
   15324     }
   15325 
   15326     if (Opcode)
   15327       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
   15328   }
   15329 
   15330   // If this is a select between two integer constants, try to do some
   15331   // optimizations.
   15332   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
   15333     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
   15334       // Don't do this for crazy integer types.
   15335       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
   15336         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
   15337         // so that TrueC (the true value) is larger than FalseC.
   15338         bool NeedsCondInvert = false;
   15339 
   15340         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
   15341             // Efficiently invertible.
   15342             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
   15343              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
   15344               isa<ConstantSDNode>(Cond.getOperand(1))))) {
   15345           NeedsCondInvert = true;
   15346           std::swap(TrueC, FalseC);
   15347         }
   15348 
   15349         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
   15350         if (FalseC->getAPIntValue() == 0 &&
   15351             TrueC->getAPIntValue().isPowerOf2()) {
   15352           if (NeedsCondInvert) // Invert the condition if needed.
   15353             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
   15354                                DAG.getConstant(1, Cond.getValueType()));
   15355 
   15356           // Zero extend the condition if needed.
   15357           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
   15358 
   15359           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
   15360           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
   15361                              DAG.getConstant(ShAmt, MVT::i8));
   15362         }
   15363 
   15364         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
   15365         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
   15366           if (NeedsCondInvert) // Invert the condition if needed.
   15367             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
   15368                                DAG.getConstant(1, Cond.getValueType()));
   15369 
   15370           // Zero extend the condition if needed.
   15371           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
   15372                              FalseC->getValueType(0), Cond);
   15373           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
   15374                              SDValue(FalseC, 0));
   15375         }
   15376 
   15377         // Optimize cases that will turn into an LEA instruction.  This requires
   15378         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
   15379         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
   15380           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
   15381           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
   15382 
   15383           bool isFastMultiplier = false;
   15384           if (Diff < 10) {
   15385             switch ((unsigned char)Diff) {
   15386               default: break;
   15387               case 1:  // result = add base, cond
   15388               case 2:  // result = lea base(    , cond*2)
   15389               case 3:  // result = lea base(cond, cond*2)
   15390               case 4:  // result = lea base(    , cond*4)
   15391               case 5:  // result = lea base(cond, cond*4)
   15392               case 8:  // result = lea base(    , cond*8)
   15393               case 9:  // result = lea base(cond, cond*8)
   15394                 isFastMultiplier = true;
   15395                 break;
   15396             }
   15397           }
   15398 
   15399           if (isFastMultiplier) {
   15400             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
   15401             if (NeedsCondInvert) // Invert the condition if needed.
   15402               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
   15403                                  DAG.getConstant(1, Cond.getValueType()));
   15404 
   15405             // Zero extend the condition if needed.
   15406             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
   15407                                Cond);
   15408             // Scale the condition by the difference.
   15409             if (Diff != 1)
   15410               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
   15411                                  DAG.getConstant(Diff, Cond.getValueType()));
   15412 
   15413             // Add the base if non-zero.
   15414             if (FalseC->getAPIntValue() != 0)
   15415               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
   15416                                  SDValue(FalseC, 0));
   15417             return Cond;
   15418           }
   15419         }
   15420       }
   15421   }
   15422 
   15423   // Canonicalize max and min:
   15424   // (x > y) ? x : y -> (x >= y) ? x : y
   15425   // (x < y) ? x : y -> (x <= y) ? x : y
   15426   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
   15427   // the need for an extra compare
   15428   // against zero. e.g.
   15429   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
   15430   // subl   %esi, %edi
   15431   // testl  %edi, %edi
   15432   // movl   $0, %eax
   15433   // cmovgl %edi, %eax
   15434   // =>
   15435   // xorl   %eax, %eax
   15436   // subl   %esi, $edi
   15437   // cmovsl %eax, %edi
   15438   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
   15439       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
   15440       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
   15441     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
   15442     switch (CC) {
   15443     default: break;
   15444     case ISD::SETLT:
   15445     case ISD::SETGT: {
   15446       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
   15447       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
   15448                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
   15449       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
   15450     }
   15451     }
   15452   }
   15453 
   15454   // Match VSELECTs into subs with unsigned saturation.
   15455   if (!DCI.isBeforeLegalize() &&
   15456       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
   15457       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
   15458       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
   15459        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
   15460     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
   15461 
   15462     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
   15463     // left side invert the predicate to simplify logic below.
   15464     SDValue Other;
   15465     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
   15466       Other = RHS;
   15467       CC = ISD::getSetCCInverse(CC, true);
   15468     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
   15469       Other = LHS;
   15470     }
   15471 
   15472     if (Other.getNode() && Other->getNumOperands() == 2 &&
   15473         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
   15474       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
   15475       SDValue CondRHS = Cond->getOperand(1);
   15476 
   15477       // Look for a general sub with unsigned saturation first.
   15478       // x >= y ? x-y : 0 --> subus x, y
   15479       // x >  y ? x-y : 0 --> subus x, y
   15480       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
   15481           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
   15482         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
   15483 
   15484       // If the RHS is a constant we have to reverse the const canonicalization.
   15485       // x > C-1 ? x+-C : 0 --> subus x, C
   15486       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
   15487           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
   15488         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
   15489         if (CondRHS.getConstantOperandVal(0) == -A-1)
   15490           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
   15491                              DAG.getConstant(-A, VT));
   15492       }
   15493 
   15494       // Another special case: If C was a sign bit, the sub has been
   15495       // canonicalized into a xor.
   15496       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
   15497       //        it's safe to decanonicalize the xor?
   15498       // x s< 0 ? x^C : 0 --> subus x, C
   15499       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
   15500           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
   15501           isSplatVector(OpRHS.getNode())) {
   15502         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
   15503         if (A.isSignBit())
   15504           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
   15505       }
   15506     }
   15507   }
   15508 
   15509   // Try to match a min/max vector operation.
   15510   if (!DCI.isBeforeLegalize() &&
   15511       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
   15512     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
   15513       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
   15514 
   15515   // If we know that this node is legal then we know that it is going to be
   15516   // matched by one of the SSE/AVX BLEND instructions. These instructions only
   15517   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
   15518   // to simplify previous instructions.
   15519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   15520   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
   15521       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
   15522     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
   15523 
   15524     // Don't optimize vector selects that map to mask-registers.
   15525     if (BitWidth == 1)
   15526       return SDValue();
   15527 
   15528     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
   15529     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
   15530 
   15531     APInt KnownZero, KnownOne;
   15532     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
   15533                                           DCI.isBeforeLegalizeOps());
   15534     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
   15535         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
   15536       DCI.CommitTargetLoweringOpt(TLO);
   15537   }
   15538 
   15539   return SDValue();
   15540 }
   15541 
   15542 // Check whether a boolean test is testing a boolean value generated by
   15543 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
   15544 // code.
   15545 //
   15546 // Simplify the following patterns:
   15547 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
   15548 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
   15549 // to (Op EFLAGS Cond)
   15550 //
   15551 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
   15552 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
   15553 // to (Op EFLAGS !Cond)
   15554 //
   15555 // where Op could be BRCOND or CMOV.
   15556 //
   15557 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
   15558   // Quit if not CMP and SUB with its value result used.
   15559   if (Cmp.getOpcode() != X86ISD::CMP &&
   15560       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
   15561       return SDValue();
   15562 
   15563   // Quit if not used as a boolean value.
   15564   if (CC != X86::COND_E && CC != X86::COND_NE)
   15565     return SDValue();
   15566 
   15567   // Check CMP operands. One of them should be 0 or 1 and the other should be
   15568   // an SetCC or extended from it.
   15569   SDValue Op1 = Cmp.getOperand(0);
   15570   SDValue Op2 = Cmp.getOperand(1);
   15571 
   15572   SDValue SetCC;
   15573   const ConstantSDNode* C = 0;
   15574   bool needOppositeCond = (CC == X86::COND_E);
   15575 
   15576   if ((C = dyn_cast<ConstantSDNode>(Op1)))
   15577     SetCC = Op2;
   15578   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
   15579     SetCC = Op1;
   15580   else // Quit if all operands are not constants.
   15581     return SDValue();
   15582 
   15583   if (C->getZExtValue() == 1)
   15584     needOppositeCond = !needOppositeCond;
   15585   else if (C->getZExtValue() != 0)
   15586     // Quit if the constant is neither 0 or 1.
   15587     return SDValue();
   15588 
   15589   // Skip 'zext' node.
   15590   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
   15591     SetCC = SetCC.getOperand(0);
   15592 
   15593   switch (SetCC.getOpcode()) {
   15594   case X86ISD::SETCC:
   15595     // Set the condition code or opposite one if necessary.
   15596     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
   15597     if (needOppositeCond)
   15598       CC = X86::GetOppositeBranchCondition(CC);
   15599     return SetCC.getOperand(1);
   15600   case X86ISD::CMOV: {
   15601     // Check whether false/true value has canonical one, i.e. 0 or 1.
   15602     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
   15603     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
   15604     // Quit if true value is not a constant.
   15605     if (!TVal)
   15606       return SDValue();
   15607     // Quit if false value is not a constant.
   15608     if (!FVal) {
   15609       // A special case for rdrand, where 0 is set if false cond is found.
   15610       SDValue Op = SetCC.getOperand(0);
   15611       if (Op.getOpcode() != X86ISD::RDRAND)
   15612         return SDValue();
   15613     }
   15614     // Quit if false value is not the constant 0 or 1.
   15615     bool FValIsFalse = true;
   15616     if (FVal && FVal->getZExtValue() != 0) {
   15617       if (FVal->getZExtValue() != 1)
   15618         return SDValue();
   15619       // If FVal is 1, opposite cond is needed.
   15620       needOppositeCond = !needOppositeCond;
   15621       FValIsFalse = false;
   15622     }
   15623     // Quit if TVal is not the constant opposite of FVal.
   15624     if (FValIsFalse && TVal->getZExtValue() != 1)
   15625       return SDValue();
   15626     if (!FValIsFalse && TVal->getZExtValue() != 0)
   15627       return SDValue();
   15628     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
   15629     if (needOppositeCond)
   15630       CC = X86::GetOppositeBranchCondition(CC);
   15631     return SetCC.getOperand(3);
   15632   }
   15633   }
   15634 
   15635   return SDValue();
   15636 }
   15637 
   15638 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
   15639 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
   15640                                   TargetLowering::DAGCombinerInfo &DCI,
   15641                                   const X86Subtarget *Subtarget) {
   15642   DebugLoc DL = N->getDebugLoc();
   15643 
   15644   // If the flag operand isn't dead, don't touch this CMOV.
   15645   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
   15646     return SDValue();
   15647 
   15648   SDValue FalseOp = N->getOperand(0);
   15649   SDValue TrueOp = N->getOperand(1);
   15650   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
   15651   SDValue Cond = N->getOperand(3);
   15652 
   15653   if (CC == X86::COND_E || CC == X86::COND_NE) {
   15654     switch (Cond.getOpcode()) {
   15655     default: break;
   15656     case X86ISD::BSR:
   15657     case X86ISD::BSF:
   15658       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
   15659       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
   15660         return (CC == X86::COND_E) ? FalseOp : TrueOp;
   15661     }
   15662   }
   15663 
   15664   SDValue Flags;
   15665 
   15666   Flags = checkBoolTestSetCCCombine(Cond, CC);
   15667   if (Flags.getNode() &&
   15668       // Extra check as FCMOV only supports a subset of X86 cond.
   15669       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
   15670     SDValue Ops[] = { FalseOp, TrueOp,
   15671                       DAG.getConstant(CC, MVT::i8), Flags };
   15672     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
   15673                        Ops, array_lengthof(Ops));
   15674   }
   15675 
   15676   // If this is a select between two integer constants, try to do some
   15677   // optimizations.  Note that the operands are ordered the opposite of SELECT
   15678   // operands.
   15679   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
   15680     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
   15681       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
   15682       // larger than FalseC (the false value).
   15683       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
   15684         CC = X86::GetOppositeBranchCondition(CC);
   15685         std::swap(TrueC, FalseC);
   15686         std::swap(TrueOp, FalseOp);
   15687       }
   15688 
   15689       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
   15690       // This is efficient for any integer data type (including i8/i16) and
   15691       // shift amount.
   15692       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
   15693         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
   15694                            DAG.getConstant(CC, MVT::i8), Cond);
   15695 
   15696         // Zero extend the condition if needed.
   15697         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
   15698 
   15699         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
   15700         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
   15701                            DAG.getConstant(ShAmt, MVT::i8));
   15702         if (N->getNumValues() == 2)  // Dead flag value?
   15703           return DCI.CombineTo(N, Cond, SDValue());
   15704         return Cond;
   15705       }
   15706 
   15707       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
   15708       // for any integer data type, including i8/i16.
   15709       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
   15710         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
   15711                            DAG.getConstant(CC, MVT::i8), Cond);
   15712 
   15713         // Zero extend the condition if needed.
   15714         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
   15715                            FalseC->getValueType(0), Cond);
   15716         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
   15717                            SDValue(FalseC, 0));
   15718 
   15719         if (N->getNumValues() == 2)  // Dead flag value?
   15720           return DCI.CombineTo(N, Cond, SDValue());
   15721         return Cond;
   15722       }
   15723 
   15724       // Optimize cases that will turn into an LEA instruction.  This requires
   15725       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
   15726       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
   15727         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
   15728         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
   15729 
   15730         bool isFastMultiplier = false;
   15731         if (Diff < 10) {
   15732           switch ((unsigned char)Diff) {
   15733           default: break;
   15734           case 1:  // result = add base, cond
   15735           case 2:  // result = lea base(    , cond*2)
   15736           case 3:  // result = lea base(cond, cond*2)
   15737           case 4:  // result = lea base(    , cond*4)
   15738           case 5:  // result = lea base(cond, cond*4)
   15739           case 8:  // result = lea base(    , cond*8)
   15740           case 9:  // result = lea base(cond, cond*8)
   15741             isFastMultiplier = true;
   15742             break;
   15743           }
   15744         }
   15745 
   15746         if (isFastMultiplier) {
   15747           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
   15748           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
   15749                              DAG.getConstant(CC, MVT::i8), Cond);
   15750           // Zero extend the condition if needed.
   15751           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
   15752                              Cond);
   15753           // Scale the condition by the difference.
   15754           if (Diff != 1)
   15755             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
   15756                                DAG.getConstant(Diff, Cond.getValueType()));
   15757 
   15758           // Add the base if non-zero.
   15759           if (FalseC->getAPIntValue() != 0)
   15760             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
   15761                                SDValue(FalseC, 0));
   15762           if (N->getNumValues() == 2)  // Dead flag value?
   15763             return DCI.CombineTo(N, Cond, SDValue());
   15764           return Cond;
   15765         }
   15766       }
   15767     }
   15768   }
   15769 
   15770   // Handle these cases:
   15771   //   (select (x != c), e, c) -> select (x != c), e, x),
   15772   //   (select (x == c), c, e) -> select (x == c), x, e)
   15773   // where the c is an integer constant, and the "select" is the combination
   15774   // of CMOV and CMP.
   15775   //
   15776   // The rationale for this change is that the conditional-move from a constant
   15777   // needs two instructions, however, conditional-move from a register needs
   15778   // only one instruction.
   15779   //
   15780   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
   15781   //  some instruction-combining opportunities. This opt needs to be
   15782   //  postponed as late as possible.
   15783   //
   15784   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
   15785     // the DCI.xxxx conditions are provided to postpone the optimization as
   15786     // late as possible.
   15787 
   15788     ConstantSDNode *CmpAgainst = 0;
   15789     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
   15790         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
   15791         !isa<ConstantSDNode>(Cond.getOperand(0))) {
   15792 
   15793       if (CC == X86::COND_NE &&
   15794           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
   15795         CC = X86::GetOppositeBranchCondition(CC);
   15796         std::swap(TrueOp, FalseOp);
   15797       }
   15798 
   15799       if (CC == X86::COND_E &&
   15800           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
   15801         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
   15802                           DAG.getConstant(CC, MVT::i8), Cond };
   15803         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
   15804                            array_lengthof(Ops));
   15805       }
   15806     }
   15807   }
   15808 
   15809   return SDValue();
   15810 }
   15811 
   15812 /// PerformMulCombine - Optimize a single multiply with constant into two
   15813 /// in order to implement it with two cheaper instructions, e.g.
   15814 /// LEA + SHL, LEA + LEA.
   15815 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
   15816                                  TargetLowering::DAGCombinerInfo &DCI) {
   15817   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
   15818     return SDValue();
   15819 
   15820   EVT VT = N->getValueType(0);
   15821   if (VT != MVT::i64)
   15822     return SDValue();
   15823 
   15824   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
   15825   if (!C)
   15826     return SDValue();
   15827   uint64_t MulAmt = C->getZExtValue();
   15828   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
   15829     return SDValue();
   15830 
   15831   uint64_t MulAmt1 = 0;
   15832   uint64_t MulAmt2 = 0;
   15833   if ((MulAmt % 9) == 0) {
   15834     MulAmt1 = 9;
   15835     MulAmt2 = MulAmt / 9;
   15836   } else if ((MulAmt % 5) == 0) {
   15837     MulAmt1 = 5;
   15838     MulAmt2 = MulAmt / 5;
   15839   } else if ((MulAmt % 3) == 0) {
   15840     MulAmt1 = 3;
   15841     MulAmt2 = MulAmt / 3;
   15842   }
   15843   if (MulAmt2 &&
   15844       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
   15845     DebugLoc DL = N->getDebugLoc();
   15846 
   15847     if (isPowerOf2_64(MulAmt2) &&
   15848         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
   15849       // If second multiplifer is pow2, issue it first. We want the multiply by
   15850       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
   15851       // is an add.
   15852       std::swap(MulAmt1, MulAmt2);
   15853 
   15854     SDValue NewMul;
   15855     if (isPowerOf2_64(MulAmt1))
   15856       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
   15857                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
   15858     else
   15859       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
   15860                            DAG.getConstant(MulAmt1, VT));
   15861 
   15862     if (isPowerOf2_64(MulAmt2))
   15863       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
   15864                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
   15865     else
   15866       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
   15867                            DAG.getConstant(MulAmt2, VT));
   15868 
   15869     // Do not add new nodes to DAG combiner worklist.
   15870     DCI.CombineTo(N, NewMul, false);
   15871   }
   15872   return SDValue();
   15873 }
   15874 
   15875 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
   15876   SDValue N0 = N->getOperand(0);
   15877   SDValue N1 = N->getOperand(1);
   15878   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   15879   EVT VT = N0.getValueType();
   15880 
   15881   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
   15882   // since the result of setcc_c is all zero's or all ones.
   15883   if (VT.isInteger() && !VT.isVector() &&
   15884       N1C && N0.getOpcode() == ISD::AND &&
   15885       N0.getOperand(1).getOpcode() == ISD::Constant) {
   15886     SDValue N00 = N0.getOperand(0);
   15887     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
   15888         ((N00.getOpcode() == ISD::ANY_EXTEND ||
   15889           N00.getOpcode() == ISD::ZERO_EXTEND) &&
   15890          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
   15891       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   15892       APInt ShAmt = N1C->getAPIntValue();
   15893       Mask = Mask.shl(ShAmt);
   15894       if (Mask != 0)
   15895         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
   15896                            N00, DAG.getConstant(Mask, VT));
   15897     }
   15898   }
   15899 
   15900   // Hardware support for vector shifts is sparse which makes us scalarize the
   15901   // vector operations in many cases. Also, on sandybridge ADD is faster than
   15902   // shl.
   15903   // (shl V, 1) -> add V,V
   15904   if (isSplatVector(N1.getNode())) {
   15905     assert(N0.getValueType().isVector() && "Invalid vector shift type");
   15906     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
   15907     // We shift all of the values by one. In many cases we do not have
   15908     // hardware support for this operation. This is better expressed as an ADD
   15909     // of two values.
   15910     if (N1C && (1 == N1C->getZExtValue())) {
   15911       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
   15912     }
   15913   }
   15914 
   15915   return SDValue();
   15916 }
   15917 
   15918 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
   15919 ///                       when possible.
   15920 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
   15921                                    TargetLowering::DAGCombinerInfo &DCI,
   15922                                    const X86Subtarget *Subtarget) {
   15923   EVT VT = N->getValueType(0);
   15924   if (N->getOpcode() == ISD::SHL) {
   15925     SDValue V = PerformSHLCombine(N, DAG);
   15926     if (V.getNode()) return V;
   15927   }
   15928 
   15929   // On X86 with SSE2 support, we can transform this to a vector shift if
   15930   // all elements are shifted by the same amount.  We can't do this in legalize
   15931   // because the a constant vector is typically transformed to a constant pool
   15932   // so we have no knowledge of the shift amount.
   15933   if (!Subtarget->hasSSE2())
   15934     return SDValue();
   15935 
   15936   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
   15937       (!Subtarget->hasInt256() ||
   15938        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
   15939     return SDValue();
   15940 
   15941   SDValue ShAmtOp = N->getOperand(1);
   15942   EVT EltVT = VT.getVectorElementType();
   15943   DebugLoc DL = N->getDebugLoc();
   15944   SDValue BaseShAmt = SDValue();
   15945   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
   15946     unsigned NumElts = VT.getVectorNumElements();
   15947     unsigned i = 0;
   15948     for (; i != NumElts; ++i) {
   15949       SDValue Arg = ShAmtOp.getOperand(i);
   15950       if (Arg.getOpcode() == ISD::UNDEF) continue;
   15951       BaseShAmt = Arg;
   15952       break;
   15953     }
   15954     // Handle the case where the build_vector is all undef
   15955     // FIXME: Should DAG allow this?
   15956     if (i == NumElts)
   15957       return SDValue();
   15958 
   15959     for (; i != NumElts; ++i) {
   15960       SDValue Arg = ShAmtOp.getOperand(i);
   15961       if (Arg.getOpcode() == ISD::UNDEF) continue;
   15962       if (Arg != BaseShAmt) {
   15963         return SDValue();
   15964       }
   15965     }
   15966   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
   15967              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
   15968     SDValue InVec = ShAmtOp.getOperand(0);
   15969     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
   15970       unsigned NumElts = InVec.getValueType().getVectorNumElements();
   15971       unsigned i = 0;
   15972       for (; i != NumElts; ++i) {
   15973         SDValue Arg = InVec.getOperand(i);
   15974         if (Arg.getOpcode() == ISD::UNDEF) continue;
   15975         BaseShAmt = Arg;
   15976         break;
   15977       }
   15978     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
   15979        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
   15980          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
   15981          if (C->getZExtValue() == SplatIdx)
   15982            BaseShAmt = InVec.getOperand(1);
   15983        }
   15984     }
   15985     if (BaseShAmt.getNode() == 0) {
   15986       // Don't create instructions with illegal types after legalize
   15987       // types has run.
   15988       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
   15989           !DCI.isBeforeLegalize())
   15990         return SDValue();
   15991 
   15992       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
   15993                               DAG.getIntPtrConstant(0));
   15994     }
   15995   } else
   15996     return SDValue();
   15997 
   15998   // The shift amount is an i32.
   15999   if (EltVT.bitsGT(MVT::i32))
   16000     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
   16001   else if (EltVT.bitsLT(MVT::i32))
   16002     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
   16003 
   16004   // The shift amount is identical so we can do a vector shift.
   16005   SDValue  ValOp = N->getOperand(0);
   16006   switch (N->getOpcode()) {
   16007   default:
   16008     llvm_unreachable("Unknown shift opcode!");
   16009   case ISD::SHL:
   16010     switch (VT.getSimpleVT().SimpleTy) {
   16011     default: return SDValue();
   16012     case MVT::v2i64:
   16013     case MVT::v4i32:
   16014     case MVT::v8i16:
   16015     case MVT::v4i64:
   16016     case MVT::v8i32:
   16017     case MVT::v16i16:
   16018       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
   16019     }
   16020   case ISD::SRA:
   16021     switch (VT.getSimpleVT().SimpleTy) {
   16022     default: return SDValue();
   16023     case MVT::v4i32:
   16024     case MVT::v8i16:
   16025     case MVT::v8i32:
   16026     case MVT::v16i16:
   16027       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
   16028     }
   16029   case ISD::SRL:
   16030     switch (VT.getSimpleVT().SimpleTy) {
   16031     default: return SDValue();
   16032     case MVT::v2i64:
   16033     case MVT::v4i32:
   16034     case MVT::v8i16:
   16035     case MVT::v4i64:
   16036     case MVT::v8i32:
   16037     case MVT::v16i16:
   16038       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
   16039     }
   16040   }
   16041 }
   16042 
   16043 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
   16044 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
   16045 // and friends.  Likewise for OR -> CMPNEQSS.
   16046 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
   16047                             TargetLowering::DAGCombinerInfo &DCI,
   16048                             const X86Subtarget *Subtarget) {
   16049   unsigned opcode;
   16050 
   16051   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
   16052   // we're requiring SSE2 for both.
   16053   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
   16054     SDValue N0 = N->getOperand(0);
   16055     SDValue N1 = N->getOperand(1);
   16056     SDValue CMP0 = N0->getOperand(1);
   16057     SDValue CMP1 = N1->getOperand(1);
   16058     DebugLoc DL = N->getDebugLoc();
   16059 
   16060     // The SETCCs should both refer to the same CMP.
   16061     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
   16062       return SDValue();
   16063 
   16064     SDValue CMP00 = CMP0->getOperand(0);
   16065     SDValue CMP01 = CMP0->getOperand(1);
   16066     EVT     VT    = CMP00.getValueType();
   16067 
   16068     if (VT == MVT::f32 || VT == MVT::f64) {
   16069       bool ExpectingFlags = false;
   16070       // Check for any users that want flags:
   16071       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
   16072            !ExpectingFlags && UI != UE; ++UI)
   16073         switch (UI->getOpcode()) {
   16074         default:
   16075         case ISD::BR_CC:
   16076         case ISD::BRCOND:
   16077         case ISD::SELECT:
   16078           ExpectingFlags = true;
   16079           break;
   16080         case ISD::CopyToReg:
   16081         case ISD::SIGN_EXTEND:
   16082         case ISD::ZERO_EXTEND:
   16083         case ISD::ANY_EXTEND:
   16084           break;
   16085         }
   16086 
   16087       if (!ExpectingFlags) {
   16088         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
   16089         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
   16090 
   16091         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
   16092           X86::CondCode tmp = cc0;
   16093           cc0 = cc1;
   16094           cc1 = tmp;
   16095         }
   16096 
   16097         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
   16098             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
   16099           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
   16100           X86ISD::NodeType NTOperator = is64BitFP ?
   16101             X86ISD::FSETCCsd : X86ISD::FSETCCss;
   16102           // FIXME: need symbolic constants for these magic numbers.
   16103           // See X86ATTInstPrinter.cpp:printSSECC().
   16104           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
   16105           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
   16106                                               DAG.getConstant(x86cc, MVT::i8));
   16107           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
   16108                                               OnesOrZeroesF);
   16109           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
   16110                                       DAG.getConstant(1, MVT::i32));
   16111           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
   16112           return OneBitOfTruth;
   16113         }
   16114       }
   16115     }
   16116   }
   16117   return SDValue();
   16118 }
   16119 
   16120 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
   16121 /// so it can be folded inside ANDNP.
   16122 static bool CanFoldXORWithAllOnes(const SDNode *N) {
   16123   EVT VT = N->getValueType(0);
   16124 
   16125   // Match direct AllOnes for 128 and 256-bit vectors
   16126   if (ISD::isBuildVectorAllOnes(N))
   16127     return true;
   16128 
   16129   // Look through a bit convert.
   16130   if (N->getOpcode() == ISD::BITCAST)
   16131     N = N->getOperand(0).getNode();
   16132 
   16133   // Sometimes the operand may come from a insert_subvector building a 256-bit
   16134   // allones vector
   16135   if (VT.is256BitVector() &&
   16136       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
   16137     SDValue V1 = N->getOperand(0);
   16138     SDValue V2 = N->getOperand(1);
   16139 
   16140     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
   16141         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
   16142         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
   16143         ISD::isBuildVectorAllOnes(V2.getNode()))
   16144       return true;
   16145   }
   16146 
   16147   return false;
   16148 }
   16149 
   16150 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
   16151 // register. In most cases we actually compare or select YMM-sized registers
   16152 // and mixing the two types creates horrible code. This method optimizes
   16153 // some of the transition sequences.
   16154 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
   16155                                  TargetLowering::DAGCombinerInfo &DCI,
   16156                                  const X86Subtarget *Subtarget) {
   16157   EVT VT = N->getValueType(0);
   16158   if (!VT.is256BitVector())
   16159     return SDValue();
   16160 
   16161   assert((N->getOpcode() == ISD::ANY_EXTEND ||
   16162           N->getOpcode() == ISD::ZERO_EXTEND ||
   16163           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
   16164 
   16165   SDValue Narrow = N->getOperand(0);
   16166   EVT NarrowVT = Narrow->getValueType(0);
   16167   if (!NarrowVT.is128BitVector())
   16168     return SDValue();
   16169 
   16170   if (Narrow->getOpcode() != ISD::XOR &&
   16171       Narrow->getOpcode() != ISD::AND &&
   16172       Narrow->getOpcode() != ISD::OR)
   16173     return SDValue();
   16174 
   16175   SDValue N0  = Narrow->getOperand(0);
   16176   SDValue N1  = Narrow->getOperand(1);
   16177   DebugLoc DL = Narrow->getDebugLoc();
   16178 
   16179   // The Left side has to be a trunc.
   16180   if (N0.getOpcode() != ISD::TRUNCATE)
   16181     return SDValue();
   16182 
   16183   // The type of the truncated inputs.
   16184   EVT WideVT = N0->getOperand(0)->getValueType(0);
   16185   if (WideVT != VT)
   16186     return SDValue();
   16187 
   16188   // The right side has to be a 'trunc' or a constant vector.
   16189   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
   16190   bool RHSConst = (isSplatVector(N1.getNode()) &&
   16191                    isa<ConstantSDNode>(N1->getOperand(0)));
   16192   if (!RHSTrunc && !RHSConst)
   16193     return SDValue();
   16194 
   16195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   16196 
   16197   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
   16198     return SDValue();
   16199 
   16200   // Set N0 and N1 to hold the inputs to the new wide operation.
   16201   N0 = N0->getOperand(0);
   16202   if (RHSConst) {
   16203     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
   16204                      N1->getOperand(0));
   16205     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
   16206     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
   16207   } else if (RHSTrunc) {
   16208     N1 = N1->getOperand(0);
   16209   }
   16210 
   16211   // Generate the wide operation.
   16212   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
   16213   unsigned Opcode = N->getOpcode();
   16214   switch (Opcode) {
   16215   case ISD::ANY_EXTEND:
   16216     return Op;
   16217   case ISD::ZERO_EXTEND: {
   16218     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
   16219     APInt Mask = APInt::getAllOnesValue(InBits);
   16220     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
   16221     return DAG.getNode(ISD::AND, DL, VT,
   16222                        Op, DAG.getConstant(Mask, VT));
   16223   }
   16224   case ISD::SIGN_EXTEND:
   16225     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
   16226                        Op, DAG.getValueType(NarrowVT));
   16227   default:
   16228     llvm_unreachable("Unexpected opcode");
   16229   }
   16230 }
   16231 
   16232 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
   16233                                  TargetLowering::DAGCombinerInfo &DCI,
   16234                                  const X86Subtarget *Subtarget) {
   16235   EVT VT = N->getValueType(0);
   16236   if (DCI.isBeforeLegalizeOps())
   16237     return SDValue();
   16238 
   16239   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
   16240   if (R.getNode())
   16241     return R;
   16242 
   16243   // Create BLSI, and BLSR instructions
   16244   // BLSI is X & (-X)
   16245   // BLSR is X & (X-1)
   16246   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
   16247     SDValue N0 = N->getOperand(0);
   16248     SDValue N1 = N->getOperand(1);
   16249     DebugLoc DL = N->getDebugLoc();
   16250 
   16251     // Check LHS for neg
   16252     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
   16253         isZero(N0.getOperand(0)))
   16254       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
   16255 
   16256     // Check RHS for neg
   16257     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
   16258         isZero(N1.getOperand(0)))
   16259       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
   16260 
   16261     // Check LHS for X-1
   16262     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
   16263         isAllOnes(N0.getOperand(1)))
   16264       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
   16265 
   16266     // Check RHS for X-1
   16267     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
   16268         isAllOnes(N1.getOperand(1)))
   16269       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
   16270 
   16271     return SDValue();
   16272   }
   16273 
   16274   // Want to form ANDNP nodes:
   16275   // 1) In the hopes of then easily combining them with OR and AND nodes
   16276   //    to form PBLEND/PSIGN.
   16277   // 2) To match ANDN packed intrinsics
   16278   if (VT != MVT::v2i64 && VT != MVT::v4i64)
   16279     return SDValue();
   16280 
   16281   SDValue N0 = N->getOperand(0);
   16282   SDValue N1 = N->getOperand(1);
   16283   DebugLoc DL = N->getDebugLoc();
   16284 
   16285   // Check LHS for vnot
   16286   if (N0.getOpcode() == ISD::XOR &&
   16287       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
   16288       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
   16289     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
   16290 
   16291   // Check RHS for vnot
   16292   if (N1.getOpcode() == ISD::XOR &&
   16293       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
   16294       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
   16295     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
   16296 
   16297   return SDValue();
   16298 }
   16299 
   16300 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
   16301                                 TargetLowering::DAGCombinerInfo &DCI,
   16302                                 const X86Subtarget *Subtarget) {
   16303   EVT VT = N->getValueType(0);
   16304   if (DCI.isBeforeLegalizeOps())
   16305     return SDValue();
   16306 
   16307   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
   16308   if (R.getNode())
   16309     return R;
   16310 
   16311   SDValue N0 = N->getOperand(0);
   16312   SDValue N1 = N->getOperand(1);
   16313 
   16314   // look for psign/blend
   16315   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
   16316     if (!Subtarget->hasSSSE3() ||
   16317         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
   16318       return SDValue();
   16319 
   16320     // Canonicalize pandn to RHS
   16321     if (N0.getOpcode() == X86ISD::ANDNP)
   16322       std::swap(N0, N1);
   16323     // or (and (m, y), (pandn m, x))
   16324     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
   16325       SDValue Mask = N1.getOperand(0);
   16326       SDValue X    = N1.getOperand(1);
   16327       SDValue Y;
   16328       if (N0.getOperand(0) == Mask)
   16329         Y = N0.getOperand(1);
   16330       if (N0.getOperand(1) == Mask)
   16331         Y = N0.getOperand(0);
   16332 
   16333       // Check to see if the mask appeared in both the AND and ANDNP and
   16334       if (!Y.getNode())
   16335         return SDValue();
   16336 
   16337       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
   16338       // Look through mask bitcast.
   16339       if (Mask.getOpcode() == ISD::BITCAST)
   16340         Mask = Mask.getOperand(0);
   16341       if (X.getOpcode() == ISD::BITCAST)
   16342         X = X.getOperand(0);
   16343       if (Y.getOpcode() == ISD::BITCAST)
   16344         Y = Y.getOperand(0);
   16345 
   16346       EVT MaskVT = Mask.getValueType();
   16347 
   16348       // Validate that the Mask operand is a vector sra node.
   16349       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
   16350       // there is no psrai.b
   16351       if (Mask.getOpcode() != X86ISD::VSRAI)
   16352         return SDValue();
   16353 
   16354       // Check that the SRA is all signbits.
   16355       SDValue SraC = Mask.getOperand(1);
   16356       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
   16357       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
   16358       if ((SraAmt + 1) != EltBits)
   16359         return SDValue();
   16360 
   16361       DebugLoc DL = N->getDebugLoc();
   16362 
   16363       // Now we know we at least have a plendvb with the mask val.  See if
   16364       // we can form a psignb/w/d.
   16365       // psign = x.type == y.type == mask.type && y = sub(0, x);
   16366       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
   16367           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
   16368           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
   16369         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
   16370                "Unsupported VT for PSIGN");
   16371         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
   16372         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
   16373       }
   16374       // PBLENDVB only available on SSE 4.1
   16375       if (!Subtarget->hasSSE41())
   16376         return SDValue();
   16377 
   16378       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
   16379 
   16380       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
   16381       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
   16382       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
   16383       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
   16384       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
   16385     }
   16386   }
   16387 
   16388   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
   16389     return SDValue();
   16390 
   16391   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
   16392   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
   16393     std::swap(N0, N1);
   16394   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
   16395     return SDValue();
   16396   if (!N0.hasOneUse() || !N1.hasOneUse())
   16397     return SDValue();
   16398 
   16399   SDValue ShAmt0 = N0.getOperand(1);
   16400   if (ShAmt0.getValueType() != MVT::i8)
   16401     return SDValue();
   16402   SDValue ShAmt1 = N1.getOperand(1);
   16403   if (ShAmt1.getValueType() != MVT::i8)
   16404     return SDValue();
   16405   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
   16406     ShAmt0 = ShAmt0.getOperand(0);
   16407   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
   16408     ShAmt1 = ShAmt1.getOperand(0);
   16409 
   16410   DebugLoc DL = N->getDebugLoc();
   16411   unsigned Opc = X86ISD::SHLD;
   16412   SDValue Op0 = N0.getOperand(0);
   16413   SDValue Op1 = N1.getOperand(0);
   16414   if (ShAmt0.getOpcode() == ISD::SUB) {
   16415     Opc = X86ISD::SHRD;
   16416     std::swap(Op0, Op1);
   16417     std::swap(ShAmt0, ShAmt1);
   16418   }
   16419 
   16420   unsigned Bits = VT.getSizeInBits();
   16421   if (ShAmt1.getOpcode() == ISD::SUB) {
   16422     SDValue Sum = ShAmt1.getOperand(0);
   16423     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
   16424       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
   16425       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
   16426         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
   16427       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
   16428         return DAG.getNode(Opc, DL, VT,
   16429                            Op0, Op1,
   16430                            DAG.getNode(ISD::TRUNCATE, DL,
   16431                                        MVT::i8, ShAmt0));
   16432     }
   16433   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
   16434     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
   16435     if (ShAmt0C &&
   16436         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
   16437       return DAG.getNode(Opc, DL, VT,
   16438                          N0.getOperand(0), N1.getOperand(0),
   16439                          DAG.getNode(ISD::TRUNCATE, DL,
   16440                                        MVT::i8, ShAmt0));
   16441   }
   16442 
   16443   return SDValue();
   16444 }
   16445 
   16446 // Generate NEG and CMOV for integer abs.
   16447 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
   16448   EVT VT = N->getValueType(0);
   16449 
   16450   // Since X86 does not have CMOV for 8-bit integer, we don't convert
   16451   // 8-bit integer abs to NEG and CMOV.
   16452   if (VT.isInteger() && VT.getSizeInBits() == 8)
   16453     return SDValue();
   16454 
   16455   SDValue N0 = N->getOperand(0);
   16456   SDValue N1 = N->getOperand(1);
   16457   DebugLoc DL = N->getDebugLoc();
   16458 
   16459   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
   16460   // and change it to SUB and CMOV.
   16461   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
   16462       N0.getOpcode() == ISD::ADD &&
   16463       N0.getOperand(1) == N1 &&
   16464       N1.getOpcode() == ISD::SRA &&
   16465       N1.getOperand(0) == N0.getOperand(0))
   16466     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
   16467       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
   16468         // Generate SUB & CMOV.
   16469         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
   16470                                   DAG.getConstant(0, VT), N0.getOperand(0));
   16471 
   16472         SDValue Ops[] = { N0.getOperand(0), Neg,
   16473                           DAG.getConstant(X86::COND_GE, MVT::i8),
   16474                           SDValue(Neg.getNode(), 1) };
   16475         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
   16476                            Ops, array_lengthof(Ops));
   16477       }
   16478   return SDValue();
   16479 }
   16480 
   16481 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
   16482 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
   16483                                  TargetLowering::DAGCombinerInfo &DCI,
   16484                                  const X86Subtarget *Subtarget) {
   16485   EVT VT = N->getValueType(0);
   16486   if (DCI.isBeforeLegalizeOps())
   16487     return SDValue();
   16488 
   16489   if (Subtarget->hasCMov()) {
   16490     SDValue RV = performIntegerAbsCombine(N, DAG);
   16491     if (RV.getNode())
   16492       return RV;
   16493   }
   16494 
   16495   // Try forming BMI if it is available.
   16496   if (!Subtarget->hasBMI())
   16497     return SDValue();
   16498 
   16499   if (VT != MVT::i32 && VT != MVT::i64)
   16500     return SDValue();
   16501 
   16502   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
   16503 
   16504   // Create BLSMSK instructions by finding X ^ (X-1)
   16505   SDValue N0 = N->getOperand(0);
   16506   SDValue N1 = N->getOperand(1);
   16507   DebugLoc DL = N->getDebugLoc();
   16508 
   16509   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
   16510       isAllOnes(N0.getOperand(1)))
   16511     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
   16512 
   16513   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
   16514       isAllOnes(N1.getOperand(1)))
   16515     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
   16516 
   16517   return SDValue();
   16518 }
   16519 
   16520 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
   16521 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
   16522                                   TargetLowering::DAGCombinerInfo &DCI,
   16523                                   const X86Subtarget *Subtarget) {
   16524   LoadSDNode *Ld = cast<LoadSDNode>(N);
   16525   EVT RegVT = Ld->getValueType(0);
   16526   EVT MemVT = Ld->getMemoryVT();
   16527   DebugLoc dl = Ld->getDebugLoc();
   16528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   16529   unsigned RegSz = RegVT.getSizeInBits();
   16530 
   16531   ISD::LoadExtType Ext = Ld->getExtensionType();
   16532   unsigned Alignment = Ld->getAlignment();
   16533   bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
   16534 
   16535   // On Sandybridge unaligned 256bit loads are inefficient.
   16536   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
   16537       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
   16538     unsigned NumElems = RegVT.getVectorNumElements();
   16539     if (NumElems < 2)
   16540       return SDValue();
   16541 
   16542     SDValue Ptr = Ld->getBasePtr();
   16543     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
   16544 
   16545     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
   16546                                   NumElems/2);
   16547     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
   16548                                 Ld->getPointerInfo(), Ld->isVolatile(),
   16549                                 Ld->isNonTemporal(), Ld->isInvariant(),
   16550                                 Alignment);
   16551     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
   16552     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
   16553                                 Ld->getPointerInfo(), Ld->isVolatile(),
   16554                                 Ld->isNonTemporal(), Ld->isInvariant(),
   16555                                 std::max(Alignment/2U, 1U));
   16556     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
   16557                              Load1.getValue(1),
   16558                              Load2.getValue(1));
   16559 
   16560     SDValue NewVec = DAG.getUNDEF(RegVT);
   16561     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
   16562     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
   16563     return DCI.CombineTo(N, NewVec, TF, true);
   16564   }
   16565 
   16566   // If this is a vector EXT Load then attempt to optimize it using a
   16567   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
   16568   // expansion is still better than scalar code.
   16569   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
   16570   // emit a shuffle and a arithmetic shift.
   16571   // TODO: It is possible to support ZExt by zeroing the undef values
   16572   // during the shuffle phase or after the shuffle.
   16573   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
   16574       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
   16575     assert(MemVT != RegVT && "Cannot extend to the same type");
   16576     assert(MemVT.isVector() && "Must load a vector from memory");
   16577 
   16578     unsigned NumElems = RegVT.getVectorNumElements();
   16579     unsigned MemSz = MemVT.getSizeInBits();
   16580     assert(RegSz > MemSz && "Register size must be greater than the mem size");
   16581 
   16582     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
   16583       return SDValue();
   16584 
   16585     // All sizes must be a power of two.
   16586     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
   16587       return SDValue();
   16588 
   16589     // Attempt to load the original value using scalar loads.
   16590     // Find the largest scalar type that divides the total loaded size.
   16591     MVT SclrLoadTy = MVT::i8;
   16592     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
   16593          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
   16594       MVT Tp = (MVT::SimpleValueType)tp;
   16595       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
   16596         SclrLoadTy = Tp;
   16597       }
   16598     }
   16599 
   16600     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
   16601     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
   16602         (64 <= MemSz))
   16603       SclrLoadTy = MVT::f64;
   16604 
   16605     // Calculate the number of scalar loads that we need to perform
   16606     // in order to load our vector from memory.
   16607     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
   16608     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
   16609       return SDValue();
   16610 
   16611     unsigned loadRegZize = RegSz;
   16612     if (Ext == ISD::SEXTLOAD && RegSz == 256)
   16613       loadRegZize /= 2;
   16614 
   16615     // Represent our vector as a sequence of elements which are the
   16616     // largest scalar that we can load.
   16617     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
   16618       loadRegZize/SclrLoadTy.getSizeInBits());
   16619 
   16620     // Represent the data using the same element type that is stored in
   16621     // memory. In practice, we ''widen'' MemVT.
   16622     EVT WideVecVT =
   16623           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
   16624                        loadRegZize/MemVT.getScalarType().getSizeInBits());
   16625 
   16626     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
   16627       "Invalid vector type");
   16628 
   16629     // We can't shuffle using an illegal type.
   16630     if (!TLI.isTypeLegal(WideVecVT))
   16631       return SDValue();
   16632 
   16633     SmallVector<SDValue, 8> Chains;
   16634     SDValue Ptr = Ld->getBasePtr();
   16635     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
   16636                                         TLI.getPointerTy());
   16637     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
   16638 
   16639     for (unsigned i = 0; i < NumLoads; ++i) {
   16640       // Perform a single load.
   16641       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
   16642                                        Ptr, Ld->getPointerInfo(),
   16643                                        Ld->isVolatile(), Ld->isNonTemporal(),
   16644                                        Ld->isInvariant(), Ld->getAlignment());
   16645       Chains.push_back(ScalarLoad.getValue(1));
   16646       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
   16647       // another round of DAGCombining.
   16648       if (i == 0)
   16649         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
   16650       else
   16651         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
   16652                           ScalarLoad, DAG.getIntPtrConstant(i));
   16653 
   16654       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
   16655     }
   16656 
   16657     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
   16658                                Chains.size());
   16659 
   16660     // Bitcast the loaded value to a vector of the original element type, in
   16661     // the size of the target vector type.
   16662     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
   16663     unsigned SizeRatio = RegSz/MemSz;
   16664 
   16665     if (Ext == ISD::SEXTLOAD) {
   16666       // If we have SSE4.1 we can directly emit a VSEXT node.
   16667       if (Subtarget->hasSSE41()) {
   16668         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
   16669         return DCI.CombineTo(N, Sext, TF, true);
   16670       }
   16671 
   16672       // Otherwise we'll shuffle the small elements in the high bits of the
   16673       // larger type and perform an arithmetic shift. If the shift is not legal
   16674       // it's better to scalarize.
   16675       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
   16676         return SDValue();
   16677 
   16678       // Redistribute the loaded elements into the different locations.
   16679       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
   16680       for (unsigned i = 0; i != NumElems; ++i)
   16681         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
   16682 
   16683       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
   16684                                            DAG.getUNDEF(WideVecVT),
   16685                                            &ShuffleVec[0]);
   16686 
   16687       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
   16688 
   16689       // Build the arithmetic shift.
   16690       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
   16691                      MemVT.getVectorElementType().getSizeInBits();
   16692       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
   16693                           DAG.getConstant(Amt, RegVT));
   16694 
   16695       return DCI.CombineTo(N, Shuff, TF, true);
   16696     }
   16697 
   16698     // Redistribute the loaded elements into the different locations.
   16699     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
   16700     for (unsigned i = 0; i != NumElems; ++i)
   16701       ShuffleVec[i*SizeRatio] = i;
   16702 
   16703     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
   16704                                          DAG.getUNDEF(WideVecVT),
   16705                                          &ShuffleVec[0]);
   16706 
   16707     // Bitcast to the requested type.
   16708     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
   16709     // Replace the original load with the new sequence
   16710     // and return the new chain.
   16711     return DCI.CombineTo(N, Shuff, TF, true);
   16712   }
   16713 
   16714   return SDValue();
   16715 }
   16716 
   16717 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
   16718 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
   16719                                    const X86Subtarget *Subtarget) {
   16720   StoreSDNode *St = cast<StoreSDNode>(N);
   16721   EVT VT = St->getValue().getValueType();
   16722   EVT StVT = St->getMemoryVT();
   16723   DebugLoc dl = St->getDebugLoc();
   16724   SDValue StoredVal = St->getOperand(1);
   16725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   16726   unsigned Alignment = St->getAlignment();
   16727   bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
   16728 
   16729   // If we are saving a concatenation of two XMM registers, perform two stores.
   16730   // On Sandy Bridge, 256-bit memory operations are executed by two
   16731   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
   16732   // memory  operation.
   16733   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
   16734       StVT == VT && !IsAligned) {
   16735     unsigned NumElems = VT.getVectorNumElements();
   16736     if (NumElems < 2)
   16737       return SDValue();
   16738 
   16739     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
   16740     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
   16741 
   16742     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
   16743     SDValue Ptr0 = St->getBasePtr();
   16744     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
   16745 
   16746     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
   16747                                 St->getPointerInfo(), St->isVolatile(),
   16748                                 St->isNonTemporal(), Alignment);
   16749     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
   16750                                 St->getPointerInfo(), St->isVolatile(),
   16751                                 St->isNonTemporal(),
   16752                                 std::max(Alignment/2U, 1U));
   16753     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
   16754   }
   16755 
   16756   // Optimize trunc store (of multiple scalars) to shuffle and store.
   16757   // First, pack all of the elements in one place. Next, store to memory
   16758   // in fewer chunks.
   16759   if (St->isTruncatingStore() && VT.isVector()) {
   16760     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   16761     unsigned NumElems = VT.getVectorNumElements();
   16762     assert(StVT != VT && "Cannot truncate to the same type");
   16763     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
   16764     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
   16765 
   16766     // From, To sizes and ElemCount must be pow of two
   16767     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
   16768     // We are going to use the original vector elt for storing.
   16769     // Accumulated smaller vector elements must be a multiple of the store size.
   16770     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
   16771 
   16772     unsigned SizeRatio  = FromSz / ToSz;
   16773 
   16774     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
   16775 
   16776     // Create a type on which we perform the shuffle
   16777     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
   16778             StVT.getScalarType(), NumElems*SizeRatio);
   16779 
   16780     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
   16781 
   16782     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
   16783     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
   16784     for (unsigned i = 0; i != NumElems; ++i)
   16785       ShuffleVec[i] = i * SizeRatio;
   16786 
   16787     // Can't shuffle using an illegal type.
   16788     if (!TLI.isTypeLegal(WideVecVT))
   16789       return SDValue();
   16790 
   16791     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
   16792                                          DAG.getUNDEF(WideVecVT),
   16793                                          &ShuffleVec[0]);
   16794     // At this point all of the data is stored at the bottom of the
   16795     // register. We now need to save it to mem.
   16796 
   16797     // Find the largest store unit
   16798     MVT StoreType = MVT::i8;
   16799     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
   16800          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
   16801       MVT Tp = (MVT::SimpleValueType)tp;
   16802       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
   16803         StoreType = Tp;
   16804     }
   16805 
   16806     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
   16807     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
   16808         (64 <= NumElems * ToSz))
   16809       StoreType = MVT::f64;
   16810 
   16811     // Bitcast the original vector into a vector of store-size units
   16812     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
   16813             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
   16814     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
   16815     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
   16816     SmallVector<SDValue, 8> Chains;
   16817     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
   16818                                         TLI.getPointerTy());
   16819     SDValue Ptr = St->getBasePtr();
   16820 
   16821     // Perform one or more big stores into memory.
   16822     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
   16823       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
   16824                                    StoreType, ShuffWide,
   16825                                    DAG.getIntPtrConstant(i));
   16826       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
   16827                                 St->getPointerInfo(), St->isVolatile(),
   16828                                 St->isNonTemporal(), St->getAlignment());
   16829       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
   16830       Chains.push_back(Ch);
   16831     }
   16832 
   16833     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
   16834                                Chains.size());
   16835   }
   16836 
   16837   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
   16838   // the FP state in cases where an emms may be missing.
   16839   // A preferable solution to the general problem is to figure out the right
   16840   // places to insert EMMS.  This qualifies as a quick hack.
   16841 
   16842   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
   16843   if (VT.getSizeInBits() != 64)
   16844     return SDValue();
   16845 
   16846   const Function *F = DAG.getMachineFunction().getFunction();
   16847   bool NoImplicitFloatOps = F->getAttributes().
   16848     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
   16849   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
   16850                      && Subtarget->hasSSE2();
   16851   if ((VT.isVector() ||
   16852        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
   16853       isa<LoadSDNode>(St->getValue()) &&
   16854       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
   16855       St->getChain().hasOneUse() && !St->isVolatile()) {
   16856     SDNode* LdVal = St->getValue().getNode();
   16857     LoadSDNode *Ld = 0;
   16858     int TokenFactorIndex = -1;
   16859     SmallVector<SDValue, 8> Ops;
   16860     SDNode* ChainVal = St->getChain().getNode();
   16861     // Must be a store of a load.  We currently handle two cases:  the load
   16862     // is a direct child, and it's under an intervening TokenFactor.  It is
   16863     // possible to dig deeper under nested TokenFactors.
   16864     if (ChainVal == LdVal)
   16865       Ld = cast<LoadSDNode>(St->getChain());
   16866     else if (St->getValue().hasOneUse() &&
   16867              ChainVal->getOpcode() == ISD::TokenFactor) {
   16868       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
   16869         if (ChainVal->getOperand(i).getNode() == LdVal) {
   16870           TokenFactorIndex = i;
   16871           Ld = cast<LoadSDNode>(St->getValue());
   16872         } else
   16873           Ops.push_back(ChainVal->getOperand(i));
   16874       }
   16875     }
   16876 
   16877     if (!Ld || !ISD::isNormalLoad(Ld))
   16878       return SDValue();
   16879 
   16880     // If this is not the MMX case, i.e. we are just turning i64 load/store
   16881     // into f64 load/store, avoid the transformation if there are multiple
   16882     // uses of the loaded value.
   16883     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
   16884       return SDValue();
   16885 
   16886     DebugLoc LdDL = Ld->getDebugLoc();
   16887     DebugLoc StDL = N->getDebugLoc();
   16888     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
   16889     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
   16890     // pair instead.
   16891     if (Subtarget->is64Bit() || F64IsLegal) {
   16892       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
   16893       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
   16894                                   Ld->getPointerInfo(), Ld->isVolatile(),
   16895                                   Ld->isNonTemporal(), Ld->isInvariant(),
   16896                                   Ld->getAlignment());
   16897       SDValue NewChain = NewLd.getValue(1);
   16898       if (TokenFactorIndex != -1) {
   16899         Ops.push_back(NewChain);
   16900         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
   16901                                Ops.size());
   16902       }
   16903       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
   16904                           St->getPointerInfo(),
   16905                           St->isVolatile(), St->isNonTemporal(),
   16906                           St->getAlignment());
   16907     }
   16908 
   16909     // Otherwise, lower to two pairs of 32-bit loads / stores.
   16910     SDValue LoAddr = Ld->getBasePtr();
   16911     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
   16912                                  DAG.getConstant(4, MVT::i32));
   16913 
   16914     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
   16915                                Ld->getPointerInfo(),
   16916                                Ld->isVolatile(), Ld->isNonTemporal(),
   16917                                Ld->isInvariant(), Ld->getAlignment());
   16918     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
   16919                                Ld->getPointerInfo().getWithOffset(4),
   16920                                Ld->isVolatile(), Ld->isNonTemporal(),
   16921                                Ld->isInvariant(),
   16922                                MinAlign(Ld->getAlignment(), 4));
   16923 
   16924     SDValue NewChain = LoLd.getValue(1);
   16925     if (TokenFactorIndex != -1) {
   16926       Ops.push_back(LoLd);
   16927       Ops.push_back(HiLd);
   16928       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
   16929                              Ops.size());
   16930     }
   16931 
   16932     LoAddr = St->getBasePtr();
   16933     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
   16934                          DAG.getConstant(4, MVT::i32));
   16935 
   16936     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
   16937                                 St->getPointerInfo(),
   16938                                 St->isVolatile(), St->isNonTemporal(),
   16939                                 St->getAlignment());
   16940     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
   16941                                 St->getPointerInfo().getWithOffset(4),
   16942                                 St->isVolatile(),
   16943                                 St->isNonTemporal(),
   16944                                 MinAlign(St->getAlignment(), 4));
   16945     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
   16946   }
   16947   return SDValue();
   16948 }
   16949 
   16950 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
   16951 /// and return the operands for the horizontal operation in LHS and RHS.  A
   16952 /// horizontal operation performs the binary operation on successive elements
   16953 /// of its first operand, then on successive elements of its second operand,
   16954 /// returning the resulting values in a vector.  For example, if
   16955 ///   A = < float a0, float a1, float a2, float a3 >
   16956 /// and
   16957 ///   B = < float b0, float b1, float b2, float b3 >
   16958 /// then the result of doing a horizontal operation on A and B is
   16959 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
   16960 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
   16961 /// A horizontal-op B, for some already available A and B, and if so then LHS is
   16962 /// set to A, RHS to B, and the routine returns 'true'.
   16963 /// Note that the binary operation should have the property that if one of the
   16964 /// operands is UNDEF then the result is UNDEF.
   16965 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
   16966   // Look for the following pattern: if
   16967   //   A = < float a0, float a1, float a2, float a3 >
   16968   //   B = < float b0, float b1, float b2, float b3 >
   16969   // and
   16970   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
   16971   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
   16972   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
   16973   // which is A horizontal-op B.
   16974 
   16975   // At least one of the operands should be a vector shuffle.
   16976   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
   16977       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
   16978     return false;
   16979 
   16980   EVT VT = LHS.getValueType();
   16981 
   16982   assert((VT.is128BitVector() || VT.is256BitVector()) &&
   16983          "Unsupported vector type for horizontal add/sub");
   16984 
   16985   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
   16986   // operate independently on 128-bit lanes.
   16987   unsigned NumElts = VT.getVectorNumElements();
   16988   unsigned NumLanes = VT.getSizeInBits()/128;
   16989   unsigned NumLaneElts = NumElts / NumLanes;
   16990   assert((NumLaneElts % 2 == 0) &&
   16991          "Vector type should have an even number of elements in each lane");
   16992   unsigned HalfLaneElts = NumLaneElts/2;
   16993 
   16994   // View LHS in the form
   16995   //   LHS = VECTOR_SHUFFLE A, B, LMask
   16996   // If LHS is not a shuffle then pretend it is the shuffle
   16997   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
   16998   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
   16999   // type VT.
   17000   SDValue A, B;
   17001   SmallVector<int, 16> LMask(NumElts);
   17002   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
   17003     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
   17004       A = LHS.getOperand(0);
   17005     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
   17006       B = LHS.getOperand(1);
   17007     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
   17008     std::copy(Mask.begin(), Mask.end(), LMask.begin());
   17009   } else {
   17010     if (LHS.getOpcode() != ISD::UNDEF)
   17011       A = LHS;
   17012     for (unsigned i = 0; i != NumElts; ++i)
   17013       LMask[i] = i;
   17014   }
   17015 
   17016   // Likewise, view RHS in the form
   17017   //   RHS = VECTOR_SHUFFLE C, D, RMask
   17018   SDValue C, D;
   17019   SmallVector<int, 16> RMask(NumElts);
   17020   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
   17021     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
   17022       C = RHS.getOperand(0);
   17023     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
   17024       D = RHS.getOperand(1);
   17025     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
   17026     std::copy(Mask.begin(), Mask.end(), RMask.begin());
   17027   } else {
   17028     if (RHS.getOpcode() != ISD::UNDEF)
   17029       C = RHS;
   17030     for (unsigned i = 0; i != NumElts; ++i)
   17031       RMask[i] = i;
   17032   }
   17033 
   17034   // Check that the shuffles are both shuffling the same vectors.
   17035   if (!(A == C && B == D) && !(A == D && B == C))
   17036     return false;
   17037 
   17038   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
   17039   if (!A.getNode() && !B.getNode())
   17040     return false;
   17041 
   17042   // If A and B occur in reverse order in RHS, then "swap" them (which means
   17043   // rewriting the mask).
   17044   if (A != C)
   17045     CommuteVectorShuffleMask(RMask, NumElts);
   17046 
   17047   // At this point LHS and RHS are equivalent to
   17048   //   LHS = VECTOR_SHUFFLE A, B, LMask
   17049   //   RHS = VECTOR_SHUFFLE A, B, RMask
   17050   // Check that the masks correspond to performing a horizontal operation.
   17051   for (unsigned i = 0; i != NumElts; ++i) {
   17052     int LIdx = LMask[i], RIdx = RMask[i];
   17053 
   17054     // Ignore any UNDEF components.
   17055     if (LIdx < 0 || RIdx < 0 ||
   17056         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
   17057         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
   17058       continue;
   17059 
   17060     // Check that successive elements are being operated on.  If not, this is
   17061     // not a horizontal operation.
   17062     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
   17063     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
   17064     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
   17065     if (!(LIdx == Index && RIdx == Index + 1) &&
   17066         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
   17067       return false;
   17068   }
   17069 
   17070   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
   17071   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
   17072   return true;
   17073 }
   17074 
   17075 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
   17076 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
   17077                                   const X86Subtarget *Subtarget) {
   17078   EVT VT = N->getValueType(0);
   17079   SDValue LHS = N->getOperand(0);
   17080   SDValue RHS = N->getOperand(1);
   17081 
   17082   // Try to synthesize horizontal adds from adds of shuffles.
   17083   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
   17084        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
   17085       isHorizontalBinOp(LHS, RHS, true))
   17086     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
   17087   return SDValue();
   17088 }
   17089 
   17090 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
   17091 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
   17092                                   const X86Subtarget *Subtarget) {
   17093   EVT VT = N->getValueType(0);
   17094   SDValue LHS = N->getOperand(0);
   17095   SDValue RHS = N->getOperand(1);
   17096 
   17097   // Try to synthesize horizontal subs from subs of shuffles.
   17098   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
   17099        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
   17100       isHorizontalBinOp(LHS, RHS, false))
   17101     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
   17102   return SDValue();
   17103 }
   17104 
   17105 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
   17106 /// X86ISD::FXOR nodes.
   17107 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
   17108   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
   17109   // F[X]OR(0.0, x) -> x
   17110   // F[X]OR(x, 0.0) -> x
   17111   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
   17112     if (C->getValueAPF().isPosZero())
   17113       return N->getOperand(1);
   17114   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
   17115     if (C->getValueAPF().isPosZero())
   17116       return N->getOperand(0);
   17117   return SDValue();
   17118 }
   17119 
   17120 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
   17121 /// X86ISD::FMAX nodes.
   17122 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
   17123   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
   17124 
   17125   // Only perform optimizations if UnsafeMath is used.
   17126   if (!DAG.getTarget().Options.UnsafeFPMath)
   17127     return SDValue();
   17128 
   17129   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
   17130   // into FMINC and FMAXC, which are Commutative operations.
   17131   unsigned NewOp = 0;
   17132   switch (N->getOpcode()) {
   17133     default: llvm_unreachable("unknown opcode");
   17134     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
   17135     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
   17136   }
   17137 
   17138   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
   17139                      N->getOperand(0), N->getOperand(1));
   17140 }
   17141 
   17142 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
   17143 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
   17144   // FAND(0.0, x) -> 0.0
   17145   // FAND(x, 0.0) -> 0.0
   17146   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
   17147     if (C->getValueAPF().isPosZero())
   17148       return N->getOperand(0);
   17149   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
   17150     if (C->getValueAPF().isPosZero())
   17151       return N->getOperand(1);
   17152   return SDValue();
   17153 }
   17154 
   17155 static SDValue PerformBTCombine(SDNode *N,
   17156                                 SelectionDAG &DAG,
   17157                                 TargetLowering::DAGCombinerInfo &DCI) {
   17158   // BT ignores high bits in the bit index operand.
   17159   SDValue Op1 = N->getOperand(1);
   17160   if (Op1.hasOneUse()) {
   17161     unsigned BitWidth = Op1.getValueSizeInBits();
   17162     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
   17163     APInt KnownZero, KnownOne;
   17164     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
   17165                                           !DCI.isBeforeLegalizeOps());
   17166     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   17167     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
   17168         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
   17169       DCI.CommitTargetLoweringOpt(TLO);
   17170   }
   17171   return SDValue();
   17172 }
   17173 
   17174 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
   17175   SDValue Op = N->getOperand(0);
   17176   if (Op.getOpcode() == ISD::BITCAST)
   17177     Op = Op.getOperand(0);
   17178   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
   17179   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
   17180       VT.getVectorElementType().getSizeInBits() ==
   17181       OpVT.getVectorElementType().getSizeInBits()) {
   17182     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
   17183   }
   17184   return SDValue();
   17185 }
   17186 
   17187 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
   17188                                                const X86Subtarget *Subtarget) {
   17189   EVT VT = N->getValueType(0);
   17190   if (!VT.isVector())
   17191     return SDValue();
   17192 
   17193   SDValue N0 = N->getOperand(0);
   17194   SDValue N1 = N->getOperand(1);
   17195   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
   17196   DebugLoc dl = N->getDebugLoc();
   17197 
   17198   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
   17199   // both SSE and AVX2 since there is no sign-extended shift right
   17200   // operation on a vector with 64-bit elements.
   17201   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
   17202   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
   17203   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
   17204       N0.getOpcode() == ISD::SIGN_EXTEND)) {
   17205     SDValue N00 = N0.getOperand(0);
   17206 
   17207     // EXTLOAD has a better solution on AVX2,
   17208     // it may be replaced with X86ISD::VSEXT node.
   17209     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
   17210       if (!ISD::isNormalLoad(N00.getNode()))
   17211         return SDValue();
   17212 
   17213     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
   17214         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
   17215                                   N00, N1);
   17216       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
   17217     }
   17218   }
   17219   return SDValue();
   17220 }
   17221 
   17222 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
   17223                                   TargetLowering::DAGCombinerInfo &DCI,
   17224                                   const X86Subtarget *Subtarget) {
   17225   if (!DCI.isBeforeLegalizeOps())
   17226     return SDValue();
   17227 
   17228   if (!Subtarget->hasFp256())
   17229     return SDValue();
   17230 
   17231   EVT VT = N->getValueType(0);
   17232   if (VT.isVector() && VT.getSizeInBits() == 256) {
   17233     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
   17234     if (R.getNode())
   17235       return R;
   17236   }
   17237 
   17238   return SDValue();
   17239 }
   17240 
   17241 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
   17242                                  const X86Subtarget* Subtarget) {
   17243   DebugLoc dl = N->getDebugLoc();
   17244   EVT VT = N->getValueType(0);
   17245 
   17246   // Let legalize expand this if it isn't a legal type yet.
   17247   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
   17248     return SDValue();
   17249 
   17250   EVT ScalarVT = VT.getScalarType();
   17251   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
   17252       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
   17253     return SDValue();
   17254 
   17255   SDValue A = N->getOperand(0);
   17256   SDValue B = N->getOperand(1);
   17257   SDValue C = N->getOperand(2);
   17258 
   17259   bool NegA = (A.getOpcode() == ISD::FNEG);
   17260   bool NegB = (B.getOpcode() == ISD::FNEG);
   17261   bool NegC = (C.getOpcode() == ISD::FNEG);
   17262 
   17263   // Negative multiplication when NegA xor NegB
   17264   bool NegMul = (NegA != NegB);
   17265   if (NegA)
   17266     A = A.getOperand(0);
   17267   if (NegB)
   17268     B = B.getOperand(0);
   17269   if (NegC)
   17270     C = C.getOperand(0);
   17271 
   17272   unsigned Opcode;
   17273   if (!NegMul)
   17274     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
   17275   else
   17276     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
   17277 
   17278   return DAG.getNode(Opcode, dl, VT, A, B, C);
   17279 }
   17280 
   17281 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
   17282                                   TargetLowering::DAGCombinerInfo &DCI,
   17283                                   const X86Subtarget *Subtarget) {
   17284   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
   17285   //           (and (i32 x86isd::setcc_carry), 1)
   17286   // This eliminates the zext. This transformation is necessary because
   17287   // ISD::SETCC is always legalized to i8.
   17288   DebugLoc dl = N->getDebugLoc();
   17289   SDValue N0 = N->getOperand(0);
   17290   EVT VT = N->getValueType(0);
   17291 
   17292   if (N0.getOpcode() == ISD::AND &&
   17293       N0.hasOneUse() &&
   17294       N0.getOperand(0).hasOneUse()) {
   17295     SDValue N00 = N0.getOperand(0);
   17296     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
   17297       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   17298       if (!C || C->getZExtValue() != 1)
   17299         return SDValue();
   17300       return DAG.getNode(ISD::AND, dl, VT,
   17301                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
   17302                                      N00.getOperand(0), N00.getOperand(1)),
   17303                          DAG.getConstant(1, VT));
   17304     }
   17305   }
   17306 
   17307   if (VT.is256BitVector()) {
   17308     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
   17309     if (R.getNode())
   17310       return R;
   17311   }
   17312 
   17313   return SDValue();
   17314 }
   17315 
   17316 // Optimize x == -y --> x+y == 0
   17317 //          x != -y --> x+y != 0
   17318 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
   17319   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
   17320   SDValue LHS = N->getOperand(0);
   17321   SDValue RHS = N->getOperand(1);
   17322 
   17323   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
   17324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
   17325       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
   17326         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
   17327                                    LHS.getValueType(), RHS, LHS.getOperand(1));
   17328         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
   17329                             addV, DAG.getConstant(0, addV.getValueType()), CC);
   17330       }
   17331   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
   17332     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
   17333       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
   17334         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
   17335                                    RHS.getValueType(), LHS, RHS.getOperand(1));
   17336         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
   17337                             addV, DAG.getConstant(0, addV.getValueType()), CC);
   17338       }
   17339   return SDValue();
   17340 }
   17341 
   17342 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
   17343 // as "sbb reg,reg", since it can be extended without zext and produces
   17344 // an all-ones bit which is more useful than 0/1 in some cases.
   17345 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
   17346   return DAG.getNode(ISD::AND, DL, MVT::i8,
   17347                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
   17348                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
   17349                      DAG.getConstant(1, MVT::i8));
   17350 }
   17351 
   17352 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
   17353 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
   17354                                    TargetLowering::DAGCombinerInfo &DCI,
   17355                                    const X86Subtarget *Subtarget) {
   17356   DebugLoc DL = N->getDebugLoc();
   17357   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
   17358   SDValue EFLAGS = N->getOperand(1);
   17359 
   17360   if (CC == X86::COND_A) {
   17361     // Try to convert COND_A into COND_B in an attempt to facilitate
   17362     // materializing "setb reg".
   17363     //
   17364     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
   17365     // cannot take an immediate as its first operand.
   17366     //
   17367     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
   17368         EFLAGS.getValueType().isInteger() &&
   17369         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
   17370       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
   17371                                    EFLAGS.getNode()->getVTList(),
   17372                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
   17373       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
   17374       return MaterializeSETB(DL, NewEFLAGS, DAG);
   17375     }
   17376   }
   17377 
   17378   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
   17379   // a zext and produces an all-ones bit which is more useful than 0/1 in some
   17380   // cases.
   17381   if (CC == X86::COND_B)
   17382     return MaterializeSETB(DL, EFLAGS, DAG);
   17383 
   17384   SDValue Flags;
   17385 
   17386   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
   17387   if (Flags.getNode()) {
   17388     SDValue Cond = DAG.getConstant(CC, MVT::i8);
   17389     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
   17390   }
   17391 
   17392   return SDValue();
   17393 }
   17394 
   17395 // Optimize branch condition evaluation.
   17396 //
   17397 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
   17398                                     TargetLowering::DAGCombinerInfo &DCI,
   17399                                     const X86Subtarget *Subtarget) {
   17400   DebugLoc DL = N->getDebugLoc();
   17401   SDValue Chain = N->getOperand(0);
   17402   SDValue Dest = N->getOperand(1);
   17403   SDValue EFLAGS = N->getOperand(3);
   17404   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
   17405 
   17406   SDValue Flags;
   17407 
   17408   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
   17409   if (Flags.getNode()) {
   17410     SDValue Cond = DAG.getConstant(CC, MVT::i8);
   17411     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
   17412                        Flags);
   17413   }
   17414 
   17415   return SDValue();
   17416 }
   17417 
   17418 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
   17419                                         const X86TargetLowering *XTLI) {
   17420   SDValue Op0 = N->getOperand(0);
   17421   EVT InVT = Op0->getValueType(0);
   17422 
   17423   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
   17424   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
   17425     DebugLoc dl = N->getDebugLoc();
   17426     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
   17427     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
   17428     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
   17429   }
   17430 
   17431   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
   17432   // a 32-bit target where SSE doesn't support i64->FP operations.
   17433   if (Op0.getOpcode() == ISD::LOAD) {
   17434     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
   17435     EVT VT = Ld->getValueType(0);
   17436     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
   17437         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
   17438         !XTLI->getSubtarget()->is64Bit() &&
   17439         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
   17440       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
   17441                                           Ld->getChain(), Op0, DAG);
   17442       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
   17443       return FILDChain;
   17444     }
   17445   }
   17446   return SDValue();
   17447 }
   17448 
   17449 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
   17450 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
   17451                                  X86TargetLowering::DAGCombinerInfo &DCI) {
   17452   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
   17453   // the result is either zero or one (depending on the input carry bit).
   17454   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
   17455   if (X86::isZeroNode(N->getOperand(0)) &&
   17456       X86::isZeroNode(N->getOperand(1)) &&
   17457       // We don't have a good way to replace an EFLAGS use, so only do this when
   17458       // dead right now.
   17459       SDValue(N, 1).use_empty()) {
   17460     DebugLoc DL = N->getDebugLoc();
   17461     EVT VT = N->getValueType(0);
   17462     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
   17463     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
   17464                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
   17465                                            DAG.getConstant(X86::COND_B,MVT::i8),
   17466                                            N->getOperand(2)),
   17467                                DAG.getConstant(1, VT));
   17468     return DCI.CombineTo(N, Res1, CarryOut);
   17469   }
   17470 
   17471   return SDValue();
   17472 }
   17473 
   17474 // fold (add Y, (sete  X, 0)) -> adc  0, Y
   17475 //      (add Y, (setne X, 0)) -> sbb -1, Y
   17476 //      (sub (sete  X, 0), Y) -> sbb  0, Y
   17477 //      (sub (setne X, 0), Y) -> adc -1, Y
   17478 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
   17479   DebugLoc DL = N->getDebugLoc();
   17480 
   17481   // Look through ZExts.
   17482   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
   17483   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
   17484     return SDValue();
   17485 
   17486   SDValue SetCC = Ext.getOperand(0);
   17487   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
   17488     return SDValue();
   17489 
   17490   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
   17491   if (CC != X86::COND_E && CC != X86::COND_NE)
   17492     return SDValue();
   17493 
   17494   SDValue Cmp = SetCC.getOperand(1);
   17495   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
   17496       !X86::isZeroNode(Cmp.getOperand(1)) ||
   17497       !Cmp.getOperand(0).getValueType().isInteger())
   17498     return SDValue();
   17499 
   17500   SDValue CmpOp0 = Cmp.getOperand(0);
   17501   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
   17502                                DAG.getConstant(1, CmpOp0.getValueType()));
   17503 
   17504   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
   17505   if (CC == X86::COND_NE)
   17506     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
   17507                        DL, OtherVal.getValueType(), OtherVal,
   17508                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
   17509   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
   17510                      DL, OtherVal.getValueType(), OtherVal,
   17511                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
   17512 }
   17513 
   17514 /// PerformADDCombine - Do target-specific dag combines on integer adds.
   17515 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
   17516                                  const X86Subtarget *Subtarget) {
   17517   EVT VT = N->getValueType(0);
   17518   SDValue Op0 = N->getOperand(0);
   17519   SDValue Op1 = N->getOperand(1);
   17520 
   17521   // Try to synthesize horizontal adds from adds of shuffles.
   17522   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
   17523        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
   17524       isHorizontalBinOp(Op0, Op1, true))
   17525     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
   17526 
   17527   return OptimizeConditionalInDecrement(N, DAG);
   17528 }
   17529 
   17530 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
   17531                                  const X86Subtarget *Subtarget) {
   17532   SDValue Op0 = N->getOperand(0);
   17533   SDValue Op1 = N->getOperand(1);
   17534 
   17535   // X86 can't encode an immediate LHS of a sub. See if we can push the
   17536   // negation into a preceding instruction.
   17537   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
   17538     // If the RHS of the sub is a XOR with one use and a constant, invert the
   17539     // immediate. Then add one to the LHS of the sub so we can turn
   17540     // X-Y -> X+~Y+1, saving one register.
   17541     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
   17542         isa<ConstantSDNode>(Op1.getOperand(1))) {
   17543       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
   17544       EVT VT = Op0.getValueType();
   17545       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
   17546                                    Op1.getOperand(0),
   17547                                    DAG.getConstant(~XorC, VT));
   17548       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
   17549                          DAG.getConstant(C->getAPIntValue()+1, VT));
   17550     }
   17551   }
   17552 
   17553   // Try to synthesize horizontal adds from adds of shuffles.
   17554   EVT VT = N->getValueType(0);
   17555   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
   17556        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
   17557       isHorizontalBinOp(Op0, Op1, true))
   17558     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
   17559 
   17560   return OptimizeConditionalInDecrement(N, DAG);
   17561 }
   17562 
   17563 /// performVZEXTCombine - Performs build vector combines
   17564 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
   17565                                         TargetLowering::DAGCombinerInfo &DCI,
   17566                                         const X86Subtarget *Subtarget) {
   17567   // (vzext (bitcast (vzext (x)) -> (vzext x)
   17568   SDValue In = N->getOperand(0);
   17569   while (In.getOpcode() == ISD::BITCAST)
   17570     In = In.getOperand(0);
   17571 
   17572   if (In.getOpcode() != X86ISD::VZEXT)
   17573     return SDValue();
   17574 
   17575   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
   17576                      In.getOperand(0));
   17577 }
   17578 
   17579 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
   17580                                              DAGCombinerInfo &DCI) const {
   17581   SelectionDAG &DAG = DCI.DAG;
   17582   switch (N->getOpcode()) {
   17583   default: break;
   17584   case ISD::EXTRACT_VECTOR_ELT:
   17585     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
   17586   case ISD::VSELECT:
   17587   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
   17588   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
   17589   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
   17590   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
   17591   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
   17592   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
   17593   case ISD::SHL:
   17594   case ISD::SRA:
   17595   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
   17596   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
   17597   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
   17598   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
   17599   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
   17600   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
   17601   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
   17602   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
   17603   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
   17604   case X86ISD::FXOR:
   17605   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
   17606   case X86ISD::FMIN:
   17607   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
   17608   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
   17609   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
   17610   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
   17611   case ISD::ANY_EXTEND:
   17612   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
   17613   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
   17614   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
   17615   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
   17616   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
   17617   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
   17618   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
   17619   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
   17620   case X86ISD::SHUFP:       // Handle all target specific shuffles
   17621   case X86ISD::PALIGNR:
   17622   case X86ISD::UNPCKH:
   17623   case X86ISD::UNPCKL:
   17624   case X86ISD::MOVHLPS:
   17625   case X86ISD::MOVLHPS:
   17626   case X86ISD::PSHUFD:
   17627   case X86ISD::PSHUFHW:
   17628   case X86ISD::PSHUFLW:
   17629   case X86ISD::MOVSS:
   17630   case X86ISD::MOVSD:
   17631   case X86ISD::VPERMILP:
   17632   case X86ISD::VPERM2X128:
   17633   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
   17634   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
   17635   }
   17636 
   17637   return SDValue();
   17638 }
   17639 
   17640 /// isTypeDesirableForOp - Return true if the target has native support for
   17641 /// the specified value type and it is 'desirable' to use the type for the
   17642 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
   17643 /// instruction encodings are longer and some i16 instructions are slow.
   17644 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
   17645   if (!isTypeLegal(VT))
   17646     return false;
   17647   if (VT != MVT::i16)
   17648     return true;
   17649 
   17650   switch (Opc) {
   17651   default:
   17652     return true;
   17653   case ISD::LOAD:
   17654   case ISD::SIGN_EXTEND:
   17655   case ISD::ZERO_EXTEND:
   17656   case ISD::ANY_EXTEND:
   17657   case ISD::SHL:
   17658   case ISD::SRL:
   17659   case ISD::SUB:
   17660   case ISD::ADD:
   17661   case ISD::MUL:
   17662   case ISD::AND:
   17663   case ISD::OR:
   17664   case ISD::XOR:
   17665     return false;
   17666   }
   17667 }
   17668 
   17669 /// IsDesirableToPromoteOp - This method query the target whether it is
   17670 /// beneficial for dag combiner to promote the specified node. If true, it
   17671 /// should return the desired promotion type by reference.
   17672 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
   17673   EVT VT = Op.getValueType();
   17674   if (VT != MVT::i16)
   17675     return false;
   17676 
   17677   bool Promote = false;
   17678   bool Commute = false;
   17679   switch (Op.getOpcode()) {
   17680   default: break;
   17681   case ISD::LOAD: {
   17682     LoadSDNode *LD = cast<LoadSDNode>(Op);
   17683     // If the non-extending load has a single use and it's not live out, then it
   17684     // might be folded.
   17685     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
   17686                                                      Op.hasOneUse()*/) {
   17687       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
   17688              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
   17689         // The only case where we'd want to promote LOAD (rather then it being
   17690         // promoted as an operand is when it's only use is liveout.
   17691         if (UI->getOpcode() != ISD::CopyToReg)
   17692           return false;
   17693       }
   17694     }
   17695     Promote = true;
   17696     break;
   17697   }
   17698   case ISD::SIGN_EXTEND:
   17699   case ISD::ZERO_EXTEND:
   17700   case ISD::ANY_EXTEND:
   17701     Promote = true;
   17702     break;
   17703   case ISD::SHL:
   17704   case ISD::SRL: {
   17705     SDValue N0 = Op.getOperand(0);
   17706     // Look out for (store (shl (load), x)).
   17707     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
   17708       return false;
   17709     Promote = true;
   17710     break;
   17711   }
   17712   case ISD::ADD:
   17713   case ISD::MUL:
   17714   case ISD::AND:
   17715   case ISD::OR:
   17716   case ISD::XOR:
   17717     Commute = true;
   17718     // fallthrough
   17719   case ISD::SUB: {
   17720     SDValue N0 = Op.getOperand(0);
   17721     SDValue N1 = Op.getOperand(1);
   17722     if (!Commute && MayFoldLoad(N1))
   17723       return false;
   17724     // Avoid disabling potential load folding opportunities.
   17725     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
   17726       return false;
   17727     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
   17728       return false;
   17729     Promote = true;
   17730   }
   17731   }
   17732 
   17733   PVT = MVT::i32;
   17734   return Promote;
   17735 }
   17736 
   17737 //===----------------------------------------------------------------------===//
   17738 //                           X86 Inline Assembly Support
   17739 //===----------------------------------------------------------------------===//
   17740 
   17741 namespace {
   17742   // Helper to match a string separated by whitespace.
   17743   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
   17744     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
   17745 
   17746     for (unsigned i = 0, e = args.size(); i != e; ++i) {
   17747       StringRef piece(*args[i]);
   17748       if (!s.startswith(piece)) // Check if the piece matches.
   17749         return false;
   17750 
   17751       s = s.substr(piece.size());
   17752       StringRef::size_type pos = s.find_first_not_of(" \t");
   17753       if (pos == 0) // We matched a prefix.
   17754         return false;
   17755 
   17756       s = s.substr(pos);
   17757     }
   17758 
   17759     return s.empty();
   17760   }
   17761   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
   17762 }
   17763 
   17764 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
   17765   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
   17766 
   17767   std::string AsmStr = IA->getAsmString();
   17768 
   17769   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
   17770   if (!Ty || Ty->getBitWidth() % 16 != 0)
   17771     return false;
   17772 
   17773   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
   17774   SmallVector<StringRef, 4> AsmPieces;
   17775   SplitString(AsmStr, AsmPieces, ";\n");
   17776 
   17777   switch (AsmPieces.size()) {
   17778   default: return false;
   17779   case 1:
   17780     // FIXME: this should verify that we are targeting a 486 or better.  If not,
   17781     // we will turn this bswap into something that will be lowered to logical
   17782     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
   17783     // lower so don't worry about this.
   17784     // bswap $0
   17785     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
   17786         matchAsm(AsmPieces[0], "bswapl", "$0") ||
   17787         matchAsm(AsmPieces[0], "bswapq", "$0") ||
   17788         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
   17789         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
   17790         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
   17791       // No need to check constraints, nothing other than the equivalent of
   17792       // "=r,0" would be valid here.
   17793       return IntrinsicLowering::LowerToByteSwap(CI);
   17794     }
   17795 
   17796     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
   17797     if (CI->getType()->isIntegerTy(16) &&
   17798         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
   17799         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
   17800          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
   17801       AsmPieces.clear();
   17802       const std::string &ConstraintsStr = IA->getConstraintString();
   17803       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
   17804       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
   17805       if (AsmPieces.size() == 4 &&
   17806           AsmPieces[0] == "~{cc}" &&
   17807           AsmPieces[1] == "~{dirflag}" &&
   17808           AsmPieces[2] == "~{flags}" &&
   17809           AsmPieces[3] == "~{fpsr}")
   17810       return IntrinsicLowering::LowerToByteSwap(CI);
   17811     }
   17812     break;
   17813   case 3:
   17814     if (CI->getType()->isIntegerTy(32) &&
   17815         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
   17816         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
   17817         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
   17818         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
   17819       AsmPieces.clear();
   17820       const std::string &ConstraintsStr = IA->getConstraintString();
   17821       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
   17822       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
   17823       if (AsmPieces.size() == 4 &&
   17824           AsmPieces[0] == "~{cc}" &&
   17825           AsmPieces[1] == "~{dirflag}" &&
   17826           AsmPieces[2] == "~{flags}" &&
   17827           AsmPieces[3] == "~{fpsr}")
   17828         return IntrinsicLowering::LowerToByteSwap(CI);
   17829     }
   17830 
   17831     if (CI->getType()->isIntegerTy(64)) {
   17832       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
   17833       if (Constraints.size() >= 2 &&
   17834           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
   17835           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
   17836         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
   17837         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
   17838             matchAsm(AsmPieces[1], "bswap", "%edx") &&
   17839             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
   17840           return IntrinsicLowering::LowerToByteSwap(CI);
   17841       }
   17842     }
   17843     break;
   17844   }
   17845   return false;
   17846 }
   17847 
   17848 /// getConstraintType - Given a constraint letter, return the type of
   17849 /// constraint it is for this target.
   17850 X86TargetLowering::ConstraintType
   17851 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
   17852   if (Constraint.size() == 1) {
   17853     switch (Constraint[0]) {
   17854     case 'R':
   17855     case 'q':
   17856     case 'Q':
   17857     case 'f':
   17858     case 't':
   17859     case 'u':
   17860     case 'y':
   17861     case 'x':
   17862     case 'Y':
   17863     case 'l':
   17864       return C_RegisterClass;
   17865     case 'a':
   17866     case 'b':
   17867     case 'c':
   17868     case 'd':
   17869     case 'S':
   17870     case 'D':
   17871     case 'A':
   17872       return C_Register;
   17873     case 'I':
   17874     case 'J':
   17875     case 'K':
   17876     case 'L':
   17877     case 'M':
   17878     case 'N':
   17879     case 'G':
   17880     case 'C':
   17881     case 'e':
   17882     case 'Z':
   17883       return C_Other;
   17884     default:
   17885       break;
   17886     }
   17887   }
   17888   return TargetLowering::getConstraintType(Constraint);
   17889 }
   17890 
   17891 /// Examine constraint type and operand type and determine a weight value.
   17892 /// This object must already have been set up with the operand type
   17893 /// and the current alternative constraint selected.
   17894 TargetLowering::ConstraintWeight
   17895   X86TargetLowering::getSingleConstraintMatchWeight(
   17896     AsmOperandInfo &info, const char *constraint) const {
   17897   ConstraintWeight weight = CW_Invalid;
   17898   Value *CallOperandVal = info.CallOperandVal;
   17899     // If we don't have a value, we can't do a match,
   17900     // but allow it at the lowest weight.
   17901   if (CallOperandVal == NULL)
   17902     return CW_Default;
   17903   Type *type = CallOperandVal->getType();
   17904   // Look at the constraint type.
   17905   switch (*constraint) {
   17906   default:
   17907     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
   17908   case 'R':
   17909   case 'q':
   17910   case 'Q':
   17911   case 'a':
   17912   case 'b':
   17913   case 'c':
   17914   case 'd':
   17915   case 'S':
   17916   case 'D':
   17917   case 'A':
   17918     if (CallOperandVal->getType()->isIntegerTy())
   17919       weight = CW_SpecificReg;
   17920     break;
   17921   case 'f':
   17922   case 't':
   17923   case 'u':
   17924     if (type->isFloatingPointTy())
   17925       weight = CW_SpecificReg;
   17926     break;
   17927   case 'y':
   17928     if (type->isX86_MMXTy() && Subtarget->hasMMX())
   17929       weight = CW_SpecificReg;
   17930     break;
   17931   case 'x':
   17932   case 'Y':
   17933     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
   17934         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
   17935       weight = CW_Register;
   17936     break;
   17937   case 'I':
   17938     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
   17939       if (C->getZExtValue() <= 31)
   17940         weight = CW_Constant;
   17941     }
   17942     break;
   17943   case 'J':
   17944     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
   17945       if (C->getZExtValue() <= 63)
   17946         weight = CW_Constant;
   17947     }
   17948     break;
   17949   case 'K':
   17950     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
   17951       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
   17952         weight = CW_Constant;
   17953     }
   17954     break;
   17955   case 'L':
   17956     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
   17957       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
   17958         weight = CW_Constant;
   17959     }
   17960     break;
   17961   case 'M':
   17962     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
   17963       if (C->getZExtValue() <= 3)
   17964         weight = CW_Constant;
   17965     }
   17966     break;
   17967   case 'N':
   17968     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
   17969       if (C->getZExtValue() <= 0xff)
   17970         weight = CW_Constant;
   17971     }
   17972     break;
   17973   case 'G':
   17974   case 'C':
   17975     if (dyn_cast<ConstantFP>(CallOperandVal)) {
   17976       weight = CW_Constant;
   17977     }
   17978     break;
   17979   case 'e':
   17980     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
   17981       if ((C->getSExtValue() >= -0x80000000LL) &&
   17982           (C->getSExtValue() <= 0x7fffffffLL))
   17983         weight = CW_Constant;
   17984     }
   17985     break;
   17986   case 'Z':
   17987     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
   17988       if (C->getZExtValue() <= 0xffffffff)
   17989         weight = CW_Constant;
   17990     }
   17991     break;
   17992   }
   17993   return weight;
   17994 }
   17995 
   17996 /// LowerXConstraint - try to replace an X constraint, which matches anything,
   17997 /// with another that has more specific requirements based on the type of the
   17998 /// corresponding operand.
   17999 const char *X86TargetLowering::
   18000 LowerXConstraint(EVT ConstraintVT) const {
   18001   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
   18002   // 'f' like normal targets.
   18003   if (ConstraintVT.isFloatingPoint()) {
   18004     if (Subtarget->hasSSE2())
   18005       return "Y";
   18006     if (Subtarget->hasSSE1())
   18007       return "x";
   18008   }
   18009 
   18010   return TargetLowering::LowerXConstraint(ConstraintVT);
   18011 }
   18012 
   18013 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
   18014 /// vector.  If it is invalid, don't add anything to Ops.
   18015 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
   18016                                                      std::string &Constraint,
   18017                                                      std::vector<SDValue>&Ops,
   18018                                                      SelectionDAG &DAG) const {
   18019   SDValue Result(0, 0);
   18020 
   18021   // Only support length 1 constraints for now.
   18022   if (Constraint.length() > 1) return;
   18023 
   18024   char ConstraintLetter = Constraint[0];
   18025   switch (ConstraintLetter) {
   18026   default: break;
   18027   case 'I':
   18028     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
   18029       if (C->getZExtValue() <= 31) {
   18030         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
   18031         break;
   18032       }
   18033     }
   18034     return;
   18035   case 'J':
   18036     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
   18037       if (C->getZExtValue() <= 63) {
   18038         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
   18039         break;
   18040       }
   18041     }
   18042     return;
   18043   case 'K':
   18044     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
   18045       if (isInt<8>(C->getSExtValue())) {
   18046         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
   18047         break;
   18048       }
   18049     }
   18050     return;
   18051   case 'N':
   18052     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
   18053       if (C->getZExtValue() <= 255) {
   18054         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
   18055         break;
   18056       }
   18057     }
   18058     return;
   18059   case 'e': {
   18060     // 32-bit signed value
   18061     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
   18062       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
   18063                                            C->getSExtValue())) {
   18064         // Widen to 64 bits here to get it sign extended.
   18065         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
   18066         break;
   18067       }
   18068     // FIXME gcc accepts some relocatable values here too, but only in certain
   18069     // memory models; it's complicated.
   18070     }
   18071     return;
   18072   }
   18073   case 'Z': {
   18074     // 32-bit unsigned value
   18075     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
   18076       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
   18077                                            C->getZExtValue())) {
   18078         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
   18079         break;
   18080       }
   18081     }
   18082     // FIXME gcc accepts some relocatable values here too, but only in certain
   18083     // memory models; it's complicated.
   18084     return;
   18085   }
   18086   case 'i': {
   18087     // Literal immediates are always ok.
   18088     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
   18089       // Widen to 64 bits here to get it sign extended.
   18090       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
   18091       break;
   18092     }
   18093 
   18094     // In any sort of PIC mode addresses need to be computed at runtime by
   18095     // adding in a register or some sort of table lookup.  These can't
   18096     // be used as immediates.
   18097     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
   18098       return;
   18099 
   18100     // If we are in non-pic codegen mode, we allow the address of a global (with
   18101     // an optional displacement) to be used with 'i'.
   18102     GlobalAddressSDNode *GA = 0;
   18103     int64_t Offset = 0;
   18104 
   18105     // Match either (GA), (GA+C), (GA+C1+C2), etc.
   18106     while (1) {
   18107       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
   18108         Offset += GA->getOffset();
   18109         break;
   18110       } else if (Op.getOpcode() == ISD::ADD) {
   18111         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
   18112           Offset += C->getZExtValue();
   18113           Op = Op.getOperand(0);
   18114           continue;
   18115         }
   18116       } else if (Op.getOpcode() == ISD::SUB) {
   18117         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
   18118           Offset += -C->getZExtValue();
   18119           Op = Op.getOperand(0);
   18120           continue;
   18121         }
   18122       }
   18123 
   18124       // Otherwise, this isn't something we can handle, reject it.
   18125       return;
   18126     }
   18127 
   18128     const GlobalValue *GV = GA->getGlobal();
   18129     // If we require an extra load to get this address, as in PIC mode, we
   18130     // can't accept it.
   18131     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
   18132                                                         getTargetMachine())))
   18133       return;
   18134 
   18135     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
   18136                                         GA->getValueType(0), Offset);
   18137     break;
   18138   }
   18139   }
   18140 
   18141   if (Result.getNode()) {
   18142     Ops.push_back(Result);
   18143     return;
   18144   }
   18145   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
   18146 }
   18147 
   18148 std::pair<unsigned, const TargetRegisterClass*>
   18149 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
   18150                                                 EVT VT) const {
   18151   // First, see if this is a constraint that directly corresponds to an LLVM
   18152   // register class.
   18153   if (Constraint.size() == 1) {
   18154     // GCC Constraint Letters
   18155     switch (Constraint[0]) {
   18156     default: break;
   18157       // TODO: Slight differences here in allocation order and leaving
   18158       // RIP in the class. Do they matter any more here than they do
   18159       // in the normal allocation?
   18160     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
   18161       if (Subtarget->is64Bit()) {
   18162         if (VT == MVT::i32 || VT == MVT::f32)
   18163           return std::make_pair(0U, &X86::GR32RegClass);
   18164         if (VT == MVT::i16)
   18165           return std::make_pair(0U, &X86::GR16RegClass);
   18166         if (VT == MVT::i8 || VT == MVT::i1)
   18167           return std::make_pair(0U, &X86::GR8RegClass);
   18168         if (VT == MVT::i64 || VT == MVT::f64)
   18169           return std::make_pair(0U, &X86::GR64RegClass);
   18170         break;
   18171       }
   18172       // 32-bit fallthrough
   18173     case 'Q':   // Q_REGS
   18174       if (VT == MVT::i32 || VT == MVT::f32)
   18175         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
   18176       if (VT == MVT::i16)
   18177         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
   18178       if (VT == MVT::i8 || VT == MVT::i1)
   18179         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
   18180       if (VT == MVT::i64)
   18181         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
   18182       break;
   18183     case 'r':   // GENERAL_REGS
   18184     case 'l':   // INDEX_REGS
   18185       if (VT == MVT::i8 || VT == MVT::i1)
   18186         return std::make_pair(0U, &X86::GR8RegClass);
   18187       if (VT == MVT::i16)
   18188         return std::make_pair(0U, &X86::GR16RegClass);
   18189       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
   18190         return std::make_pair(0U, &X86::GR32RegClass);
   18191       return std::make_pair(0U, &X86::GR64RegClass);
   18192     case 'R':   // LEGACY_REGS
   18193       if (VT == MVT::i8 || VT == MVT::i1)
   18194         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
   18195       if (VT == MVT::i16)
   18196         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
   18197       if (VT == MVT::i32 || !Subtarget->is64Bit())
   18198         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
   18199       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
   18200     case 'f':  // FP Stack registers.
   18201       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
   18202       // value to the correct fpstack register class.
   18203       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
   18204         return std::make_pair(0U, &X86::RFP32RegClass);
   18205       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
   18206         return std::make_pair(0U, &X86::RFP64RegClass);
   18207       return std::make_pair(0U, &X86::RFP80RegClass);
   18208     case 'y':   // MMX_REGS if MMX allowed.
   18209       if (!Subtarget->hasMMX()) break;
   18210       return std::make_pair(0U, &X86::VR64RegClass);
   18211     case 'Y':   // SSE_REGS if SSE2 allowed
   18212       if (!Subtarget->hasSSE2()) break;
   18213       // FALL THROUGH.
   18214     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
   18215       if (!Subtarget->hasSSE1()) break;
   18216 
   18217       switch (VT.getSimpleVT().SimpleTy) {
   18218       default: break;
   18219       // Scalar SSE types.
   18220       case MVT::f32:
   18221       case MVT::i32:
   18222         return std::make_pair(0U, &X86::FR32RegClass);
   18223       case MVT::f64:
   18224       case MVT::i64:
   18225         return std::make_pair(0U, &X86::FR64RegClass);
   18226       // Vector types.
   18227       case MVT::v16i8:
   18228       case MVT::v8i16:
   18229       case MVT::v4i32:
   18230       case MVT::v2i64:
   18231       case MVT::v4f32:
   18232       case MVT::v2f64:
   18233         return std::make_pair(0U, &X86::VR128RegClass);
   18234       // AVX types.
   18235       case MVT::v32i8:
   18236       case MVT::v16i16:
   18237       case MVT::v8i32:
   18238       case MVT::v4i64:
   18239       case MVT::v8f32:
   18240       case MVT::v4f64:
   18241         return std::make_pair(0U, &X86::VR256RegClass);
   18242       }
   18243       break;
   18244     }
   18245   }
   18246 
   18247   // Use the default implementation in TargetLowering to convert the register
   18248   // constraint into a member of a register class.
   18249   std::pair<unsigned, const TargetRegisterClass*> Res;
   18250   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
   18251 
   18252   // Not found as a standard register?
   18253   if (Res.second == 0) {
   18254     // Map st(0) -> st(7) -> ST0
   18255     if (Constraint.size() == 7 && Constraint[0] == '{' &&
   18256         std::tolower(Constraint[1]) == 's' &&
   18257         std::tolower(Constraint[2]) == 't' &&
   18258         Constraint[3] == '(' &&
   18259         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
   18260         Constraint[5] == ')' &&
   18261         Constraint[6] == '}') {
   18262 
   18263       Res.first = X86::ST0+Constraint[4]-'0';
   18264       Res.second = &X86::RFP80RegClass;
   18265       return Res;
   18266     }
   18267 
   18268     // GCC allows "st(0)" to be called just plain "st".
   18269     if (StringRef("{st}").equals_lower(Constraint)) {
   18270       Res.first = X86::ST0;
   18271       Res.second = &X86::RFP80RegClass;
   18272       return Res;
   18273     }
   18274 
   18275     // flags -> EFLAGS
   18276     if (StringRef("{flags}").equals_lower(Constraint)) {
   18277       Res.first = X86::EFLAGS;
   18278       Res.second = &X86::CCRRegClass;
   18279       return Res;
   18280     }
   18281 
   18282     // 'A' means EAX + EDX.
   18283     if (Constraint == "A") {
   18284       Res.first = X86::EAX;
   18285       Res.second = &X86::GR32_ADRegClass;
   18286       return Res;
   18287     }
   18288     return Res;
   18289   }
   18290 
   18291   // Otherwise, check to see if this is a register class of the wrong value
   18292   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
   18293   // turn into {ax},{dx}.
   18294   if (Res.second->hasType(VT))
   18295     return Res;   // Correct type already, nothing to do.
   18296 
   18297   // All of the single-register GCC register classes map their values onto
   18298   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
   18299   // really want an 8-bit or 32-bit register, map to the appropriate register
   18300   // class and return the appropriate register.
   18301   if (Res.second == &X86::GR16RegClass) {
   18302     if (VT == MVT::i8 || VT == MVT::i1) {
   18303       unsigned DestReg = 0;
   18304       switch (Res.first) {
   18305       default: break;
   18306       case X86::AX: DestReg = X86::AL; break;
   18307       case X86::DX: DestReg = X86::DL; break;
   18308       case X86::CX: DestReg = X86::CL; break;
   18309       case X86::BX: DestReg = X86::BL; break;
   18310       }
   18311       if (DestReg) {
   18312         Res.first = DestReg;
   18313         Res.second = &X86::GR8RegClass;
   18314       }
   18315     } else if (VT == MVT::i32 || VT == MVT::f32) {
   18316       unsigned DestReg = 0;
   18317       switch (Res.first) {
   18318       default: break;
   18319       case X86::AX: DestReg = X86::EAX; break;
   18320       case X86::DX: DestReg = X86::EDX; break;
   18321       case X86::CX: DestReg = X86::ECX; break;
   18322       case X86::BX: DestReg = X86::EBX; break;
   18323       case X86::SI: DestReg = X86::ESI; break;
   18324       case X86::DI: DestReg = X86::EDI; break;
   18325       case X86::BP: DestReg = X86::EBP; break;
   18326       case X86::SP: DestReg = X86::ESP; break;
   18327       }
   18328       if (DestReg) {
   18329         Res.first = DestReg;
   18330         Res.second = &X86::GR32RegClass;
   18331       }
   18332     } else if (VT == MVT::i64 || VT == MVT::f64) {
   18333       unsigned DestReg = 0;
   18334       switch (Res.first) {
   18335       default: break;
   18336       case X86::AX: DestReg = X86::RAX; break;
   18337       case X86::DX: DestReg = X86::RDX; break;
   18338       case X86::CX: DestReg = X86::RCX; break;
   18339       case X86::BX: DestReg = X86::RBX; break;
   18340       case X86::SI: DestReg = X86::RSI; break;
   18341       case X86::DI: DestReg = X86::RDI; break;
   18342       case X86::BP: DestReg = X86::RBP; break;
   18343       case X86::SP: DestReg = X86::RSP; break;
   18344       }
   18345       if (DestReg) {
   18346         Res.first = DestReg;
   18347         Res.second = &X86::GR64RegClass;
   18348       }
   18349     }
   18350   } else if (Res.second == &X86::FR32RegClass ||
   18351              Res.second == &X86::FR64RegClass ||
   18352              Res.second == &X86::VR128RegClass) {
   18353     // Handle references to XMM physical registers that got mapped into the
   18354     // wrong class.  This can happen with constraints like {xmm0} where the
   18355     // target independent register mapper will just pick the first match it can
   18356     // find, ignoring the required type.
   18357 
   18358     if (VT == MVT::f32 || VT == MVT::i32)
   18359       Res.second = &X86::FR32RegClass;
   18360     else if (VT == MVT::f64 || VT == MVT::i64)
   18361       Res.second = &X86::FR64RegClass;
   18362     else if (X86::VR128RegClass.hasType(VT))
   18363       Res.second = &X86::VR128RegClass;
   18364     else if (X86::VR256RegClass.hasType(VT))
   18365       Res.second = &X86::VR256RegClass;
   18366   }
   18367 
   18368   return Res;
   18369 }
   18370