Add alignment value to allowsUnalignedMemoryAccess
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
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 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.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/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     if (Subtarget->is64Bit()) {
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022     }
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063
1064     // Custom lower v2i64 and v2f64 selects.
1065     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1066     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1067     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1068     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1069
1070     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1075     // As there is no 64-bit GPR available, we need build a special custom
1076     // sequence to convert from v2i32 to v2f32.
1077     if (!Subtarget->is64Bit())
1078       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1079
1080     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1082
1083     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1084
1085     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1087     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1088   }
1089
1090   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1094     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1099     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1101
1102     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1105     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1106     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1112
1113     // FIXME: Do we need to handle scalar-to-vector here?
1114     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1115
1116     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1121     // There is no BLENDI for byte vectors. We don't need to custom lower
1122     // some vselects for now.
1123     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1124
1125     // SSE41 brings specific instructions for doing vector sign extend even in
1126     // cases where we don't have SRA.
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130
1131     // i8 and i16 vectors are custom , because the source register and source
1132     // source memory operand types are not the same width.  f32 vectors are
1133     // custom since the immediate controlling the insert encodes additional
1134     // information.
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1139
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144
1145     // FIXME: these should be Legal but thats only for the case where
1146     // the index is constant.  For now custom expand to deal with that.
1147     if (Subtarget->is64Bit()) {
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1150     }
1151   }
1152
1153   if (Subtarget->hasSSE2()) {
1154     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1161     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1162
1163     // In the customized shift lowering, the legal cases in AVX2 will be
1164     // recognized.
1165     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1172   }
1173
1174   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1181
1182     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1185
1186     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1197     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1210     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1211
1212     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213     // even though v8i16 is a legal type.
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1217
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1220     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1221
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1224
1225     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1226
1227     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1240
1241     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1244
1245     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1249
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1262
1263     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1270     }
1271
1272     if (Subtarget->hasInt256()) {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287
1288       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1291       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1292
1293       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1294       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1295     } else {
1296       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1305
1306       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1309       // Don't lower v32i8 because there is no 128-bit byte mul
1310     }
1311
1312     // In the customized shift lowering, the legal cases in AVX2 will be
1313     // recognized.
1314     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1315     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1316
1317     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1318     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1319
1320     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1321
1322     // Custom lower several nodes for 256-bit types.
1323     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Extract subvector is special because the value type
1328       // (result) is 128-bit but the source is 256-bit wide.
1329       if (VT.is128BitVector())
1330         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331
1332       // Do not attempt to custom lower other non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1337       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1338       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1339       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1341       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1342       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1343     }
1344
1345     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347       MVT VT = (MVT::SimpleValueType)i;
1348
1349       // Do not attempt to promote non-256-bit vectors
1350       if (!VT.is256BitVector())
1351         continue;
1352
1353       setOperationAction(ISD::AND,    VT, Promote);
1354       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1355       setOperationAction(ISD::OR,     VT, Promote);
1356       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1357       setOperationAction(ISD::XOR,    VT, Promote);
1358       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1359       setOperationAction(ISD::LOAD,   VT, Promote);
1360       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1361       setOperationAction(ISD::SELECT, VT, Promote);
1362       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1363     }
1364   }
1365
1366   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1371
1372     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1373     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1374     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1375
1376     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1377     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1378     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1379     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1380     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1381     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1393     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1394
1395     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1400     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1401     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1403
1404     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1407     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1408     if (Subtarget->is64Bit()) {
1409       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1413     }
1414     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1422     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1423     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1424
1425     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460
1461     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1473     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1474
1475     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1476     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1477
1478     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1480     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1482     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1483     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1484
1485     if (Subtarget->hasCDI()) {
1486       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1487       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1488     }
1489
1490     // Custom lower several nodes.
1491     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493       MVT VT = (MVT::SimpleValueType)i;
1494
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       // Extract subvector is special because the value type
1497       // (result) is 256/128-bit but the source is 512-bit wide.
1498       if (VT.is128BitVector() || VT.is256BitVector())
1499         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500
1501       if (VT.getVectorElementType() == MVT::i1)
1502         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503
1504       // Do not attempt to custom lower other non-512-bit vectors
1505       if (!VT.is512BitVector())
1506         continue;
1507
1508       if ( EltSize >= 32) {
1509         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1510         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1511         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1512         setOperationAction(ISD::VSELECT,             VT, Legal);
1513         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1514         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1515         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1516       }
1517     }
1518     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519       MVT VT = (MVT::SimpleValueType)i;
1520
1521       // Do not attempt to promote non-256-bit vectors
1522       if (!VT.is512BitVector())
1523         continue;
1524
1525       setOperationAction(ISD::SELECT, VT, Promote);
1526       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1527     }
1528   }// has  AVX-512
1529
1530   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1532     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1533   }
1534
1535   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536   // of this type with custom code.
1537   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1540                        Custom);
1541   }
1542
1543   // We want to custom lower some of our intrinsics.
1544   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547   if (!Subtarget->is64Bit())
1548     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549
1550   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551   // handle type legalization for these operations here.
1552   //
1553   // FIXME: We really should do custom legalization for addition and
1554   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1555   // than generic legalization for 64-bit multiplication-with-overflow, though.
1556   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557     // Add/Sub/Mul with overflow operations are custom lowered.
1558     MVT VT = IntVTs[i];
1559     setOperationAction(ISD::SADDO, VT, Custom);
1560     setOperationAction(ISD::UADDO, VT, Custom);
1561     setOperationAction(ISD::SSUBO, VT, Custom);
1562     setOperationAction(ISD::USUBO, VT, Custom);
1563     setOperationAction(ISD::SMULO, VT, Custom);
1564     setOperationAction(ISD::UMULO, VT, Custom);
1565   }
1566
1567   // There are no 8-bit 3-address imul/mul instructions
1568   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570
1571   if (!Subtarget->is64Bit()) {
1572     // These libcalls are not available in 32-bit.
1573     setLibcallName(RTLIB::SHL_I128, nullptr);
1574     setLibcallName(RTLIB::SRL_I128, nullptr);
1575     setLibcallName(RTLIB::SRA_I128, nullptr);
1576   }
1577
1578   // Combine sin / cos into one node or libcall if possible.
1579   if (Subtarget->hasSinCos()) {
1580     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582     if (Subtarget->isTargetDarwin()) {
1583       // For MacOSX, we don't want to the normal expansion of a libcall to
1584       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585       // traffic.
1586       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1588     }
1589   }
1590
1591   if (Subtarget->isTargetWin64()) {
1592     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::SREM, MVT::i128, Custom);
1595     setOperationAction(ISD::UREM, MVT::i128, Custom);
1596     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1598   }
1599
1600   // We have target-specific dag combine patterns for the following nodes:
1601   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603   setTargetDAGCombine(ISD::VSELECT);
1604   setTargetDAGCombine(ISD::SELECT);
1605   setTargetDAGCombine(ISD::SHL);
1606   setTargetDAGCombine(ISD::SRA);
1607   setTargetDAGCombine(ISD::SRL);
1608   setTargetDAGCombine(ISD::OR);
1609   setTargetDAGCombine(ISD::AND);
1610   setTargetDAGCombine(ISD::ADD);
1611   setTargetDAGCombine(ISD::FADD);
1612   setTargetDAGCombine(ISD::FSUB);
1613   setTargetDAGCombine(ISD::FMA);
1614   setTargetDAGCombine(ISD::SUB);
1615   setTargetDAGCombine(ISD::LOAD);
1616   setTargetDAGCombine(ISD::STORE);
1617   setTargetDAGCombine(ISD::ZERO_EXTEND);
1618   setTargetDAGCombine(ISD::ANY_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621   setTargetDAGCombine(ISD::TRUNCATE);
1622   setTargetDAGCombine(ISD::SINT_TO_FP);
1623   setTargetDAGCombine(ISD::SETCC);
1624   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625   setTargetDAGCombine(ISD::BUILD_VECTOR);
1626   if (Subtarget->is64Bit())
1627     setTargetDAGCombine(ISD::MUL);
1628   setTargetDAGCombine(ISD::XOR);
1629
1630   computeRegisterProperties();
1631
1632   // On Darwin, -Os means optimize for size without hurting performance,
1633   // do not reduce the limit.
1634   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   setPrefLoopAlignment(4); // 2^4 bytes.
1641
1642   // Predictable cmov don't hurt on atom because it's in-order.
1643   PredictableSelectIsExpensive = !Subtarget->isAtom();
1644
1645   setPrefFunctionAlignment(4); // 2^4 bytes.
1646 }
1647
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651          Subtarget->is64Bit();
1652 }
1653
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656   if (ExperimentalVectorWideningLegalization &&
1657       VT.getVectorNumElements() != 1 &&
1658       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659     return TypeWidenVector;
1660
1661   return TargetLoweringBase::getPreferredVectorAction(VT);
1662 }
1663
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1665   if (!VT.isVector())
1666     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1667
1668   if (Subtarget->hasAVX512())
1669     switch(VT.getVectorNumElements()) {
1670     case  8: return MVT::v8i1;
1671     case 16: return MVT::v16i1;
1672   }
1673
1674   return VT.changeVectorElementTypeToInteger();
1675 }
1676
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1680   if (MaxAlign == 16)
1681     return;
1682   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683     if (VTy->getBitWidth() == 128)
1684       MaxAlign = 16;
1685   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686     unsigned EltAlign = 0;
1687     getMaxByValAlign(ATy->getElementType(), EltAlign);
1688     if (EltAlign > MaxAlign)
1689       MaxAlign = EltAlign;
1690   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692       unsigned EltAlign = 0;
1693       getMaxByValAlign(STy->getElementType(i), EltAlign);
1694       if (EltAlign > MaxAlign)
1695         MaxAlign = EltAlign;
1696       if (MaxAlign == 16)
1697         break;
1698     }
1699   }
1700 }
1701
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707   if (Subtarget->is64Bit()) {
1708     // Max of 8 and alignment of type.
1709     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1710     if (TyAlign > 8)
1711       return TyAlign;
1712     return 8;
1713   }
1714
1715   unsigned Align = 4;
1716   if (Subtarget->hasSSE1())
1717     getMaxByValAlign(Ty, Align);
1718   return Align;
1719 }
1720
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1732 EVT
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734                                        unsigned DstAlign, unsigned SrcAlign,
1735                                        bool IsMemset, bool ZeroMemset,
1736                                        bool MemcpyStrSrc,
1737                                        MachineFunction &MF) const {
1738   const Function *F = MF.getFunction();
1739   if ((!IsMemset || ZeroMemset) &&
1740       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741                                        Attribute::NoImplicitFloat)) {
1742     if (Size >= 16 &&
1743         (Subtarget->isUnalignedMemAccessFast() ||
1744          ((DstAlign == 0 || DstAlign >= 16) &&
1745           (SrcAlign == 0 || SrcAlign >= 16)))) {
1746       if (Size >= 32) {
1747         if (Subtarget->hasInt256())
1748           return MVT::v8i32;
1749         if (Subtarget->hasFp256())
1750           return MVT::v8f32;
1751       }
1752       if (Subtarget->hasSSE2())
1753         return MVT::v4i32;
1754       if (Subtarget->hasSSE1())
1755         return MVT::v4f32;
1756     } else if (!MemcpyStrSrc && Size >= 8 &&
1757                !Subtarget->is64Bit() &&
1758                Subtarget->hasSSE2()) {
1759       // Do not use f64 to lower memcpy if source is string constant. It's
1760       // better to use i32 to avoid the loads.
1761       return MVT::f64;
1762     }
1763   }
1764   if (Subtarget->is64Bit() && Size >= 8)
1765     return MVT::i64;
1766   return MVT::i32;
1767 }
1768
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1770   if (VT == MVT::f32)
1771     return X86ScalarSSEf32;
1772   else if (VT == MVT::f64)
1773     return X86ScalarSSEf64;
1774   return true;
1775 }
1776
1777 bool
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1779                                                   unsigned,
1780                                                   unsigned,
1781                                                   bool *Fast) const {
1782   if (Fast)
1783     *Fast = Subtarget->isUnalignedMemAccessFast();
1784   return true;
1785 }
1786
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function.  The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1792   // symbol.
1793   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794       Subtarget->isPICStyleGOT())
1795     return MachineJumpTableInfo::EK_Custom32;
1796
1797   // Otherwise, use the normal jump table encoding heuristics.
1798   return TargetLowering::getJumpTableEncoding();
1799 }
1800
1801 const MCExpr *
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803                                              const MachineBasicBlock *MBB,
1804                                              unsigned uid,MCContext &Ctx) const{
1805   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806          Subtarget->isPICStyleGOT());
1807   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808   // entries.
1809   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1811 }
1812
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1814 /// jumptable.
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816                                                     SelectionDAG &DAG) const {
1817   if (!Subtarget->is64Bit())
1818     // This doesn't have SDLoc associated with it, but is not really the
1819     // same as a Register.
1820     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1821   return Table;
1822 }
1823
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1826 /// MCExpr.
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829                              MCContext &Ctx) const {
1830   // X86-64 uses RIP relative addressing based on the jump table label.
1831   if (Subtarget->isPICStyleRIPRel())
1832     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833
1834   // Otherwise, the reference is relative to the PIC base.
1835   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1836 }
1837
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841   const TargetRegisterClass *RRC = nullptr;
1842   uint8_t Cost = 1;
1843   switch (VT.SimpleTy) {
1844   default:
1845     return TargetLowering::findRepresentativeClass(VT);
1846   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847     RRC = Subtarget->is64Bit() ?
1848       (const TargetRegisterClass*)&X86::GR64RegClass :
1849       (const TargetRegisterClass*)&X86::GR32RegClass;
1850     break;
1851   case MVT::x86mmx:
1852     RRC = &X86::VR64RegClass;
1853     break;
1854   case MVT::f32: case MVT::f64:
1855   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856   case MVT::v4f32: case MVT::v2f64:
1857   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1858   case MVT::v4f64:
1859     RRC = &X86::VR128RegClass;
1860     break;
1861   }
1862   return std::make_pair(RRC, Cost);
1863 }
1864
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866                                                unsigned &Offset) const {
1867   if (!Subtarget->isTargetLinux())
1868     return false;
1869
1870   if (Subtarget->is64Bit()) {
1871     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1872     Offset = 0x28;
1873     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1874       AddressSpace = 256;
1875     else
1876       AddressSpace = 257;
1877   } else {
1878     // %gs:0x14 on i386
1879     Offset = 0x14;
1880     AddressSpace = 256;
1881   }
1882   return true;
1883 }
1884
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886                                             unsigned DestAS) const {
1887   assert(SrcAS != DestAS && "Expected different address spaces!");
1888
1889   return SrcAS < 256 && DestAS < 256;
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 //               Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1895
1896 #include "X86GenCallingConv.inc"
1897
1898 bool
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900                                   MachineFunction &MF, bool isVarArg,
1901                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                         LLVMContext &Context) const {
1903   SmallVector<CCValAssign, 16> RVLocs;
1904   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1905                  RVLocs, Context);
1906   return CCInfo.CheckReturn(Outs, RetCC_X86);
1907 }
1908
1909 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1910   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1911   return ScratchRegs;
1912 }
1913
1914 SDValue
1915 X86TargetLowering::LowerReturn(SDValue Chain,
1916                                CallingConv::ID CallConv, bool isVarArg,
1917                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1918                                const SmallVectorImpl<SDValue> &OutVals,
1919                                SDLoc dl, SelectionDAG &DAG) const {
1920   MachineFunction &MF = DAG.getMachineFunction();
1921   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1922
1923   SmallVector<CCValAssign, 16> RVLocs;
1924   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1925                  RVLocs, *DAG.getContext());
1926   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1927
1928   SDValue Flag;
1929   SmallVector<SDValue, 6> RetOps;
1930   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931   // Operand #1 = Bytes To Pop
1932   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1933                    MVT::i16));
1934
1935   // Copy the result values into the output registers.
1936   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937     CCValAssign &VA = RVLocs[i];
1938     assert(VA.isRegLoc() && "Can only return in registers!");
1939     SDValue ValToCopy = OutVals[i];
1940     EVT ValVT = ValToCopy.getValueType();
1941
1942     // Promote values to the appropriate types
1943     if (VA.getLocInfo() == CCValAssign::SExt)
1944       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945     else if (VA.getLocInfo() == CCValAssign::ZExt)
1946       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::AExt)
1948       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949     else if (VA.getLocInfo() == CCValAssign::BCvt)
1950       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951
1952     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953            "Unexpected FP-extend for return value.");  
1954
1955     // If this is x86-64, and we disabled SSE, we can't return FP values,
1956     // or SSE or MMX vectors.
1957     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960       report_fatal_error("SSE register return with SSE disabled");
1961     }
1962     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1963     // llvm-gcc has never done it right and no one has noticed, so this
1964     // should be OK for now.
1965     if (ValVT == MVT::f64 &&
1966         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967       report_fatal_error("SSE2 register return with SSE2 disabled");
1968
1969     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970     // the RET instruction and handled by the FP Stackifier.
1971     if (VA.getLocReg() == X86::ST0 ||
1972         VA.getLocReg() == X86::ST1) {
1973       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974       // change the value to the FP stack register class.
1975       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977       RetOps.push_back(ValToCopy);
1978       // Don't emit a copytoreg.
1979       continue;
1980     }
1981
1982     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983     // which is returned in RAX / RDX.
1984     if (Subtarget->is64Bit()) {
1985       if (ValVT == MVT::x86mmx) {
1986         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989                                   ValToCopy);
1990           // If we don't have SSE2 available, convert to v4f32 so the generated
1991           // register is legal.
1992           if (!Subtarget->hasSSE2())
1993             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1994         }
1995       }
1996     }
1997
1998     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999     Flag = Chain.getValue(1);
2000     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2001   }
2002
2003   // The x86-64 ABIs require that for returning structs by value we copy
2004   // the sret argument into %rax/%eax (depending on ABI) for the return.
2005   // Win32 requires us to put the sret argument to %eax as well.
2006   // We saved the argument into a virtual register in the entry block,
2007   // so now we copy the value out and into %rax/%eax.
2008   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2009       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2010     MachineFunction &MF = DAG.getMachineFunction();
2011     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2012     unsigned Reg = FuncInfo->getSRetReturnReg();
2013     assert(Reg &&
2014            "SRetReturnReg should have been set in LowerFormalArguments().");
2015     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2016
2017     unsigned RetValReg
2018         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019           X86::RAX : X86::EAX;
2020     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021     Flag = Chain.getValue(1);
2022
2023     // RAX/EAX now acts like a return value.
2024     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2025   }
2026
2027   RetOps[0] = Chain;  // Update chain.
2028
2029   // Add the flag if we have it.
2030   if (Flag.getNode())
2031     RetOps.push_back(Flag);
2032
2033   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2034 }
2035
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037   if (N->getNumValues() != 1)
2038     return false;
2039   if (!N->hasNUsesOfValue(1, 0))
2040     return false;
2041
2042   SDValue TCChain = Chain;
2043   SDNode *Copy = *N->use_begin();
2044   if (Copy->getOpcode() == ISD::CopyToReg) {
2045     // If the copy has a glue operand, we conservatively assume it isn't safe to
2046     // perform a tail call.
2047     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2048       return false;
2049     TCChain = Copy->getOperand(0);
2050   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2051     return false;
2052
2053   bool HasRet = false;
2054   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055        UI != UE; ++UI) {
2056     if (UI->getOpcode() != X86ISD::RET_FLAG)
2057       return false;
2058     HasRet = true;
2059   }
2060
2061   if (!HasRet)
2062     return false;
2063
2064   Chain = TCChain;
2065   return true;
2066 }
2067
2068 MVT
2069 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2070                                             ISD::NodeType ExtendKind) const {
2071   MVT ReturnMVT;
2072   // TODO: Is this also valid on 32-bit?
2073   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2074     ReturnMVT = MVT::i8;
2075   else
2076     ReturnMVT = MVT::i32;
2077
2078   MVT MinVT = getRegisterType(ReturnMVT);
2079   return VT.bitsLT(MinVT) ? MinVT : VT;
2080 }
2081
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2084 ///
2085 SDValue
2086 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2087                                    CallingConv::ID CallConv, bool isVarArg,
2088                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2089                                    SDLoc dl, SelectionDAG &DAG,
2090                                    SmallVectorImpl<SDValue> &InVals) const {
2091
2092   // Assign locations to each value returned by this call.
2093   SmallVector<CCValAssign, 16> RVLocs;
2094   bool Is64Bit = Subtarget->is64Bit();
2095   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2096                  DAG.getTarget(), RVLocs, *DAG.getContext());
2097   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2098
2099   // Copy all of the result registers out of their specified physreg.
2100   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2101     CCValAssign &VA = RVLocs[i];
2102     EVT CopyVT = VA.getValVT();
2103
2104     // If this is x86-64, and we disabled SSE, we can't return FP values
2105     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2106         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2107       report_fatal_error("SSE register return with SSE disabled");
2108     }
2109
2110     SDValue Val;
2111
2112     // If this is a call to a function that returns an fp value on the floating
2113     // point stack, we must guarantee the value is popped from the stack, so
2114     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2115     // if the return value is not used. We use the FpPOP_RETVAL instruction
2116     // instead.
2117     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2118       // If we prefer to use the value in xmm registers, copy it out as f80 and
2119       // use a truncate to move it from fp stack reg to xmm reg.
2120       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2121       SDValue Ops[] = { Chain, InFlag };
2122       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2123                                          MVT::Other, MVT::Glue, Ops), 1);
2124       Val = Chain.getValue(0);
2125
2126       // Round the f80 to the right size, which also moves it to the appropriate
2127       // xmm register.
2128       if (CopyVT != VA.getValVT())
2129         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2130                           // This truncation won't change the value.
2131                           DAG.getIntPtrConstant(1));
2132     } else {
2133       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2134                                  CopyVT, InFlag).getValue(1);
2135       Val = Chain.getValue(0);
2136     }
2137     InFlag = Chain.getValue(2);
2138     InVals.push_back(Val);
2139   }
2140
2141   return Chain;
2142 }
2143
2144 //===----------------------------------------------------------------------===//
2145 //                C & StdCall & Fast Calling Convention implementation
2146 //===----------------------------------------------------------------------===//
2147 //  StdCall calling convention seems to be standard for many Windows' API
2148 //  routines and around. It differs from C calling convention just a little:
2149 //  callee should clean up the stack, not caller. Symbols should be also
2150 //  decorated in some fancy way :) It doesn't support any vector arguments.
2151 //  For info on fast calling convention see Fast Calling Convention (tail call)
2152 //  implementation LowerX86_32FastCCCallTo.
2153
2154 /// CallIsStructReturn - Determines whether a call uses struct return
2155 /// semantics.
2156 enum StructReturnType {
2157   NotStructReturn,
2158   RegStructReturn,
2159   StackStructReturn
2160 };
2161 static StructReturnType
2162 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2163   if (Outs.empty())
2164     return NotStructReturn;
2165
2166   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2167   if (!Flags.isSRet())
2168     return NotStructReturn;
2169   if (Flags.isInReg())
2170     return RegStructReturn;
2171   return StackStructReturn;
2172 }
2173
2174 /// ArgsAreStructReturn - Determines whether a function uses struct
2175 /// return semantics.
2176 static StructReturnType
2177 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2178   if (Ins.empty())
2179     return NotStructReturn;
2180
2181   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2182   if (!Flags.isSRet())
2183     return NotStructReturn;
2184   if (Flags.isInReg())
2185     return RegStructReturn;
2186   return StackStructReturn;
2187 }
2188
2189 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2190 /// by "Src" to address "Dst" with size and alignment information specified by
2191 /// the specific parameter attribute. The copy will be passed as a byval
2192 /// function parameter.
2193 static SDValue
2194 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2195                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2196                           SDLoc dl) {
2197   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2198
2199   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2200                        /*isVolatile*/false, /*AlwaysInline=*/true,
2201                        MachinePointerInfo(), MachinePointerInfo());
2202 }
2203
2204 /// IsTailCallConvention - Return true if the calling convention is one that
2205 /// supports tail call optimization.
2206 static bool IsTailCallConvention(CallingConv::ID CC) {
2207   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2208           CC == CallingConv::HiPE);
2209 }
2210
2211 /// \brief Return true if the calling convention is a C calling convention.
2212 static bool IsCCallConvention(CallingConv::ID CC) {
2213   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2214           CC == CallingConv::X86_64_SysV);
2215 }
2216
2217 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2218   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2219     return false;
2220
2221   CallSite CS(CI);
2222   CallingConv::ID CalleeCC = CS.getCallingConv();
2223   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2224     return false;
2225
2226   return true;
2227 }
2228
2229 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2230 /// a tailcall target by changing its ABI.
2231 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2232                                    bool GuaranteedTailCallOpt) {
2233   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2234 }
2235
2236 SDValue
2237 X86TargetLowering::LowerMemArgument(SDValue Chain,
2238                                     CallingConv::ID CallConv,
2239                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2240                                     SDLoc dl, SelectionDAG &DAG,
2241                                     const CCValAssign &VA,
2242                                     MachineFrameInfo *MFI,
2243                                     unsigned i) const {
2244   // Create the nodes corresponding to a load from this parameter slot.
2245   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2246   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2247       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2248   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2249   EVT ValVT;
2250
2251   // If value is passed by pointer we have address passed instead of the value
2252   // itself.
2253   if (VA.getLocInfo() == CCValAssign::Indirect)
2254     ValVT = VA.getLocVT();
2255   else
2256     ValVT = VA.getValVT();
2257
2258   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2259   // changed with more analysis.
2260   // In case of tail call optimization mark all arguments mutable. Since they
2261   // could be overwritten by lowering of arguments in case of a tail call.
2262   if (Flags.isByVal()) {
2263     unsigned Bytes = Flags.getByValSize();
2264     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2265     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2266     return DAG.getFrameIndex(FI, getPointerTy());
2267   } else {
2268     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2269                                     VA.getLocMemOffset(), isImmutable);
2270     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2271     return DAG.getLoad(ValVT, dl, Chain, FIN,
2272                        MachinePointerInfo::getFixedStack(FI),
2273                        false, false, false, 0);
2274   }
2275 }
2276
2277 SDValue
2278 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2279                                         CallingConv::ID CallConv,
2280                                         bool isVarArg,
2281                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2282                                         SDLoc dl,
2283                                         SelectionDAG &DAG,
2284                                         SmallVectorImpl<SDValue> &InVals)
2285                                           const {
2286   MachineFunction &MF = DAG.getMachineFunction();
2287   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2288
2289   const Function* Fn = MF.getFunction();
2290   if (Fn->hasExternalLinkage() &&
2291       Subtarget->isTargetCygMing() &&
2292       Fn->getName() == "main")
2293     FuncInfo->setForceFramePointer(true);
2294
2295   MachineFrameInfo *MFI = MF.getFrameInfo();
2296   bool Is64Bit = Subtarget->is64Bit();
2297   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2298
2299   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2300          "Var args not supported with calling convention fastcc, ghc or hipe");
2301
2302   // Assign locations to all of the incoming arguments.
2303   SmallVector<CCValAssign, 16> ArgLocs;
2304   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2305                  ArgLocs, *DAG.getContext());
2306
2307   // Allocate shadow area for Win64
2308   if (IsWin64)
2309     CCInfo.AllocateStack(32, 8);
2310
2311   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2312
2313   unsigned LastVal = ~0U;
2314   SDValue ArgValue;
2315   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2316     CCValAssign &VA = ArgLocs[i];
2317     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2318     // places.
2319     assert(VA.getValNo() != LastVal &&
2320            "Don't support value assigned to multiple locs yet");
2321     (void)LastVal;
2322     LastVal = VA.getValNo();
2323
2324     if (VA.isRegLoc()) {
2325       EVT RegVT = VA.getLocVT();
2326       const TargetRegisterClass *RC;
2327       if (RegVT == MVT::i32)
2328         RC = &X86::GR32RegClass;
2329       else if (Is64Bit && RegVT == MVT::i64)
2330         RC = &X86::GR64RegClass;
2331       else if (RegVT == MVT::f32)
2332         RC = &X86::FR32RegClass;
2333       else if (RegVT == MVT::f64)
2334         RC = &X86::FR64RegClass;
2335       else if (RegVT.is512BitVector())
2336         RC = &X86::VR512RegClass;
2337       else if (RegVT.is256BitVector())
2338         RC = &X86::VR256RegClass;
2339       else if (RegVT.is128BitVector())
2340         RC = &X86::VR128RegClass;
2341       else if (RegVT == MVT::x86mmx)
2342         RC = &X86::VR64RegClass;
2343       else if (RegVT == MVT::i1)
2344         RC = &X86::VK1RegClass;
2345       else if (RegVT == MVT::v8i1)
2346         RC = &X86::VK8RegClass;
2347       else if (RegVT == MVT::v16i1)
2348         RC = &X86::VK16RegClass;
2349       else if (RegVT == MVT::v32i1)
2350         RC = &X86::VK32RegClass;
2351       else if (RegVT == MVT::v64i1)
2352         RC = &X86::VK64RegClass;
2353       else
2354         llvm_unreachable("Unknown argument type!");
2355
2356       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2357       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2358
2359       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2360       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2361       // right size.
2362       if (VA.getLocInfo() == CCValAssign::SExt)
2363         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2364                                DAG.getValueType(VA.getValVT()));
2365       else if (VA.getLocInfo() == CCValAssign::ZExt)
2366         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2367                                DAG.getValueType(VA.getValVT()));
2368       else if (VA.getLocInfo() == CCValAssign::BCvt)
2369         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2370
2371       if (VA.isExtInLoc()) {
2372         // Handle MMX values passed in XMM regs.
2373         if (RegVT.isVector())
2374           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2375         else
2376           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2377       }
2378     } else {
2379       assert(VA.isMemLoc());
2380       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2381     }
2382
2383     // If value is passed via pointer - do a load.
2384     if (VA.getLocInfo() == CCValAssign::Indirect)
2385       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2386                              MachinePointerInfo(), false, false, false, 0);
2387
2388     InVals.push_back(ArgValue);
2389   }
2390
2391   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2392     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2393       // The x86-64 ABIs require that for returning structs by value we copy
2394       // the sret argument into %rax/%eax (depending on ABI) for the return.
2395       // Win32 requires us to put the sret argument to %eax as well.
2396       // Save the argument into a virtual register so that we can access it
2397       // from the return points.
2398       if (Ins[i].Flags.isSRet()) {
2399         unsigned Reg = FuncInfo->getSRetReturnReg();
2400         if (!Reg) {
2401           MVT PtrTy = getPointerTy();
2402           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2403           FuncInfo->setSRetReturnReg(Reg);
2404         }
2405         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2406         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2407         break;
2408       }
2409     }
2410   }
2411
2412   unsigned StackSize = CCInfo.getNextStackOffset();
2413   // Align stack specially for tail calls.
2414   if (FuncIsMadeTailCallSafe(CallConv,
2415                              MF.getTarget().Options.GuaranteedTailCallOpt))
2416     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2417
2418   // If the function takes variable number of arguments, make a frame index for
2419   // the start of the first vararg value... for expansion of llvm.va_start.
2420   if (isVarArg) {
2421     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2422                     CallConv != CallingConv::X86_ThisCall)) {
2423       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2424     }
2425     if (Is64Bit) {
2426       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2427
2428       // FIXME: We should really autogenerate these arrays
2429       static const MCPhysReg GPR64ArgRegsWin64[] = {
2430         X86::RCX, X86::RDX, X86::R8,  X86::R9
2431       };
2432       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2433         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2434       };
2435       static const MCPhysReg XMMArgRegs64Bit[] = {
2436         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2437         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2438       };
2439       const MCPhysReg *GPR64ArgRegs;
2440       unsigned NumXMMRegs = 0;
2441
2442       if (IsWin64) {
2443         // The XMM registers which might contain var arg parameters are shadowed
2444         // in their paired GPR.  So we only need to save the GPR to their home
2445         // slots.
2446         TotalNumIntRegs = 4;
2447         GPR64ArgRegs = GPR64ArgRegsWin64;
2448       } else {
2449         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2450         GPR64ArgRegs = GPR64ArgRegs64Bit;
2451
2452         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2453                                                 TotalNumXMMRegs);
2454       }
2455       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2456                                                        TotalNumIntRegs);
2457
2458       bool NoImplicitFloatOps = Fn->getAttributes().
2459         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2460       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2461              "SSE register cannot be used when SSE is disabled!");
2462       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2463                NoImplicitFloatOps) &&
2464              "SSE register cannot be used when SSE is disabled!");
2465       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2466           !Subtarget->hasSSE1())
2467         // Kernel mode asks for SSE to be disabled, so don't push them
2468         // on the stack.
2469         TotalNumXMMRegs = 0;
2470
2471       if (IsWin64) {
2472         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2473         // Get to the caller-allocated home save location.  Add 8 to account
2474         // for the return address.
2475         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2476         FuncInfo->setRegSaveFrameIndex(
2477           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2478         // Fixup to set vararg frame on shadow area (4 x i64).
2479         if (NumIntRegs < 4)
2480           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2481       } else {
2482         // For X86-64, if there are vararg parameters that are passed via
2483         // registers, then we must store them to their spots on the stack so
2484         // they may be loaded by deferencing the result of va_next.
2485         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2486         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2487         FuncInfo->setRegSaveFrameIndex(
2488           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2489                                false));
2490       }
2491
2492       // Store the integer parameter registers.
2493       SmallVector<SDValue, 8> MemOps;
2494       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2495                                         getPointerTy());
2496       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2497       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2498         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2499                                   DAG.getIntPtrConstant(Offset));
2500         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2501                                      &X86::GR64RegClass);
2502         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2503         SDValue Store =
2504           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2505                        MachinePointerInfo::getFixedStack(
2506                          FuncInfo->getRegSaveFrameIndex(), Offset),
2507                        false, false, 0);
2508         MemOps.push_back(Store);
2509         Offset += 8;
2510       }
2511
2512       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2513         // Now store the XMM (fp + vector) parameter registers.
2514         SmallVector<SDValue, 11> SaveXMMOps;
2515         SaveXMMOps.push_back(Chain);
2516
2517         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2518         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2519         SaveXMMOps.push_back(ALVal);
2520
2521         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2522                                FuncInfo->getRegSaveFrameIndex()));
2523         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2524                                FuncInfo->getVarArgsFPOffset()));
2525
2526         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2527           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2528                                        &X86::VR128RegClass);
2529           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2530           SaveXMMOps.push_back(Val);
2531         }
2532         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2533                                      MVT::Other, SaveXMMOps));
2534       }
2535
2536       if (!MemOps.empty())
2537         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2538     }
2539   }
2540
2541   // Some CCs need callee pop.
2542   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2543                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2544     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2545   } else {
2546     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2547     // If this is an sret function, the return should pop the hidden pointer.
2548     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2549         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2550         argsAreStructReturn(Ins) == StackStructReturn)
2551       FuncInfo->setBytesToPopOnReturn(4);
2552   }
2553
2554   if (!Is64Bit) {
2555     // RegSaveFrameIndex is X86-64 only.
2556     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2557     if (CallConv == CallingConv::X86_FastCall ||
2558         CallConv == CallingConv::X86_ThisCall)
2559       // fastcc functions can't have varargs.
2560       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2561   }
2562
2563   FuncInfo->setArgumentStackSize(StackSize);
2564
2565   return Chain;
2566 }
2567
2568 SDValue
2569 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2570                                     SDValue StackPtr, SDValue Arg,
2571                                     SDLoc dl, SelectionDAG &DAG,
2572                                     const CCValAssign &VA,
2573                                     ISD::ArgFlagsTy Flags) const {
2574   unsigned LocMemOffset = VA.getLocMemOffset();
2575   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2576   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2577   if (Flags.isByVal())
2578     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2579
2580   return DAG.getStore(Chain, dl, Arg, PtrOff,
2581                       MachinePointerInfo::getStack(LocMemOffset),
2582                       false, false, 0);
2583 }
2584
2585 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2586 /// optimization is performed and it is required.
2587 SDValue
2588 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2589                                            SDValue &OutRetAddr, SDValue Chain,
2590                                            bool IsTailCall, bool Is64Bit,
2591                                            int FPDiff, SDLoc dl) const {
2592   // Adjust the Return address stack slot.
2593   EVT VT = getPointerTy();
2594   OutRetAddr = getReturnAddressFrameIndex(DAG);
2595
2596   // Load the "old" Return address.
2597   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2598                            false, false, false, 0);
2599   return SDValue(OutRetAddr.getNode(), 1);
2600 }
2601
2602 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2603 /// optimization is performed and it is required (FPDiff!=0).
2604 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2605                                         SDValue Chain, SDValue RetAddrFrIdx,
2606                                         EVT PtrVT, unsigned SlotSize,
2607                                         int FPDiff, SDLoc dl) {
2608   // Store the return address to the appropriate stack slot.
2609   if (!FPDiff) return Chain;
2610   // Calculate the new stack slot for the return address.
2611   int NewReturnAddrFI =
2612     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2613                                          false);
2614   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2615   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2616                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2617                        false, false, 0);
2618   return Chain;
2619 }
2620
2621 SDValue
2622 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2623                              SmallVectorImpl<SDValue> &InVals) const {
2624   SelectionDAG &DAG                     = CLI.DAG;
2625   SDLoc &dl                             = CLI.DL;
2626   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2627   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2628   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2629   SDValue Chain                         = CLI.Chain;
2630   SDValue Callee                        = CLI.Callee;
2631   CallingConv::ID CallConv              = CLI.CallConv;
2632   bool &isTailCall                      = CLI.IsTailCall;
2633   bool isVarArg                         = CLI.IsVarArg;
2634
2635   MachineFunction &MF = DAG.getMachineFunction();
2636   bool Is64Bit        = Subtarget->is64Bit();
2637   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2638   StructReturnType SR = callIsStructReturn(Outs);
2639   bool IsSibcall      = false;
2640
2641   if (MF.getTarget().Options.DisableTailCalls)
2642     isTailCall = false;
2643
2644   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2645   if (IsMustTail) {
2646     // Force this to be a tail call.  The verifier rules are enough to ensure
2647     // that we can lower this successfully without moving the return address
2648     // around.
2649     isTailCall = true;
2650   } else if (isTailCall) {
2651     // Check if it's really possible to do a tail call.
2652     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2653                     isVarArg, SR != NotStructReturn,
2654                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2655                     Outs, OutVals, Ins, DAG);
2656
2657     // Sibcalls are automatically detected tailcalls which do not require
2658     // ABI changes.
2659     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2660       IsSibcall = true;
2661
2662     if (isTailCall)
2663       ++NumTailCalls;
2664   }
2665
2666   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2667          "Var args not supported with calling convention fastcc, ghc or hipe");
2668
2669   // Analyze operands of the call, assigning locations to each operand.
2670   SmallVector<CCValAssign, 16> ArgLocs;
2671   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2672                  ArgLocs, *DAG.getContext());
2673
2674   // Allocate shadow area for Win64
2675   if (IsWin64)
2676     CCInfo.AllocateStack(32, 8);
2677
2678   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2679
2680   // Get a count of how many bytes are to be pushed on the stack.
2681   unsigned NumBytes = CCInfo.getNextStackOffset();
2682   if (IsSibcall)
2683     // This is a sibcall. The memory operands are available in caller's
2684     // own caller's stack.
2685     NumBytes = 0;
2686   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2687            IsTailCallConvention(CallConv))
2688     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2689
2690   int FPDiff = 0;
2691   if (isTailCall && !IsSibcall && !IsMustTail) {
2692     // Lower arguments at fp - stackoffset + fpdiff.
2693     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2694     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2695
2696     FPDiff = NumBytesCallerPushed - NumBytes;
2697
2698     // Set the delta of movement of the returnaddr stackslot.
2699     // But only set if delta is greater than previous delta.
2700     if (FPDiff < X86Info->getTCReturnAddrDelta())
2701       X86Info->setTCReturnAddrDelta(FPDiff);
2702   }
2703
2704   unsigned NumBytesToPush = NumBytes;
2705   unsigned NumBytesToPop = NumBytes;
2706
2707   // If we have an inalloca argument, all stack space has already been allocated
2708   // for us and be right at the top of the stack.  We don't support multiple
2709   // arguments passed in memory when using inalloca.
2710   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2711     NumBytesToPush = 0;
2712     if (!ArgLocs.back().isMemLoc())
2713       report_fatal_error("cannot use inalloca attribute on a register "
2714                          "parameter");
2715     if (ArgLocs.back().getLocMemOffset() != 0)
2716       report_fatal_error("any parameter with the inalloca attribute must be "
2717                          "the only memory argument");
2718   }
2719
2720   if (!IsSibcall)
2721     Chain = DAG.getCALLSEQ_START(
2722         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2723
2724   SDValue RetAddrFrIdx;
2725   // Load return address for tail calls.
2726   if (isTailCall && FPDiff)
2727     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2728                                     Is64Bit, FPDiff, dl);
2729
2730   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2731   SmallVector<SDValue, 8> MemOpChains;
2732   SDValue StackPtr;
2733
2734   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2735   // of tail call optimization arguments are handle later.
2736   const X86RegisterInfo *RegInfo =
2737     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2738   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2739     // Skip inalloca arguments, they have already been written.
2740     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2741     if (Flags.isInAlloca())
2742       continue;
2743
2744     CCValAssign &VA = ArgLocs[i];
2745     EVT RegVT = VA.getLocVT();
2746     SDValue Arg = OutVals[i];
2747     bool isByVal = Flags.isByVal();
2748
2749     // Promote the value if needed.
2750     switch (VA.getLocInfo()) {
2751     default: llvm_unreachable("Unknown loc info!");
2752     case CCValAssign::Full: break;
2753     case CCValAssign::SExt:
2754       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2755       break;
2756     case CCValAssign::ZExt:
2757       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2758       break;
2759     case CCValAssign::AExt:
2760       if (RegVT.is128BitVector()) {
2761         // Special case: passing MMX values in XMM registers.
2762         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2763         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2764         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2765       } else
2766         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2767       break;
2768     case CCValAssign::BCvt:
2769       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2770       break;
2771     case CCValAssign::Indirect: {
2772       // Store the argument.
2773       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2774       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2775       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2776                            MachinePointerInfo::getFixedStack(FI),
2777                            false, false, 0);
2778       Arg = SpillSlot;
2779       break;
2780     }
2781     }
2782
2783     if (VA.isRegLoc()) {
2784       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2785       if (isVarArg && IsWin64) {
2786         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2787         // shadow reg if callee is a varargs function.
2788         unsigned ShadowReg = 0;
2789         switch (VA.getLocReg()) {
2790         case X86::XMM0: ShadowReg = X86::RCX; break;
2791         case X86::XMM1: ShadowReg = X86::RDX; break;
2792         case X86::XMM2: ShadowReg = X86::R8; break;
2793         case X86::XMM3: ShadowReg = X86::R9; break;
2794         }
2795         if (ShadowReg)
2796           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2797       }
2798     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2799       assert(VA.isMemLoc());
2800       if (!StackPtr.getNode())
2801         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2802                                       getPointerTy());
2803       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2804                                              dl, DAG, VA, Flags));
2805     }
2806   }
2807
2808   if (!MemOpChains.empty())
2809     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2810
2811   if (Subtarget->isPICStyleGOT()) {
2812     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2813     // GOT pointer.
2814     if (!isTailCall) {
2815       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2816                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2817     } else {
2818       // If we are tail calling and generating PIC/GOT style code load the
2819       // address of the callee into ECX. The value in ecx is used as target of
2820       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2821       // for tail calls on PIC/GOT architectures. Normally we would just put the
2822       // address of GOT into ebx and then call target@PLT. But for tail calls
2823       // ebx would be restored (since ebx is callee saved) before jumping to the
2824       // target@PLT.
2825
2826       // Note: The actual moving to ECX is done further down.
2827       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2828       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2829           !G->getGlobal()->hasProtectedVisibility())
2830         Callee = LowerGlobalAddress(Callee, DAG);
2831       else if (isa<ExternalSymbolSDNode>(Callee))
2832         Callee = LowerExternalSymbol(Callee, DAG);
2833     }
2834   }
2835
2836   if (Is64Bit && isVarArg && !IsWin64) {
2837     // From AMD64 ABI document:
2838     // For calls that may call functions that use varargs or stdargs
2839     // (prototype-less calls or calls to functions containing ellipsis (...) in
2840     // the declaration) %al is used as hidden argument to specify the number
2841     // of SSE registers used. The contents of %al do not need to match exactly
2842     // the number of registers, but must be an ubound on the number of SSE
2843     // registers used and is in the range 0 - 8 inclusive.
2844
2845     // Count the number of XMM registers allocated.
2846     static const MCPhysReg XMMArgRegs[] = {
2847       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2848       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2849     };
2850     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2851     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2852            && "SSE registers cannot be used when SSE is disabled");
2853
2854     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2855                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2856   }
2857
2858   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2859   // don't need this because the eligibility check rejects calls that require
2860   // shuffling arguments passed in memory.
2861   if (!IsSibcall && isTailCall) {
2862     // Force all the incoming stack arguments to be loaded from the stack
2863     // before any new outgoing arguments are stored to the stack, because the
2864     // outgoing stack slots may alias the incoming argument stack slots, and
2865     // the alias isn't otherwise explicit. This is slightly more conservative
2866     // than necessary, because it means that each store effectively depends
2867     // on every argument instead of just those arguments it would clobber.
2868     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2869
2870     SmallVector<SDValue, 8> MemOpChains2;
2871     SDValue FIN;
2872     int FI = 0;
2873     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2874       CCValAssign &VA = ArgLocs[i];
2875       if (VA.isRegLoc())
2876         continue;
2877       assert(VA.isMemLoc());
2878       SDValue Arg = OutVals[i];
2879       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2880       // Skip inalloca arguments.  They don't require any work.
2881       if (Flags.isInAlloca())
2882         continue;
2883       // Create frame index.
2884       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2885       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2886       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2887       FIN = DAG.getFrameIndex(FI, getPointerTy());
2888
2889       if (Flags.isByVal()) {
2890         // Copy relative to framepointer.
2891         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2892         if (!StackPtr.getNode())
2893           StackPtr = DAG.getCopyFromReg(Chain, dl,
2894                                         RegInfo->getStackRegister(),
2895                                         getPointerTy());
2896         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2897
2898         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2899                                                          ArgChain,
2900                                                          Flags, DAG, dl));
2901       } else {
2902         // Store relative to framepointer.
2903         MemOpChains2.push_back(
2904           DAG.getStore(ArgChain, dl, Arg, FIN,
2905                        MachinePointerInfo::getFixedStack(FI),
2906                        false, false, 0));
2907       }
2908     }
2909
2910     if (!MemOpChains2.empty())
2911       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2912
2913     // Store the return address to the appropriate stack slot.
2914     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2915                                      getPointerTy(), RegInfo->getSlotSize(),
2916                                      FPDiff, dl);
2917   }
2918
2919   // Build a sequence of copy-to-reg nodes chained together with token chain
2920   // and flag operands which copy the outgoing args into registers.
2921   SDValue InFlag;
2922   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2923     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2924                              RegsToPass[i].second, InFlag);
2925     InFlag = Chain.getValue(1);
2926   }
2927
2928   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2929     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2930     // In the 64-bit large code model, we have to make all calls
2931     // through a register, since the call instruction's 32-bit
2932     // pc-relative offset may not be large enough to hold the whole
2933     // address.
2934   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2935     // If the callee is a GlobalAddress node (quite common, every direct call
2936     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2937     // it.
2938
2939     // We should use extra load for direct calls to dllimported functions in
2940     // non-JIT mode.
2941     const GlobalValue *GV = G->getGlobal();
2942     if (!GV->hasDLLImportStorageClass()) {
2943       unsigned char OpFlags = 0;
2944       bool ExtraLoad = false;
2945       unsigned WrapperKind = ISD::DELETED_NODE;
2946
2947       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2948       // external symbols most go through the PLT in PIC mode.  If the symbol
2949       // has hidden or protected visibility, or if it is static or local, then
2950       // we don't need to use the PLT - we can directly call it.
2951       if (Subtarget->isTargetELF() &&
2952           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2953           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2954         OpFlags = X86II::MO_PLT;
2955       } else if (Subtarget->isPICStyleStubAny() &&
2956                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2957                  (!Subtarget->getTargetTriple().isMacOSX() ||
2958                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2959         // PC-relative references to external symbols should go through $stub,
2960         // unless we're building with the leopard linker or later, which
2961         // automatically synthesizes these stubs.
2962         OpFlags = X86II::MO_DARWIN_STUB;
2963       } else if (Subtarget->isPICStyleRIPRel() &&
2964                  isa<Function>(GV) &&
2965                  cast<Function>(GV)->getAttributes().
2966                    hasAttribute(AttributeSet::FunctionIndex,
2967                                 Attribute::NonLazyBind)) {
2968         // If the function is marked as non-lazy, generate an indirect call
2969         // which loads from the GOT directly. This avoids runtime overhead
2970         // at the cost of eager binding (and one extra byte of encoding).
2971         OpFlags = X86II::MO_GOTPCREL;
2972         WrapperKind = X86ISD::WrapperRIP;
2973         ExtraLoad = true;
2974       }
2975
2976       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2977                                           G->getOffset(), OpFlags);
2978
2979       // Add a wrapper if needed.
2980       if (WrapperKind != ISD::DELETED_NODE)
2981         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2982       // Add extra indirection if needed.
2983       if (ExtraLoad)
2984         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2985                              MachinePointerInfo::getGOT(),
2986                              false, false, false, 0);
2987     }
2988   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2989     unsigned char OpFlags = 0;
2990
2991     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2992     // external symbols should go through the PLT.
2993     if (Subtarget->isTargetELF() &&
2994         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2995       OpFlags = X86II::MO_PLT;
2996     } else if (Subtarget->isPICStyleStubAny() &&
2997                (!Subtarget->getTargetTriple().isMacOSX() ||
2998                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2999       // PC-relative references to external symbols should go through $stub,
3000       // unless we're building with the leopard linker or later, which
3001       // automatically synthesizes these stubs.
3002       OpFlags = X86II::MO_DARWIN_STUB;
3003     }
3004
3005     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3006                                          OpFlags);
3007   }
3008
3009   // Returns a chain & a flag for retval copy to use.
3010   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3011   SmallVector<SDValue, 8> Ops;
3012
3013   if (!IsSibcall && isTailCall) {
3014     Chain = DAG.getCALLSEQ_END(Chain,
3015                                DAG.getIntPtrConstant(NumBytesToPop, true),
3016                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3017     InFlag = Chain.getValue(1);
3018   }
3019
3020   Ops.push_back(Chain);
3021   Ops.push_back(Callee);
3022
3023   if (isTailCall)
3024     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3025
3026   // Add argument registers to the end of the list so that they are known live
3027   // into the call.
3028   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3029     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3030                                   RegsToPass[i].second.getValueType()));
3031
3032   // Add a register mask operand representing the call-preserved registers.
3033   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3034   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3035   assert(Mask && "Missing call preserved mask for calling convention");
3036   Ops.push_back(DAG.getRegisterMask(Mask));
3037
3038   if (InFlag.getNode())
3039     Ops.push_back(InFlag);
3040
3041   if (isTailCall) {
3042     // We used to do:
3043     //// If this is the first return lowered for this function, add the regs
3044     //// to the liveout set for the function.
3045     // This isn't right, although it's probably harmless on x86; liveouts
3046     // should be computed from returns not tail calls.  Consider a void
3047     // function making a tail call to a function returning int.
3048     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3049   }
3050
3051   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3052   InFlag = Chain.getValue(1);
3053
3054   // Create the CALLSEQ_END node.
3055   unsigned NumBytesForCalleeToPop;
3056   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3057                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3058     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3059   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3060            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3061            SR == StackStructReturn)
3062     // If this is a call to a struct-return function, the callee
3063     // pops the hidden struct pointer, so we have to push it back.
3064     // This is common for Darwin/X86, Linux & Mingw32 targets.
3065     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3066     NumBytesForCalleeToPop = 4;
3067   else
3068     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3069
3070   // Returns a flag for retval copy to use.
3071   if (!IsSibcall) {
3072     Chain = DAG.getCALLSEQ_END(Chain,
3073                                DAG.getIntPtrConstant(NumBytesToPop, true),
3074                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3075                                                      true),
3076                                InFlag, dl);
3077     InFlag = Chain.getValue(1);
3078   }
3079
3080   // Handle result values, copying them out of physregs into vregs that we
3081   // return.
3082   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3083                          Ins, dl, DAG, InVals);
3084 }
3085
3086 //===----------------------------------------------------------------------===//
3087 //                Fast Calling Convention (tail call) implementation
3088 //===----------------------------------------------------------------------===//
3089
3090 //  Like std call, callee cleans arguments, convention except that ECX is
3091 //  reserved for storing the tail called function address. Only 2 registers are
3092 //  free for argument passing (inreg). Tail call optimization is performed
3093 //  provided:
3094 //                * tailcallopt is enabled
3095 //                * caller/callee are fastcc
3096 //  On X86_64 architecture with GOT-style position independent code only local
3097 //  (within module) calls are supported at the moment.
3098 //  To keep the stack aligned according to platform abi the function
3099 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3100 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3101 //  If a tail called function callee has more arguments than the caller the
3102 //  caller needs to make sure that there is room to move the RETADDR to. This is
3103 //  achieved by reserving an area the size of the argument delta right after the
3104 //  original RETADDR, but before the saved framepointer or the spilled registers
3105 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3106 //  stack layout:
3107 //    arg1
3108 //    arg2
3109 //    RETADDR
3110 //    [ new RETADDR
3111 //      move area ]
3112 //    (possible EBP)
3113 //    ESI
3114 //    EDI
3115 //    local1 ..
3116
3117 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3118 /// for a 16 byte align requirement.
3119 unsigned
3120 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3121                                                SelectionDAG& DAG) const {
3122   MachineFunction &MF = DAG.getMachineFunction();
3123   const TargetMachine &TM = MF.getTarget();
3124   const X86RegisterInfo *RegInfo =
3125     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3126   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3127   unsigned StackAlignment = TFI.getStackAlignment();
3128   uint64_t AlignMask = StackAlignment - 1;
3129   int64_t Offset = StackSize;
3130   unsigned SlotSize = RegInfo->getSlotSize();
3131   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3132     // Number smaller than 12 so just add the difference.
3133     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3134   } else {
3135     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3136     Offset = ((~AlignMask) & Offset) + StackAlignment +
3137       (StackAlignment-SlotSize);
3138   }
3139   return Offset;
3140 }
3141
3142 /// MatchingStackOffset - Return true if the given stack call argument is
3143 /// already available in the same position (relatively) of the caller's
3144 /// incoming argument stack.
3145 static
3146 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3147                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3148                          const X86InstrInfo *TII) {
3149   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3150   int FI = INT_MAX;
3151   if (Arg.getOpcode() == ISD::CopyFromReg) {
3152     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3153     if (!TargetRegisterInfo::isVirtualRegister(VR))
3154       return false;
3155     MachineInstr *Def = MRI->getVRegDef(VR);
3156     if (!Def)
3157       return false;
3158     if (!Flags.isByVal()) {
3159       if (!TII->isLoadFromStackSlot(Def, FI))
3160         return false;
3161     } else {
3162       unsigned Opcode = Def->getOpcode();
3163       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3164           Def->getOperand(1).isFI()) {
3165         FI = Def->getOperand(1).getIndex();
3166         Bytes = Flags.getByValSize();
3167       } else
3168         return false;
3169     }
3170   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3171     if (Flags.isByVal())
3172       // ByVal argument is passed in as a pointer but it's now being
3173       // dereferenced. e.g.
3174       // define @foo(%struct.X* %A) {
3175       //   tail call @bar(%struct.X* byval %A)
3176       // }
3177       return false;
3178     SDValue Ptr = Ld->getBasePtr();
3179     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3180     if (!FINode)
3181       return false;
3182     FI = FINode->getIndex();
3183   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3184     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3185     FI = FINode->getIndex();
3186     Bytes = Flags.getByValSize();
3187   } else
3188     return false;
3189
3190   assert(FI != INT_MAX);
3191   if (!MFI->isFixedObjectIndex(FI))
3192     return false;
3193   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3194 }
3195
3196 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3197 /// for tail call optimization. Targets which want to do tail call
3198 /// optimization should implement this function.
3199 bool
3200 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3201                                                      CallingConv::ID CalleeCC,
3202                                                      bool isVarArg,
3203                                                      bool isCalleeStructRet,
3204                                                      bool isCallerStructRet,
3205                                                      Type *RetTy,
3206                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3207                                     const SmallVectorImpl<SDValue> &OutVals,
3208                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3209                                                      SelectionDAG &DAG) const {
3210   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3211     return false;
3212
3213   // If -tailcallopt is specified, make fastcc functions tail-callable.
3214   const MachineFunction &MF = DAG.getMachineFunction();
3215   const Function *CallerF = MF.getFunction();
3216
3217   // If the function return type is x86_fp80 and the callee return type is not,
3218   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3219   // perform a tailcall optimization here.
3220   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3221     return false;
3222
3223   CallingConv::ID CallerCC = CallerF->getCallingConv();
3224   bool CCMatch = CallerCC == CalleeCC;
3225   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3226   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3227
3228   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3229     if (IsTailCallConvention(CalleeCC) && CCMatch)
3230       return true;
3231     return false;
3232   }
3233
3234   // Look for obvious safe cases to perform tail call optimization that do not
3235   // require ABI changes. This is what gcc calls sibcall.
3236
3237   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3238   // emit a special epilogue.
3239   const X86RegisterInfo *RegInfo =
3240     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3241   if (RegInfo->needsStackRealignment(MF))
3242     return false;
3243
3244   // Also avoid sibcall optimization if either caller or callee uses struct
3245   // return semantics.
3246   if (isCalleeStructRet || isCallerStructRet)
3247     return false;
3248
3249   // An stdcall/thiscall caller is expected to clean up its arguments; the
3250   // callee isn't going to do that.
3251   // FIXME: this is more restrictive than needed. We could produce a tailcall
3252   // when the stack adjustment matches. For example, with a thiscall that takes
3253   // only one argument.
3254   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3255                    CallerCC == CallingConv::X86_ThisCall))
3256     return false;
3257
3258   // Do not sibcall optimize vararg calls unless all arguments are passed via
3259   // registers.
3260   if (isVarArg && !Outs.empty()) {
3261
3262     // Optimizing for varargs on Win64 is unlikely to be safe without
3263     // additional testing.
3264     if (IsCalleeWin64 || IsCallerWin64)
3265       return false;
3266
3267     SmallVector<CCValAssign, 16> ArgLocs;
3268     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3269                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3270
3271     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3272     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3273       if (!ArgLocs[i].isRegLoc())
3274         return false;
3275   }
3276
3277   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3278   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3279   // this into a sibcall.
3280   bool Unused = false;
3281   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3282     if (!Ins[i].Used) {
3283       Unused = true;
3284       break;
3285     }
3286   }
3287   if (Unused) {
3288     SmallVector<CCValAssign, 16> RVLocs;
3289     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3290                    DAG.getTarget(), RVLocs, *DAG.getContext());
3291     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3292     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3293       CCValAssign &VA = RVLocs[i];
3294       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3295         return false;
3296     }
3297   }
3298
3299   // If the calling conventions do not match, then we'd better make sure the
3300   // results are returned in the same way as what the caller expects.
3301   if (!CCMatch) {
3302     SmallVector<CCValAssign, 16> RVLocs1;
3303     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3304                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3305     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3306
3307     SmallVector<CCValAssign, 16> RVLocs2;
3308     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3309                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3310     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3311
3312     if (RVLocs1.size() != RVLocs2.size())
3313       return false;
3314     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3315       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3316         return false;
3317       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3318         return false;
3319       if (RVLocs1[i].isRegLoc()) {
3320         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3321           return false;
3322       } else {
3323         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3324           return false;
3325       }
3326     }
3327   }
3328
3329   // If the callee takes no arguments then go on to check the results of the
3330   // call.
3331   if (!Outs.empty()) {
3332     // Check if stack adjustment is needed. For now, do not do this if any
3333     // argument is passed on the stack.
3334     SmallVector<CCValAssign, 16> ArgLocs;
3335     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3336                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3337
3338     // Allocate shadow area for Win64
3339     if (IsCalleeWin64)
3340       CCInfo.AllocateStack(32, 8);
3341
3342     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3343     if (CCInfo.getNextStackOffset()) {
3344       MachineFunction &MF = DAG.getMachineFunction();
3345       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3346         return false;
3347
3348       // Check if the arguments are already laid out in the right way as
3349       // the caller's fixed stack objects.
3350       MachineFrameInfo *MFI = MF.getFrameInfo();
3351       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3352       const X86InstrInfo *TII =
3353           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3354       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3355         CCValAssign &VA = ArgLocs[i];
3356         SDValue Arg = OutVals[i];
3357         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3358         if (VA.getLocInfo() == CCValAssign::Indirect)
3359           return false;
3360         if (!VA.isRegLoc()) {
3361           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3362                                    MFI, MRI, TII))
3363             return false;
3364         }
3365       }
3366     }
3367
3368     // If the tailcall address may be in a register, then make sure it's
3369     // possible to register allocate for it. In 32-bit, the call address can
3370     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3371     // callee-saved registers are restored. These happen to be the same
3372     // registers used to pass 'inreg' arguments so watch out for those.
3373     if (!Subtarget->is64Bit() &&
3374         ((!isa<GlobalAddressSDNode>(Callee) &&
3375           !isa<ExternalSymbolSDNode>(Callee)) ||
3376          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3377       unsigned NumInRegs = 0;
3378       // In PIC we need an extra register to formulate the address computation
3379       // for the callee.
3380       unsigned MaxInRegs =
3381         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3382
3383       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3384         CCValAssign &VA = ArgLocs[i];
3385         if (!VA.isRegLoc())
3386           continue;
3387         unsigned Reg = VA.getLocReg();
3388         switch (Reg) {
3389         default: break;
3390         case X86::EAX: case X86::EDX: case X86::ECX:
3391           if (++NumInRegs == MaxInRegs)
3392             return false;
3393           break;
3394         }
3395       }
3396     }
3397   }
3398
3399   return true;
3400 }
3401
3402 FastISel *
3403 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3404                                   const TargetLibraryInfo *libInfo) const {
3405   return X86::createFastISel(funcInfo, libInfo);
3406 }
3407
3408 //===----------------------------------------------------------------------===//
3409 //                           Other Lowering Hooks
3410 //===----------------------------------------------------------------------===//
3411
3412 static bool MayFoldLoad(SDValue Op) {
3413   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3414 }
3415
3416 static bool MayFoldIntoStore(SDValue Op) {
3417   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3418 }
3419
3420 static bool isTargetShuffle(unsigned Opcode) {
3421   switch(Opcode) {
3422   default: return false;
3423   case X86ISD::PSHUFD:
3424   case X86ISD::PSHUFHW:
3425   case X86ISD::PSHUFLW:
3426   case X86ISD::SHUFP:
3427   case X86ISD::PALIGNR:
3428   case X86ISD::MOVLHPS:
3429   case X86ISD::MOVLHPD:
3430   case X86ISD::MOVHLPS:
3431   case X86ISD::MOVLPS:
3432   case X86ISD::MOVLPD:
3433   case X86ISD::MOVSHDUP:
3434   case X86ISD::MOVSLDUP:
3435   case X86ISD::MOVDDUP:
3436   case X86ISD::MOVSS:
3437   case X86ISD::MOVSD:
3438   case X86ISD::UNPCKL:
3439   case X86ISD::UNPCKH:
3440   case X86ISD::VPERMILP:
3441   case X86ISD::VPERM2X128:
3442   case X86ISD::VPERMI:
3443     return true;
3444   }
3445 }
3446
3447 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3448                                     SDValue V1, SelectionDAG &DAG) {
3449   switch(Opc) {
3450   default: llvm_unreachable("Unknown x86 shuffle node");
3451   case X86ISD::MOVSHDUP:
3452   case X86ISD::MOVSLDUP:
3453   case X86ISD::MOVDDUP:
3454     return DAG.getNode(Opc, dl, VT, V1);
3455   }
3456 }
3457
3458 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3459                                     SDValue V1, unsigned TargetMask,
3460                                     SelectionDAG &DAG) {
3461   switch(Opc) {
3462   default: llvm_unreachable("Unknown x86 shuffle node");
3463   case X86ISD::PSHUFD:
3464   case X86ISD::PSHUFHW:
3465   case X86ISD::PSHUFLW:
3466   case X86ISD::VPERMILP:
3467   case X86ISD::VPERMI:
3468     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3469   }
3470 }
3471
3472 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3473                                     SDValue V1, SDValue V2, unsigned TargetMask,
3474                                     SelectionDAG &DAG) {
3475   switch(Opc) {
3476   default: llvm_unreachable("Unknown x86 shuffle node");
3477   case X86ISD::PALIGNR:
3478   case X86ISD::SHUFP:
3479   case X86ISD::VPERM2X128:
3480     return DAG.getNode(Opc, dl, VT, V1, V2,
3481                        DAG.getConstant(TargetMask, MVT::i8));
3482   }
3483 }
3484
3485 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3486                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3487   switch(Opc) {
3488   default: llvm_unreachable("Unknown x86 shuffle node");
3489   case X86ISD::MOVLHPS:
3490   case X86ISD::MOVLHPD:
3491   case X86ISD::MOVHLPS:
3492   case X86ISD::MOVLPS:
3493   case X86ISD::MOVLPD:
3494   case X86ISD::MOVSS:
3495   case X86ISD::MOVSD:
3496   case X86ISD::UNPCKL:
3497   case X86ISD::UNPCKH:
3498     return DAG.getNode(Opc, dl, VT, V1, V2);
3499   }
3500 }
3501
3502 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3503   MachineFunction &MF = DAG.getMachineFunction();
3504   const X86RegisterInfo *RegInfo =
3505     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3506   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3507   int ReturnAddrIndex = FuncInfo->getRAIndex();
3508
3509   if (ReturnAddrIndex == 0) {
3510     // Set up a frame object for the return address.
3511     unsigned SlotSize = RegInfo->getSlotSize();
3512     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3513                                                            -(int64_t)SlotSize,
3514                                                            false);
3515     FuncInfo->setRAIndex(ReturnAddrIndex);
3516   }
3517
3518   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3519 }
3520
3521 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3522                                        bool hasSymbolicDisplacement) {
3523   // Offset should fit into 32 bit immediate field.
3524   if (!isInt<32>(Offset))
3525     return false;
3526
3527   // If we don't have a symbolic displacement - we don't have any extra
3528   // restrictions.
3529   if (!hasSymbolicDisplacement)
3530     return true;
3531
3532   // FIXME: Some tweaks might be needed for medium code model.
3533   if (M != CodeModel::Small && M != CodeModel::Kernel)
3534     return false;
3535
3536   // For small code model we assume that latest object is 16MB before end of 31
3537   // bits boundary. We may also accept pretty large negative constants knowing
3538   // that all objects are in the positive half of address space.
3539   if (M == CodeModel::Small && Offset < 16*1024*1024)
3540     return true;
3541
3542   // For kernel code model we know that all object resist in the negative half
3543   // of 32bits address space. We may not accept negative offsets, since they may
3544   // be just off and we may accept pretty large positive ones.
3545   if (M == CodeModel::Kernel && Offset > 0)
3546     return true;
3547
3548   return false;
3549 }
3550
3551 /// isCalleePop - Determines whether the callee is required to pop its
3552 /// own arguments. Callee pop is necessary to support tail calls.
3553 bool X86::isCalleePop(CallingConv::ID CallingConv,
3554                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3555   if (IsVarArg)
3556     return false;
3557
3558   switch (CallingConv) {
3559   default:
3560     return false;
3561   case CallingConv::X86_StdCall:
3562     return !is64Bit;
3563   case CallingConv::X86_FastCall:
3564     return !is64Bit;
3565   case CallingConv::X86_ThisCall:
3566     return !is64Bit;
3567   case CallingConv::Fast:
3568     return TailCallOpt;
3569   case CallingConv::GHC:
3570     return TailCallOpt;
3571   case CallingConv::HiPE:
3572     return TailCallOpt;
3573   }
3574 }
3575
3576 /// \brief Return true if the condition is an unsigned comparison operation.
3577 static bool isX86CCUnsigned(unsigned X86CC) {
3578   switch (X86CC) {
3579   default: llvm_unreachable("Invalid integer condition!");
3580   case X86::COND_E:     return true;
3581   case X86::COND_G:     return false;
3582   case X86::COND_GE:    return false;
3583   case X86::COND_L:     return false;
3584   case X86::COND_LE:    return false;
3585   case X86::COND_NE:    return true;
3586   case X86::COND_B:     return true;
3587   case X86::COND_A:     return true;
3588   case X86::COND_BE:    return true;
3589   case X86::COND_AE:    return true;
3590   }
3591   llvm_unreachable("covered switch fell through?!");
3592 }
3593
3594 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3595 /// specific condition code, returning the condition code and the LHS/RHS of the
3596 /// comparison to make.
3597 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3598                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3599   if (!isFP) {
3600     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3601       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3602         // X > -1   -> X == 0, jump !sign.
3603         RHS = DAG.getConstant(0, RHS.getValueType());
3604         return X86::COND_NS;
3605       }
3606       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3607         // X < 0   -> X == 0, jump on sign.
3608         return X86::COND_S;
3609       }
3610       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3611         // X < 1   -> X <= 0
3612         RHS = DAG.getConstant(0, RHS.getValueType());
3613         return X86::COND_LE;
3614       }
3615     }
3616
3617     switch (SetCCOpcode) {
3618     default: llvm_unreachable("Invalid integer condition!");
3619     case ISD::SETEQ:  return X86::COND_E;
3620     case ISD::SETGT:  return X86::COND_G;
3621     case ISD::SETGE:  return X86::COND_GE;
3622     case ISD::SETLT:  return X86::COND_L;
3623     case ISD::SETLE:  return X86::COND_LE;
3624     case ISD::SETNE:  return X86::COND_NE;
3625     case ISD::SETULT: return X86::COND_B;
3626     case ISD::SETUGT: return X86::COND_A;
3627     case ISD::SETULE: return X86::COND_BE;
3628     case ISD::SETUGE: return X86::COND_AE;
3629     }
3630   }
3631
3632   // First determine if it is required or is profitable to flip the operands.
3633
3634   // If LHS is a foldable load, but RHS is not, flip the condition.
3635   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3636       !ISD::isNON_EXTLoad(RHS.getNode())) {
3637     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3638     std::swap(LHS, RHS);
3639   }
3640
3641   switch (SetCCOpcode) {
3642   default: break;
3643   case ISD::SETOLT:
3644   case ISD::SETOLE:
3645   case ISD::SETUGT:
3646   case ISD::SETUGE:
3647     std::swap(LHS, RHS);
3648     break;
3649   }
3650
3651   // On a floating point condition, the flags are set as follows:
3652   // ZF  PF  CF   op
3653   //  0 | 0 | 0 | X > Y
3654   //  0 | 0 | 1 | X < Y
3655   //  1 | 0 | 0 | X == Y
3656   //  1 | 1 | 1 | unordered
3657   switch (SetCCOpcode) {
3658   default: llvm_unreachable("Condcode should be pre-legalized away");
3659   case ISD::SETUEQ:
3660   case ISD::SETEQ:   return X86::COND_E;
3661   case ISD::SETOLT:              // flipped
3662   case ISD::SETOGT:
3663   case ISD::SETGT:   return X86::COND_A;
3664   case ISD::SETOLE:              // flipped
3665   case ISD::SETOGE:
3666   case ISD::SETGE:   return X86::COND_AE;
3667   case ISD::SETUGT:              // flipped
3668   case ISD::SETULT:
3669   case ISD::SETLT:   return X86::COND_B;
3670   case ISD::SETUGE:              // flipped
3671   case ISD::SETULE:
3672   case ISD::SETLE:   return X86::COND_BE;
3673   case ISD::SETONE:
3674   case ISD::SETNE:   return X86::COND_NE;
3675   case ISD::SETUO:   return X86::COND_P;
3676   case ISD::SETO:    return X86::COND_NP;
3677   case ISD::SETOEQ:
3678   case ISD::SETUNE:  return X86::COND_INVALID;
3679   }
3680 }
3681
3682 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3683 /// code. Current x86 isa includes the following FP cmov instructions:
3684 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3685 static bool hasFPCMov(unsigned X86CC) {
3686   switch (X86CC) {
3687   default:
3688     return false;
3689   case X86::COND_B:
3690   case X86::COND_BE:
3691   case X86::COND_E:
3692   case X86::COND_P:
3693   case X86::COND_A:
3694   case X86::COND_AE:
3695   case X86::COND_NE:
3696   case X86::COND_NP:
3697     return true;
3698   }
3699 }
3700
3701 /// isFPImmLegal - Returns true if the target can instruction select the
3702 /// specified FP immediate natively. If false, the legalizer will
3703 /// materialize the FP immediate as a load from a constant pool.
3704 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3705   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3706     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3707       return true;
3708   }
3709   return false;
3710 }
3711
3712 /// \brief Returns true if it is beneficial to convert a load of a constant
3713 /// to just the constant itself.
3714 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3715                                                           Type *Ty) const {
3716   assert(Ty->isIntegerTy());
3717
3718   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3719   if (BitSize == 0 || BitSize > 64)
3720     return false;
3721   return true;
3722 }
3723
3724 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3725 /// the specified range (L, H].
3726 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3727   return (Val < 0) || (Val >= Low && Val < Hi);
3728 }
3729
3730 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3731 /// specified value.
3732 static bool isUndefOrEqual(int Val, int CmpVal) {
3733   return (Val < 0 || Val == CmpVal);
3734 }
3735
3736 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3737 /// from position Pos and ending in Pos+Size, falls within the specified
3738 /// sequential range (L, L+Pos]. or is undef.
3739 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3740                                        unsigned Pos, unsigned Size, int Low) {
3741   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3742     if (!isUndefOrEqual(Mask[i], Low))
3743       return false;
3744   return true;
3745 }
3746
3747 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3748 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3749 /// the second operand.
3750 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3751   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3752     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3753   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3754     return (Mask[0] < 2 && Mask[1] < 2);
3755   return false;
3756 }
3757
3758 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3759 /// is suitable for input to PSHUFHW.
3760 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3761   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3762     return false;
3763
3764   // Lower quadword copied in order or undef.
3765   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3766     return false;
3767
3768   // Upper quadword shuffled.
3769   for (unsigned i = 4; i != 8; ++i)
3770     if (!isUndefOrInRange(Mask[i], 4, 8))
3771       return false;
3772
3773   if (VT == MVT::v16i16) {
3774     // Lower quadword copied in order or undef.
3775     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3776       return false;
3777
3778     // Upper quadword shuffled.
3779     for (unsigned i = 12; i != 16; ++i)
3780       if (!isUndefOrInRange(Mask[i], 12, 16))
3781         return false;
3782   }
3783
3784   return true;
3785 }
3786
3787 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3788 /// is suitable for input to PSHUFLW.
3789 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3790   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3791     return false;
3792
3793   // Upper quadword copied in order.
3794   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3795     return false;
3796
3797   // Lower quadword shuffled.
3798   for (unsigned i = 0; i != 4; ++i)
3799     if (!isUndefOrInRange(Mask[i], 0, 4))
3800       return false;
3801
3802   if (VT == MVT::v16i16) {
3803     // Upper quadword copied in order.
3804     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3805       return false;
3806
3807     // Lower quadword shuffled.
3808     for (unsigned i = 8; i != 12; ++i)
3809       if (!isUndefOrInRange(Mask[i], 8, 12))
3810         return false;
3811   }
3812
3813   return true;
3814 }
3815
3816 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3817 /// is suitable for input to PALIGNR.
3818 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3819                           const X86Subtarget *Subtarget) {
3820   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3821       (VT.is256BitVector() && !Subtarget->hasInt256()))
3822     return false;
3823
3824   unsigned NumElts = VT.getVectorNumElements();
3825   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3826   unsigned NumLaneElts = NumElts/NumLanes;
3827
3828   // Do not handle 64-bit element shuffles with palignr.
3829   if (NumLaneElts == 2)
3830     return false;
3831
3832   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3833     unsigned i;
3834     for (i = 0; i != NumLaneElts; ++i) {
3835       if (Mask[i+l] >= 0)
3836         break;
3837     }
3838
3839     // Lane is all undef, go to next lane
3840     if (i == NumLaneElts)
3841       continue;
3842
3843     int Start = Mask[i+l];
3844
3845     // Make sure its in this lane in one of the sources
3846     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3847         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3848       return false;
3849
3850     // If not lane 0, then we must match lane 0
3851     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3852       return false;
3853
3854     // Correct second source to be contiguous with first source
3855     if (Start >= (int)NumElts)
3856       Start -= NumElts - NumLaneElts;
3857
3858     // Make sure we're shifting in the right direction.
3859     if (Start <= (int)(i+l))
3860       return false;
3861
3862     Start -= i;
3863
3864     // Check the rest of the elements to see if they are consecutive.
3865     for (++i; i != NumLaneElts; ++i) {
3866       int Idx = Mask[i+l];
3867
3868       // Make sure its in this lane
3869       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3870           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3871         return false;
3872
3873       // If not lane 0, then we must match lane 0
3874       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3875         return false;
3876
3877       if (Idx >= (int)NumElts)
3878         Idx -= NumElts - NumLaneElts;
3879
3880       if (!isUndefOrEqual(Idx, Start+i))
3881         return false;
3882
3883     }
3884   }
3885
3886   return true;
3887 }
3888
3889 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3890 /// the two vector operands have swapped position.
3891 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3892                                      unsigned NumElems) {
3893   for (unsigned i = 0; i != NumElems; ++i) {
3894     int idx = Mask[i];
3895     if (idx < 0)
3896       continue;
3897     else if (idx < (int)NumElems)
3898       Mask[i] = idx + NumElems;
3899     else
3900       Mask[i] = idx - NumElems;
3901   }
3902 }
3903
3904 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3905 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3906 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3907 /// reverse of what x86 shuffles want.
3908 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3909
3910   unsigned NumElems = VT.getVectorNumElements();
3911   unsigned NumLanes = VT.getSizeInBits()/128;
3912   unsigned NumLaneElems = NumElems/NumLanes;
3913
3914   if (NumLaneElems != 2 && NumLaneElems != 4)
3915     return false;
3916
3917   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3918   bool symetricMaskRequired =
3919     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3920
3921   // VSHUFPSY divides the resulting vector into 4 chunks.
3922   // The sources are also splitted into 4 chunks, and each destination
3923   // chunk must come from a different source chunk.
3924   //
3925   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3926   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3927   //
3928   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3929   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3930   //
3931   // VSHUFPDY divides the resulting vector into 4 chunks.
3932   // The sources are also splitted into 4 chunks, and each destination
3933   // chunk must come from a different source chunk.
3934   //
3935   //  SRC1 =>      X3       X2       X1       X0
3936   //  SRC2 =>      Y3       Y2       Y1       Y0
3937   //
3938   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3939   //
3940   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3941   unsigned HalfLaneElems = NumLaneElems/2;
3942   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3943     for (unsigned i = 0; i != NumLaneElems; ++i) {
3944       int Idx = Mask[i+l];
3945       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3946       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3947         return false;
3948       // For VSHUFPSY, the mask of the second half must be the same as the
3949       // first but with the appropriate offsets. This works in the same way as
3950       // VPERMILPS works with masks.
3951       if (!symetricMaskRequired || Idx < 0)
3952         continue;
3953       if (MaskVal[i] < 0) {
3954         MaskVal[i] = Idx - l;
3955         continue;
3956       }
3957       if ((signed)(Idx - l) != MaskVal[i])
3958         return false;
3959     }
3960   }
3961
3962   return true;
3963 }
3964
3965 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3967 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3968   if (!VT.is128BitVector())
3969     return false;
3970
3971   unsigned NumElems = VT.getVectorNumElements();
3972
3973   if (NumElems != 4)
3974     return false;
3975
3976   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3977   return isUndefOrEqual(Mask[0], 6) &&
3978          isUndefOrEqual(Mask[1], 7) &&
3979          isUndefOrEqual(Mask[2], 2) &&
3980          isUndefOrEqual(Mask[3], 3);
3981 }
3982
3983 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3984 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3985 /// <2, 3, 2, 3>
3986 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3987   if (!VT.is128BitVector())
3988     return false;
3989
3990   unsigned NumElems = VT.getVectorNumElements();
3991
3992   if (NumElems != 4)
3993     return false;
3994
3995   return isUndefOrEqual(Mask[0], 2) &&
3996          isUndefOrEqual(Mask[1], 3) &&
3997          isUndefOrEqual(Mask[2], 2) &&
3998          isUndefOrEqual(Mask[3], 3);
3999 }
4000
4001 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4002 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4003 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4004   if (!VT.is128BitVector())
4005     return false;
4006
4007   unsigned NumElems = VT.getVectorNumElements();
4008
4009   if (NumElems != 2 && NumElems != 4)
4010     return false;
4011
4012   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4013     if (!isUndefOrEqual(Mask[i], i + NumElems))
4014       return false;
4015
4016   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4017     if (!isUndefOrEqual(Mask[i], i))
4018       return false;
4019
4020   return true;
4021 }
4022
4023 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4024 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4025 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4026   if (!VT.is128BitVector())
4027     return false;
4028
4029   unsigned NumElems = VT.getVectorNumElements();
4030
4031   if (NumElems != 2 && NumElems != 4)
4032     return false;
4033
4034   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4035     if (!isUndefOrEqual(Mask[i], i))
4036       return false;
4037
4038   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4039     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4040       return false;
4041
4042   return true;
4043 }
4044
4045 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4046 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4047 /// i. e: If all but one element come from the same vector.
4048 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4049   // TODO: Deal with AVX's VINSERTPS
4050   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4051     return false;
4052
4053   unsigned CorrectPosV1 = 0;
4054   unsigned CorrectPosV2 = 0;
4055   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4056     if (Mask[i] == -1) {
4057       ++CorrectPosV1;
4058       ++CorrectPosV2;
4059       continue;
4060     }
4061
4062     if (Mask[i] == i)
4063       ++CorrectPosV1;
4064     else if (Mask[i] == i + 4)
4065       ++CorrectPosV2;
4066   }
4067
4068   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4069     // We have 3 elements (undefs count as elements from any vector) from one
4070     // vector, and one from another.
4071     return true;
4072
4073   return false;
4074 }
4075
4076 //
4077 // Some special combinations that can be optimized.
4078 //
4079 static
4080 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4081                                SelectionDAG &DAG) {
4082   MVT VT = SVOp->getSimpleValueType(0);
4083   SDLoc dl(SVOp);
4084
4085   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4086     return SDValue();
4087
4088   ArrayRef<int> Mask = SVOp->getMask();
4089
4090   // These are the special masks that may be optimized.
4091   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4092   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4093   bool MatchEvenMask = true;
4094   bool MatchOddMask  = true;
4095   for (int i=0; i<8; ++i) {
4096     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4097       MatchEvenMask = false;
4098     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4099       MatchOddMask = false;
4100   }
4101
4102   if (!MatchEvenMask && !MatchOddMask)
4103     return SDValue();
4104
4105   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4106
4107   SDValue Op0 = SVOp->getOperand(0);
4108   SDValue Op1 = SVOp->getOperand(1);
4109
4110   if (MatchEvenMask) {
4111     // Shift the second operand right to 32 bits.
4112     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4113     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4114   } else {
4115     // Shift the first operand left to 32 bits.
4116     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4117     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4118   }
4119   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4120   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4121 }
4122
4123 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4124 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4125 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4126                          bool HasInt256, bool V2IsSplat = false) {
4127
4128   assert(VT.getSizeInBits() >= 128 &&
4129          "Unsupported vector type for unpckl");
4130
4131   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4132   unsigned NumLanes;
4133   unsigned NumOf256BitLanes;
4134   unsigned NumElts = VT.getVectorNumElements();
4135   if (VT.is256BitVector()) {
4136     if (NumElts != 4 && NumElts != 8 &&
4137         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4138     return false;
4139     NumLanes = 2;
4140     NumOf256BitLanes = 1;
4141   } else if (VT.is512BitVector()) {
4142     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4143            "Unsupported vector type for unpckh");
4144     NumLanes = 2;
4145     NumOf256BitLanes = 2;
4146   } else {
4147     NumLanes = 1;
4148     NumOf256BitLanes = 1;
4149   }
4150
4151   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4152   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4153
4154   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4155     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4156       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4157         int BitI  = Mask[l256*NumEltsInStride+l+i];
4158         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4159         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4160           return false;
4161         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4162           return false;
4163         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4164           return false;
4165       }
4166     }
4167   }
4168   return true;
4169 }
4170
4171 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4172 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4173 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4174                          bool HasInt256, bool V2IsSplat = false) {
4175   assert(VT.getSizeInBits() >= 128 &&
4176          "Unsupported vector type for unpckh");
4177
4178   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4179   unsigned NumLanes;
4180   unsigned NumOf256BitLanes;
4181   unsigned NumElts = VT.getVectorNumElements();
4182   if (VT.is256BitVector()) {
4183     if (NumElts != 4 && NumElts != 8 &&
4184         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4185     return false;
4186     NumLanes = 2;
4187     NumOf256BitLanes = 1;
4188   } else if (VT.is512BitVector()) {
4189     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4190            "Unsupported vector type for unpckh");
4191     NumLanes = 2;
4192     NumOf256BitLanes = 2;
4193   } else {
4194     NumLanes = 1;
4195     NumOf256BitLanes = 1;
4196   }
4197
4198   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4199   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4200
4201   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4202     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4203       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4204         int BitI  = Mask[l256*NumEltsInStride+l+i];
4205         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4206         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4207           return false;
4208         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4209           return false;
4210         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4211           return false;
4212       }
4213     }
4214   }
4215   return true;
4216 }
4217
4218 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4219 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4220 /// <0, 0, 1, 1>
4221 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4222   unsigned NumElts = VT.getVectorNumElements();
4223   bool Is256BitVec = VT.is256BitVector();
4224
4225   if (VT.is512BitVector())
4226     return false;
4227   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4228          "Unsupported vector type for unpckh");
4229
4230   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4231       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4232     return false;
4233
4234   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4235   // FIXME: Need a better way to get rid of this, there's no latency difference
4236   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4237   // the former later. We should also remove the "_undef" special mask.
4238   if (NumElts == 4 && Is256BitVec)
4239     return false;
4240
4241   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4242   // independently on 128-bit lanes.
4243   unsigned NumLanes = VT.getSizeInBits()/128;
4244   unsigned NumLaneElts = NumElts/NumLanes;
4245
4246   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4247     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4248       int BitI  = Mask[l+i];
4249       int BitI1 = Mask[l+i+1];
4250
4251       if (!isUndefOrEqual(BitI, j))
4252         return false;
4253       if (!isUndefOrEqual(BitI1, j))
4254         return false;
4255     }
4256   }
4257
4258   return true;
4259 }
4260
4261 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4262 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4263 /// <2, 2, 3, 3>
4264 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4265   unsigned NumElts = VT.getVectorNumElements();
4266
4267   if (VT.is512BitVector())
4268     return false;
4269
4270   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4271          "Unsupported vector type for unpckh");
4272
4273   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4274       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4275     return false;
4276
4277   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4278   // independently on 128-bit lanes.
4279   unsigned NumLanes = VT.getSizeInBits()/128;
4280   unsigned NumLaneElts = NumElts/NumLanes;
4281
4282   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4283     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4284       int BitI  = Mask[l+i];
4285       int BitI1 = Mask[l+i+1];
4286       if (!isUndefOrEqual(BitI, j))
4287         return false;
4288       if (!isUndefOrEqual(BitI1, j))
4289         return false;
4290     }
4291   }
4292   return true;
4293 }
4294
4295 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4296 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4297 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4298   if (!VT.is512BitVector())
4299     return false;
4300
4301   unsigned NumElts = VT.getVectorNumElements();
4302   unsigned HalfSize = NumElts/2;
4303   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4304     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4305       *Imm = 1;
4306       return true;
4307     }
4308   }
4309   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4310     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4311       *Imm = 0;
4312       return true;
4313     }
4314   }
4315   return false;
4316 }
4317
4318 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4319 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4320 /// MOVSD, and MOVD, i.e. setting the lowest element.
4321 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4322   if (VT.getVectorElementType().getSizeInBits() < 32)
4323     return false;
4324   if (!VT.is128BitVector())
4325     return false;
4326
4327   unsigned NumElts = VT.getVectorNumElements();
4328
4329   if (!isUndefOrEqual(Mask[0], NumElts))
4330     return false;
4331
4332   for (unsigned i = 1; i != NumElts; ++i)
4333     if (!isUndefOrEqual(Mask[i], i))
4334       return false;
4335
4336   return true;
4337 }
4338
4339 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4340 /// as permutations between 128-bit chunks or halves. As an example: this
4341 /// shuffle bellow:
4342 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4343 /// The first half comes from the second half of V1 and the second half from the
4344 /// the second half of V2.
4345 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4346   if (!HasFp256 || !VT.is256BitVector())
4347     return false;
4348
4349   // The shuffle result is divided into half A and half B. In total the two
4350   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4351   // B must come from C, D, E or F.
4352   unsigned HalfSize = VT.getVectorNumElements()/2;
4353   bool MatchA = false, MatchB = false;
4354
4355   // Check if A comes from one of C, D, E, F.
4356   for (unsigned Half = 0; Half != 4; ++Half) {
4357     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4358       MatchA = true;
4359       break;
4360     }
4361   }
4362
4363   // Check if B comes from one of C, D, E, F.
4364   for (unsigned Half = 0; Half != 4; ++Half) {
4365     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4366       MatchB = true;
4367       break;
4368     }
4369   }
4370
4371   return MatchA && MatchB;
4372 }
4373
4374 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4375 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4376 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4377   MVT VT = SVOp->getSimpleValueType(0);
4378
4379   unsigned HalfSize = VT.getVectorNumElements()/2;
4380
4381   unsigned FstHalf = 0, SndHalf = 0;
4382   for (unsigned i = 0; i < HalfSize; ++i) {
4383     if (SVOp->getMaskElt(i) > 0) {
4384       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4385       break;
4386     }
4387   }
4388   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4389     if (SVOp->getMaskElt(i) > 0) {
4390       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4391       break;
4392     }
4393   }
4394
4395   return (FstHalf | (SndHalf << 4));
4396 }
4397
4398 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4399 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4400   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4401   if (EltSize < 32)
4402     return false;
4403
4404   unsigned NumElts = VT.getVectorNumElements();
4405   Imm8 = 0;
4406   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4407     for (unsigned i = 0; i != NumElts; ++i) {
4408       if (Mask[i] < 0)
4409         continue;
4410       Imm8 |= Mask[i] << (i*2);
4411     }
4412     return true;
4413   }
4414
4415   unsigned LaneSize = 4;
4416   SmallVector<int, 4> MaskVal(LaneSize, -1);
4417
4418   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4419     for (unsigned i = 0; i != LaneSize; ++i) {
4420       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4421         return false;
4422       if (Mask[i+l] < 0)
4423         continue;
4424       if (MaskVal[i] < 0) {
4425         MaskVal[i] = Mask[i+l] - l;
4426         Imm8 |= MaskVal[i] << (i*2);
4427         continue;
4428       }
4429       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4430         return false;
4431     }
4432   }
4433   return true;
4434 }
4435
4436 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4437 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4438 /// Note that VPERMIL mask matching is different depending whether theunderlying
4439 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4440 /// to the same elements of the low, but to the higher half of the source.
4441 /// In VPERMILPD the two lanes could be shuffled independently of each other
4442 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4443 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4444   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4445   if (VT.getSizeInBits() < 256 || EltSize < 32)
4446     return false;
4447   bool symetricMaskRequired = (EltSize == 32);
4448   unsigned NumElts = VT.getVectorNumElements();
4449
4450   unsigned NumLanes = VT.getSizeInBits()/128;
4451   unsigned LaneSize = NumElts/NumLanes;
4452   // 2 or 4 elements in one lane
4453
4454   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4455   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4456     for (unsigned i = 0; i != LaneSize; ++i) {
4457       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4458         return false;
4459       if (symetricMaskRequired) {
4460         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4461           ExpectedMaskVal[i] = Mask[i+l] - l;
4462           continue;
4463         }
4464         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4465           return false;
4466       }
4467     }
4468   }
4469   return true;
4470 }
4471
4472 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4473 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4474 /// element of vector 2 and the other elements to come from vector 1 in order.
4475 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4476                                bool V2IsSplat = false, bool V2IsUndef = false) {
4477   if (!VT.is128BitVector())
4478     return false;
4479
4480   unsigned NumOps = VT.getVectorNumElements();
4481   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4482     return false;
4483
4484   if (!isUndefOrEqual(Mask[0], 0))
4485     return false;
4486
4487   for (unsigned i = 1; i != NumOps; ++i)
4488     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4489           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4490           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4491       return false;
4492
4493   return true;
4494 }
4495
4496 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4497 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4498 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4499 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4500                            const X86Subtarget *Subtarget) {
4501   if (!Subtarget->hasSSE3())
4502     return false;
4503
4504   unsigned NumElems = VT.getVectorNumElements();
4505
4506   if ((VT.is128BitVector() && NumElems != 4) ||
4507       (VT.is256BitVector() && NumElems != 8) ||
4508       (VT.is512BitVector() && NumElems != 16))
4509     return false;
4510
4511   // "i+1" is the value the indexed mask element must have
4512   for (unsigned i = 0; i != NumElems; i += 2)
4513     if (!isUndefOrEqual(Mask[i], i+1) ||
4514         !isUndefOrEqual(Mask[i+1], i+1))
4515       return false;
4516
4517   return true;
4518 }
4519
4520 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4521 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4522 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4523 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4524                            const X86Subtarget *Subtarget) {
4525   if (!Subtarget->hasSSE3())
4526     return false;
4527
4528   unsigned NumElems = VT.getVectorNumElements();
4529
4530   if ((VT.is128BitVector() && NumElems != 4) ||
4531       (VT.is256BitVector() && NumElems != 8) ||
4532       (VT.is512BitVector() && NumElems != 16))
4533     return false;
4534
4535   // "i" is the value the indexed mask element must have
4536   for (unsigned i = 0; i != NumElems; i += 2)
4537     if (!isUndefOrEqual(Mask[i], i) ||
4538         !isUndefOrEqual(Mask[i+1], i))
4539       return false;
4540
4541   return true;
4542 }
4543
4544 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4545 /// specifies a shuffle of elements that is suitable for input to 256-bit
4546 /// version of MOVDDUP.
4547 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4548   if (!HasFp256 || !VT.is256BitVector())
4549     return false;
4550
4551   unsigned NumElts = VT.getVectorNumElements();
4552   if (NumElts != 4)
4553     return false;
4554
4555   for (unsigned i = 0; i != NumElts/2; ++i)
4556     if (!isUndefOrEqual(Mask[i], 0))
4557       return false;
4558   for (unsigned i = NumElts/2; i != NumElts; ++i)
4559     if (!isUndefOrEqual(Mask[i], NumElts/2))
4560       return false;
4561   return true;
4562 }
4563
4564 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4565 /// specifies a shuffle of elements that is suitable for input to 128-bit
4566 /// version of MOVDDUP.
4567 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4568   if (!VT.is128BitVector())
4569     return false;
4570
4571   unsigned e = VT.getVectorNumElements() / 2;
4572   for (unsigned i = 0; i != e; ++i)
4573     if (!isUndefOrEqual(Mask[i], i))
4574       return false;
4575   for (unsigned i = 0; i != e; ++i)
4576     if (!isUndefOrEqual(Mask[e+i], i))
4577       return false;
4578   return true;
4579 }
4580
4581 /// isVEXTRACTIndex - Return true if the specified
4582 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4583 /// suitable for instruction that extract 128 or 256 bit vectors
4584 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4585   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4586   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4587     return false;
4588
4589   // The index should be aligned on a vecWidth-bit boundary.
4590   uint64_t Index =
4591     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4592
4593   MVT VT = N->getSimpleValueType(0);
4594   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4595   bool Result = (Index * ElSize) % vecWidth == 0;
4596
4597   return Result;
4598 }
4599
4600 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4601 /// operand specifies a subvector insert that is suitable for input to
4602 /// insertion of 128 or 256-bit subvectors
4603 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4604   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4605   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4606     return false;
4607   // The index should be aligned on a vecWidth-bit boundary.
4608   uint64_t Index =
4609     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4610
4611   MVT VT = N->getSimpleValueType(0);
4612   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4613   bool Result = (Index * ElSize) % vecWidth == 0;
4614
4615   return Result;
4616 }
4617
4618 bool X86::isVINSERT128Index(SDNode *N) {
4619   return isVINSERTIndex(N, 128);
4620 }
4621
4622 bool X86::isVINSERT256Index(SDNode *N) {
4623   return isVINSERTIndex(N, 256);
4624 }
4625
4626 bool X86::isVEXTRACT128Index(SDNode *N) {
4627   return isVEXTRACTIndex(N, 128);
4628 }
4629
4630 bool X86::isVEXTRACT256Index(SDNode *N) {
4631   return isVEXTRACTIndex(N, 256);
4632 }
4633
4634 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4635 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4636 /// Handles 128-bit and 256-bit.
4637 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4638   MVT VT = N->getSimpleValueType(0);
4639
4640   assert((VT.getSizeInBits() >= 128) &&
4641          "Unsupported vector type for PSHUF/SHUFP");
4642
4643   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4644   // independently on 128-bit lanes.
4645   unsigned NumElts = VT.getVectorNumElements();
4646   unsigned NumLanes = VT.getSizeInBits()/128;
4647   unsigned NumLaneElts = NumElts/NumLanes;
4648
4649   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4650          "Only supports 2, 4 or 8 elements per lane");
4651
4652   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4653   unsigned Mask = 0;
4654   for (unsigned i = 0; i != NumElts; ++i) {
4655     int Elt = N->getMaskElt(i);
4656     if (Elt < 0) continue;
4657     Elt &= NumLaneElts - 1;
4658     unsigned ShAmt = (i << Shift) % 8;
4659     Mask |= Elt << ShAmt;
4660   }
4661
4662   return Mask;
4663 }
4664
4665 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4666 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4667 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4668   MVT VT = N->getSimpleValueType(0);
4669
4670   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4671          "Unsupported vector type for PSHUFHW");
4672
4673   unsigned NumElts = VT.getVectorNumElements();
4674
4675   unsigned Mask = 0;
4676   for (unsigned l = 0; l != NumElts; l += 8) {
4677     // 8 nodes per lane, but we only care about the last 4.
4678     for (unsigned i = 0; i < 4; ++i) {
4679       int Elt = N->getMaskElt(l+i+4);
4680       if (Elt < 0) continue;
4681       Elt &= 0x3; // only 2-bits.
4682       Mask |= Elt << (i * 2);
4683     }
4684   }
4685
4686   return Mask;
4687 }
4688
4689 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4690 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4691 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4692   MVT VT = N->getSimpleValueType(0);
4693
4694   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4695          "Unsupported vector type for PSHUFHW");
4696
4697   unsigned NumElts = VT.getVectorNumElements();
4698
4699   unsigned Mask = 0;
4700   for (unsigned l = 0; l != NumElts; l += 8) {
4701     // 8 nodes per lane, but we only care about the first 4.
4702     for (unsigned i = 0; i < 4; ++i) {
4703       int Elt = N->getMaskElt(l+i);
4704       if (Elt < 0) continue;
4705       Elt &= 0x3; // only 2-bits
4706       Mask |= Elt << (i * 2);
4707     }
4708   }
4709
4710   return Mask;
4711 }
4712
4713 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4714 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4715 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4716   MVT VT = SVOp->getSimpleValueType(0);
4717   unsigned EltSize = VT.is512BitVector() ? 1 :
4718     VT.getVectorElementType().getSizeInBits() >> 3;
4719
4720   unsigned NumElts = VT.getVectorNumElements();
4721   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4722   unsigned NumLaneElts = NumElts/NumLanes;
4723
4724   int Val = 0;
4725   unsigned i;
4726   for (i = 0; i != NumElts; ++i) {
4727     Val = SVOp->getMaskElt(i);
4728     if (Val >= 0)
4729       break;
4730   }
4731   if (Val >= (int)NumElts)
4732     Val -= NumElts - NumLaneElts;
4733
4734   assert(Val - i > 0 && "PALIGNR imm should be positive");
4735   return (Val - i) * EltSize;
4736 }
4737
4738 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4739   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4740   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4741     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4742
4743   uint64_t Index =
4744     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4745
4746   MVT VecVT = N->getOperand(0).getSimpleValueType();
4747   MVT ElVT = VecVT.getVectorElementType();
4748
4749   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4750   return Index / NumElemsPerChunk;
4751 }
4752
4753 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4754   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4755   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4756     llvm_unreachable("Illegal insert subvector for VINSERT");
4757
4758   uint64_t Index =
4759     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4760
4761   MVT VecVT = N->getSimpleValueType(0);
4762   MVT ElVT = VecVT.getVectorElementType();
4763
4764   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4765   return Index / NumElemsPerChunk;
4766 }
4767
4768 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4769 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4770 /// and VINSERTI128 instructions.
4771 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4772   return getExtractVEXTRACTImmediate(N, 128);
4773 }
4774
4775 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4776 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4777 /// and VINSERTI64x4 instructions.
4778 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4779   return getExtractVEXTRACTImmediate(N, 256);
4780 }
4781
4782 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4783 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4784 /// and VINSERTI128 instructions.
4785 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4786   return getInsertVINSERTImmediate(N, 128);
4787 }
4788
4789 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4790 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4791 /// and VINSERTI64x4 instructions.
4792 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4793   return getInsertVINSERTImmediate(N, 256);
4794 }
4795
4796 /// isZero - Returns true if Elt is a constant integer zero
4797 static bool isZero(SDValue V) {
4798   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4799   return C && C->isNullValue();
4800 }
4801
4802 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4803 /// constant +0.0.
4804 bool X86::isZeroNode(SDValue Elt) {
4805   if (isZero(Elt))
4806     return true;
4807   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4808     return CFP->getValueAPF().isPosZero();
4809   return false;
4810 }
4811
4812 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4813 /// match movhlps. The lower half elements should come from upper half of
4814 /// V1 (and in order), and the upper half elements should come from the upper
4815 /// half of V2 (and in order).
4816 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4817   if (!VT.is128BitVector())
4818     return false;
4819   if (VT.getVectorNumElements() != 4)
4820     return false;
4821   for (unsigned i = 0, e = 2; i != e; ++i)
4822     if (!isUndefOrEqual(Mask[i], i+2))
4823       return false;
4824   for (unsigned i = 2; i != 4; ++i)
4825     if (!isUndefOrEqual(Mask[i], i+4))
4826       return false;
4827   return true;
4828 }
4829
4830 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4831 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4832 /// required.
4833 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4834   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4835     return false;
4836   N = N->getOperand(0).getNode();
4837   if (!ISD::isNON_EXTLoad(N))
4838     return false;
4839   if (LD)
4840     *LD = cast<LoadSDNode>(N);
4841   return true;
4842 }
4843
4844 // Test whether the given value is a vector value which will be legalized
4845 // into a load.
4846 static bool WillBeConstantPoolLoad(SDNode *N) {
4847   if (N->getOpcode() != ISD::BUILD_VECTOR)
4848     return false;
4849
4850   // Check for any non-constant elements.
4851   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4852     switch (N->getOperand(i).getNode()->getOpcode()) {
4853     case ISD::UNDEF:
4854     case ISD::ConstantFP:
4855     case ISD::Constant:
4856       break;
4857     default:
4858       return false;
4859     }
4860
4861   // Vectors of all-zeros and all-ones are materialized with special
4862   // instructions rather than being loaded.
4863   return !ISD::isBuildVectorAllZeros(N) &&
4864          !ISD::isBuildVectorAllOnes(N);
4865 }
4866
4867 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4868 /// match movlp{s|d}. The lower half elements should come from lower half of
4869 /// V1 (and in order), and the upper half elements should come from the upper
4870 /// half of V2 (and in order). And since V1 will become the source of the
4871 /// MOVLP, it must be either a vector load or a scalar load to vector.
4872 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4873                                ArrayRef<int> Mask, MVT VT) {
4874   if (!VT.is128BitVector())
4875     return false;
4876
4877   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4878     return false;
4879   // Is V2 is a vector load, don't do this transformation. We will try to use
4880   // load folding shufps op.
4881   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4882     return false;
4883
4884   unsigned NumElems = VT.getVectorNumElements();
4885
4886   if (NumElems != 2 && NumElems != 4)
4887     return false;
4888   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4889     if (!isUndefOrEqual(Mask[i], i))
4890       return false;
4891   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4892     if (!isUndefOrEqual(Mask[i], i+NumElems))
4893       return false;
4894   return true;
4895 }
4896
4897 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4898 /// to an zero vector.
4899 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4900 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4901   SDValue V1 = N->getOperand(0);
4902   SDValue V2 = N->getOperand(1);
4903   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4904   for (unsigned i = 0; i != NumElems; ++i) {
4905     int Idx = N->getMaskElt(i);
4906     if (Idx >= (int)NumElems) {
4907       unsigned Opc = V2.getOpcode();
4908       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4909         continue;
4910       if (Opc != ISD::BUILD_VECTOR ||
4911           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4912         return false;
4913     } else if (Idx >= 0) {
4914       unsigned Opc = V1.getOpcode();
4915       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4916         continue;
4917       if (Opc != ISD::BUILD_VECTOR ||
4918           !X86::isZeroNode(V1.getOperand(Idx)))
4919         return false;
4920     }
4921   }
4922   return true;
4923 }
4924
4925 /// getZeroVector - Returns a vector of specified type with all zero elements.
4926 ///
4927 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4928                              SelectionDAG &DAG, SDLoc dl) {
4929   assert(VT.isVector() && "Expected a vector type");
4930
4931   // Always build SSE zero vectors as <4 x i32> bitcasted
4932   // to their dest type. This ensures they get CSE'd.
4933   SDValue Vec;
4934   if (VT.is128BitVector()) {  // SSE
4935     if (Subtarget->hasSSE2()) {  // SSE2
4936       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4937       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4938     } else { // SSE1
4939       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4940       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4941     }
4942   } else if (VT.is256BitVector()) { // AVX
4943     if (Subtarget->hasInt256()) { // AVX2
4944       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4945       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4946       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4947     } else {
4948       // 256-bit logic and arithmetic instructions in AVX are all
4949       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4950       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4951       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4952       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4953     }
4954   } else if (VT.is512BitVector()) { // AVX-512
4955       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4956       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4957                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4958       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4959   } else if (VT.getScalarType() == MVT::i1) {
4960     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4961     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4962     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4963     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4964   } else
4965     llvm_unreachable("Unexpected vector type");
4966
4967   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4968 }
4969
4970 /// getOnesVector - Returns a vector of specified type with all bits set.
4971 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4972 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4973 /// Then bitcast to their original type, ensuring they get CSE'd.
4974 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4975                              SDLoc dl) {
4976   assert(VT.isVector() && "Expected a vector type");
4977
4978   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4979   SDValue Vec;
4980   if (VT.is256BitVector()) {
4981     if (HasInt256) { // AVX2
4982       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4983       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4984     } else { // AVX
4985       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4986       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4987     }
4988   } else if (VT.is128BitVector()) {
4989     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4990   } else
4991     llvm_unreachable("Unexpected vector type");
4992
4993   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4994 }
4995
4996 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4997 /// that point to V2 points to its first element.
4998 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4999   for (unsigned i = 0; i != NumElems; ++i) {
5000     if (Mask[i] > (int)NumElems) {
5001       Mask[i] = NumElems;
5002     }
5003   }
5004 }
5005
5006 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5007 /// operation of specified width.
5008 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5009                        SDValue V2) {
5010   unsigned NumElems = VT.getVectorNumElements();
5011   SmallVector<int, 8> Mask;
5012   Mask.push_back(NumElems);
5013   for (unsigned i = 1; i != NumElems; ++i)
5014     Mask.push_back(i);
5015   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5016 }
5017
5018 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5019 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5020                           SDValue V2) {
5021   unsigned NumElems = VT.getVectorNumElements();
5022   SmallVector<int, 8> Mask;
5023   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5024     Mask.push_back(i);
5025     Mask.push_back(i + NumElems);
5026   }
5027   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5028 }
5029
5030 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5031 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5032                           SDValue V2) {
5033   unsigned NumElems = VT.getVectorNumElements();
5034   SmallVector<int, 8> Mask;
5035   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5036     Mask.push_back(i + Half);
5037     Mask.push_back(i + NumElems + Half);
5038   }
5039   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5040 }
5041
5042 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5043 // a generic shuffle instruction because the target has no such instructions.
5044 // Generate shuffles which repeat i16 and i8 several times until they can be
5045 // represented by v4f32 and then be manipulated by target suported shuffles.
5046 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5047   MVT VT = V.getSimpleValueType();
5048   int NumElems = VT.getVectorNumElements();
5049   SDLoc dl(V);
5050
5051   while (NumElems > 4) {
5052     if (EltNo < NumElems/2) {
5053       V = getUnpackl(DAG, dl, VT, V, V);
5054     } else {
5055       V = getUnpackh(DAG, dl, VT, V, V);
5056       EltNo -= NumElems/2;
5057     }
5058     NumElems >>= 1;
5059   }
5060   return V;
5061 }
5062
5063 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5064 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5065   MVT VT = V.getSimpleValueType();
5066   SDLoc dl(V);
5067
5068   if (VT.is128BitVector()) {
5069     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5070     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5071     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5072                              &SplatMask[0]);
5073   } else if (VT.is256BitVector()) {
5074     // To use VPERMILPS to splat scalars, the second half of indicies must
5075     // refer to the higher part, which is a duplication of the lower one,
5076     // because VPERMILPS can only handle in-lane permutations.
5077     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5078                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5079
5080     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5081     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5082                              &SplatMask[0]);
5083   } else
5084     llvm_unreachable("Vector size not supported");
5085
5086   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5087 }
5088
5089 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5090 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5091   MVT SrcVT = SV->getSimpleValueType(0);
5092   SDValue V1 = SV->getOperand(0);
5093   SDLoc dl(SV);
5094
5095   int EltNo = SV->getSplatIndex();
5096   int NumElems = SrcVT.getVectorNumElements();
5097   bool Is256BitVec = SrcVT.is256BitVector();
5098
5099   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5100          "Unknown how to promote splat for type");
5101
5102   // Extract the 128-bit part containing the splat element and update
5103   // the splat element index when it refers to the higher register.
5104   if (Is256BitVec) {
5105     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5106     if (EltNo >= NumElems/2)
5107       EltNo -= NumElems/2;
5108   }
5109
5110   // All i16 and i8 vector types can't be used directly by a generic shuffle
5111   // instruction because the target has no such instruction. Generate shuffles
5112   // which repeat i16 and i8 several times until they fit in i32, and then can
5113   // be manipulated by target suported shuffles.
5114   MVT EltVT = SrcVT.getVectorElementType();
5115   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5116     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5117
5118   // Recreate the 256-bit vector and place the same 128-bit vector
5119   // into the low and high part. This is necessary because we want
5120   // to use VPERM* to shuffle the vectors
5121   if (Is256BitVec) {
5122     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5123   }
5124
5125   return getLegalSplat(DAG, V1, EltNo);
5126 }
5127
5128 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5129 /// vector of zero or undef vector.  This produces a shuffle where the low
5130 /// element of V2 is swizzled into the zero/undef vector, landing at element
5131 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5132 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5133                                            bool IsZero,
5134                                            const X86Subtarget *Subtarget,
5135                                            SelectionDAG &DAG) {
5136   MVT VT = V2.getSimpleValueType();
5137   SDValue V1 = IsZero
5138     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5139   unsigned NumElems = VT.getVectorNumElements();
5140   SmallVector<int, 16> MaskVec;
5141   for (unsigned i = 0; i != NumElems; ++i)
5142     // If this is the insertion idx, put the low elt of V2 here.
5143     MaskVec.push_back(i == Idx ? NumElems : i);
5144   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5145 }
5146
5147 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5148 /// target specific opcode. Returns true if the Mask could be calculated.
5149 /// Sets IsUnary to true if only uses one source.
5150 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5151                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5152   unsigned NumElems = VT.getVectorNumElements();
5153   SDValue ImmN;
5154
5155   IsUnary = false;
5156   switch(N->getOpcode()) {
5157   case X86ISD::SHUFP:
5158     ImmN = N->getOperand(N->getNumOperands()-1);
5159     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5160     break;
5161   case X86ISD::UNPCKH:
5162     DecodeUNPCKHMask(VT, Mask);
5163     break;
5164   case X86ISD::UNPCKL:
5165     DecodeUNPCKLMask(VT, Mask);
5166     break;
5167   case X86ISD::MOVHLPS:
5168     DecodeMOVHLPSMask(NumElems, Mask);
5169     break;
5170   case X86ISD::MOVLHPS:
5171     DecodeMOVLHPSMask(NumElems, Mask);
5172     break;
5173   case X86ISD::PALIGNR:
5174     ImmN = N->getOperand(N->getNumOperands()-1);
5175     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5176     break;
5177   case X86ISD::PSHUFD:
5178   case X86ISD::VPERMILP:
5179     ImmN = N->getOperand(N->getNumOperands()-1);
5180     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5181     IsUnary = true;
5182     break;
5183   case X86ISD::PSHUFHW:
5184     ImmN = N->getOperand(N->getNumOperands()-1);
5185     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5186     IsUnary = true;
5187     break;
5188   case X86ISD::PSHUFLW:
5189     ImmN = N->getOperand(N->getNumOperands()-1);
5190     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5191     IsUnary = true;
5192     break;
5193   case X86ISD::VPERMI:
5194     ImmN = N->getOperand(N->getNumOperands()-1);
5195     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5196     IsUnary = true;
5197     break;
5198   case X86ISD::MOVSS:
5199   case X86ISD::MOVSD: {
5200     // The index 0 always comes from the first element of the second source,
5201     // this is why MOVSS and MOVSD are used in the first place. The other
5202     // elements come from the other positions of the first source vector
5203     Mask.push_back(NumElems);
5204     for (unsigned i = 1; i != NumElems; ++i) {
5205       Mask.push_back(i);
5206     }
5207     break;
5208   }
5209   case X86ISD::VPERM2X128:
5210     ImmN = N->getOperand(N->getNumOperands()-1);
5211     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5212     if (Mask.empty()) return false;
5213     break;
5214   case X86ISD::MOVDDUP:
5215   case X86ISD::MOVLHPD:
5216   case X86ISD::MOVLPD:
5217   case X86ISD::MOVLPS:
5218   case X86ISD::MOVSHDUP:
5219   case X86ISD::MOVSLDUP:
5220     // Not yet implemented
5221     return false;
5222   default: llvm_unreachable("unknown target shuffle node");
5223   }
5224
5225   return true;
5226 }
5227
5228 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5229 /// element of the result of the vector shuffle.
5230 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5231                                    unsigned Depth) {
5232   if (Depth == 6)
5233     return SDValue();  // Limit search depth.
5234
5235   SDValue V = SDValue(N, 0);
5236   EVT VT = V.getValueType();
5237   unsigned Opcode = V.getOpcode();
5238
5239   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5240   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5241     int Elt = SV->getMaskElt(Index);
5242
5243     if (Elt < 0)
5244       return DAG.getUNDEF(VT.getVectorElementType());
5245
5246     unsigned NumElems = VT.getVectorNumElements();
5247     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5248                                          : SV->getOperand(1);
5249     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5250   }
5251
5252   // Recurse into target specific vector shuffles to find scalars.
5253   if (isTargetShuffle(Opcode)) {
5254     MVT ShufVT = V.getSimpleValueType();
5255     unsigned NumElems = ShufVT.getVectorNumElements();
5256     SmallVector<int, 16> ShuffleMask;
5257     bool IsUnary;
5258
5259     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5260       return SDValue();
5261
5262     int Elt = ShuffleMask[Index];
5263     if (Elt < 0)
5264       return DAG.getUNDEF(ShufVT.getVectorElementType());
5265
5266     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5267                                          : N->getOperand(1);
5268     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5269                                Depth+1);
5270   }
5271
5272   // Actual nodes that may contain scalar elements
5273   if (Opcode == ISD::BITCAST) {
5274     V = V.getOperand(0);
5275     EVT SrcVT = V.getValueType();
5276     unsigned NumElems = VT.getVectorNumElements();
5277
5278     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5279       return SDValue();
5280   }
5281
5282   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5283     return (Index == 0) ? V.getOperand(0)
5284                         : DAG.getUNDEF(VT.getVectorElementType());
5285
5286   if (V.getOpcode() == ISD::BUILD_VECTOR)
5287     return V.getOperand(Index);
5288
5289   return SDValue();
5290 }
5291
5292 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5293 /// shuffle operation which come from a consecutively from a zero. The
5294 /// search can start in two different directions, from left or right.
5295 /// We count undefs as zeros until PreferredNum is reached.
5296 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5297                                          unsigned NumElems, bool ZerosFromLeft,
5298                                          SelectionDAG &DAG,
5299                                          unsigned PreferredNum = -1U) {
5300   unsigned NumZeros = 0;
5301   for (unsigned i = 0; i != NumElems; ++i) {
5302     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5303     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5304     if (!Elt.getNode())
5305       break;
5306
5307     if (X86::isZeroNode(Elt))
5308       ++NumZeros;
5309     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5310       NumZeros = std::min(NumZeros + 1, PreferredNum);
5311     else
5312       break;
5313   }
5314
5315   return NumZeros;
5316 }
5317
5318 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5319 /// correspond consecutively to elements from one of the vector operands,
5320 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5321 static
5322 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5323                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5324                               unsigned NumElems, unsigned &OpNum) {
5325   bool SeenV1 = false;
5326   bool SeenV2 = false;
5327
5328   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5329     int Idx = SVOp->getMaskElt(i);
5330     // Ignore undef indicies
5331     if (Idx < 0)
5332       continue;
5333
5334     if (Idx < (int)NumElems)
5335       SeenV1 = true;
5336     else
5337       SeenV2 = true;
5338
5339     // Only accept consecutive elements from the same vector
5340     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5341       return false;
5342   }
5343
5344   OpNum = SeenV1 ? 0 : 1;
5345   return true;
5346 }
5347
5348 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5349 /// logical left shift of a vector.
5350 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5351                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5352   unsigned NumElems =
5353     SVOp->getSimpleValueType(0).getVectorNumElements();
5354   unsigned NumZeros = getNumOfConsecutiveZeros(
5355       SVOp, NumElems, false /* check zeros from right */, DAG,
5356       SVOp->getMaskElt(0));
5357   unsigned OpSrc;
5358
5359   if (!NumZeros)
5360     return false;
5361
5362   // Considering the elements in the mask that are not consecutive zeros,
5363   // check if they consecutively come from only one of the source vectors.
5364   //
5365   //               V1 = {X, A, B, C}     0
5366   //                         \  \  \    /
5367   //   vector_shuffle V1, V2 <1, 2, 3, X>
5368   //
5369   if (!isShuffleMaskConsecutive(SVOp,
5370             0,                   // Mask Start Index
5371             NumElems-NumZeros,   // Mask End Index(exclusive)
5372             NumZeros,            // Where to start looking in the src vector
5373             NumElems,            // Number of elements in vector
5374             OpSrc))              // Which source operand ?
5375     return false;
5376
5377   isLeft = false;
5378   ShAmt = NumZeros;
5379   ShVal = SVOp->getOperand(OpSrc);
5380   return true;
5381 }
5382
5383 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5384 /// logical left shift of a vector.
5385 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5386                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5387   unsigned NumElems =
5388     SVOp->getSimpleValueType(0).getVectorNumElements();
5389   unsigned NumZeros = getNumOfConsecutiveZeros(
5390       SVOp, NumElems, true /* check zeros from left */, DAG,
5391       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5392   unsigned OpSrc;
5393
5394   if (!NumZeros)
5395     return false;
5396
5397   // Considering the elements in the mask that are not consecutive zeros,
5398   // check if they consecutively come from only one of the source vectors.
5399   //
5400   //                           0    { A, B, X, X } = V2
5401   //                          / \    /  /
5402   //   vector_shuffle V1, V2 <X, X, 4, 5>
5403   //
5404   if (!isShuffleMaskConsecutive(SVOp,
5405             NumZeros,     // Mask Start Index
5406             NumElems,     // Mask End Index(exclusive)
5407             0,            // Where to start looking in the src vector
5408             NumElems,     // Number of elements in vector
5409             OpSrc))       // Which source operand ?
5410     return false;
5411
5412   isLeft = true;
5413   ShAmt = NumZeros;
5414   ShVal = SVOp->getOperand(OpSrc);
5415   return true;
5416 }
5417
5418 /// isVectorShift - Returns true if the shuffle can be implemented as a
5419 /// logical left or right shift of a vector.
5420 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5421                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5422   // Although the logic below support any bitwidth size, there are no
5423   // shift instructions which handle more than 128-bit vectors.
5424   if (!SVOp->getSimpleValueType(0).is128BitVector())
5425     return false;
5426
5427   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5428       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5429     return true;
5430
5431   return false;
5432 }
5433
5434 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5435 ///
5436 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5437                                        unsigned NumNonZero, unsigned NumZero,
5438                                        SelectionDAG &DAG,
5439                                        const X86Subtarget* Subtarget,
5440                                        const TargetLowering &TLI) {
5441   if (NumNonZero > 8)
5442     return SDValue();
5443
5444   SDLoc dl(Op);
5445   SDValue V;
5446   bool First = true;
5447   for (unsigned i = 0; i < 16; ++i) {
5448     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5449     if (ThisIsNonZero && First) {
5450       if (NumZero)
5451         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5452       else
5453         V = DAG.getUNDEF(MVT::v8i16);
5454       First = false;
5455     }
5456
5457     if ((i & 1) != 0) {
5458       SDValue ThisElt, LastElt;
5459       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5460       if (LastIsNonZero) {
5461         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5462                               MVT::i16, Op.getOperand(i-1));
5463       }
5464       if (ThisIsNonZero) {
5465         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5466         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5467                               ThisElt, DAG.getConstant(8, MVT::i8));
5468         if (LastIsNonZero)
5469           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5470       } else
5471         ThisElt = LastElt;
5472
5473       if (ThisElt.getNode())
5474         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5475                         DAG.getIntPtrConstant(i/2));
5476     }
5477   }
5478
5479   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5480 }
5481
5482 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5483 ///
5484 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5485                                      unsigned NumNonZero, unsigned NumZero,
5486                                      SelectionDAG &DAG,
5487                                      const X86Subtarget* Subtarget,
5488                                      const TargetLowering &TLI) {
5489   if (NumNonZero > 4)
5490     return SDValue();
5491
5492   SDLoc dl(Op);
5493   SDValue V;
5494   bool First = true;
5495   for (unsigned i = 0; i < 8; ++i) {
5496     bool isNonZero = (NonZeros & (1 << i)) != 0;
5497     if (isNonZero) {
5498       if (First) {
5499         if (NumZero)
5500           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5501         else
5502           V = DAG.getUNDEF(MVT::v8i16);
5503         First = false;
5504       }
5505       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5506                       MVT::v8i16, V, Op.getOperand(i),
5507                       DAG.getIntPtrConstant(i));
5508     }
5509   }
5510
5511   return V;
5512 }
5513
5514 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5515 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5516                                      unsigned NonZeros, unsigned NumNonZero,
5517                                      unsigned NumZero, SelectionDAG &DAG,
5518                                      const X86Subtarget *Subtarget,
5519                                      const TargetLowering &TLI) {
5520   // We know there's at least one non-zero element
5521   unsigned FirstNonZeroIdx = 0;
5522   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5523   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5524          X86::isZeroNode(FirstNonZero)) {
5525     ++FirstNonZeroIdx;
5526     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5527   }
5528
5529   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5530       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5531     return SDValue();
5532
5533   SDValue V = FirstNonZero.getOperand(0);
5534   MVT VVT = V.getSimpleValueType();
5535   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5536     return SDValue();
5537
5538   unsigned FirstNonZeroDst =
5539       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5540   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5541   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5542   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5543
5544   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5545     SDValue Elem = Op.getOperand(Idx);
5546     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5547       continue;
5548
5549     // TODO: What else can be here? Deal with it.
5550     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5551       return SDValue();
5552
5553     // TODO: Some optimizations are still possible here
5554     // ex: Getting one element from a vector, and the rest from another.
5555     if (Elem.getOperand(0) != V)
5556       return SDValue();
5557
5558     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5559     if (Dst == Idx)
5560       ++CorrectIdx;
5561     else if (IncorrectIdx == -1U) {
5562       IncorrectIdx = Idx;
5563       IncorrectDst = Dst;
5564     } else
5565       // There was already one element with an incorrect index.
5566       // We can't optimize this case to an insertps.
5567       return SDValue();
5568   }
5569
5570   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5571     SDLoc dl(Op);
5572     EVT VT = Op.getSimpleValueType();
5573     unsigned ElementMoveMask = 0;
5574     if (IncorrectIdx == -1U)
5575       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5576     else
5577       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5578
5579     SDValue InsertpsMask =
5580         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5581     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5582   }
5583
5584   return SDValue();
5585 }
5586
5587 /// getVShift - Return a vector logical shift node.
5588 ///
5589 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5590                          unsigned NumBits, SelectionDAG &DAG,
5591                          const TargetLowering &TLI, SDLoc dl) {
5592   assert(VT.is128BitVector() && "Unknown type for VShift");
5593   EVT ShVT = MVT::v2i64;
5594   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5595   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5596   return DAG.getNode(ISD::BITCAST, dl, VT,
5597                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5598                              DAG.getConstant(NumBits,
5599                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5600 }
5601
5602 static SDValue
5603 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5604
5605   // Check if the scalar load can be widened into a vector load. And if
5606   // the address is "base + cst" see if the cst can be "absorbed" into
5607   // the shuffle mask.
5608   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5609     SDValue Ptr = LD->getBasePtr();
5610     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5611       return SDValue();
5612     EVT PVT = LD->getValueType(0);
5613     if (PVT != MVT::i32 && PVT != MVT::f32)
5614       return SDValue();
5615
5616     int FI = -1;
5617     int64_t Offset = 0;
5618     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5619       FI = FINode->getIndex();
5620       Offset = 0;
5621     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5622                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5623       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5624       Offset = Ptr.getConstantOperandVal(1);
5625       Ptr = Ptr.getOperand(0);
5626     } else {
5627       return SDValue();
5628     }
5629
5630     // FIXME: 256-bit vector instructions don't require a strict alignment,
5631     // improve this code to support it better.
5632     unsigned RequiredAlign = VT.getSizeInBits()/8;
5633     SDValue Chain = LD->getChain();
5634     // Make sure the stack object alignment is at least 16 or 32.
5635     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5636     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5637       if (MFI->isFixedObjectIndex(FI)) {
5638         // Can't change the alignment. FIXME: It's possible to compute
5639         // the exact stack offset and reference FI + adjust offset instead.
5640         // If someone *really* cares about this. That's the way to implement it.
5641         return SDValue();
5642       } else {
5643         MFI->setObjectAlignment(FI, RequiredAlign);
5644       }
5645     }
5646
5647     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5648     // Ptr + (Offset & ~15).
5649     if (Offset < 0)
5650       return SDValue();
5651     if ((Offset % RequiredAlign) & 3)
5652       return SDValue();
5653     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5654     if (StartOffset)
5655       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5656                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5657
5658     int EltNo = (Offset - StartOffset) >> 2;
5659     unsigned NumElems = VT.getVectorNumElements();
5660
5661     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5662     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5663                              LD->getPointerInfo().getWithOffset(StartOffset),
5664                              false, false, false, 0);
5665
5666     SmallVector<int, 8> Mask;
5667     for (unsigned i = 0; i != NumElems; ++i)
5668       Mask.push_back(EltNo);
5669
5670     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5671   }
5672
5673   return SDValue();
5674 }
5675
5676 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5677 /// vector of type 'VT', see if the elements can be replaced by a single large
5678 /// load which has the same value as a build_vector whose operands are 'elts'.
5679 ///
5680 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5681 ///
5682 /// FIXME: we'd also like to handle the case where the last elements are zero
5683 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5684 /// There's even a handy isZeroNode for that purpose.
5685 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5686                                         SDLoc &DL, SelectionDAG &DAG,
5687                                         bool isAfterLegalize) {
5688   EVT EltVT = VT.getVectorElementType();
5689   unsigned NumElems = Elts.size();
5690
5691   LoadSDNode *LDBase = nullptr;
5692   unsigned LastLoadedElt = -1U;
5693
5694   // For each element in the initializer, see if we've found a load or an undef.
5695   // If we don't find an initial load element, or later load elements are
5696   // non-consecutive, bail out.
5697   for (unsigned i = 0; i < NumElems; ++i) {
5698     SDValue Elt = Elts[i];
5699
5700     if (!Elt.getNode() ||
5701         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5702       return SDValue();
5703     if (!LDBase) {
5704       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5705         return SDValue();
5706       LDBase = cast<LoadSDNode>(Elt.getNode());
5707       LastLoadedElt = i;
5708       continue;
5709     }
5710     if (Elt.getOpcode() == ISD::UNDEF)
5711       continue;
5712
5713     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5714     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5715       return SDValue();
5716     LastLoadedElt = i;
5717   }
5718
5719   // If we have found an entire vector of loads and undefs, then return a large
5720   // load of the entire vector width starting at the base pointer.  If we found
5721   // consecutive loads for the low half, generate a vzext_load node.
5722   if (LastLoadedElt == NumElems - 1) {
5723
5724     if (isAfterLegalize &&
5725         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5726       return SDValue();
5727
5728     SDValue NewLd = SDValue();
5729
5730     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5731       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5732                           LDBase->getPointerInfo(),
5733                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5734                           LDBase->isInvariant(), 0);
5735     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5736                         LDBase->getPointerInfo(),
5737                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5738                         LDBase->isInvariant(), LDBase->getAlignment());
5739
5740     if (LDBase->hasAnyUseOfValue(1)) {
5741       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5742                                      SDValue(LDBase, 1),
5743                                      SDValue(NewLd.getNode(), 1));
5744       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5745       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5746                              SDValue(NewLd.getNode(), 1));
5747     }
5748
5749     return NewLd;
5750   }
5751   if (NumElems == 4 && LastLoadedElt == 1 &&
5752       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5753     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5754     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5755     SDValue ResNode =
5756         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5757                                 LDBase->getPointerInfo(),
5758                                 LDBase->getAlignment(),
5759                                 false/*isVolatile*/, true/*ReadMem*/,
5760                                 false/*WriteMem*/);
5761
5762     // Make sure the newly-created LOAD is in the same position as LDBase in
5763     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5764     // update uses of LDBase's output chain to use the TokenFactor.
5765     if (LDBase->hasAnyUseOfValue(1)) {
5766       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5767                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5768       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5769       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5770                              SDValue(ResNode.getNode(), 1));
5771     }
5772
5773     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5774   }
5775   return SDValue();
5776 }
5777
5778 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5779 /// to generate a splat value for the following cases:
5780 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5781 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5782 /// a scalar load, or a constant.
5783 /// The VBROADCAST node is returned when a pattern is found,
5784 /// or SDValue() otherwise.
5785 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5786                                     SelectionDAG &DAG) {
5787   if (!Subtarget->hasFp256())
5788     return SDValue();
5789
5790   MVT VT = Op.getSimpleValueType();
5791   SDLoc dl(Op);
5792
5793   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5794          "Unsupported vector type for broadcast.");
5795
5796   SDValue Ld;
5797   bool ConstSplatVal;
5798
5799   switch (Op.getOpcode()) {
5800     default:
5801       // Unknown pattern found.
5802       return SDValue();
5803
5804     case ISD::BUILD_VECTOR: {
5805       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5806       BitVector UndefElements;
5807       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5808
5809       // We need a splat of a single value to use broadcast, and it doesn't
5810       // make any sense if the value is only in one element of the vector.
5811       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5812         return SDValue();
5813
5814       Ld = Splat;
5815       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5816                        Ld.getOpcode() == ISD::ConstantFP);
5817
5818       // Make sure that all of the users of a non-constant load are from the
5819       // BUILD_VECTOR node.
5820       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5821         return SDValue();
5822       break;
5823     }
5824
5825     case ISD::VECTOR_SHUFFLE: {
5826       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5827
5828       // Shuffles must have a splat mask where the first element is
5829       // broadcasted.
5830       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5831         return SDValue();
5832
5833       SDValue Sc = Op.getOperand(0);
5834       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5835           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5836
5837         if (!Subtarget->hasInt256())
5838           return SDValue();
5839
5840         // Use the register form of the broadcast instruction available on AVX2.
5841         if (VT.getSizeInBits() >= 256)
5842           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5843         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5844       }
5845
5846       Ld = Sc.getOperand(0);
5847       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5848                        Ld.getOpcode() == ISD::ConstantFP);
5849
5850       // The scalar_to_vector node and the suspected
5851       // load node must have exactly one user.
5852       // Constants may have multiple users.
5853
5854       // AVX-512 has register version of the broadcast
5855       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5856         Ld.getValueType().getSizeInBits() >= 32;
5857       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5858           !hasRegVer))
5859         return SDValue();
5860       break;
5861     }
5862   }
5863
5864   bool IsGE256 = (VT.getSizeInBits() >= 256);
5865
5866   // Handle the broadcasting a single constant scalar from the constant pool
5867   // into a vector. On Sandybridge it is still better to load a constant vector
5868   // from the constant pool and not to broadcast it from a scalar.
5869   if (ConstSplatVal && Subtarget->hasInt256()) {
5870     EVT CVT = Ld.getValueType();
5871     assert(!CVT.isVector() && "Must not broadcast a vector type");
5872     unsigned ScalarSize = CVT.getSizeInBits();
5873
5874     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5875       const Constant *C = nullptr;
5876       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5877         C = CI->getConstantIntValue();
5878       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5879         C = CF->getConstantFPValue();
5880
5881       assert(C && "Invalid constant type");
5882
5883       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5884       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5885       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5886       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5887                        MachinePointerInfo::getConstantPool(),
5888                        false, false, false, Alignment);
5889
5890       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5891     }
5892   }
5893
5894   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5895   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5896
5897   // Handle AVX2 in-register broadcasts.
5898   if (!IsLoad && Subtarget->hasInt256() &&
5899       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5900     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5901
5902   // The scalar source must be a normal load.
5903   if (!IsLoad)
5904     return SDValue();
5905
5906   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5907     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5908
5909   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5910   // double since there is no vbroadcastsd xmm
5911   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5912     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5913       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5914   }
5915
5916   // Unsupported broadcast.
5917   return SDValue();
5918 }
5919
5920 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5921 /// underlying vector and index.
5922 ///
5923 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5924 /// index.
5925 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5926                                          SDValue ExtIdx) {
5927   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5928   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5929     return Idx;
5930
5931   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5932   // lowered this:
5933   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5934   // to:
5935   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5936   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5937   //                           undef)
5938   //                       Constant<0>)
5939   // In this case the vector is the extract_subvector expression and the index
5940   // is 2, as specified by the shuffle.
5941   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5942   SDValue ShuffleVec = SVOp->getOperand(0);
5943   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5944   assert(ShuffleVecVT.getVectorElementType() ==
5945          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5946
5947   int ShuffleIdx = SVOp->getMaskElt(Idx);
5948   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5949     ExtractedFromVec = ShuffleVec;
5950     return ShuffleIdx;
5951   }
5952   return Idx;
5953 }
5954
5955 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5956   MVT VT = Op.getSimpleValueType();
5957
5958   // Skip if insert_vec_elt is not supported.
5959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5960   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5961     return SDValue();
5962
5963   SDLoc DL(Op);
5964   unsigned NumElems = Op.getNumOperands();
5965
5966   SDValue VecIn1;
5967   SDValue VecIn2;
5968   SmallVector<unsigned, 4> InsertIndices;
5969   SmallVector<int, 8> Mask(NumElems, -1);
5970
5971   for (unsigned i = 0; i != NumElems; ++i) {
5972     unsigned Opc = Op.getOperand(i).getOpcode();
5973
5974     if (Opc == ISD::UNDEF)
5975       continue;
5976
5977     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5978       // Quit if more than 1 elements need inserting.
5979       if (InsertIndices.size() > 1)
5980         return SDValue();
5981
5982       InsertIndices.push_back(i);
5983       continue;
5984     }
5985
5986     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5987     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5988     // Quit if non-constant index.
5989     if (!isa<ConstantSDNode>(ExtIdx))
5990       return SDValue();
5991     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5992
5993     // Quit if extracted from vector of different type.
5994     if (ExtractedFromVec.getValueType() != VT)
5995       return SDValue();
5996
5997     if (!VecIn1.getNode())
5998       VecIn1 = ExtractedFromVec;
5999     else if (VecIn1 != ExtractedFromVec) {
6000       if (!VecIn2.getNode())
6001         VecIn2 = ExtractedFromVec;
6002       else if (VecIn2 != ExtractedFromVec)
6003         // Quit if more than 2 vectors to shuffle
6004         return SDValue();
6005     }
6006
6007     if (ExtractedFromVec == VecIn1)
6008       Mask[i] = Idx;
6009     else if (ExtractedFromVec == VecIn2)
6010       Mask[i] = Idx + NumElems;
6011   }
6012
6013   if (!VecIn1.getNode())
6014     return SDValue();
6015
6016   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6017   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6018   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6019     unsigned Idx = InsertIndices[i];
6020     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6021                      DAG.getIntPtrConstant(Idx));
6022   }
6023
6024   return NV;
6025 }
6026
6027 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6028 SDValue
6029 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6030
6031   MVT VT = Op.getSimpleValueType();
6032   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6033          "Unexpected type in LowerBUILD_VECTORvXi1!");
6034
6035   SDLoc dl(Op);
6036   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6037     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6038     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6039     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6040   }
6041
6042   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6043     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6044     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6045     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6046   }
6047
6048   bool AllContants = true;
6049   uint64_t Immediate = 0;
6050   int NonConstIdx = -1;
6051   bool IsSplat = true;
6052   unsigned NumNonConsts = 0;
6053   unsigned NumConsts = 0;
6054   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6055     SDValue In = Op.getOperand(idx);
6056     if (In.getOpcode() == ISD::UNDEF)
6057       continue;
6058     if (!isa<ConstantSDNode>(In)) {
6059       AllContants = false;
6060       NonConstIdx = idx;
6061       NumNonConsts++;
6062     }
6063     else {
6064       NumConsts++;
6065       if (cast<ConstantSDNode>(In)->getZExtValue())
6066       Immediate |= (1ULL << idx);
6067     }
6068     if (In != Op.getOperand(0))
6069       IsSplat = false;
6070   }
6071
6072   if (AllContants) {
6073     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6074       DAG.getConstant(Immediate, MVT::i16));
6075     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6076                        DAG.getIntPtrConstant(0));
6077   }
6078
6079   if (NumNonConsts == 1 && NonConstIdx != 0) {
6080     SDValue DstVec;
6081     if (NumConsts) {
6082       SDValue VecAsImm = DAG.getConstant(Immediate,
6083                                          MVT::getIntegerVT(VT.getSizeInBits()));
6084       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6085     }
6086     else 
6087       DstVec = DAG.getUNDEF(VT);
6088     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6089                        Op.getOperand(NonConstIdx),
6090                        DAG.getIntPtrConstant(NonConstIdx));
6091   }
6092   if (!IsSplat && (NonConstIdx != 0))
6093     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6094   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6095   SDValue Select;
6096   if (IsSplat)
6097     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6098                           DAG.getConstant(-1, SelectVT),
6099                           DAG.getConstant(0, SelectVT));
6100   else
6101     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6102                          DAG.getConstant((Immediate | 1), SelectVT),
6103                          DAG.getConstant(Immediate, SelectVT));
6104   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6105 }
6106
6107 /// \brief Return true if \p N implements a horizontal binop and return the
6108 /// operands for the horizontal binop into V0 and V1.
6109 /// 
6110 /// This is a helper function of PerformBUILD_VECTORCombine.
6111 /// This function checks that the build_vector \p N in input implements a
6112 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6113 /// operation to match.
6114 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6115 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6116 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6117 /// arithmetic sub.
6118 ///
6119 /// This function only analyzes elements of \p N whose indices are
6120 /// in range [BaseIdx, LastIdx).
6121 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6122                               SelectionDAG &DAG,
6123                               unsigned BaseIdx, unsigned LastIdx,
6124                               SDValue &V0, SDValue &V1) {
6125   EVT VT = N->getValueType(0);
6126
6127   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6128   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6129          "Invalid Vector in input!");
6130   
6131   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6132   bool CanFold = true;
6133   unsigned ExpectedVExtractIdx = BaseIdx;
6134   unsigned NumElts = LastIdx - BaseIdx;
6135   V0 = DAG.getUNDEF(VT);
6136   V1 = DAG.getUNDEF(VT);
6137
6138   // Check if N implements a horizontal binop.
6139   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6140     SDValue Op = N->getOperand(i + BaseIdx);
6141
6142     // Skip UNDEFs.
6143     if (Op->getOpcode() == ISD::UNDEF) {
6144       // Update the expected vector extract index.
6145       if (i * 2 == NumElts)
6146         ExpectedVExtractIdx = BaseIdx;
6147       ExpectedVExtractIdx += 2;
6148       continue;
6149     }
6150
6151     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6152
6153     if (!CanFold)
6154       break;
6155
6156     SDValue Op0 = Op.getOperand(0);
6157     SDValue Op1 = Op.getOperand(1);
6158
6159     // Try to match the following pattern:
6160     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6161     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6162         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6163         Op0.getOperand(0) == Op1.getOperand(0) &&
6164         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6165         isa<ConstantSDNode>(Op1.getOperand(1)));
6166     if (!CanFold)
6167       break;
6168
6169     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6170     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6171
6172     if (i * 2 < NumElts) {
6173       if (V0.getOpcode() == ISD::UNDEF)
6174         V0 = Op0.getOperand(0);
6175     } else {
6176       if (V1.getOpcode() == ISD::UNDEF)
6177         V1 = Op0.getOperand(0);
6178       if (i * 2 == NumElts)
6179         ExpectedVExtractIdx = BaseIdx;
6180     }
6181
6182     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6183     if (I0 == ExpectedVExtractIdx)
6184       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6185     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6186       // Try to match the following dag sequence:
6187       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6188       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6189     } else
6190       CanFold = false;
6191
6192     ExpectedVExtractIdx += 2;
6193   }
6194
6195   return CanFold;
6196 }
6197
6198 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6199 /// a concat_vector. 
6200 ///
6201 /// This is a helper function of PerformBUILD_VECTORCombine.
6202 /// This function expects two 256-bit vectors called V0 and V1.
6203 /// At first, each vector is split into two separate 128-bit vectors.
6204 /// Then, the resulting 128-bit vectors are used to implement two
6205 /// horizontal binary operations. 
6206 ///
6207 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6208 ///
6209 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6210 /// the two new horizontal binop.
6211 /// When Mode is set, the first horizontal binop dag node would take as input
6212 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6213 /// horizontal binop dag node would take as input the lower 128-bit of V1
6214 /// and the upper 128-bit of V1.
6215 ///   Example:
6216 ///     HADD V0_LO, V0_HI
6217 ///     HADD V1_LO, V1_HI
6218 ///
6219 /// Otherwise, the first horizontal binop dag node takes as input the lower
6220 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6221 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6222 ///   Example:
6223 ///     HADD V0_LO, V1_LO
6224 ///     HADD V0_HI, V1_HI
6225 ///
6226 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6227 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6228 /// the upper 128-bits of the result.
6229 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6230                                      SDLoc DL, SelectionDAG &DAG,
6231                                      unsigned X86Opcode, bool Mode,
6232                                      bool isUndefLO, bool isUndefHI) {
6233   EVT VT = V0.getValueType();
6234   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6235          "Invalid nodes in input!");
6236
6237   unsigned NumElts = VT.getVectorNumElements();
6238   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6239   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6240   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6241   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6242   EVT NewVT = V0_LO.getValueType();
6243
6244   SDValue LO = DAG.getUNDEF(NewVT);
6245   SDValue HI = DAG.getUNDEF(NewVT);
6246
6247   if (Mode) {
6248     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6249     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6250       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6251     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6252       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6253   } else {
6254     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6255     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6256                        V1_LO->getOpcode() != ISD::UNDEF))
6257       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6258
6259     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6260                        V1_HI->getOpcode() != ISD::UNDEF))
6261       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6262   }
6263
6264   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6265 }
6266
6267 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6268 /// sequence of 'vadd + vsub + blendi'.
6269 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6270                            const X86Subtarget *Subtarget) {
6271   SDLoc DL(BV);
6272   EVT VT = BV->getValueType(0);
6273   unsigned NumElts = VT.getVectorNumElements();
6274   SDValue InVec0 = DAG.getUNDEF(VT);
6275   SDValue InVec1 = DAG.getUNDEF(VT);
6276
6277   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6278           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6279
6280   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6282   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6283     return SDValue();
6284
6285   // Odd-numbered elements in the input build vector are obtained from
6286   // adding two integer/float elements.
6287   // Even-numbered elements in the input build vector are obtained from
6288   // subtracting two integer/float elements.
6289   unsigned ExpectedOpcode = ISD::FSUB;
6290   unsigned NextExpectedOpcode = ISD::FADD;
6291   bool AddFound = false;
6292   bool SubFound = false;
6293
6294   for (unsigned i = 0, e = NumElts; i != e; i++) {
6295     SDValue Op = BV->getOperand(i);
6296       
6297     // Skip 'undef' values.
6298     unsigned Opcode = Op.getOpcode();
6299     if (Opcode == ISD::UNDEF) {
6300       std::swap(ExpectedOpcode, NextExpectedOpcode);
6301       continue;
6302     }
6303       
6304     // Early exit if we found an unexpected opcode.
6305     if (Opcode != ExpectedOpcode)
6306       return SDValue();
6307
6308     SDValue Op0 = Op.getOperand(0);
6309     SDValue Op1 = Op.getOperand(1);
6310
6311     // Try to match the following pattern:
6312     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6313     // Early exit if we cannot match that sequence.
6314     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6315         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6316         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6317         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6318         Op0.getOperand(1) != Op1.getOperand(1))
6319       return SDValue();
6320
6321     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6322     if (I0 != i)
6323       return SDValue();
6324
6325     // We found a valid add/sub node. Update the information accordingly.
6326     if (i & 1)
6327       AddFound = true;
6328     else
6329       SubFound = true;
6330
6331     // Update InVec0 and InVec1.
6332     if (InVec0.getOpcode() == ISD::UNDEF)
6333       InVec0 = Op0.getOperand(0);
6334     if (InVec1.getOpcode() == ISD::UNDEF)
6335       InVec1 = Op1.getOperand(0);
6336
6337     // Make sure that operands in input to each add/sub node always
6338     // come from a same pair of vectors.
6339     if (InVec0 != Op0.getOperand(0)) {
6340       if (ExpectedOpcode == ISD::FSUB)
6341         return SDValue();
6342
6343       // FADD is commutable. Try to commute the operands
6344       // and then test again.
6345       std::swap(Op0, Op1);
6346       if (InVec0 != Op0.getOperand(0))
6347         return SDValue();
6348     }
6349
6350     if (InVec1 != Op1.getOperand(0))
6351       return SDValue();
6352
6353     // Update the pair of expected opcodes.
6354     std::swap(ExpectedOpcode, NextExpectedOpcode);
6355   }
6356
6357   // Don't try to fold this build_vector into a VSELECT if it has
6358   // too many UNDEF operands.
6359   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6360       InVec1.getOpcode() != ISD::UNDEF) {
6361     // Emit a sequence of vector add and sub followed by a VSELECT.
6362     // The new VSELECT will be lowered into a BLENDI.
6363     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6364     // and emit a single ADDSUB instruction.
6365     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6366     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6367
6368     // Construct the VSELECT mask.
6369     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6370     EVT SVT = MaskVT.getVectorElementType();
6371     unsigned SVTBits = SVT.getSizeInBits();
6372     SmallVector<SDValue, 8> Ops;
6373
6374     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6375       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6376                             APInt::getAllOnesValue(SVTBits);
6377       SDValue Constant = DAG.getConstant(Value, SVT);
6378       Ops.push_back(Constant);
6379     }
6380
6381     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6382     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6383   }
6384   
6385   return SDValue();
6386 }
6387
6388 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6389                                           const X86Subtarget *Subtarget) {
6390   SDLoc DL(N);
6391   EVT VT = N->getValueType(0);
6392   unsigned NumElts = VT.getVectorNumElements();
6393   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6394   SDValue InVec0, InVec1;
6395
6396   // Try to match an ADDSUB.
6397   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6398       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6399     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6400     if (Value.getNode())
6401       return Value;
6402   }
6403
6404   // Try to match horizontal ADD/SUB.
6405   unsigned NumUndefsLO = 0;
6406   unsigned NumUndefsHI = 0;
6407   unsigned Half = NumElts/2;
6408
6409   // Count the number of UNDEF operands in the build_vector in input.
6410   for (unsigned i = 0, e = Half; i != e; ++i)
6411     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6412       NumUndefsLO++;
6413
6414   for (unsigned i = Half, e = NumElts; i != e; ++i)
6415     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6416       NumUndefsHI++;
6417
6418   // Early exit if this is either a build_vector of all UNDEFs or all the
6419   // operands but one are UNDEF.
6420   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6421     return SDValue();
6422
6423   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6424     // Try to match an SSE3 float HADD/HSUB.
6425     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6426       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6427     
6428     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6429       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6430   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6431     // Try to match an SSSE3 integer HADD/HSUB.
6432     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6433       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6434     
6435     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6436       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6437   }
6438   
6439   if (!Subtarget->hasAVX())
6440     return SDValue();
6441
6442   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6443     // Try to match an AVX horizontal add/sub of packed single/double
6444     // precision floating point values from 256-bit vectors.
6445     SDValue InVec2, InVec3;
6446     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6447         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6448         ((InVec0.getOpcode() == ISD::UNDEF ||
6449           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6450         ((InVec1.getOpcode() == ISD::UNDEF ||
6451           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6452       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6453
6454     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6455         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6456         ((InVec0.getOpcode() == ISD::UNDEF ||
6457           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6458         ((InVec1.getOpcode() == ISD::UNDEF ||
6459           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6460       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6461   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6462     // Try to match an AVX2 horizontal add/sub of signed integers.
6463     SDValue InVec2, InVec3;
6464     unsigned X86Opcode;
6465     bool CanFold = true;
6466
6467     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6468         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6469         ((InVec0.getOpcode() == ISD::UNDEF ||
6470           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6471         ((InVec1.getOpcode() == ISD::UNDEF ||
6472           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6473       X86Opcode = X86ISD::HADD;
6474     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6475         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6476         ((InVec0.getOpcode() == ISD::UNDEF ||
6477           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6478         ((InVec1.getOpcode() == ISD::UNDEF ||
6479           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6480       X86Opcode = X86ISD::HSUB;
6481     else
6482       CanFold = false;
6483
6484     if (CanFold) {
6485       // Fold this build_vector into a single horizontal add/sub.
6486       // Do this only if the target has AVX2.
6487       if (Subtarget->hasAVX2())
6488         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6489  
6490       // Do not try to expand this build_vector into a pair of horizontal
6491       // add/sub if we can emit a pair of scalar add/sub.
6492       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6493         return SDValue();
6494
6495       // Convert this build_vector into a pair of horizontal binop followed by
6496       // a concat vector.
6497       bool isUndefLO = NumUndefsLO == Half;
6498       bool isUndefHI = NumUndefsHI == Half;
6499       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6500                                    isUndefLO, isUndefHI);
6501     }
6502   }
6503
6504   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6505        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6506     unsigned X86Opcode;
6507     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6508       X86Opcode = X86ISD::HADD;
6509     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6510       X86Opcode = X86ISD::HSUB;
6511     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6512       X86Opcode = X86ISD::FHADD;
6513     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6514       X86Opcode = X86ISD::FHSUB;
6515     else
6516       return SDValue();
6517
6518     // Don't try to expand this build_vector into a pair of horizontal add/sub
6519     // if we can simply emit a pair of scalar add/sub.
6520     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6521       return SDValue();
6522
6523     // Convert this build_vector into two horizontal add/sub followed by
6524     // a concat vector.
6525     bool isUndefLO = NumUndefsLO == Half;
6526     bool isUndefHI = NumUndefsHI == Half;
6527     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6528                                  isUndefLO, isUndefHI);
6529   }
6530
6531   return SDValue();
6532 }
6533
6534 SDValue
6535 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6536   SDLoc dl(Op);
6537
6538   MVT VT = Op.getSimpleValueType();
6539   MVT ExtVT = VT.getVectorElementType();
6540   unsigned NumElems = Op.getNumOperands();
6541
6542   // Generate vectors for predicate vectors.
6543   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6544     return LowerBUILD_VECTORvXi1(Op, DAG);
6545
6546   // Vectors containing all zeros can be matched by pxor and xorps later
6547   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6548     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6549     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6550     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6551       return Op;
6552
6553     return getZeroVector(VT, Subtarget, DAG, dl);
6554   }
6555
6556   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6557   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6558   // vpcmpeqd on 256-bit vectors.
6559   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6560     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6561       return Op;
6562
6563     if (!VT.is512BitVector())
6564       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6565   }
6566
6567   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6568   if (Broadcast.getNode())
6569     return Broadcast;
6570
6571   unsigned EVTBits = ExtVT.getSizeInBits();
6572
6573   unsigned NumZero  = 0;
6574   unsigned NumNonZero = 0;
6575   unsigned NonZeros = 0;
6576   bool IsAllConstants = true;
6577   SmallSet<SDValue, 8> Values;
6578   for (unsigned i = 0; i < NumElems; ++i) {
6579     SDValue Elt = Op.getOperand(i);
6580     if (Elt.getOpcode() == ISD::UNDEF)
6581       continue;
6582     Values.insert(Elt);
6583     if (Elt.getOpcode() != ISD::Constant &&
6584         Elt.getOpcode() != ISD::ConstantFP)
6585       IsAllConstants = false;
6586     if (X86::isZeroNode(Elt))
6587       NumZero++;
6588     else {
6589       NonZeros |= (1 << i);
6590       NumNonZero++;
6591     }
6592   }
6593
6594   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6595   if (NumNonZero == 0)
6596     return DAG.getUNDEF(VT);
6597
6598   // Special case for single non-zero, non-undef, element.
6599   if (NumNonZero == 1) {
6600     unsigned Idx = countTrailingZeros(NonZeros);
6601     SDValue Item = Op.getOperand(Idx);
6602
6603     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6604     // the value are obviously zero, truncate the value to i32 and do the
6605     // insertion that way.  Only do this if the value is non-constant or if the
6606     // value is a constant being inserted into element 0.  It is cheaper to do
6607     // a constant pool load than it is to do a movd + shuffle.
6608     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6609         (!IsAllConstants || Idx == 0)) {
6610       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6611         // Handle SSE only.
6612         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6613         EVT VecVT = MVT::v4i32;
6614         unsigned VecElts = 4;
6615
6616         // Truncate the value (which may itself be a constant) to i32, and
6617         // convert it to a vector with movd (S2V+shuffle to zero extend).
6618         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6619         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6620         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6621
6622         // Now we have our 32-bit value zero extended in the low element of
6623         // a vector.  If Idx != 0, swizzle it into place.
6624         if (Idx != 0) {
6625           SmallVector<int, 4> Mask;
6626           Mask.push_back(Idx);
6627           for (unsigned i = 1; i != VecElts; ++i)
6628             Mask.push_back(i);
6629           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6630                                       &Mask[0]);
6631         }
6632         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6633       }
6634     }
6635
6636     // If we have a constant or non-constant insertion into the low element of
6637     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6638     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6639     // depending on what the source datatype is.
6640     if (Idx == 0) {
6641       if (NumZero == 0)
6642         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6643
6644       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6645           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6646         if (VT.is256BitVector() || VT.is512BitVector()) {
6647           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6648           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6649                              Item, DAG.getIntPtrConstant(0));
6650         }
6651         assert(VT.is128BitVector() && "Expected an SSE value type!");
6652         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6653         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6654         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6655       }
6656
6657       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6658         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6659         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6660         if (VT.is256BitVector()) {
6661           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6662           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6663         } else {
6664           assert(VT.is128BitVector() && "Expected an SSE value type!");
6665           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6666         }
6667         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6668       }
6669     }
6670
6671     // Is it a vector logical left shift?
6672     if (NumElems == 2 && Idx == 1 &&
6673         X86::isZeroNode(Op.getOperand(0)) &&
6674         !X86::isZeroNode(Op.getOperand(1))) {
6675       unsigned NumBits = VT.getSizeInBits();
6676       return getVShift(true, VT,
6677                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6678                                    VT, Op.getOperand(1)),
6679                        NumBits/2, DAG, *this, dl);
6680     }
6681
6682     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6683       return SDValue();
6684
6685     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6686     // is a non-constant being inserted into an element other than the low one,
6687     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6688     // movd/movss) to move this into the low element, then shuffle it into
6689     // place.
6690     if (EVTBits == 32) {
6691       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6692
6693       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6694       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6695       SmallVector<int, 8> MaskVec;
6696       for (unsigned i = 0; i != NumElems; ++i)
6697         MaskVec.push_back(i == Idx ? 0 : 1);
6698       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6699     }
6700   }
6701
6702   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6703   if (Values.size() == 1) {
6704     if (EVTBits == 32) {
6705       // Instead of a shuffle like this:
6706       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6707       // Check if it's possible to issue this instead.
6708       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6709       unsigned Idx = countTrailingZeros(NonZeros);
6710       SDValue Item = Op.getOperand(Idx);
6711       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6712         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6713     }
6714     return SDValue();
6715   }
6716
6717   // A vector full of immediates; various special cases are already
6718   // handled, so this is best done with a single constant-pool load.
6719   if (IsAllConstants)
6720     return SDValue();
6721
6722   // For AVX-length vectors, build the individual 128-bit pieces and use
6723   // shuffles to put them in place.
6724   if (VT.is256BitVector() || VT.is512BitVector()) {
6725     SmallVector<SDValue, 64> V;
6726     for (unsigned i = 0; i != NumElems; ++i)
6727       V.push_back(Op.getOperand(i));
6728
6729     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6730
6731     // Build both the lower and upper subvector.
6732     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6733                                 makeArrayRef(&V[0], NumElems/2));
6734     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6735                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6736
6737     // Recreate the wider vector with the lower and upper part.
6738     if (VT.is256BitVector())
6739       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6740     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6741   }
6742
6743   // Let legalizer expand 2-wide build_vectors.
6744   if (EVTBits == 64) {
6745     if (NumNonZero == 1) {
6746       // One half is zero or undef.
6747       unsigned Idx = countTrailingZeros(NonZeros);
6748       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6749                                  Op.getOperand(Idx));
6750       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6751     }
6752     return SDValue();
6753   }
6754
6755   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6756   if (EVTBits == 8 && NumElems == 16) {
6757     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6758                                         Subtarget, *this);
6759     if (V.getNode()) return V;
6760   }
6761
6762   if (EVTBits == 16 && NumElems == 8) {
6763     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6764                                       Subtarget, *this);
6765     if (V.getNode()) return V;
6766   }
6767
6768   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6769   if (EVTBits == 32 && NumElems == 4) {
6770     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6771                                       NumZero, DAG, Subtarget, *this);
6772     if (V.getNode())
6773       return V;
6774   }
6775
6776   // If element VT is == 32 bits, turn it into a number of shuffles.
6777   SmallVector<SDValue, 8> V(NumElems);
6778   if (NumElems == 4 && NumZero > 0) {
6779     for (unsigned i = 0; i < 4; ++i) {
6780       bool isZero = !(NonZeros & (1 << i));
6781       if (isZero)
6782         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6783       else
6784         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6785     }
6786
6787     for (unsigned i = 0; i < 2; ++i) {
6788       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6789         default: break;
6790         case 0:
6791           V[i] = V[i*2];  // Must be a zero vector.
6792           break;
6793         case 1:
6794           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6795           break;
6796         case 2:
6797           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6798           break;
6799         case 3:
6800           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6801           break;
6802       }
6803     }
6804
6805     bool Reverse1 = (NonZeros & 0x3) == 2;
6806     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6807     int MaskVec[] = {
6808       Reverse1 ? 1 : 0,
6809       Reverse1 ? 0 : 1,
6810       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6811       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6812     };
6813     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6814   }
6815
6816   if (Values.size() > 1 && VT.is128BitVector()) {
6817     // Check for a build vector of consecutive loads.
6818     for (unsigned i = 0; i < NumElems; ++i)
6819       V[i] = Op.getOperand(i);
6820
6821     // Check for elements which are consecutive loads.
6822     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6823     if (LD.getNode())
6824       return LD;
6825
6826     // Check for a build vector from mostly shuffle plus few inserting.
6827     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6828     if (Sh.getNode())
6829       return Sh;
6830
6831     // For SSE 4.1, use insertps to put the high elements into the low element.
6832     if (getSubtarget()->hasSSE41()) {
6833       SDValue Result;
6834       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6835         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6836       else
6837         Result = DAG.getUNDEF(VT);
6838
6839       for (unsigned i = 1; i < NumElems; ++i) {
6840         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6841         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6842                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6843       }
6844       return Result;
6845     }
6846
6847     // Otherwise, expand into a number of unpckl*, start by extending each of
6848     // our (non-undef) elements to the full vector width with the element in the
6849     // bottom slot of the vector (which generates no code for SSE).
6850     for (unsigned i = 0; i < NumElems; ++i) {
6851       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6852         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6853       else
6854         V[i] = DAG.getUNDEF(VT);
6855     }
6856
6857     // Next, we iteratively mix elements, e.g. for v4f32:
6858     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6859     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6860     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6861     unsigned EltStride = NumElems >> 1;
6862     while (EltStride != 0) {
6863       for (unsigned i = 0; i < EltStride; ++i) {
6864         // If V[i+EltStride] is undef and this is the first round of mixing,
6865         // then it is safe to just drop this shuffle: V[i] is already in the
6866         // right place, the one element (since it's the first round) being
6867         // inserted as undef can be dropped.  This isn't safe for successive
6868         // rounds because they will permute elements within both vectors.
6869         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6870             EltStride == NumElems/2)
6871           continue;
6872
6873         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6874       }
6875       EltStride >>= 1;
6876     }
6877     return V[0];
6878   }
6879   return SDValue();
6880 }
6881
6882 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6883 // to create 256-bit vectors from two other 128-bit ones.
6884 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6885   SDLoc dl(Op);
6886   MVT ResVT = Op.getSimpleValueType();
6887
6888   assert((ResVT.is256BitVector() ||
6889           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6890
6891   SDValue V1 = Op.getOperand(0);
6892   SDValue V2 = Op.getOperand(1);
6893   unsigned NumElems = ResVT.getVectorNumElements();
6894   if(ResVT.is256BitVector())
6895     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6896
6897   if (Op.getNumOperands() == 4) {
6898     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6899                                 ResVT.getVectorNumElements()/2);
6900     SDValue V3 = Op.getOperand(2);
6901     SDValue V4 = Op.getOperand(3);
6902     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6903       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6904   }
6905   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6906 }
6907
6908 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6909   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6910   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6911          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6912           Op.getNumOperands() == 4)));
6913
6914   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6915   // from two other 128-bit ones.
6916
6917   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6918   return LowerAVXCONCAT_VECTORS(Op, DAG);
6919 }
6920
6921
6922 //===----------------------------------------------------------------------===//
6923 // Vector shuffle lowering
6924 //
6925 // This is an experimental code path for lowering vector shuffles on x86. It is
6926 // designed to handle arbitrary vector shuffles and blends, gracefully
6927 // degrading performance as necessary. It works hard to recognize idiomatic
6928 // shuffles and lower them to optimal instruction patterns without leaving
6929 // a framework that allows reasonably efficient handling of all vector shuffle
6930 // patterns.
6931 //===----------------------------------------------------------------------===//
6932
6933 /// \brief Tiny helper function to identify a no-op mask.
6934 ///
6935 /// This is a somewhat boring predicate function. It checks whether the mask
6936 /// array input, which is assumed to be a single-input shuffle mask of the kind
6937 /// used by the X86 shuffle instructions (not a fully general
6938 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6939 /// in-place shuffle are 'no-op's.
6940 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6941   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6942     if (Mask[i] != -1 && Mask[i] != i)
6943       return false;
6944   return true;
6945 }
6946
6947 /// \brief Helper function to classify a mask as a single-input mask.
6948 ///
6949 /// This isn't a generic single-input test because in the vector shuffle
6950 /// lowering we canonicalize single inputs to be the first input operand. This
6951 /// means we can more quickly test for a single input by only checking whether
6952 /// an input from the second operand exists. We also assume that the size of
6953 /// mask corresponds to the size of the input vectors which isn't true in the
6954 /// fully general case.
6955 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6956   for (int M : Mask)
6957     if (M >= (int)Mask.size())
6958       return false;
6959   return true;
6960 }
6961
6962 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6963 ///
6964 /// This helper function produces an 8-bit shuffle immediate corresponding to
6965 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6966 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6967 /// example.
6968 ///
6969 /// NB: We rely heavily on "undef" masks preserving the input lane.
6970 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6971                                           SelectionDAG &DAG) {
6972   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6973   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6974   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6975   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6976   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6977
6978   unsigned Imm = 0;
6979   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6980   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6981   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6982   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6983   return DAG.getConstant(Imm, MVT::i8);
6984 }
6985
6986 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6987 ///
6988 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6989 /// support for floating point shuffles but not integer shuffles. These
6990 /// instructions will incur a domain crossing penalty on some chips though so
6991 /// it is better to avoid lowering through this for integer vectors where
6992 /// possible.
6993 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6994                                        const X86Subtarget *Subtarget,
6995                                        SelectionDAG &DAG) {
6996   SDLoc DL(Op);
6997   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6998   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6999   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7000   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7001   ArrayRef<int> Mask = SVOp->getMask();
7002   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7003
7004   if (isSingleInputShuffleMask(Mask)) {
7005     // Straight shuffle of a single input vector. Simulate this by using the
7006     // single input as both of the "inputs" to this instruction..
7007     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7008     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7009                        DAG.getConstant(SHUFPDMask, MVT::i8));
7010   }
7011   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7012   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7013
7014   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7015   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7016                      DAG.getConstant(SHUFPDMask, MVT::i8));
7017 }
7018
7019 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7020 ///
7021 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7022 /// the integer unit to minimize domain crossing penalties. However, for blends
7023 /// it falls back to the floating point shuffle operation with appropriate bit
7024 /// casting.
7025 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7026                                        const X86Subtarget *Subtarget,
7027                                        SelectionDAG &DAG) {
7028   SDLoc DL(Op);
7029   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7030   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7031   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7032   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7033   ArrayRef<int> Mask = SVOp->getMask();
7034   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7035
7036   if (isSingleInputShuffleMask(Mask)) {
7037     // Straight shuffle of a single input vector. For everything from SSE2
7038     // onward this has a single fast instruction with no scary immediates.
7039     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7040     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7041     int WidenedMask[4] = {
7042         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7043         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7044     return DAG.getNode(
7045         ISD::BITCAST, DL, MVT::v2i64,
7046         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7047                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7048   }
7049
7050   // We implement this with SHUFPD which is pretty lame because it will likely
7051   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7052   // However, all the alternatives are still more cycles and newer chips don't
7053   // have this problem. It would be really nice if x86 had better shuffles here.
7054   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7055   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7056   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7057                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7058 }
7059
7060 /// \brief Lower 4-lane 32-bit floating point shuffles.
7061 ///
7062 /// Uses instructions exclusively from the floating point unit to minimize
7063 /// domain crossing penalties, as these are sufficient to implement all v4f32
7064 /// shuffles.
7065 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7066                                        const X86Subtarget *Subtarget,
7067                                        SelectionDAG &DAG) {
7068   SDLoc DL(Op);
7069   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7070   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7071   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7072   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7073   ArrayRef<int> Mask = SVOp->getMask();
7074   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7075
7076   SDValue LowV = V1, HighV = V2;
7077   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7078
7079   int NumV2Elements =
7080       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7081
7082   if (NumV2Elements == 0)
7083     // Straight shuffle of a single input vector. We pass the input vector to
7084     // both operands to simulate this with a SHUFPS.
7085     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7086                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7087
7088   if (NumV2Elements == 1) {
7089     int V2Index =
7090         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7091         Mask.begin();
7092     // Compute the index adjacent to V2Index and in the same half by toggling
7093     // the low bit.
7094     int V2AdjIndex = V2Index ^ 1;
7095
7096     if (Mask[V2AdjIndex] == -1) {
7097       // Handles all the cases where we have a single V2 element and an undef.
7098       // This will only ever happen in the high lanes because we commute the
7099       // vector otherwise.
7100       if (V2Index < 2)
7101         std::swap(LowV, HighV);
7102       NewMask[V2Index] -= 4;
7103     } else {
7104       // Handle the case where the V2 element ends up adjacent to a V1 element.
7105       // To make this work, blend them together as the first step.
7106       int V1Index = V2AdjIndex;
7107       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7108       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7109                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7110
7111       // Now proceed to reconstruct the final blend as we have the necessary
7112       // high or low half formed.
7113       if (V2Index < 2) {
7114         LowV = V2;
7115         HighV = V1;
7116       } else {
7117         HighV = V2;
7118       }
7119       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7120       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7121     }
7122   } else if (NumV2Elements == 2) {
7123     if (Mask[0] < 4 && Mask[1] < 4) {
7124       // Handle the easy case where we have V1 in the low lanes and V2 in the
7125       // high lanes. We never see this reversed because we sort the shuffle.
7126       NewMask[2] -= 4;
7127       NewMask[3] -= 4;
7128     } else {
7129       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7130       // trying to place elements directly, just blend them and set up the final
7131       // shuffle to place them.
7132
7133       // The first two blend mask elements are for V1, the second two are for
7134       // V2.
7135       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7136                           Mask[2] < 4 ? Mask[2] : Mask[3],
7137                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7138                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7139       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7140                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7141
7142       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7143       // a blend.
7144       LowV = HighV = V1;
7145       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7146       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7147       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7148       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7149     }
7150   }
7151   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7152                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7153 }
7154
7155 /// \brief Lower 4-lane i32 vector shuffles.
7156 ///
7157 /// We try to handle these with integer-domain shuffles where we can, but for
7158 /// blends we use the floating point domain blend instructions.
7159 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7160                                        const X86Subtarget *Subtarget,
7161                                        SelectionDAG &DAG) {
7162   SDLoc DL(Op);
7163   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7164   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7165   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7166   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7167   ArrayRef<int> Mask = SVOp->getMask();
7168   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7169
7170   if (isSingleInputShuffleMask(Mask))
7171     // Straight shuffle of a single input vector. For everything from SSE2
7172     // onward this has a single fast instruction with no scary immediates.
7173     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7174                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7175
7176   // We implement this with SHUFPS because it can blend from two vectors.
7177   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7178   // up the inputs, bypassing domain shift penalties that we would encur if we
7179   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7180   // relevant.
7181   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7182                      DAG.getVectorShuffle(
7183                          MVT::v4f32, DL,
7184                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7185                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7186 }
7187
7188 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7189 /// shuffle lowering, and the most complex part.
7190 ///
7191 /// The lowering strategy is to try to form pairs of input lanes which are
7192 /// targeted at the same half of the final vector, and then use a dword shuffle
7193 /// to place them onto the right half, and finally unpack the paired lanes into
7194 /// their final position.
7195 ///
7196 /// The exact breakdown of how to form these dword pairs and align them on the
7197 /// correct sides is really tricky. See the comments within the function for
7198 /// more of the details.
7199 static SDValue lowerV8I16SingleInputVectorShuffle(
7200     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7201     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7202   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7203   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7204   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7205
7206   SmallVector<int, 4> LoInputs;
7207   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7208                [](int M) { return M >= 0; });
7209   std::sort(LoInputs.begin(), LoInputs.end());
7210   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7211   SmallVector<int, 4> HiInputs;
7212   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7213                [](int M) { return M >= 0; });
7214   std::sort(HiInputs.begin(), HiInputs.end());
7215   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7216   int NumLToL =
7217       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7218   int NumHToL = LoInputs.size() - NumLToL;
7219   int NumLToH =
7220       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7221   int NumHToH = HiInputs.size() - NumLToH;
7222   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7223   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7224   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7225   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7226
7227   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7228   // such inputs we can swap two of the dwords across the half mark and end up
7229   // with <=2 inputs to each half in each half. Once there, we can fall through
7230   // to the generic code below. For example:
7231   //
7232   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7233   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7234   //
7235   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7236   // and 2-2.
7237   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7238                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7239     // Compute the index of dword with only one word among the three inputs in
7240     // a half by taking the sum of the half with three inputs and subtracting
7241     // the sum of the actual three inputs. The difference is the remaining
7242     // slot.
7243     int DWordA = (ThreeInputHalfSum -
7244                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7245                  2;
7246     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7247
7248     int PSHUFDMask[] = {0, 1, 2, 3};
7249     PSHUFDMask[DWordA] = DWordB;
7250     PSHUFDMask[DWordB] = DWordA;
7251     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7252                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7253                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7254                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7255
7256     // Adjust the mask to match the new locations of A and B.
7257     for (int &M : Mask)
7258       if (M != -1 && M/2 == DWordA)
7259         M = 2 * DWordB + M % 2;
7260       else if (M != -1 && M/2 == DWordB)
7261         M = 2 * DWordA + M % 2;
7262
7263     // Recurse back into this routine to re-compute state now that this isn't
7264     // a 3 and 1 problem.
7265     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7266                                 Mask);
7267   };
7268   if (NumLToL == 3 && NumHToL == 1)
7269     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7270   else if (NumLToL == 1 && NumHToL == 3)
7271     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7272   else if (NumLToH == 1 && NumHToH == 3)
7273     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7274   else if (NumLToH == 3 && NumHToH == 1)
7275     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7276
7277   // At this point there are at most two inputs to the low and high halves from
7278   // each half. That means the inputs can always be grouped into dwords and
7279   // those dwords can then be moved to the correct half with a dword shuffle.
7280   // We use at most one low and one high word shuffle to collect these paired
7281   // inputs into dwords, and finally a dword shuffle to place them.
7282   int PSHUFLMask[4] = {-1, -1, -1, -1};
7283   int PSHUFHMask[4] = {-1, -1, -1, -1};
7284   int PSHUFDMask[4] = {-1, -1, -1, -1};
7285
7286   // First fix the masks for all the inputs that are staying in their
7287   // original halves. This will then dictate the targets of the cross-half
7288   // shuffles.
7289   auto fixInPlaceInputs = [&PSHUFDMask](
7290       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7291       MutableArrayRef<int> HalfMask, int HalfOffset) {
7292     if (InPlaceInputs.empty())
7293       return;
7294     if (InPlaceInputs.size() == 1) {
7295       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7296           InPlaceInputs[0] - HalfOffset;
7297       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7298       return;
7299     }
7300
7301     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7302     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7303         InPlaceInputs[0] - HalfOffset;
7304     // Put the second input next to the first so that they are packed into
7305     // a dword. We find the adjacent index by toggling the low bit.
7306     int AdjIndex = InPlaceInputs[0] ^ 1;
7307     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7308     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7309     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7310   };
7311   if (!HToLInputs.empty())
7312     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7313   if (!LToHInputs.empty())
7314     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7315
7316   // Now gather the cross-half inputs and place them into a free dword of
7317   // their target half.
7318   // FIXME: This operation could almost certainly be simplified dramatically to
7319   // look more like the 3-1 fixing operation.
7320   auto moveInputsToRightHalf = [&PSHUFDMask](
7321       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7322       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7323       int SourceOffset, int DestOffset) {
7324     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7325       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7326     };
7327     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7328                                                int Word) {
7329       int LowWord = Word & ~1;
7330       int HighWord = Word | 1;
7331       return isWordClobbered(SourceHalfMask, LowWord) ||
7332              isWordClobbered(SourceHalfMask, HighWord);
7333     };
7334
7335     if (IncomingInputs.empty())
7336       return;
7337
7338     if (ExistingInputs.empty()) {
7339       // Map any dwords with inputs from them into the right half.
7340       for (int Input : IncomingInputs) {
7341         // If the source half mask maps over the inputs, turn those into
7342         // swaps and use the swapped lane.
7343         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7344           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7345             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7346                 Input - SourceOffset;
7347             // We have to swap the uses in our half mask in one sweep.
7348             for (int &M : HalfMask)
7349               if (M == SourceHalfMask[Input - SourceOffset])
7350                 M = Input;
7351               else if (M == Input)
7352                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7353           } else {
7354             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7355                        Input - SourceOffset &&
7356                    "Previous placement doesn't match!");
7357           }
7358           // Note that this correctly re-maps both when we do a swap and when
7359           // we observe the other side of the swap above. We rely on that to
7360           // avoid swapping the members of the input list directly.
7361           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7362         }
7363
7364         // Map the input's dword into the correct half.
7365         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7366           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7367         else
7368           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7369                      Input / 2 &&
7370                  "Previous placement doesn't match!");
7371       }
7372
7373       // And just directly shift any other-half mask elements to be same-half
7374       // as we will have mirrored the dword containing the element into the
7375       // same position within that half.
7376       for (int &M : HalfMask)
7377         if (M >= SourceOffset && M < SourceOffset + 4) {
7378           M = M - SourceOffset + DestOffset;
7379           assert(M >= 0 && "This should never wrap below zero!");
7380         }
7381       return;
7382     }
7383
7384     // Ensure we have the input in a viable dword of its current half. This
7385     // is particularly tricky because the original position may be clobbered
7386     // by inputs being moved and *staying* in that half.
7387     if (IncomingInputs.size() == 1) {
7388       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7389         int InputFixed = std::find(std::begin(SourceHalfMask),
7390                                    std::end(SourceHalfMask), -1) -
7391                          std::begin(SourceHalfMask) + SourceOffset;
7392         SourceHalfMask[InputFixed - SourceOffset] =
7393             IncomingInputs[0] - SourceOffset;
7394         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7395                      InputFixed);
7396         IncomingInputs[0] = InputFixed;
7397       }
7398     } else if (IncomingInputs.size() == 2) {
7399       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7400           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7401         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7402         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7403                "Not all dwords can be clobbered!");
7404         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7405         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7406         for (int &M : HalfMask)
7407           if (M == IncomingInputs[0])
7408             M = SourceDWordBase + SourceOffset;
7409           else if (M == IncomingInputs[1])
7410             M = SourceDWordBase + 1 + SourceOffset;
7411         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7412         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7413       }
7414     } else {
7415       llvm_unreachable("Unhandled input size!");
7416     }
7417
7418     // Now hoist the DWord down to the right half.
7419     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7420     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7421     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7422     for (int Input : IncomingInputs)
7423       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7424                    FreeDWord * 2 + Input % 2);
7425   };
7426   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7427                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7428   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7429                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7430
7431   // Now enact all the shuffles we've computed to move the inputs into their
7432   // target half.
7433   if (!isNoopShuffleMask(PSHUFLMask))
7434     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7435                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7436   if (!isNoopShuffleMask(PSHUFHMask))
7437     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7438                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7439   if (!isNoopShuffleMask(PSHUFDMask))
7440     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7441                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7442                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7443                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7444
7445   // At this point, each half should contain all its inputs, and we can then
7446   // just shuffle them into their final position.
7447   assert(std::count_if(LoMask.begin(), LoMask.end(),
7448                        [](int M) { return M >= 4; }) == 0 &&
7449          "Failed to lift all the high half inputs to the low mask!");
7450   assert(std::count_if(HiMask.begin(), HiMask.end(),
7451                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7452          "Failed to lift all the low half inputs to the high mask!");
7453
7454   // Do a half shuffle for the low mask.
7455   if (!isNoopShuffleMask(LoMask))
7456     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7457                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7458
7459   // Do a half shuffle with the high mask after shifting its values down.
7460   for (int &M : HiMask)
7461     if (M >= 0)
7462       M -= 4;
7463   if (!isNoopShuffleMask(HiMask))
7464     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7465                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7466
7467   return V;
7468 }
7469
7470 /// \brief Detect whether the mask pattern should be lowered through
7471 /// interleaving.
7472 ///
7473 /// This essentially tests whether viewing the mask as an interleaving of two
7474 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7475 /// lowering it through interleaving is a significantly better strategy.
7476 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7477   int NumEvenInputs[2] = {0, 0};
7478   int NumOddInputs[2] = {0, 0};
7479   int NumLoInputs[2] = {0, 0};
7480   int NumHiInputs[2] = {0, 0};
7481   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7482     if (Mask[i] < 0)
7483       continue;
7484
7485     int InputIdx = Mask[i] >= Size;
7486
7487     if (i < Size / 2)
7488       ++NumLoInputs[InputIdx];
7489     else
7490       ++NumHiInputs[InputIdx];
7491
7492     if ((i % 2) == 0)
7493       ++NumEvenInputs[InputIdx];
7494     else
7495       ++NumOddInputs[InputIdx];
7496   }
7497
7498   // The minimum number of cross-input results for both the interleaved and
7499   // split cases. If interleaving results in fewer cross-input results, return
7500   // true.
7501   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7502                                     NumEvenInputs[0] + NumOddInputs[1]);
7503   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7504                               NumLoInputs[0] + NumHiInputs[1]);
7505   return InterleavedCrosses < SplitCrosses;
7506 }
7507
7508 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7509 ///
7510 /// This strategy only works when the inputs from each vector fit into a single
7511 /// half of that vector, and generally there are not so many inputs as to leave
7512 /// the in-place shuffles required highly constrained (and thus expensive). It
7513 /// shifts all the inputs into a single side of both input vectors and then
7514 /// uses an unpack to interleave these inputs in a single vector. At that
7515 /// point, we will fall back on the generic single input shuffle lowering.
7516 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7517                                                  SDValue V2,
7518                                                  MutableArrayRef<int> Mask,
7519                                                  const X86Subtarget *Subtarget,
7520                                                  SelectionDAG &DAG) {
7521   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7522   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7523   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7524   for (int i = 0; i < 8; ++i)
7525     if (Mask[i] >= 0 && Mask[i] < 4)
7526       LoV1Inputs.push_back(i);
7527     else if (Mask[i] >= 4 && Mask[i] < 8)
7528       HiV1Inputs.push_back(i);
7529     else if (Mask[i] >= 8 && Mask[i] < 12)
7530       LoV2Inputs.push_back(i);
7531     else if (Mask[i] >= 12)
7532       HiV2Inputs.push_back(i);
7533
7534   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7535   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7536   (void)NumV1Inputs;
7537   (void)NumV2Inputs;
7538   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7539   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7540   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7541
7542   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7543                      HiV1Inputs.size() + HiV2Inputs.size();
7544
7545   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7546                               ArrayRef<int> HiInputs, bool MoveToLo,
7547                               int MaskOffset) {
7548     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7549     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7550     if (BadInputs.empty())
7551       return V;
7552
7553     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7554     int MoveOffset = MoveToLo ? 0 : 4;
7555
7556     if (GoodInputs.empty()) {
7557       for (int BadInput : BadInputs) {
7558         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7559         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7560       }
7561     } else {
7562       if (GoodInputs.size() == 2) {
7563         // If the low inputs are spread across two dwords, pack them into
7564         // a single dword.
7565         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7566             Mask[GoodInputs[0]] - MaskOffset;
7567         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7568             Mask[GoodInputs[1]] - MaskOffset;
7569         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7570         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7571       } else {
7572         // Otherwise pin the low inputs.
7573         for (int GoodInput : GoodInputs)
7574           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7575       }
7576
7577       int MoveMaskIdx =
7578           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7579           std::begin(MoveMask);
7580       assert(MoveMaskIdx >= MoveOffset && "Established above");
7581
7582       if (BadInputs.size() == 2) {
7583         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7584         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7585         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7586             Mask[BadInputs[0]] - MaskOffset;
7587         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7588             Mask[BadInputs[1]] - MaskOffset;
7589         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7590         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7591       } else {
7592         assert(BadInputs.size() == 1 && "All sizes handled");
7593         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7594         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7595       }
7596     }
7597
7598     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7599                                 MoveMask);
7600   };
7601   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7602                         /*MaskOffset*/ 0);
7603   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7604                         /*MaskOffset*/ 8);
7605
7606   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7607   // cross-half traffic in the final shuffle.
7608
7609   // Munge the mask to be a single-input mask after the unpack merges the
7610   // results.
7611   for (int &M : Mask)
7612     if (M != -1)
7613       M = 2 * (M % 4) + (M / 8);
7614
7615   return DAG.getVectorShuffle(
7616       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7617                                   DL, MVT::v8i16, V1, V2),
7618       DAG.getUNDEF(MVT::v8i16), Mask);
7619 }
7620
7621 /// \brief Generic lowering of 8-lane i16 shuffles.
7622 ///
7623 /// This handles both single-input shuffles and combined shuffle/blends with
7624 /// two inputs. The single input shuffles are immediately delegated to
7625 /// a dedicated lowering routine.
7626 ///
7627 /// The blends are lowered in one of three fundamental ways. If there are few
7628 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7629 /// of the input is significantly cheaper when lowered as an interleaving of
7630 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7631 /// halves of the inputs separately (making them have relatively few inputs)
7632 /// and then concatenate them.
7633 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7634                                        const X86Subtarget *Subtarget,
7635                                        SelectionDAG &DAG) {
7636   SDLoc DL(Op);
7637   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7638   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7639   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7640   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7641   ArrayRef<int> OrigMask = SVOp->getMask();
7642   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7643                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7644   MutableArrayRef<int> Mask(MaskStorage);
7645
7646   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7647
7648   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7649   auto isV2 = [](int M) { return M >= 8; };
7650
7651   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7652   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7653
7654   if (NumV2Inputs == 0)
7655     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7656
7657   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7658                             "to be V1-input shuffles.");
7659
7660   if (NumV1Inputs + NumV2Inputs <= 4)
7661     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7662
7663   // Check whether an interleaving lowering is likely to be more efficient.
7664   // This isn't perfect but it is a strong heuristic that tends to work well on
7665   // the kinds of shuffles that show up in practice.
7666   //
7667   // FIXME: Handle 1x, 2x, and 4x interleaving.
7668   if (shouldLowerAsInterleaving(Mask)) {
7669     // FIXME: Figure out whether we should pack these into the low or high
7670     // halves.
7671
7672     int EMask[8], OMask[8];
7673     for (int i = 0; i < 4; ++i) {
7674       EMask[i] = Mask[2*i];
7675       OMask[i] = Mask[2*i + 1];
7676       EMask[i + 4] = -1;
7677       OMask[i + 4] = -1;
7678     }
7679
7680     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7681     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7682
7683     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7684   }
7685
7686   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7687   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7688
7689   for (int i = 0; i < 4; ++i) {
7690     LoBlendMask[i] = Mask[i];
7691     HiBlendMask[i] = Mask[i + 4];
7692   }
7693
7694   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7695   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7696   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7697   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7698
7699   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7700                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7701 }
7702
7703 /// \brief Generic lowering of v16i8 shuffles.
7704 ///
7705 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7706 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7707 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7708 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7709 /// back together.
7710 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7711                                        const X86Subtarget *Subtarget,
7712                                        SelectionDAG &DAG) {
7713   SDLoc DL(Op);
7714   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7715   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7716   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7717   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7718   ArrayRef<int> OrigMask = SVOp->getMask();
7719   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7720   int MaskStorage[16] = {
7721       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7722       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7723       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7724       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7725   MutableArrayRef<int> Mask(MaskStorage);
7726   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7727   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7728
7729   // For single-input shuffles, there are some nicer lowering tricks we can use.
7730   if (isSingleInputShuffleMask(Mask)) {
7731     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7732     // Notably, this handles splat and partial-splat shuffles more efficiently.
7733     // However, it only makes sense if the pre-duplication shuffle simplifies
7734     // things significantly. Currently, this means we need to be able to
7735     // express the pre-duplication shuffle as an i16 shuffle.
7736     //
7737     // FIXME: We should check for other patterns which can be widened into an
7738     // i16 shuffle as well.
7739     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7740       for (int i = 0; i < 16; i += 2) {
7741         if (Mask[i] != Mask[i + 1])
7742           return false;
7743       }
7744       return true;
7745     };
7746     auto tryToWidenViaDuplication = [&]() -> SDValue {
7747       if (!canWidenViaDuplication(Mask))
7748         return SDValue();
7749       SmallVector<int, 4> LoInputs;
7750       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7751                    [](int M) { return M >= 0 && M < 8; });
7752       std::sort(LoInputs.begin(), LoInputs.end());
7753       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7754                      LoInputs.end());
7755       SmallVector<int, 4> HiInputs;
7756       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7757                    [](int M) { return M >= 8; });
7758       std::sort(HiInputs.begin(), HiInputs.end());
7759       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7760                      HiInputs.end());
7761
7762       bool TargetLo = LoInputs.size() >= HiInputs.size();
7763       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7764       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7765
7766       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7767       SmallDenseMap<int, int, 8> LaneMap;
7768       for (int I : InPlaceInputs) {
7769         PreDupI16Shuffle[I/2] = I/2;
7770         LaneMap[I] = I;
7771       }
7772       int j = TargetLo ? 0 : 4, je = j + 4;
7773       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7774         // Check if j is already a shuffle of this input. This happens when
7775         // there are two adjacent bytes after we move the low one.
7776         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7777           // If we haven't yet mapped the input, search for a slot into which
7778           // we can map it.
7779           while (j < je && PreDupI16Shuffle[j] != -1)
7780             ++j;
7781
7782           if (j == je)
7783             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7784             return SDValue();
7785
7786           // Map this input with the i16 shuffle.
7787           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7788         }
7789
7790         // Update the lane map based on the mapping we ended up with.
7791         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7792       }
7793       V1 = DAG.getNode(
7794           ISD::BITCAST, DL, MVT::v16i8,
7795           DAG.getVectorShuffle(MVT::v8i16, DL,
7796                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7797                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7798
7799       // Unpack the bytes to form the i16s that will be shuffled into place.
7800       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7801                        MVT::v16i8, V1, V1);
7802
7803       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7804       for (int i = 0; i < 16; i += 2) {
7805         if (Mask[i] != -1)
7806           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7807         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7808       }
7809       return DAG.getNode(
7810           ISD::BITCAST, DL, MVT::v16i8,
7811           DAG.getVectorShuffle(MVT::v8i16, DL,
7812                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7813                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7814     };
7815     if (SDValue V = tryToWidenViaDuplication())
7816       return V;
7817   }
7818
7819   // Check whether an interleaving lowering is likely to be more efficient.
7820   // This isn't perfect but it is a strong heuristic that tends to work well on
7821   // the kinds of shuffles that show up in practice.
7822   //
7823   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7824   if (shouldLowerAsInterleaving(Mask)) {
7825     // FIXME: Figure out whether we should pack these into the low or high
7826     // halves.
7827
7828     int EMask[16], OMask[16];
7829     for (int i = 0; i < 8; ++i) {
7830       EMask[i] = Mask[2*i];
7831       OMask[i] = Mask[2*i + 1];
7832       EMask[i + 8] = -1;
7833       OMask[i + 8] = -1;
7834     }
7835
7836     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7837     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7838
7839     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7840   }
7841
7842   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7843   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7844   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7845   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7846
7847   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7848                             MutableArrayRef<int> V1HalfBlendMask,
7849                             MutableArrayRef<int> V2HalfBlendMask) {
7850     for (int i = 0; i < 8; ++i)
7851       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7852         V1HalfBlendMask[i] = HalfMask[i];
7853         HalfMask[i] = i;
7854       } else if (HalfMask[i] >= 16) {
7855         V2HalfBlendMask[i] = HalfMask[i] - 16;
7856         HalfMask[i] = i + 8;
7857       }
7858   };
7859   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7860   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7861
7862   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7863
7864   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7865                              MutableArrayRef<int> HiBlendMask) {
7866     SDValue V1, V2;
7867     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7868     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7869     // i16s.
7870     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7871                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7872         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7873                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7874       // Use a mask to drop the high bytes.
7875       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7876       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7877                        DAG.getConstant(0x00FF, MVT::v8i16));
7878
7879       // This will be a single vector shuffle instead of a blend so nuke V2.
7880       V2 = DAG.getUNDEF(MVT::v8i16);
7881
7882       // Squash the masks to point directly into V1.
7883       for (int &M : LoBlendMask)
7884         if (M >= 0)
7885           M /= 2;
7886       for (int &M : HiBlendMask)
7887         if (M >= 0)
7888           M /= 2;
7889     } else {
7890       // Otherwise just unpack the low half of V into V1 and the high half into
7891       // V2 so that we can blend them as i16s.
7892       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7893                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7894       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7895                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7896     }
7897
7898     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7899     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7900     return std::make_pair(BlendedLo, BlendedHi);
7901   };
7902   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7903   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7904   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7905
7906   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7907   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7908
7909   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7910 }
7911
7912 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7913 ///
7914 /// This routine breaks down the specific type of 128-bit shuffle and
7915 /// dispatches to the lowering routines accordingly.
7916 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7917                                         MVT VT, const X86Subtarget *Subtarget,
7918                                         SelectionDAG &DAG) {
7919   switch (VT.SimpleTy) {
7920   case MVT::v2i64:
7921     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7922   case MVT::v2f64:
7923     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7924   case MVT::v4i32:
7925     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7926   case MVT::v4f32:
7927     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7928   case MVT::v8i16:
7929     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7930   case MVT::v16i8:
7931     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7932
7933   default:
7934     llvm_unreachable("Unimplemented!");
7935   }
7936 }
7937
7938 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7939 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7940   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7941     if (Mask[i] + 1 != Mask[i+1])
7942       return false;
7943
7944   return true;
7945 }
7946
7947 /// \brief Top-level lowering for x86 vector shuffles.
7948 ///
7949 /// This handles decomposition, canonicalization, and lowering of all x86
7950 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7951 /// above in helper routines. The canonicalization attempts to widen shuffles
7952 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7953 /// s.t. only one of the two inputs needs to be tested, etc.
7954 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7955                                   SelectionDAG &DAG) {
7956   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7957   ArrayRef<int> Mask = SVOp->getMask();
7958   SDValue V1 = Op.getOperand(0);
7959   SDValue V2 = Op.getOperand(1);
7960   MVT VT = Op.getSimpleValueType();
7961   int NumElements = VT.getVectorNumElements();
7962   SDLoc dl(Op);
7963
7964   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7965
7966   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7967   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7968   if (V1IsUndef && V2IsUndef)
7969     return DAG.getUNDEF(VT);
7970
7971   // When we create a shuffle node we put the UNDEF node to second operand,
7972   // but in some cases the first operand may be transformed to UNDEF.
7973   // In this case we should just commute the node.
7974   if (V1IsUndef)
7975     return DAG.getCommutedVectorShuffle(*SVOp);
7976
7977   // Check for non-undef masks pointing at an undef vector and make the masks
7978   // undef as well. This makes it easier to match the shuffle based solely on
7979   // the mask.
7980   if (V2IsUndef)
7981     for (int M : Mask)
7982       if (M >= NumElements) {
7983         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7984         for (int &M : NewMask)
7985           if (M >= NumElements)
7986             M = -1;
7987         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7988       }
7989
7990   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7991   // lanes but wider integers. We cap this to not form integers larger than i64
7992   // but it might be interesting to form i128 integers to handle flipping the
7993   // low and high halves of AVX 256-bit vectors.
7994   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7995       areAdjacentMasksSequential(Mask)) {
7996     SmallVector<int, 8> NewMask;
7997     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7998       NewMask.push_back(Mask[i] / 2);
7999     MVT NewVT =
8000         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8001                          VT.getVectorNumElements() / 2);
8002     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8003     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8004     return DAG.getNode(ISD::BITCAST, dl, VT,
8005                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8006   }
8007
8008   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8009   for (int M : SVOp->getMask())
8010     if (M < 0)
8011       ++NumUndefElements;
8012     else if (M < NumElements)
8013       ++NumV1Elements;
8014     else
8015       ++NumV2Elements;
8016
8017   // Commute the shuffle as needed such that more elements come from V1 than
8018   // V2. This allows us to match the shuffle pattern strictly on how many
8019   // elements come from V1 without handling the symmetric cases.
8020   if (NumV2Elements > NumV1Elements)
8021     return DAG.getCommutedVectorShuffle(*SVOp);
8022
8023   // When the number of V1 and V2 elements are the same, try to minimize the
8024   // number of uses of V2 in the low half of the vector.
8025   if (NumV1Elements == NumV2Elements) {
8026     int LowV1Elements = 0, LowV2Elements = 0;
8027     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8028       if (M >= NumElements)
8029         ++LowV2Elements;
8030       else if (M >= 0)
8031         ++LowV1Elements;
8032     if (LowV2Elements > LowV1Elements)
8033       return DAG.getCommutedVectorShuffle(*SVOp);
8034   }
8035
8036   // For each vector width, delegate to a specialized lowering routine.
8037   if (VT.getSizeInBits() == 128)
8038     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8039
8040   llvm_unreachable("Unimplemented!");
8041 }
8042
8043
8044 //===----------------------------------------------------------------------===//
8045 // Legacy vector shuffle lowering
8046 //
8047 // This code is the legacy code handling vector shuffles until the above
8048 // replaces its functionality and performance.
8049 //===----------------------------------------------------------------------===//
8050
8051 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8052                         bool hasInt256, unsigned *MaskOut = nullptr) {
8053   MVT EltVT = VT.getVectorElementType();
8054
8055   // There is no blend with immediate in AVX-512.
8056   if (VT.is512BitVector())
8057     return false;
8058
8059   if (!hasSSE41 || EltVT == MVT::i8)
8060     return false;
8061   if (!hasInt256 && VT == MVT::v16i16)
8062     return false;
8063
8064   unsigned MaskValue = 0;
8065   unsigned NumElems = VT.getVectorNumElements();
8066   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8067   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8068   unsigned NumElemsInLane = NumElems / NumLanes;
8069
8070   // Blend for v16i16 should be symetric for the both lanes.
8071   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8072
8073     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8074     int EltIdx = MaskVals[i];
8075
8076     if ((EltIdx < 0 || EltIdx == (int)i) &&
8077         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8078       continue;
8079
8080     if (((unsigned)EltIdx == (i + NumElems)) &&
8081         (SndLaneEltIdx < 0 ||
8082          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8083       MaskValue |= (1 << i);
8084     else
8085       return false;
8086   }
8087
8088   if (MaskOut)
8089     *MaskOut = MaskValue;
8090   return true;
8091 }
8092
8093 // Try to lower a shuffle node into a simple blend instruction.
8094 // This function assumes isBlendMask returns true for this
8095 // SuffleVectorSDNode
8096 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8097                                           unsigned MaskValue,
8098                                           const X86Subtarget *Subtarget,
8099                                           SelectionDAG &DAG) {
8100   MVT VT = SVOp->getSimpleValueType(0);
8101   MVT EltVT = VT.getVectorElementType();
8102   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8103                      Subtarget->hasInt256() && "Trying to lower a "
8104                                                "VECTOR_SHUFFLE to a Blend but "
8105                                                "with the wrong mask"));
8106   SDValue V1 = SVOp->getOperand(0);
8107   SDValue V2 = SVOp->getOperand(1);
8108   SDLoc dl(SVOp);
8109   unsigned NumElems = VT.getVectorNumElements();
8110
8111   // Convert i32 vectors to floating point if it is not AVX2.
8112   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8113   MVT BlendVT = VT;
8114   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8115     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8116                                NumElems);
8117     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8118     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8119   }
8120
8121   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8122                             DAG.getConstant(MaskValue, MVT::i32));
8123   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8124 }
8125
8126 /// In vector type \p VT, return true if the element at index \p InputIdx
8127 /// falls on a different 128-bit lane than \p OutputIdx.
8128 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8129                                      unsigned OutputIdx) {
8130   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8131   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8132 }
8133
8134 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8135 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8136 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8137 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8138 /// zero.
8139 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8140                          SelectionDAG &DAG) {
8141   MVT VT = V1.getSimpleValueType();
8142   assert(VT.is128BitVector() || VT.is256BitVector());
8143
8144   MVT EltVT = VT.getVectorElementType();
8145   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8146   unsigned NumElts = VT.getVectorNumElements();
8147
8148   SmallVector<SDValue, 32> PshufbMask;
8149   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8150     int InputIdx = MaskVals[OutputIdx];
8151     unsigned InputByteIdx;
8152
8153     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8154       InputByteIdx = 0x80;
8155     else {
8156       // Cross lane is not allowed.
8157       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8158         return SDValue();
8159       InputByteIdx = InputIdx * EltSizeInBytes;
8160       // Index is an byte offset within the 128-bit lane.
8161       InputByteIdx &= 0xf;
8162     }
8163
8164     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8165       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8166       if (InputByteIdx != 0x80)
8167         ++InputByteIdx;
8168     }
8169   }
8170
8171   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8172   if (ShufVT != VT)
8173     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8174   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8175                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8176 }
8177
8178 // v8i16 shuffles - Prefer shuffles in the following order:
8179 // 1. [all]   pshuflw, pshufhw, optional move
8180 // 2. [ssse3] 1 x pshufb
8181 // 3. [ssse3] 2 x pshufb + 1 x por
8182 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8183 static SDValue
8184 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8185                          SelectionDAG &DAG) {
8186   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8187   SDValue V1 = SVOp->getOperand(0);
8188   SDValue V2 = SVOp->getOperand(1);
8189   SDLoc dl(SVOp);
8190   SmallVector<int, 8> MaskVals;
8191
8192   // Determine if more than 1 of the words in each of the low and high quadwords
8193   // of the result come from the same quadword of one of the two inputs.  Undef
8194   // mask values count as coming from any quadword, for better codegen.
8195   //
8196   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8197   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8198   unsigned LoQuad[] = { 0, 0, 0, 0 };
8199   unsigned HiQuad[] = { 0, 0, 0, 0 };
8200   // Indices of quads used.
8201   std::bitset<4> InputQuads;
8202   for (unsigned i = 0; i < 8; ++i) {
8203     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8204     int EltIdx = SVOp->getMaskElt(i);
8205     MaskVals.push_back(EltIdx);
8206     if (EltIdx < 0) {
8207       ++Quad[0];
8208       ++Quad[1];
8209       ++Quad[2];
8210       ++Quad[3];
8211       continue;
8212     }
8213     ++Quad[EltIdx / 4];
8214     InputQuads.set(EltIdx / 4);
8215   }
8216
8217   int BestLoQuad = -1;
8218   unsigned MaxQuad = 1;
8219   for (unsigned i = 0; i < 4; ++i) {
8220     if (LoQuad[i] > MaxQuad) {
8221       BestLoQuad = i;
8222       MaxQuad = LoQuad[i];
8223     }
8224   }
8225
8226   int BestHiQuad = -1;
8227   MaxQuad = 1;
8228   for (unsigned i = 0; i < 4; ++i) {
8229     if (HiQuad[i] > MaxQuad) {
8230       BestHiQuad = i;
8231       MaxQuad = HiQuad[i];
8232     }
8233   }
8234
8235   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8236   // of the two input vectors, shuffle them into one input vector so only a
8237   // single pshufb instruction is necessary. If there are more than 2 input
8238   // quads, disable the next transformation since it does not help SSSE3.
8239   bool V1Used = InputQuads[0] || InputQuads[1];
8240   bool V2Used = InputQuads[2] || InputQuads[3];
8241   if (Subtarget->hasSSSE3()) {
8242     if (InputQuads.count() == 2 && V1Used && V2Used) {
8243       BestLoQuad = InputQuads[0] ? 0 : 1;
8244       BestHiQuad = InputQuads[2] ? 2 : 3;
8245     }
8246     if (InputQuads.count() > 2) {
8247       BestLoQuad = -1;
8248       BestHiQuad = -1;
8249     }
8250   }
8251
8252   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8253   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8254   // words from all 4 input quadwords.
8255   SDValue NewV;
8256   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8257     int MaskV[] = {
8258       BestLoQuad < 0 ? 0 : BestLoQuad,
8259       BestHiQuad < 0 ? 1 : BestHiQuad
8260     };
8261     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8262                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8263                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8264     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8265
8266     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8267     // source words for the shuffle, to aid later transformations.
8268     bool AllWordsInNewV = true;
8269     bool InOrder[2] = { true, true };
8270     for (unsigned i = 0; i != 8; ++i) {
8271       int idx = MaskVals[i];
8272       if (idx != (int)i)
8273         InOrder[i/4] = false;
8274       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8275         continue;
8276       AllWordsInNewV = false;
8277       break;
8278     }
8279
8280     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8281     if (AllWordsInNewV) {
8282       for (int i = 0; i != 8; ++i) {
8283         int idx = MaskVals[i];
8284         if (idx < 0)
8285           continue;
8286         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8287         if ((idx != i) && idx < 4)
8288           pshufhw = false;
8289         if ((idx != i) && idx > 3)
8290           pshuflw = false;
8291       }
8292       V1 = NewV;
8293       V2Used = false;
8294       BestLoQuad = 0;
8295       BestHiQuad = 1;
8296     }
8297
8298     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8299     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8300     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8301       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8302       unsigned TargetMask = 0;
8303       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8304                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8305       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8306       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8307                              getShufflePSHUFLWImmediate(SVOp);
8308       V1 = NewV.getOperand(0);
8309       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8310     }
8311   }
8312
8313   // Promote splats to a larger type which usually leads to more efficient code.
8314   // FIXME: Is this true if pshufb is available?
8315   if (SVOp->isSplat())
8316     return PromoteSplat(SVOp, DAG);
8317
8318   // If we have SSSE3, and all words of the result are from 1 input vector,
8319   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8320   // is present, fall back to case 4.
8321   if (Subtarget->hasSSSE3()) {
8322     SmallVector<SDValue,16> pshufbMask;
8323
8324     // If we have elements from both input vectors, set the high bit of the
8325     // shuffle mask element to zero out elements that come from V2 in the V1
8326     // mask, and elements that come from V1 in the V2 mask, so that the two
8327     // results can be OR'd together.
8328     bool TwoInputs = V1Used && V2Used;
8329     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8330     if (!TwoInputs)
8331       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8332
8333     // Calculate the shuffle mask for the second input, shuffle it, and
8334     // OR it with the first shuffled input.
8335     CommuteVectorShuffleMask(MaskVals, 8);
8336     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8337     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8338     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8339   }
8340
8341   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8342   // and update MaskVals with new element order.
8343   std::bitset<8> InOrder;
8344   if (BestLoQuad >= 0) {
8345     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8346     for (int i = 0; i != 4; ++i) {
8347       int idx = MaskVals[i];
8348       if (idx < 0) {
8349         InOrder.set(i);
8350       } else if ((idx / 4) == BestLoQuad) {
8351         MaskV[i] = idx & 3;
8352         InOrder.set(i);
8353       }
8354     }
8355     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8356                                 &MaskV[0]);
8357
8358     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8359       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8360       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8361                                   NewV.getOperand(0),
8362                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8363     }
8364   }
8365
8366   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8367   // and update MaskVals with the new element order.
8368   if (BestHiQuad >= 0) {
8369     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8370     for (unsigned i = 4; i != 8; ++i) {
8371       int idx = MaskVals[i];
8372       if (idx < 0) {
8373         InOrder.set(i);
8374       } else if ((idx / 4) == BestHiQuad) {
8375         MaskV[i] = (idx & 3) + 4;
8376         InOrder.set(i);
8377       }
8378     }
8379     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8380                                 &MaskV[0]);
8381
8382     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8383       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8384       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8385                                   NewV.getOperand(0),
8386                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8387     }
8388   }
8389
8390   // In case BestHi & BestLo were both -1, which means each quadword has a word
8391   // from each of the four input quadwords, calculate the InOrder bitvector now
8392   // before falling through to the insert/extract cleanup.
8393   if (BestLoQuad == -1 && BestHiQuad == -1) {
8394     NewV = V1;
8395     for (int i = 0; i != 8; ++i)
8396       if (MaskVals[i] < 0 || MaskVals[i] == i)
8397         InOrder.set(i);
8398   }
8399
8400   // The other elements are put in the right place using pextrw and pinsrw.
8401   for (unsigned i = 0; i != 8; ++i) {
8402     if (InOrder[i])
8403       continue;
8404     int EltIdx = MaskVals[i];
8405     if (EltIdx < 0)
8406       continue;
8407     SDValue ExtOp = (EltIdx < 8) ?
8408       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8409                   DAG.getIntPtrConstant(EltIdx)) :
8410       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8411                   DAG.getIntPtrConstant(EltIdx - 8));
8412     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8413                        DAG.getIntPtrConstant(i));
8414   }
8415   return NewV;
8416 }
8417
8418 /// \brief v16i16 shuffles
8419 ///
8420 /// FIXME: We only support generation of a single pshufb currently.  We can
8421 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8422 /// well (e.g 2 x pshufb + 1 x por).
8423 static SDValue
8424 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8425   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8426   SDValue V1 = SVOp->getOperand(0);
8427   SDValue V2 = SVOp->getOperand(1);
8428   SDLoc dl(SVOp);
8429
8430   if (V2.getOpcode() != ISD::UNDEF)
8431     return SDValue();
8432
8433   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8434   return getPSHUFB(MaskVals, V1, dl, DAG);
8435 }
8436
8437 // v16i8 shuffles - Prefer shuffles in the following order:
8438 // 1. [ssse3] 1 x pshufb
8439 // 2. [ssse3] 2 x pshufb + 1 x por
8440 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8441 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8442                                         const X86Subtarget* Subtarget,
8443                                         SelectionDAG &DAG) {
8444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8445   SDValue V1 = SVOp->getOperand(0);
8446   SDValue V2 = SVOp->getOperand(1);
8447   SDLoc dl(SVOp);
8448   ArrayRef<int> MaskVals = SVOp->getMask();
8449
8450   // Promote splats to a larger type which usually leads to more efficient code.
8451   // FIXME: Is this true if pshufb is available?
8452   if (SVOp->isSplat())
8453     return PromoteSplat(SVOp, DAG);
8454
8455   // If we have SSSE3, case 1 is generated when all result bytes come from
8456   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8457   // present, fall back to case 3.
8458
8459   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8460   if (Subtarget->hasSSSE3()) {
8461     SmallVector<SDValue,16> pshufbMask;
8462
8463     // If all result elements are from one input vector, then only translate
8464     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8465     //
8466     // Otherwise, we have elements from both input vectors, and must zero out
8467     // elements that come from V2 in the first mask, and V1 in the second mask
8468     // so that we can OR them together.
8469     for (unsigned i = 0; i != 16; ++i) {
8470       int EltIdx = MaskVals[i];
8471       if (EltIdx < 0 || EltIdx >= 16)
8472         EltIdx = 0x80;
8473       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8474     }
8475     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8476                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8477                                  MVT::v16i8, pshufbMask));
8478
8479     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8480     // the 2nd operand if it's undefined or zero.
8481     if (V2.getOpcode() == ISD::UNDEF ||
8482         ISD::isBuildVectorAllZeros(V2.getNode()))
8483       return V1;
8484
8485     // Calculate the shuffle mask for the second input, shuffle it, and
8486     // OR it with the first shuffled input.
8487     pshufbMask.clear();
8488     for (unsigned i = 0; i != 16; ++i) {
8489       int EltIdx = MaskVals[i];
8490       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8491       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8492     }
8493     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8494                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8495                                  MVT::v16i8, pshufbMask));
8496     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8497   }
8498
8499   // No SSSE3 - Calculate in place words and then fix all out of place words
8500   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8501   // the 16 different words that comprise the two doublequadword input vectors.
8502   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8503   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8504   SDValue NewV = V1;
8505   for (int i = 0; i != 8; ++i) {
8506     int Elt0 = MaskVals[i*2];
8507     int Elt1 = MaskVals[i*2+1];
8508
8509     // This word of the result is all undef, skip it.
8510     if (Elt0 < 0 && Elt1 < 0)
8511       continue;
8512
8513     // This word of the result is already in the correct place, skip it.
8514     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8515       continue;
8516
8517     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8518     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8519     SDValue InsElt;
8520
8521     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8522     // using a single extract together, load it and store it.
8523     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8524       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8525                            DAG.getIntPtrConstant(Elt1 / 2));
8526       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8527                         DAG.getIntPtrConstant(i));
8528       continue;
8529     }
8530
8531     // If Elt1 is defined, extract it from the appropriate source.  If the
8532     // source byte is not also odd, shift the extracted word left 8 bits
8533     // otherwise clear the bottom 8 bits if we need to do an or.
8534     if (Elt1 >= 0) {
8535       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8536                            DAG.getIntPtrConstant(Elt1 / 2));
8537       if ((Elt1 & 1) == 0)
8538         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8539                              DAG.getConstant(8,
8540                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8541       else if (Elt0 >= 0)
8542         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8543                              DAG.getConstant(0xFF00, MVT::i16));
8544     }
8545     // If Elt0 is defined, extract it from the appropriate source.  If the
8546     // source byte is not also even, shift the extracted word right 8 bits. If
8547     // Elt1 was also defined, OR the extracted values together before
8548     // inserting them in the result.
8549     if (Elt0 >= 0) {
8550       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8551                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8552       if ((Elt0 & 1) != 0)
8553         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8554                               DAG.getConstant(8,
8555                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8556       else if (Elt1 >= 0)
8557         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8558                              DAG.getConstant(0x00FF, MVT::i16));
8559       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8560                          : InsElt0;
8561     }
8562     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8563                        DAG.getIntPtrConstant(i));
8564   }
8565   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8566 }
8567
8568 // v32i8 shuffles - Translate to VPSHUFB if possible.
8569 static
8570 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8571                                  const X86Subtarget *Subtarget,
8572                                  SelectionDAG &DAG) {
8573   MVT VT = SVOp->getSimpleValueType(0);
8574   SDValue V1 = SVOp->getOperand(0);
8575   SDValue V2 = SVOp->getOperand(1);
8576   SDLoc dl(SVOp);
8577   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8578
8579   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8580   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8581   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8582
8583   // VPSHUFB may be generated if
8584   // (1) one of input vector is undefined or zeroinitializer.
8585   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8586   // And (2) the mask indexes don't cross the 128-bit lane.
8587   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8588       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8589     return SDValue();
8590
8591   if (V1IsAllZero && !V2IsAllZero) {
8592     CommuteVectorShuffleMask(MaskVals, 32);
8593     V1 = V2;
8594   }
8595   return getPSHUFB(MaskVals, V1, dl, DAG);
8596 }
8597
8598 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8599 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8600 /// done when every pair / quad of shuffle mask elements point to elements in
8601 /// the right sequence. e.g.
8602 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8603 static
8604 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8605                                  SelectionDAG &DAG) {
8606   MVT VT = SVOp->getSimpleValueType(0);
8607   SDLoc dl(SVOp);
8608   unsigned NumElems = VT.getVectorNumElements();
8609   MVT NewVT;
8610   unsigned Scale;
8611   switch (VT.SimpleTy) {
8612   default: llvm_unreachable("Unexpected!");
8613   case MVT::v2i64:
8614   case MVT::v2f64:
8615            return SDValue(SVOp, 0);
8616   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8617   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8618   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8619   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8620   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8621   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8622   }
8623
8624   SmallVector<int, 8> MaskVec;
8625   for (unsigned i = 0; i != NumElems; i += Scale) {
8626     int StartIdx = -1;
8627     for (unsigned j = 0; j != Scale; ++j) {
8628       int EltIdx = SVOp->getMaskElt(i+j);
8629       if (EltIdx < 0)
8630         continue;
8631       if (StartIdx < 0)
8632         StartIdx = (EltIdx / Scale);
8633       if (EltIdx != (int)(StartIdx*Scale + j))
8634         return SDValue();
8635     }
8636     MaskVec.push_back(StartIdx);
8637   }
8638
8639   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8640   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8641   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8642 }
8643
8644 /// getVZextMovL - Return a zero-extending vector move low node.
8645 ///
8646 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8647                             SDValue SrcOp, SelectionDAG &DAG,
8648                             const X86Subtarget *Subtarget, SDLoc dl) {
8649   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8650     LoadSDNode *LD = nullptr;
8651     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8652       LD = dyn_cast<LoadSDNode>(SrcOp);
8653     if (!LD) {
8654       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8655       // instead.
8656       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8657       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8658           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8659           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8660           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8661         // PR2108
8662         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8663         return DAG.getNode(ISD::BITCAST, dl, VT,
8664                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8665                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8666                                                    OpVT,
8667                                                    SrcOp.getOperand(0)
8668                                                           .getOperand(0))));
8669       }
8670     }
8671   }
8672
8673   return DAG.getNode(ISD::BITCAST, dl, VT,
8674                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8675                                  DAG.getNode(ISD::BITCAST, dl,
8676                                              OpVT, SrcOp)));
8677 }
8678
8679 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8680 /// which could not be matched by any known target speficic shuffle
8681 static SDValue
8682 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8683
8684   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8685   if (NewOp.getNode())
8686     return NewOp;
8687
8688   MVT VT = SVOp->getSimpleValueType(0);
8689
8690   unsigned NumElems = VT.getVectorNumElements();
8691   unsigned NumLaneElems = NumElems / 2;
8692
8693   SDLoc dl(SVOp);
8694   MVT EltVT = VT.getVectorElementType();
8695   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8696   SDValue Output[2];
8697
8698   SmallVector<int, 16> Mask;
8699   for (unsigned l = 0; l < 2; ++l) {
8700     // Build a shuffle mask for the output, discovering on the fly which
8701     // input vectors to use as shuffle operands (recorded in InputUsed).
8702     // If building a suitable shuffle vector proves too hard, then bail
8703     // out with UseBuildVector set.
8704     bool UseBuildVector = false;
8705     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8706     unsigned LaneStart = l * NumLaneElems;
8707     for (unsigned i = 0; i != NumLaneElems; ++i) {
8708       // The mask element.  This indexes into the input.
8709       int Idx = SVOp->getMaskElt(i+LaneStart);
8710       if (Idx < 0) {
8711         // the mask element does not index into any input vector.
8712         Mask.push_back(-1);
8713         continue;
8714       }
8715
8716       // The input vector this mask element indexes into.
8717       int Input = Idx / NumLaneElems;
8718
8719       // Turn the index into an offset from the start of the input vector.
8720       Idx -= Input * NumLaneElems;
8721
8722       // Find or create a shuffle vector operand to hold this input.
8723       unsigned OpNo;
8724       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8725         if (InputUsed[OpNo] == Input)
8726           // This input vector is already an operand.
8727           break;
8728         if (InputUsed[OpNo] < 0) {
8729           // Create a new operand for this input vector.
8730           InputUsed[OpNo] = Input;
8731           break;
8732         }
8733       }
8734
8735       if (OpNo >= array_lengthof(InputUsed)) {
8736         // More than two input vectors used!  Give up on trying to create a
8737         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8738         UseBuildVector = true;
8739         break;
8740       }
8741
8742       // Add the mask index for the new shuffle vector.
8743       Mask.push_back(Idx + OpNo * NumLaneElems);
8744     }
8745
8746     if (UseBuildVector) {
8747       SmallVector<SDValue, 16> SVOps;
8748       for (unsigned i = 0; i != NumLaneElems; ++i) {
8749         // The mask element.  This indexes into the input.
8750         int Idx = SVOp->getMaskElt(i+LaneStart);
8751         if (Idx < 0) {
8752           SVOps.push_back(DAG.getUNDEF(EltVT));
8753           continue;
8754         }
8755
8756         // The input vector this mask element indexes into.
8757         int Input = Idx / NumElems;
8758
8759         // Turn the index into an offset from the start of the input vector.
8760         Idx -= Input * NumElems;
8761
8762         // Extract the vector element by hand.
8763         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8764                                     SVOp->getOperand(Input),
8765                                     DAG.getIntPtrConstant(Idx)));
8766       }
8767
8768       // Construct the output using a BUILD_VECTOR.
8769       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8770     } else if (InputUsed[0] < 0) {
8771       // No input vectors were used! The result is undefined.
8772       Output[l] = DAG.getUNDEF(NVT);
8773     } else {
8774       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8775                                         (InputUsed[0] % 2) * NumLaneElems,
8776                                         DAG, dl);
8777       // If only one input was used, use an undefined vector for the other.
8778       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8779         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8780                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8781       // At least one input vector was used. Create a new shuffle vector.
8782       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8783     }
8784
8785     Mask.clear();
8786   }
8787
8788   // Concatenate the result back
8789   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8790 }
8791
8792 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8793 /// 4 elements, and match them with several different shuffle types.
8794 static SDValue
8795 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8796   SDValue V1 = SVOp->getOperand(0);
8797   SDValue V2 = SVOp->getOperand(1);
8798   SDLoc dl(SVOp);
8799   MVT VT = SVOp->getSimpleValueType(0);
8800
8801   assert(VT.is128BitVector() && "Unsupported vector size");
8802
8803   std::pair<int, int> Locs[4];
8804   int Mask1[] = { -1, -1, -1, -1 };
8805   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8806
8807   unsigned NumHi = 0;
8808   unsigned NumLo = 0;
8809   for (unsigned i = 0; i != 4; ++i) {
8810     int Idx = PermMask[i];
8811     if (Idx < 0) {
8812       Locs[i] = std::make_pair(-1, -1);
8813     } else {
8814       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8815       if (Idx < 4) {
8816         Locs[i] = std::make_pair(0, NumLo);
8817         Mask1[NumLo] = Idx;
8818         NumLo++;
8819       } else {
8820         Locs[i] = std::make_pair(1, NumHi);
8821         if (2+NumHi < 4)
8822           Mask1[2+NumHi] = Idx;
8823         NumHi++;
8824       }
8825     }
8826   }
8827
8828   if (NumLo <= 2 && NumHi <= 2) {
8829     // If no more than two elements come from either vector. This can be
8830     // implemented with two shuffles. First shuffle gather the elements.
8831     // The second shuffle, which takes the first shuffle as both of its
8832     // vector operands, put the elements into the right order.
8833     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8834
8835     int Mask2[] = { -1, -1, -1, -1 };
8836
8837     for (unsigned i = 0; i != 4; ++i)
8838       if (Locs[i].first != -1) {
8839         unsigned Idx = (i < 2) ? 0 : 4;
8840         Idx += Locs[i].first * 2 + Locs[i].second;
8841         Mask2[i] = Idx;
8842       }
8843
8844     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8845   }
8846
8847   if (NumLo == 3 || NumHi == 3) {
8848     // Otherwise, we must have three elements from one vector, call it X, and
8849     // one element from the other, call it Y.  First, use a shufps to build an
8850     // intermediate vector with the one element from Y and the element from X
8851     // that will be in the same half in the final destination (the indexes don't
8852     // matter). Then, use a shufps to build the final vector, taking the half
8853     // containing the element from Y from the intermediate, and the other half
8854     // from X.
8855     if (NumHi == 3) {
8856       // Normalize it so the 3 elements come from V1.
8857       CommuteVectorShuffleMask(PermMask, 4);
8858       std::swap(V1, V2);
8859     }
8860
8861     // Find the element from V2.
8862     unsigned HiIndex;
8863     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8864       int Val = PermMask[HiIndex];
8865       if (Val < 0)
8866         continue;
8867       if (Val >= 4)
8868         break;
8869     }
8870
8871     Mask1[0] = PermMask[HiIndex];
8872     Mask1[1] = -1;
8873     Mask1[2] = PermMask[HiIndex^1];
8874     Mask1[3] = -1;
8875     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8876
8877     if (HiIndex >= 2) {
8878       Mask1[0] = PermMask[0];
8879       Mask1[1] = PermMask[1];
8880       Mask1[2] = HiIndex & 1 ? 6 : 4;
8881       Mask1[3] = HiIndex & 1 ? 4 : 6;
8882       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8883     }
8884
8885     Mask1[0] = HiIndex & 1 ? 2 : 0;
8886     Mask1[1] = HiIndex & 1 ? 0 : 2;
8887     Mask1[2] = PermMask[2];
8888     Mask1[3] = PermMask[3];
8889     if (Mask1[2] >= 0)
8890       Mask1[2] += 4;
8891     if (Mask1[3] >= 0)
8892       Mask1[3] += 4;
8893     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8894   }
8895
8896   // Break it into (shuffle shuffle_hi, shuffle_lo).
8897   int LoMask[] = { -1, -1, -1, -1 };
8898   int HiMask[] = { -1, -1, -1, -1 };
8899
8900   int *MaskPtr = LoMask;
8901   unsigned MaskIdx = 0;
8902   unsigned LoIdx = 0;
8903   unsigned HiIdx = 2;
8904   for (unsigned i = 0; i != 4; ++i) {
8905     if (i == 2) {
8906       MaskPtr = HiMask;
8907       MaskIdx = 1;
8908       LoIdx = 0;
8909       HiIdx = 2;
8910     }
8911     int Idx = PermMask[i];
8912     if (Idx < 0) {
8913       Locs[i] = std::make_pair(-1, -1);
8914     } else if (Idx < 4) {
8915       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8916       MaskPtr[LoIdx] = Idx;
8917       LoIdx++;
8918     } else {
8919       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8920       MaskPtr[HiIdx] = Idx;
8921       HiIdx++;
8922     }
8923   }
8924
8925   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8926   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8927   int MaskOps[] = { -1, -1, -1, -1 };
8928   for (unsigned i = 0; i != 4; ++i)
8929     if (Locs[i].first != -1)
8930       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8931   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8932 }
8933
8934 static bool MayFoldVectorLoad(SDValue V) {
8935   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8936     V = V.getOperand(0);
8937
8938   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8939     V = V.getOperand(0);
8940   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8941       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8942     // BUILD_VECTOR (load), undef
8943     V = V.getOperand(0);
8944
8945   return MayFoldLoad(V);
8946 }
8947
8948 static
8949 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8950   MVT VT = Op.getSimpleValueType();
8951
8952   // Canonizalize to v2f64.
8953   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8954   return DAG.getNode(ISD::BITCAST, dl, VT,
8955                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8956                                           V1, DAG));
8957 }
8958
8959 static
8960 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8961                         bool HasSSE2) {
8962   SDValue V1 = Op.getOperand(0);
8963   SDValue V2 = Op.getOperand(1);
8964   MVT VT = Op.getSimpleValueType();
8965
8966   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8967
8968   if (HasSSE2 && VT == MVT::v2f64)
8969     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8970
8971   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8972   return DAG.getNode(ISD::BITCAST, dl, VT,
8973                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8974                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8975                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8976 }
8977
8978 static
8979 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8980   SDValue V1 = Op.getOperand(0);
8981   SDValue V2 = Op.getOperand(1);
8982   MVT VT = Op.getSimpleValueType();
8983
8984   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8985          "unsupported shuffle type");
8986
8987   if (V2.getOpcode() == ISD::UNDEF)
8988     V2 = V1;
8989
8990   // v4i32 or v4f32
8991   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8992 }
8993
8994 static
8995 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8996   SDValue V1 = Op.getOperand(0);
8997   SDValue V2 = Op.getOperand(1);
8998   MVT VT = Op.getSimpleValueType();
8999   unsigned NumElems = VT.getVectorNumElements();
9000
9001   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9002   // operand of these instructions is only memory, so check if there's a
9003   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9004   // same masks.
9005   bool CanFoldLoad = false;
9006
9007   // Trivial case, when V2 comes from a load.
9008   if (MayFoldVectorLoad(V2))
9009     CanFoldLoad = true;
9010
9011   // When V1 is a load, it can be folded later into a store in isel, example:
9012   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9013   //    turns into:
9014   //  (MOVLPSmr addr:$src1, VR128:$src2)
9015   // So, recognize this potential and also use MOVLPS or MOVLPD
9016   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9017     CanFoldLoad = true;
9018
9019   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9020   if (CanFoldLoad) {
9021     if (HasSSE2 && NumElems == 2)
9022       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9023
9024     if (NumElems == 4)
9025       // If we don't care about the second element, proceed to use movss.
9026       if (SVOp->getMaskElt(1) != -1)
9027         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9028   }
9029
9030   // movl and movlp will both match v2i64, but v2i64 is never matched by
9031   // movl earlier because we make it strict to avoid messing with the movlp load
9032   // folding logic (see the code above getMOVLP call). Match it here then,
9033   // this is horrible, but will stay like this until we move all shuffle
9034   // matching to x86 specific nodes. Note that for the 1st condition all
9035   // types are matched with movsd.
9036   if (HasSSE2) {
9037     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9038     // as to remove this logic from here, as much as possible
9039     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9040       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9041     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9042   }
9043
9044   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9045
9046   // Invert the operand order and use SHUFPS to match it.
9047   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9048                               getShuffleSHUFImmediate(SVOp), DAG);
9049 }
9050
9051 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9052                                          SelectionDAG &DAG) {
9053   SDLoc dl(Load);
9054   MVT VT = Load->getSimpleValueType(0);
9055   MVT EVT = VT.getVectorElementType();
9056   SDValue Addr = Load->getOperand(1);
9057   SDValue NewAddr = DAG.getNode(
9058       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9059       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9060
9061   SDValue NewLoad =
9062       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9063                   DAG.getMachineFunction().getMachineMemOperand(
9064                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9065   return NewLoad;
9066 }
9067
9068 // It is only safe to call this function if isINSERTPSMask is true for
9069 // this shufflevector mask.
9070 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9071                            SelectionDAG &DAG) {
9072   // Generate an insertps instruction when inserting an f32 from memory onto a
9073   // v4f32 or when copying a member from one v4f32 to another.
9074   // We also use it for transferring i32 from one register to another,
9075   // since it simply copies the same bits.
9076   // If we're transferring an i32 from memory to a specific element in a
9077   // register, we output a generic DAG that will match the PINSRD
9078   // instruction.
9079   MVT VT = SVOp->getSimpleValueType(0);
9080   MVT EVT = VT.getVectorElementType();
9081   SDValue V1 = SVOp->getOperand(0);
9082   SDValue V2 = SVOp->getOperand(1);
9083   auto Mask = SVOp->getMask();
9084   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9085          "unsupported vector type for insertps/pinsrd");
9086
9087   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9088   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9089   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9090
9091   SDValue From;
9092   SDValue To;
9093   unsigned DestIndex;
9094   if (FromV1 == 1) {
9095     From = V1;
9096     To = V2;
9097     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9098                 Mask.begin();
9099
9100     // If we have 1 element from each vector, we have to check if we're
9101     // changing V1's element's place. If so, we're done. Otherwise, we
9102     // should assume we're changing V2's element's place and behave
9103     // accordingly.
9104     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9105     assert(DestIndex <= INT32_MAX && "truncated destination index");
9106     if (FromV1 == FromV2 &&
9107         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9108       From = V2;
9109       To = V1;
9110       DestIndex =
9111           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9112     }
9113   } else {
9114     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9115            "More than one element from V1 and from V2, or no elements from one "
9116            "of the vectors. This case should not have returned true from "
9117            "isINSERTPSMask");
9118     From = V2;
9119     To = V1;
9120     DestIndex =
9121         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9122   }
9123
9124   // Get an index into the source vector in the range [0,4) (the mask is
9125   // in the range [0,8) because it can address V1 and V2)
9126   unsigned SrcIndex = Mask[DestIndex] % 4;
9127   if (MayFoldLoad(From)) {
9128     // Trivial case, when From comes from a load and is only used by the
9129     // shuffle. Make it use insertps from the vector that we need from that
9130     // load.
9131     SDValue NewLoad =
9132         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9133     if (!NewLoad.getNode())
9134       return SDValue();
9135
9136     if (EVT == MVT::f32) {
9137       // Create this as a scalar to vector to match the instruction pattern.
9138       SDValue LoadScalarToVector =
9139           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9140       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9141       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9142                          InsertpsMask);
9143     } else { // EVT == MVT::i32
9144       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9145       // instruction, to match the PINSRD instruction, which loads an i32 to a
9146       // certain vector element.
9147       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9148                          DAG.getConstant(DestIndex, MVT::i32));
9149     }
9150   }
9151
9152   // Vector-element-to-vector
9153   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9154   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9155 }
9156
9157 // Reduce a vector shuffle to zext.
9158 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9159                                     SelectionDAG &DAG) {
9160   // PMOVZX is only available from SSE41.
9161   if (!Subtarget->hasSSE41())
9162     return SDValue();
9163
9164   MVT VT = Op.getSimpleValueType();
9165
9166   // Only AVX2 support 256-bit vector integer extending.
9167   if (!Subtarget->hasInt256() && VT.is256BitVector())
9168     return SDValue();
9169
9170   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9171   SDLoc DL(Op);
9172   SDValue V1 = Op.getOperand(0);
9173   SDValue V2 = Op.getOperand(1);
9174   unsigned NumElems = VT.getVectorNumElements();
9175
9176   // Extending is an unary operation and the element type of the source vector
9177   // won't be equal to or larger than i64.
9178   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9179       VT.getVectorElementType() == MVT::i64)
9180     return SDValue();
9181
9182   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9183   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9184   while ((1U << Shift) < NumElems) {
9185     if (SVOp->getMaskElt(1U << Shift) == 1)
9186       break;
9187     Shift += 1;
9188     // The maximal ratio is 8, i.e. from i8 to i64.
9189     if (Shift > 3)
9190       return SDValue();
9191   }
9192
9193   // Check the shuffle mask.
9194   unsigned Mask = (1U << Shift) - 1;
9195   for (unsigned i = 0; i != NumElems; ++i) {
9196     int EltIdx = SVOp->getMaskElt(i);
9197     if ((i & Mask) != 0 && EltIdx != -1)
9198       return SDValue();
9199     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9200       return SDValue();
9201   }
9202
9203   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9204   MVT NeVT = MVT::getIntegerVT(NBits);
9205   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9206
9207   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9208     return SDValue();
9209
9210   // Simplify the operand as it's prepared to be fed into shuffle.
9211   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9212   if (V1.getOpcode() == ISD::BITCAST &&
9213       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9214       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9215       V1.getOperand(0).getOperand(0)
9216         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9217     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9218     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9219     ConstantSDNode *CIdx =
9220       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9221     // If it's foldable, i.e. normal load with single use, we will let code
9222     // selection to fold it. Otherwise, we will short the conversion sequence.
9223     if (CIdx && CIdx->getZExtValue() == 0 &&
9224         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9225       MVT FullVT = V.getSimpleValueType();
9226       MVT V1VT = V1.getSimpleValueType();
9227       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9228         // The "ext_vec_elt" node is wider than the result node.
9229         // In this case we should extract subvector from V.
9230         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9231         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9232         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9233                                         FullVT.getVectorNumElements()/Ratio);
9234         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9235                         DAG.getIntPtrConstant(0));
9236       }
9237       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9238     }
9239   }
9240
9241   return DAG.getNode(ISD::BITCAST, DL, VT,
9242                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9243 }
9244
9245 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9246                                       SelectionDAG &DAG) {
9247   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9248   MVT VT = Op.getSimpleValueType();
9249   SDLoc dl(Op);
9250   SDValue V1 = Op.getOperand(0);
9251   SDValue V2 = Op.getOperand(1);
9252
9253   if (isZeroShuffle(SVOp))
9254     return getZeroVector(VT, Subtarget, DAG, dl);
9255
9256   // Handle splat operations
9257   if (SVOp->isSplat()) {
9258     // Use vbroadcast whenever the splat comes from a foldable load
9259     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9260     if (Broadcast.getNode())
9261       return Broadcast;
9262   }
9263
9264   // Check integer expanding shuffles.
9265   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9266   if (NewOp.getNode())
9267     return NewOp;
9268
9269   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9270   // do it!
9271   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9272       VT == MVT::v32i8) {
9273     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9274     if (NewOp.getNode())
9275       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9276   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9277     // FIXME: Figure out a cleaner way to do this.
9278     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9279       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9280       if (NewOp.getNode()) {
9281         MVT NewVT = NewOp.getSimpleValueType();
9282         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9283                                NewVT, true, false))
9284           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9285                               dl);
9286       }
9287     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9288       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9289       if (NewOp.getNode()) {
9290         MVT NewVT = NewOp.getSimpleValueType();
9291         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9292           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9293                               dl);
9294       }
9295     }
9296   }
9297   return SDValue();
9298 }
9299
9300 SDValue
9301 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9302   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9303   SDValue V1 = Op.getOperand(0);
9304   SDValue V2 = Op.getOperand(1);
9305   MVT VT = Op.getSimpleValueType();
9306   SDLoc dl(Op);
9307   unsigned NumElems = VT.getVectorNumElements();
9308   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9309   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9310   bool V1IsSplat = false;
9311   bool V2IsSplat = false;
9312   bool HasSSE2 = Subtarget->hasSSE2();
9313   bool HasFp256    = Subtarget->hasFp256();
9314   bool HasInt256   = Subtarget->hasInt256();
9315   MachineFunction &MF = DAG.getMachineFunction();
9316   bool OptForSize = MF.getFunction()->getAttributes().
9317     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9318
9319   // Check if we should use the experimental vector shuffle lowering. If so,
9320   // delegate completely to that code path.
9321   if (ExperimentalVectorShuffleLowering)
9322     return lowerVectorShuffle(Op, Subtarget, DAG);
9323
9324   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9325
9326   if (V1IsUndef && V2IsUndef)
9327     return DAG.getUNDEF(VT);
9328
9329   // When we create a shuffle node we put the UNDEF node to second operand,
9330   // but in some cases the first operand may be transformed to UNDEF.
9331   // In this case we should just commute the node.
9332   if (V1IsUndef)
9333     return DAG.getCommutedVectorShuffle(*SVOp);
9334
9335   // Vector shuffle lowering takes 3 steps:
9336   //
9337   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9338   //    narrowing and commutation of operands should be handled.
9339   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9340   //    shuffle nodes.
9341   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9342   //    so the shuffle can be broken into other shuffles and the legalizer can
9343   //    try the lowering again.
9344   //
9345   // The general idea is that no vector_shuffle operation should be left to
9346   // be matched during isel, all of them must be converted to a target specific
9347   // node here.
9348
9349   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9350   // narrowing and commutation of operands should be handled. The actual code
9351   // doesn't include all of those, work in progress...
9352   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9353   if (NewOp.getNode())
9354     return NewOp;
9355
9356   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9357
9358   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9359   // unpckh_undef). Only use pshufd if speed is more important than size.
9360   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9361     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9362   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9363     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9364
9365   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9366       V2IsUndef && MayFoldVectorLoad(V1))
9367     return getMOVDDup(Op, dl, V1, DAG);
9368
9369   if (isMOVHLPS_v_undef_Mask(M, VT))
9370     return getMOVHighToLow(Op, dl, DAG);
9371
9372   // Use to match splats
9373   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9374       (VT == MVT::v2f64 || VT == MVT::v2i64))
9375     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9376
9377   if (isPSHUFDMask(M, VT)) {
9378     // The actual implementation will match the mask in the if above and then
9379     // during isel it can match several different instructions, not only pshufd
9380     // as its name says, sad but true, emulate the behavior for now...
9381     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9382       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9383
9384     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9385
9386     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9387       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9388
9389     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9390       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9391                                   DAG);
9392
9393     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9394                                 TargetMask, DAG);
9395   }
9396
9397   if (isPALIGNRMask(M, VT, Subtarget))
9398     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9399                                 getShufflePALIGNRImmediate(SVOp),
9400                                 DAG);
9401
9402   // Check if this can be converted into a logical shift.
9403   bool isLeft = false;
9404   unsigned ShAmt = 0;
9405   SDValue ShVal;
9406   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9407   if (isShift && ShVal.hasOneUse()) {
9408     // If the shifted value has multiple uses, it may be cheaper to use
9409     // v_set0 + movlhps or movhlps, etc.
9410     MVT EltVT = VT.getVectorElementType();
9411     ShAmt *= EltVT.getSizeInBits();
9412     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9413   }
9414
9415   if (isMOVLMask(M, VT)) {
9416     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9417       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9418     if (!isMOVLPMask(M, VT)) {
9419       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9420         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9421
9422       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9423         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9424     }
9425   }
9426
9427   // FIXME: fold these into legal mask.
9428   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9429     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9430
9431   if (isMOVHLPSMask(M, VT))
9432     return getMOVHighToLow(Op, dl, DAG);
9433
9434   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9435     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9436
9437   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9438     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9439
9440   if (isMOVLPMask(M, VT))
9441     return getMOVLP(Op, dl, DAG, HasSSE2);
9442
9443   if (ShouldXformToMOVHLPS(M, VT) ||
9444       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9445     return DAG.getCommutedVectorShuffle(*SVOp);
9446
9447   if (isShift) {
9448     // No better options. Use a vshldq / vsrldq.
9449     MVT EltVT = VT.getVectorElementType();
9450     ShAmt *= EltVT.getSizeInBits();
9451     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9452   }
9453
9454   bool Commuted = false;
9455   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9456   // 1,1,1,1 -> v8i16 though.
9457   BitVector UndefElements;
9458   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9459     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9460       V1IsSplat = true;
9461   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9462     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9463       V2IsSplat = true;
9464
9465   // Canonicalize the splat or undef, if present, to be on the RHS.
9466   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9467     CommuteVectorShuffleMask(M, NumElems);
9468     std::swap(V1, V2);
9469     std::swap(V1IsSplat, V2IsSplat);
9470     Commuted = true;
9471   }
9472
9473   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9474     // Shuffling low element of v1 into undef, just return v1.
9475     if (V2IsUndef)
9476       return V1;
9477     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9478     // the instruction selector will not match, so get a canonical MOVL with
9479     // swapped operands to undo the commute.
9480     return getMOVL(DAG, dl, VT, V2, V1);
9481   }
9482
9483   if (isUNPCKLMask(M, VT, HasInt256))
9484     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9485
9486   if (isUNPCKHMask(M, VT, HasInt256))
9487     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9488
9489   if (V2IsSplat) {
9490     // Normalize mask so all entries that point to V2 points to its first
9491     // element then try to match unpck{h|l} again. If match, return a
9492     // new vector_shuffle with the corrected mask.p
9493     SmallVector<int, 8> NewMask(M.begin(), M.end());
9494     NormalizeMask(NewMask, NumElems);
9495     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9496       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9497     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9498       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9499   }
9500
9501   if (Commuted) {
9502     // Commute is back and try unpck* again.
9503     // FIXME: this seems wrong.
9504     CommuteVectorShuffleMask(M, NumElems);
9505     std::swap(V1, V2);
9506     std::swap(V1IsSplat, V2IsSplat);
9507
9508     if (isUNPCKLMask(M, VT, HasInt256))
9509       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9510
9511     if (isUNPCKHMask(M, VT, HasInt256))
9512       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9513   }
9514
9515   // Normalize the node to match x86 shuffle ops if needed
9516   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9517     return DAG.getCommutedVectorShuffle(*SVOp);
9518
9519   // The checks below are all present in isShuffleMaskLegal, but they are
9520   // inlined here right now to enable us to directly emit target specific
9521   // nodes, and remove one by one until they don't return Op anymore.
9522
9523   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9524       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9525     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9526       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9527   }
9528
9529   if (isPSHUFHWMask(M, VT, HasInt256))
9530     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9531                                 getShufflePSHUFHWImmediate(SVOp),
9532                                 DAG);
9533
9534   if (isPSHUFLWMask(M, VT, HasInt256))
9535     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9536                                 getShufflePSHUFLWImmediate(SVOp),
9537                                 DAG);
9538
9539   unsigned MaskValue;
9540   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9541                   &MaskValue))
9542     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9543
9544   if (isSHUFPMask(M, VT))
9545     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9546                                 getShuffleSHUFImmediate(SVOp), DAG);
9547
9548   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9549     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9550   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9551     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9552
9553   //===--------------------------------------------------------------------===//
9554   // Generate target specific nodes for 128 or 256-bit shuffles only
9555   // supported in the AVX instruction set.
9556   //
9557
9558   // Handle VMOVDDUPY permutations
9559   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9560     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9561
9562   // Handle VPERMILPS/D* permutations
9563   if (isVPERMILPMask(M, VT)) {
9564     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9565       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9566                                   getShuffleSHUFImmediate(SVOp), DAG);
9567     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9568                                 getShuffleSHUFImmediate(SVOp), DAG);
9569   }
9570
9571   unsigned Idx;
9572   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9573     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9574                               Idx*(NumElems/2), DAG, dl);
9575
9576   // Handle VPERM2F128/VPERM2I128 permutations
9577   if (isVPERM2X128Mask(M, VT, HasFp256))
9578     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9579                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9580
9581   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9582     return getINSERTPS(SVOp, dl, DAG);
9583
9584   unsigned Imm8;
9585   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9586     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9587
9588   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9589       VT.is512BitVector()) {
9590     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9591     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9592     SmallVector<SDValue, 16> permclMask;
9593     for (unsigned i = 0; i != NumElems; ++i) {
9594       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9595     }
9596
9597     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9598     if (V2IsUndef)
9599       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9600       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9601                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9602     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9603                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9604   }
9605
9606   //===--------------------------------------------------------------------===//
9607   // Since no target specific shuffle was selected for this generic one,
9608   // lower it into other known shuffles. FIXME: this isn't true yet, but
9609   // this is the plan.
9610   //
9611
9612   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9613   if (VT == MVT::v8i16) {
9614     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9615     if (NewOp.getNode())
9616       return NewOp;
9617   }
9618
9619   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9620     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9621     if (NewOp.getNode())
9622       return NewOp;
9623   }
9624
9625   if (VT == MVT::v16i8) {
9626     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9627     if (NewOp.getNode())
9628       return NewOp;
9629   }
9630
9631   if (VT == MVT::v32i8) {
9632     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9633     if (NewOp.getNode())
9634       return NewOp;
9635   }
9636
9637   // Handle all 128-bit wide vectors with 4 elements, and match them with
9638   // several different shuffle types.
9639   if (NumElems == 4 && VT.is128BitVector())
9640     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9641
9642   // Handle general 256-bit shuffles
9643   if (VT.is256BitVector())
9644     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9645
9646   return SDValue();
9647 }
9648
9649 // This function assumes its argument is a BUILD_VECTOR of constants or
9650 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9651 // true.
9652 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9653                                     unsigned &MaskValue) {
9654   MaskValue = 0;
9655   unsigned NumElems = BuildVector->getNumOperands();
9656   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9657   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9658   unsigned NumElemsInLane = NumElems / NumLanes;
9659
9660   // Blend for v16i16 should be symetric for the both lanes.
9661   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9662     SDValue EltCond = BuildVector->getOperand(i);
9663     SDValue SndLaneEltCond =
9664         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9665
9666     int Lane1Cond = -1, Lane2Cond = -1;
9667     if (isa<ConstantSDNode>(EltCond))
9668       Lane1Cond = !isZero(EltCond);
9669     if (isa<ConstantSDNode>(SndLaneEltCond))
9670       Lane2Cond = !isZero(SndLaneEltCond);
9671
9672     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9673       // Lane1Cond != 0, means we want the first argument.
9674       // Lane1Cond == 0, means we want the second argument.
9675       // The encoding of this argument is 0 for the first argument, 1
9676       // for the second. Therefore, invert the condition.
9677       MaskValue |= !Lane1Cond << i;
9678     else if (Lane1Cond < 0)
9679       MaskValue |= !Lane2Cond << i;
9680     else
9681       return false;
9682   }
9683   return true;
9684 }
9685
9686 // Try to lower a vselect node into a simple blend instruction.
9687 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9688                                    SelectionDAG &DAG) {
9689   SDValue Cond = Op.getOperand(0);
9690   SDValue LHS = Op.getOperand(1);
9691   SDValue RHS = Op.getOperand(2);
9692   SDLoc dl(Op);
9693   MVT VT = Op.getSimpleValueType();
9694   MVT EltVT = VT.getVectorElementType();
9695   unsigned NumElems = VT.getVectorNumElements();
9696
9697   // There is no blend with immediate in AVX-512.
9698   if (VT.is512BitVector())
9699     return SDValue();
9700
9701   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9702     return SDValue();
9703   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9704     return SDValue();
9705
9706   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9707     return SDValue();
9708
9709   // Check the mask for BLEND and build the value.
9710   unsigned MaskValue = 0;
9711   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9712     return SDValue();
9713
9714   // Convert i32 vectors to floating point if it is not AVX2.
9715   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9716   MVT BlendVT = VT;
9717   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9718     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9719                                NumElems);
9720     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9721     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9722   }
9723
9724   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9725                             DAG.getConstant(MaskValue, MVT::i32));
9726   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9727 }
9728
9729 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9730   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9731   if (BlendOp.getNode())
9732     return BlendOp;
9733
9734   // Some types for vselect were previously set to Expand, not Legal or
9735   // Custom. Return an empty SDValue so we fall-through to Expand, after
9736   // the Custom lowering phase.
9737   MVT VT = Op.getSimpleValueType();
9738   switch (VT.SimpleTy) {
9739   default:
9740     break;
9741   case MVT::v8i16:
9742   case MVT::v16i16:
9743     return SDValue();
9744   }
9745
9746   // We couldn't create a "Blend with immediate" node.
9747   // This node should still be legal, but we'll have to emit a blendv*
9748   // instruction.
9749   return Op;
9750 }
9751
9752 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9753   MVT VT = Op.getSimpleValueType();
9754   SDLoc dl(Op);
9755
9756   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9757     return SDValue();
9758
9759   if (VT.getSizeInBits() == 8) {
9760     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9761                                   Op.getOperand(0), Op.getOperand(1));
9762     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9763                                   DAG.getValueType(VT));
9764     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9765   }
9766
9767   if (VT.getSizeInBits() == 16) {
9768     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9769     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9770     if (Idx == 0)
9771       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9772                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9773                                      DAG.getNode(ISD::BITCAST, dl,
9774                                                  MVT::v4i32,
9775                                                  Op.getOperand(0)),
9776                                      Op.getOperand(1)));
9777     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9778                                   Op.getOperand(0), Op.getOperand(1));
9779     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9780                                   DAG.getValueType(VT));
9781     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9782   }
9783
9784   if (VT == MVT::f32) {
9785     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9786     // the result back to FR32 register. It's only worth matching if the
9787     // result has a single use which is a store or a bitcast to i32.  And in
9788     // the case of a store, it's not worth it if the index is a constant 0,
9789     // because a MOVSSmr can be used instead, which is smaller and faster.
9790     if (!Op.hasOneUse())
9791       return SDValue();
9792     SDNode *User = *Op.getNode()->use_begin();
9793     if ((User->getOpcode() != ISD::STORE ||
9794          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9795           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9796         (User->getOpcode() != ISD::BITCAST ||
9797          User->getValueType(0) != MVT::i32))
9798       return SDValue();
9799     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9800                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9801                                               Op.getOperand(0)),
9802                                               Op.getOperand(1));
9803     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9804   }
9805
9806   if (VT == MVT::i32 || VT == MVT::i64) {
9807     // ExtractPS/pextrq works with constant index.
9808     if (isa<ConstantSDNode>(Op.getOperand(1)))
9809       return Op;
9810   }
9811   return SDValue();
9812 }
9813
9814 /// Extract one bit from mask vector, like v16i1 or v8i1.
9815 /// AVX-512 feature.
9816 SDValue
9817 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9818   SDValue Vec = Op.getOperand(0);
9819   SDLoc dl(Vec);
9820   MVT VecVT = Vec.getSimpleValueType();
9821   SDValue Idx = Op.getOperand(1);
9822   MVT EltVT = Op.getSimpleValueType();
9823
9824   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9825
9826   // variable index can't be handled in mask registers,
9827   // extend vector to VR512
9828   if (!isa<ConstantSDNode>(Idx)) {
9829     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9830     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9831     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9832                               ExtVT.getVectorElementType(), Ext, Idx);
9833     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9834   }
9835
9836   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9837   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9838   unsigned MaxSift = rc->getSize()*8 - 1;
9839   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9840                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9841   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9842                     DAG.getConstant(MaxSift, MVT::i8));
9843   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9844                        DAG.getIntPtrConstant(0));
9845 }
9846
9847 SDValue
9848 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9849                                            SelectionDAG &DAG) const {
9850   SDLoc dl(Op);
9851   SDValue Vec = Op.getOperand(0);
9852   MVT VecVT = Vec.getSimpleValueType();
9853   SDValue Idx = Op.getOperand(1);
9854
9855   if (Op.getSimpleValueType() == MVT::i1)
9856     return ExtractBitFromMaskVector(Op, DAG);
9857
9858   if (!isa<ConstantSDNode>(Idx)) {
9859     if (VecVT.is512BitVector() ||
9860         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9861          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9862
9863       MVT MaskEltVT =
9864         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9865       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9866                                     MaskEltVT.getSizeInBits());
9867
9868       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9869       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9870                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9871                                 Idx, DAG.getConstant(0, getPointerTy()));
9872       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9873       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9874                         Perm, DAG.getConstant(0, getPointerTy()));
9875     }
9876     return SDValue();
9877   }
9878
9879   // If this is a 256-bit vector result, first extract the 128-bit vector and
9880   // then extract the element from the 128-bit vector.
9881   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9882
9883     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9884     // Get the 128-bit vector.
9885     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9886     MVT EltVT = VecVT.getVectorElementType();
9887
9888     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9889
9890     //if (IdxVal >= NumElems/2)
9891     //  IdxVal -= NumElems/2;
9892     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9893     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9894                        DAG.getConstant(IdxVal, MVT::i32));
9895   }
9896
9897   assert(VecVT.is128BitVector() && "Unexpected vector length");
9898
9899   if (Subtarget->hasSSE41()) {
9900     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9901     if (Res.getNode())
9902       return Res;
9903   }
9904
9905   MVT VT = Op.getSimpleValueType();
9906   // TODO: handle v16i8.
9907   if (VT.getSizeInBits() == 16) {
9908     SDValue Vec = Op.getOperand(0);
9909     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9910     if (Idx == 0)
9911       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9912                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9913                                      DAG.getNode(ISD::BITCAST, dl,
9914                                                  MVT::v4i32, Vec),
9915                                      Op.getOperand(1)));
9916     // Transform it so it match pextrw which produces a 32-bit result.
9917     MVT EltVT = MVT::i32;
9918     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9919                                   Op.getOperand(0), Op.getOperand(1));
9920     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9921                                   DAG.getValueType(VT));
9922     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9923   }
9924
9925   if (VT.getSizeInBits() == 32) {
9926     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9927     if (Idx == 0)
9928       return Op;
9929
9930     // SHUFPS the element to the lowest double word, then movss.
9931     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9932     MVT VVT = Op.getOperand(0).getSimpleValueType();
9933     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9934                                        DAG.getUNDEF(VVT), Mask);
9935     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9936                        DAG.getIntPtrConstant(0));
9937   }
9938
9939   if (VT.getSizeInBits() == 64) {
9940     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9941     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9942     //        to match extract_elt for f64.
9943     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9944     if (Idx == 0)
9945       return Op;
9946
9947     // UNPCKHPD the element to the lowest double word, then movsd.
9948     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9949     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9950     int Mask[2] = { 1, -1 };
9951     MVT VVT = Op.getOperand(0).getSimpleValueType();
9952     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9953                                        DAG.getUNDEF(VVT), Mask);
9954     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9955                        DAG.getIntPtrConstant(0));
9956   }
9957
9958   return SDValue();
9959 }
9960
9961 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9962   MVT VT = Op.getSimpleValueType();
9963   MVT EltVT = VT.getVectorElementType();
9964   SDLoc dl(Op);
9965
9966   SDValue N0 = Op.getOperand(0);
9967   SDValue N1 = Op.getOperand(1);
9968   SDValue N2 = Op.getOperand(2);
9969
9970   if (!VT.is128BitVector())
9971     return SDValue();
9972
9973   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9974       isa<ConstantSDNode>(N2)) {
9975     unsigned Opc;
9976     if (VT == MVT::v8i16)
9977       Opc = X86ISD::PINSRW;
9978     else if (VT == MVT::v16i8)
9979       Opc = X86ISD::PINSRB;
9980     else
9981       Opc = X86ISD::PINSRB;
9982
9983     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9984     // argument.
9985     if (N1.getValueType() != MVT::i32)
9986       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9987     if (N2.getValueType() != MVT::i32)
9988       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9989     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9990   }
9991
9992   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9993     // Bits [7:6] of the constant are the source select.  This will always be
9994     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9995     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9996     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9997     // Bits [5:4] of the constant are the destination select.  This is the
9998     //  value of the incoming immediate.
9999     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10000     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10001     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10002     // Create this as a scalar to vector..
10003     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10004     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10005   }
10006
10007   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10008     // PINSR* works with constant index.
10009     return Op;
10010   }
10011   return SDValue();
10012 }
10013
10014 /// Insert one bit to mask vector, like v16i1 or v8i1.
10015 /// AVX-512 feature.
10016 SDValue 
10017 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10018   SDLoc dl(Op);
10019   SDValue Vec = Op.getOperand(0);
10020   SDValue Elt = Op.getOperand(1);
10021   SDValue Idx = Op.getOperand(2);
10022   MVT VecVT = Vec.getSimpleValueType();
10023
10024   if (!isa<ConstantSDNode>(Idx)) {
10025     // Non constant index. Extend source and destination,
10026     // insert element and then truncate the result.
10027     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10028     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10029     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10030       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10031       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10032     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10033   }
10034
10035   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10036   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10037   if (Vec.getOpcode() == ISD::UNDEF)
10038     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10039                        DAG.getConstant(IdxVal, MVT::i8));
10040   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10041   unsigned MaxSift = rc->getSize()*8 - 1;
10042   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10043                     DAG.getConstant(MaxSift, MVT::i8));
10044   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10045                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10046   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10047 }
10048 SDValue
10049 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10050   MVT VT = Op.getSimpleValueType();
10051   MVT EltVT = VT.getVectorElementType();
10052   
10053   if (EltVT == MVT::i1)
10054     return InsertBitToMaskVector(Op, DAG);
10055
10056   SDLoc dl(Op);
10057   SDValue N0 = Op.getOperand(0);
10058   SDValue N1 = Op.getOperand(1);
10059   SDValue N2 = Op.getOperand(2);
10060
10061   // If this is a 256-bit vector result, first extract the 128-bit vector,
10062   // insert the element into the extracted half and then place it back.
10063   if (VT.is256BitVector() || VT.is512BitVector()) {
10064     if (!isa<ConstantSDNode>(N2))
10065       return SDValue();
10066
10067     // Get the desired 128-bit vector half.
10068     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10069     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10070
10071     // Insert the element into the desired half.
10072     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10073     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10074
10075     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10076                     DAG.getConstant(IdxIn128, MVT::i32));
10077
10078     // Insert the changed part back to the 256-bit vector
10079     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10080   }
10081
10082   if (Subtarget->hasSSE41())
10083     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10084
10085   if (EltVT == MVT::i8)
10086     return SDValue();
10087
10088   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10089     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10090     // as its second argument.
10091     if (N1.getValueType() != MVT::i32)
10092       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10093     if (N2.getValueType() != MVT::i32)
10094       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10095     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10096   }
10097   return SDValue();
10098 }
10099
10100 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10101   SDLoc dl(Op);
10102   MVT OpVT = Op.getSimpleValueType();
10103
10104   // If this is a 256-bit vector result, first insert into a 128-bit
10105   // vector and then insert into the 256-bit vector.
10106   if (!OpVT.is128BitVector()) {
10107     // Insert into a 128-bit vector.
10108     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10109     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10110                                  OpVT.getVectorNumElements() / SizeFactor);
10111
10112     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10113
10114     // Insert the 128-bit vector.
10115     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10116   }
10117
10118   if (OpVT == MVT::v1i64 &&
10119       Op.getOperand(0).getValueType() == MVT::i64)
10120     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10121
10122   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10123   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10124   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10125                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10126 }
10127
10128 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10129 // a simple subregister reference or explicit instructions to grab
10130 // upper bits of a vector.
10131 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10132                                       SelectionDAG &DAG) {
10133   SDLoc dl(Op);
10134   SDValue In =  Op.getOperand(0);
10135   SDValue Idx = Op.getOperand(1);
10136   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10137   MVT ResVT   = Op.getSimpleValueType();
10138   MVT InVT    = In.getSimpleValueType();
10139
10140   if (Subtarget->hasFp256()) {
10141     if (ResVT.is128BitVector() &&
10142         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10143         isa<ConstantSDNode>(Idx)) {
10144       return Extract128BitVector(In, IdxVal, DAG, dl);
10145     }
10146     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10147         isa<ConstantSDNode>(Idx)) {
10148       return Extract256BitVector(In, IdxVal, DAG, dl);
10149     }
10150   }
10151   return SDValue();
10152 }
10153
10154 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10155 // simple superregister reference or explicit instructions to insert
10156 // the upper bits of a vector.
10157 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10158                                      SelectionDAG &DAG) {
10159   if (Subtarget->hasFp256()) {
10160     SDLoc dl(Op.getNode());
10161     SDValue Vec = Op.getNode()->getOperand(0);
10162     SDValue SubVec = Op.getNode()->getOperand(1);
10163     SDValue Idx = Op.getNode()->getOperand(2);
10164
10165     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10166          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10167         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10168         isa<ConstantSDNode>(Idx)) {
10169       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10170       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10171     }
10172
10173     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10174         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10175         isa<ConstantSDNode>(Idx)) {
10176       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10177       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10178     }
10179   }
10180   return SDValue();
10181 }
10182
10183 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10184 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10185 // one of the above mentioned nodes. It has to be wrapped because otherwise
10186 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10187 // be used to form addressing mode. These wrapped nodes will be selected
10188 // into MOV32ri.
10189 SDValue
10190 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10191   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10192
10193   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10194   // global base reg.
10195   unsigned char OpFlag = 0;
10196   unsigned WrapperKind = X86ISD::Wrapper;
10197   CodeModel::Model M = DAG.getTarget().getCodeModel();
10198
10199   if (Subtarget->isPICStyleRIPRel() &&
10200       (M == CodeModel::Small || M == CodeModel::Kernel))
10201     WrapperKind = X86ISD::WrapperRIP;
10202   else if (Subtarget->isPICStyleGOT())
10203     OpFlag = X86II::MO_GOTOFF;
10204   else if (Subtarget->isPICStyleStubPIC())
10205     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10206
10207   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10208                                              CP->getAlignment(),
10209                                              CP->getOffset(), OpFlag);
10210   SDLoc DL(CP);
10211   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10212   // With PIC, the address is actually $g + Offset.
10213   if (OpFlag) {
10214     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10215                          DAG.getNode(X86ISD::GlobalBaseReg,
10216                                      SDLoc(), getPointerTy()),
10217                          Result);
10218   }
10219
10220   return Result;
10221 }
10222
10223 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10224   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10225
10226   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10227   // global base reg.
10228   unsigned char OpFlag = 0;
10229   unsigned WrapperKind = X86ISD::Wrapper;
10230   CodeModel::Model M = DAG.getTarget().getCodeModel();
10231
10232   if (Subtarget->isPICStyleRIPRel() &&
10233       (M == CodeModel::Small || M == CodeModel::Kernel))
10234     WrapperKind = X86ISD::WrapperRIP;
10235   else if (Subtarget->isPICStyleGOT())
10236     OpFlag = X86II::MO_GOTOFF;
10237   else if (Subtarget->isPICStyleStubPIC())
10238     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10239
10240   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10241                                           OpFlag);
10242   SDLoc DL(JT);
10243   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10244
10245   // With PIC, the address is actually $g + Offset.
10246   if (OpFlag)
10247     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10248                          DAG.getNode(X86ISD::GlobalBaseReg,
10249                                      SDLoc(), getPointerTy()),
10250                          Result);
10251
10252   return Result;
10253 }
10254
10255 SDValue
10256 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10257   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10258
10259   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10260   // global base reg.
10261   unsigned char OpFlag = 0;
10262   unsigned WrapperKind = X86ISD::Wrapper;
10263   CodeModel::Model M = DAG.getTarget().getCodeModel();
10264
10265   if (Subtarget->isPICStyleRIPRel() &&
10266       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10267     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10268       OpFlag = X86II::MO_GOTPCREL;
10269     WrapperKind = X86ISD::WrapperRIP;
10270   } else if (Subtarget->isPICStyleGOT()) {
10271     OpFlag = X86II::MO_GOT;
10272   } else if (Subtarget->isPICStyleStubPIC()) {
10273     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10274   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10275     OpFlag = X86II::MO_DARWIN_NONLAZY;
10276   }
10277
10278   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10279
10280   SDLoc DL(Op);
10281   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10282
10283   // With PIC, the address is actually $g + Offset.
10284   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10285       !Subtarget->is64Bit()) {
10286     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10287                          DAG.getNode(X86ISD::GlobalBaseReg,
10288                                      SDLoc(), getPointerTy()),
10289                          Result);
10290   }
10291
10292   // For symbols that require a load from a stub to get the address, emit the
10293   // load.
10294   if (isGlobalStubReference(OpFlag))
10295     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10296                          MachinePointerInfo::getGOT(), false, false, false, 0);
10297
10298   return Result;
10299 }
10300
10301 SDValue
10302 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10303   // Create the TargetBlockAddressAddress node.
10304   unsigned char OpFlags =
10305     Subtarget->ClassifyBlockAddressReference();
10306   CodeModel::Model M = DAG.getTarget().getCodeModel();
10307   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10308   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10309   SDLoc dl(Op);
10310   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10311                                              OpFlags);
10312
10313   if (Subtarget->isPICStyleRIPRel() &&
10314       (M == CodeModel::Small || M == CodeModel::Kernel))
10315     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10316   else
10317     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10318
10319   // With PIC, the address is actually $g + Offset.
10320   if (isGlobalRelativeToPICBase(OpFlags)) {
10321     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10322                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10323                          Result);
10324   }
10325
10326   return Result;
10327 }
10328
10329 SDValue
10330 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10331                                       int64_t Offset, SelectionDAG &DAG) const {
10332   // Create the TargetGlobalAddress node, folding in the constant
10333   // offset if it is legal.
10334   unsigned char OpFlags =
10335       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10336   CodeModel::Model M = DAG.getTarget().getCodeModel();
10337   SDValue Result;
10338   if (OpFlags == X86II::MO_NO_FLAG &&
10339       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10340     // A direct static reference to a global.
10341     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10342     Offset = 0;
10343   } else {
10344     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10345   }
10346
10347   if (Subtarget->isPICStyleRIPRel() &&
10348       (M == CodeModel::Small || M == CodeModel::Kernel))
10349     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10350   else
10351     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10352
10353   // With PIC, the address is actually $g + Offset.
10354   if (isGlobalRelativeToPICBase(OpFlags)) {
10355     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10356                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10357                          Result);
10358   }
10359
10360   // For globals that require a load from a stub to get the address, emit the
10361   // load.
10362   if (isGlobalStubReference(OpFlags))
10363     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10364                          MachinePointerInfo::getGOT(), false, false, false, 0);
10365
10366   // If there was a non-zero offset that we didn't fold, create an explicit
10367   // addition for it.
10368   if (Offset != 0)
10369     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10370                          DAG.getConstant(Offset, getPointerTy()));
10371
10372   return Result;
10373 }
10374
10375 SDValue
10376 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10377   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10378   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10379   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10380 }
10381
10382 static SDValue
10383 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10384            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10385            unsigned char OperandFlags, bool LocalDynamic = false) {
10386   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10387   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10388   SDLoc dl(GA);
10389   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10390                                            GA->getValueType(0),
10391                                            GA->getOffset(),
10392                                            OperandFlags);
10393
10394   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10395                                            : X86ISD::TLSADDR;
10396
10397   if (InFlag) {
10398     SDValue Ops[] = { Chain,  TGA, *InFlag };
10399     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10400   } else {
10401     SDValue Ops[]  = { Chain, TGA };
10402     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10403   }
10404
10405   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10406   MFI->setAdjustsStack(true);
10407
10408   SDValue Flag = Chain.getValue(1);
10409   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10410 }
10411
10412 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10413 static SDValue
10414 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10415                                 const EVT PtrVT) {
10416   SDValue InFlag;
10417   SDLoc dl(GA);  // ? function entry point might be better
10418   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10419                                    DAG.getNode(X86ISD::GlobalBaseReg,
10420                                                SDLoc(), PtrVT), InFlag);
10421   InFlag = Chain.getValue(1);
10422
10423   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10424 }
10425
10426 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10427 static SDValue
10428 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10429                                 const EVT PtrVT) {
10430   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10431                     X86::RAX, X86II::MO_TLSGD);
10432 }
10433
10434 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10435                                            SelectionDAG &DAG,
10436                                            const EVT PtrVT,
10437                                            bool is64Bit) {
10438   SDLoc dl(GA);
10439
10440   // Get the start address of the TLS block for this module.
10441   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10442       .getInfo<X86MachineFunctionInfo>();
10443   MFI->incNumLocalDynamicTLSAccesses();
10444
10445   SDValue Base;
10446   if (is64Bit) {
10447     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10448                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10449   } else {
10450     SDValue InFlag;
10451     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10452         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10453     InFlag = Chain.getValue(1);
10454     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10455                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10456   }
10457
10458   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10459   // of Base.
10460
10461   // Build x@dtpoff.
10462   unsigned char OperandFlags = X86II::MO_DTPOFF;
10463   unsigned WrapperKind = X86ISD::Wrapper;
10464   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10465                                            GA->getValueType(0),
10466                                            GA->getOffset(), OperandFlags);
10467   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10468
10469   // Add x@dtpoff with the base.
10470   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10471 }
10472
10473 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10474 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10475                                    const EVT PtrVT, TLSModel::Model model,
10476                                    bool is64Bit, bool isPIC) {
10477   SDLoc dl(GA);
10478
10479   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10480   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10481                                                          is64Bit ? 257 : 256));
10482
10483   SDValue ThreadPointer =
10484       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10485                   MachinePointerInfo(Ptr), false, false, false, 0);
10486
10487   unsigned char OperandFlags = 0;
10488   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10489   // initialexec.
10490   unsigned WrapperKind = X86ISD::Wrapper;
10491   if (model == TLSModel::LocalExec) {
10492     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10493   } else if (model == TLSModel::InitialExec) {
10494     if (is64Bit) {
10495       OperandFlags = X86II::MO_GOTTPOFF;
10496       WrapperKind = X86ISD::WrapperRIP;
10497     } else {
10498       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10499     }
10500   } else {
10501     llvm_unreachable("Unexpected model");
10502   }
10503
10504   // emit "addl x@ntpoff,%eax" (local exec)
10505   // or "addl x@indntpoff,%eax" (initial exec)
10506   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10507   SDValue TGA =
10508       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10509                                  GA->getOffset(), OperandFlags);
10510   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10511
10512   if (model == TLSModel::InitialExec) {
10513     if (isPIC && !is64Bit) {
10514       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10515                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10516                            Offset);
10517     }
10518
10519     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10520                          MachinePointerInfo::getGOT(), false, false, false, 0);
10521   }
10522
10523   // The address of the thread local variable is the add of the thread
10524   // pointer with the offset of the variable.
10525   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10526 }
10527
10528 SDValue
10529 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10530
10531   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10532   const GlobalValue *GV = GA->getGlobal();
10533
10534   if (Subtarget->isTargetELF()) {
10535     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10536
10537     switch (model) {
10538       case TLSModel::GeneralDynamic:
10539         if (Subtarget->is64Bit())
10540           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10541         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10542       case TLSModel::LocalDynamic:
10543         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10544                                            Subtarget->is64Bit());
10545       case TLSModel::InitialExec:
10546       case TLSModel::LocalExec:
10547         return LowerToTLSExecModel(
10548             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10549             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10550     }
10551     llvm_unreachable("Unknown TLS model.");
10552   }
10553
10554   if (Subtarget->isTargetDarwin()) {
10555     // Darwin only has one model of TLS.  Lower to that.
10556     unsigned char OpFlag = 0;
10557     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10558                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10559
10560     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10561     // global base reg.
10562     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10563                  !Subtarget->is64Bit();
10564     if (PIC32)
10565       OpFlag = X86II::MO_TLVP_PIC_BASE;
10566     else
10567       OpFlag = X86II::MO_TLVP;
10568     SDLoc DL(Op);
10569     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10570                                                 GA->getValueType(0),
10571                                                 GA->getOffset(), OpFlag);
10572     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10573
10574     // With PIC32, the address is actually $g + Offset.
10575     if (PIC32)
10576       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10577                            DAG.getNode(X86ISD::GlobalBaseReg,
10578                                        SDLoc(), getPointerTy()),
10579                            Offset);
10580
10581     // Lowering the machine isd will make sure everything is in the right
10582     // location.
10583     SDValue Chain = DAG.getEntryNode();
10584     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10585     SDValue Args[] = { Chain, Offset };
10586     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10587
10588     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10589     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10590     MFI->setAdjustsStack(true);
10591
10592     // And our return value (tls address) is in the standard call return value
10593     // location.
10594     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10595     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10596                               Chain.getValue(1));
10597   }
10598
10599   if (Subtarget->isTargetKnownWindowsMSVC() ||
10600       Subtarget->isTargetWindowsGNU()) {
10601     // Just use the implicit TLS architecture
10602     // Need to generate someting similar to:
10603     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10604     //                                  ; from TEB
10605     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10606     //   mov     rcx, qword [rdx+rcx*8]
10607     //   mov     eax, .tls$:tlsvar
10608     //   [rax+rcx] contains the address
10609     // Windows 64bit: gs:0x58
10610     // Windows 32bit: fs:__tls_array
10611
10612     SDLoc dl(GA);
10613     SDValue Chain = DAG.getEntryNode();
10614
10615     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10616     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10617     // use its literal value of 0x2C.
10618     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10619                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10620                                                              256)
10621                                         : Type::getInt32PtrTy(*DAG.getContext(),
10622                                                               257));
10623
10624     SDValue TlsArray =
10625         Subtarget->is64Bit()
10626             ? DAG.getIntPtrConstant(0x58)
10627             : (Subtarget->isTargetWindowsGNU()
10628                    ? DAG.getIntPtrConstant(0x2C)
10629                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10630
10631     SDValue ThreadPointer =
10632         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10633                     MachinePointerInfo(Ptr), false, false, false, 0);
10634
10635     // Load the _tls_index variable
10636     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10637     if (Subtarget->is64Bit())
10638       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10639                            IDX, MachinePointerInfo(), MVT::i32,
10640                            false, false, 0);
10641     else
10642       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10643                         false, false, false, 0);
10644
10645     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10646                                     getPointerTy());
10647     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10648
10649     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10650     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10651                       false, false, false, 0);
10652
10653     // Get the offset of start of .tls section
10654     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10655                                              GA->getValueType(0),
10656                                              GA->getOffset(), X86II::MO_SECREL);
10657     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10658
10659     // The address of the thread local variable is the add of the thread
10660     // pointer with the offset of the variable.
10661     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10662   }
10663
10664   llvm_unreachable("TLS not implemented for this target.");
10665 }
10666
10667 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10668 /// and take a 2 x i32 value to shift plus a shift amount.
10669 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10670   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10671   MVT VT = Op.getSimpleValueType();
10672   unsigned VTBits = VT.getSizeInBits();
10673   SDLoc dl(Op);
10674   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10675   SDValue ShOpLo = Op.getOperand(0);
10676   SDValue ShOpHi = Op.getOperand(1);
10677   SDValue ShAmt  = Op.getOperand(2);
10678   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10679   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10680   // during isel.
10681   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10682                                   DAG.getConstant(VTBits - 1, MVT::i8));
10683   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10684                                      DAG.getConstant(VTBits - 1, MVT::i8))
10685                        : DAG.getConstant(0, VT);
10686
10687   SDValue Tmp2, Tmp3;
10688   if (Op.getOpcode() == ISD::SHL_PARTS) {
10689     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10690     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10691   } else {
10692     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10693     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10694   }
10695
10696   // If the shift amount is larger or equal than the width of a part we can't
10697   // rely on the results of shld/shrd. Insert a test and select the appropriate
10698   // values for large shift amounts.
10699   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10700                                 DAG.getConstant(VTBits, MVT::i8));
10701   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10702                              AndNode, DAG.getConstant(0, MVT::i8));
10703
10704   SDValue Hi, Lo;
10705   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10706   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10707   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10708
10709   if (Op.getOpcode() == ISD::SHL_PARTS) {
10710     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10711     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10712   } else {
10713     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10714     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10715   }
10716
10717   SDValue Ops[2] = { Lo, Hi };
10718   return DAG.getMergeValues(Ops, dl);
10719 }
10720
10721 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10722                                            SelectionDAG &DAG) const {
10723   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10724
10725   if (SrcVT.isVector())
10726     return SDValue();
10727
10728   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10729          "Unknown SINT_TO_FP to lower!");
10730
10731   // These are really Legal; return the operand so the caller accepts it as
10732   // Legal.
10733   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10734     return Op;
10735   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10736       Subtarget->is64Bit()) {
10737     return Op;
10738   }
10739
10740   SDLoc dl(Op);
10741   unsigned Size = SrcVT.getSizeInBits()/8;
10742   MachineFunction &MF = DAG.getMachineFunction();
10743   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10744   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10745   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10746                                StackSlot,
10747                                MachinePointerInfo::getFixedStack(SSFI),
10748                                false, false, 0);
10749   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10750 }
10751
10752 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10753                                      SDValue StackSlot,
10754                                      SelectionDAG &DAG) const {
10755   // Build the FILD
10756   SDLoc DL(Op);
10757   SDVTList Tys;
10758   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10759   if (useSSE)
10760     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10761   else
10762     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10763
10764   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10765
10766   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10767   MachineMemOperand *MMO;
10768   if (FI) {
10769     int SSFI = FI->getIndex();
10770     MMO =
10771       DAG.getMachineFunction()
10772       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10773                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10774   } else {
10775     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10776     StackSlot = StackSlot.getOperand(1);
10777   }
10778   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10779   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10780                                            X86ISD::FILD, DL,
10781                                            Tys, Ops, SrcVT, MMO);
10782
10783   if (useSSE) {
10784     Chain = Result.getValue(1);
10785     SDValue InFlag = Result.getValue(2);
10786
10787     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10788     // shouldn't be necessary except that RFP cannot be live across
10789     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10790     MachineFunction &MF = DAG.getMachineFunction();
10791     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10792     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10793     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10794     Tys = DAG.getVTList(MVT::Other);
10795     SDValue Ops[] = {
10796       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10797     };
10798     MachineMemOperand *MMO =
10799       DAG.getMachineFunction()
10800       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10801                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10802
10803     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10804                                     Ops, Op.getValueType(), MMO);
10805     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10806                          MachinePointerInfo::getFixedStack(SSFI),
10807                          false, false, false, 0);
10808   }
10809
10810   return Result;
10811 }
10812
10813 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10814 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10815                                                SelectionDAG &DAG) const {
10816   // This algorithm is not obvious. Here it is what we're trying to output:
10817   /*
10818      movq       %rax,  %xmm0
10819      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10820      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10821      #ifdef __SSE3__
10822        haddpd   %xmm0, %xmm0
10823      #else
10824        pshufd   $0x4e, %xmm0, %xmm1
10825        addpd    %xmm1, %xmm0
10826      #endif
10827   */
10828
10829   SDLoc dl(Op);
10830   LLVMContext *Context = DAG.getContext();
10831
10832   // Build some magic constants.
10833   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10834   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10835   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10836
10837   SmallVector<Constant*,2> CV1;
10838   CV1.push_back(
10839     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10840                                       APInt(64, 0x4330000000000000ULL))));
10841   CV1.push_back(
10842     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10843                                       APInt(64, 0x4530000000000000ULL))));
10844   Constant *C1 = ConstantVector::get(CV1);
10845   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10846
10847   // Load the 64-bit value into an XMM register.
10848   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10849                             Op.getOperand(0));
10850   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10851                               MachinePointerInfo::getConstantPool(),
10852                               false, false, false, 16);
10853   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10854                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10855                               CLod0);
10856
10857   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10858                               MachinePointerInfo::getConstantPool(),
10859                               false, false, false, 16);
10860   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10861   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10862   SDValue Result;
10863
10864   if (Subtarget->hasSSE3()) {
10865     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10866     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10867   } else {
10868     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10869     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10870                                            S2F, 0x4E, DAG);
10871     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10872                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10873                          Sub);
10874   }
10875
10876   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10877                      DAG.getIntPtrConstant(0));
10878 }
10879
10880 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10881 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10882                                                SelectionDAG &DAG) const {
10883   SDLoc dl(Op);
10884   // FP constant to bias correct the final result.
10885   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10886                                    MVT::f64);
10887
10888   // Load the 32-bit value into an XMM register.
10889   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10890                              Op.getOperand(0));
10891
10892   // Zero out the upper parts of the register.
10893   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10894
10895   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10896                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10897                      DAG.getIntPtrConstant(0));
10898
10899   // Or the load with the bias.
10900   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10901                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10902                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10903                                                    MVT::v2f64, Load)),
10904                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10905                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10906                                                    MVT::v2f64, Bias)));
10907   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10908                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10909                    DAG.getIntPtrConstant(0));
10910
10911   // Subtract the bias.
10912   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10913
10914   // Handle final rounding.
10915   EVT DestVT = Op.getValueType();
10916
10917   if (DestVT.bitsLT(MVT::f64))
10918     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10919                        DAG.getIntPtrConstant(0));
10920   if (DestVT.bitsGT(MVT::f64))
10921     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10922
10923   // Handle final rounding.
10924   return Sub;
10925 }
10926
10927 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10928                                                SelectionDAG &DAG) const {
10929   SDValue N0 = Op.getOperand(0);
10930   MVT SVT = N0.getSimpleValueType();
10931   SDLoc dl(Op);
10932
10933   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10934           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10935          "Custom UINT_TO_FP is not supported!");
10936
10937   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10938   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10939                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10940 }
10941
10942 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10943                                            SelectionDAG &DAG) const {
10944   SDValue N0 = Op.getOperand(0);
10945   SDLoc dl(Op);
10946
10947   if (Op.getValueType().isVector())
10948     return lowerUINT_TO_FP_vec(Op, DAG);
10949
10950   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10951   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10952   // the optimization here.
10953   if (DAG.SignBitIsZero(N0))
10954     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10955
10956   MVT SrcVT = N0.getSimpleValueType();
10957   MVT DstVT = Op.getSimpleValueType();
10958   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10959     return LowerUINT_TO_FP_i64(Op, DAG);
10960   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10961     return LowerUINT_TO_FP_i32(Op, DAG);
10962   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10963     return SDValue();
10964
10965   // Make a 64-bit buffer, and use it to build an FILD.
10966   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10967   if (SrcVT == MVT::i32) {
10968     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10969     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10970                                      getPointerTy(), StackSlot, WordOff);
10971     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10972                                   StackSlot, MachinePointerInfo(),
10973                                   false, false, 0);
10974     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10975                                   OffsetSlot, MachinePointerInfo(),
10976                                   false, false, 0);
10977     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10978     return Fild;
10979   }
10980
10981   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10982   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10983                                StackSlot, MachinePointerInfo(),
10984                                false, false, 0);
10985   // For i64 source, we need to add the appropriate power of 2 if the input
10986   // was negative.  This is the same as the optimization in
10987   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10988   // we must be careful to do the computation in x87 extended precision, not
10989   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10990   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10991   MachineMemOperand *MMO =
10992     DAG.getMachineFunction()
10993     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10994                           MachineMemOperand::MOLoad, 8, 8);
10995
10996   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10997   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10998   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10999                                          MVT::i64, MMO);
11000
11001   APInt FF(32, 0x5F800000ULL);
11002
11003   // Check whether the sign bit is set.
11004   SDValue SignSet = DAG.getSetCC(dl,
11005                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11006                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11007                                  ISD::SETLT);
11008
11009   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11010   SDValue FudgePtr = DAG.getConstantPool(
11011                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11012                                          getPointerTy());
11013
11014   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11015   SDValue Zero = DAG.getIntPtrConstant(0);
11016   SDValue Four = DAG.getIntPtrConstant(4);
11017   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11018                                Zero, Four);
11019   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11020
11021   // Load the value out, extending it from f32 to f80.
11022   // FIXME: Avoid the extend by constructing the right constant pool?
11023   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11024                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11025                                  MVT::f32, false, false, 4);
11026   // Extend everything to 80 bits to force it to be done on x87.
11027   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11028   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11029 }
11030
11031 std::pair<SDValue,SDValue>
11032 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11033                                     bool IsSigned, bool IsReplace) const {
11034   SDLoc DL(Op);
11035
11036   EVT DstTy = Op.getValueType();
11037
11038   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11039     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11040     DstTy = MVT::i64;
11041   }
11042
11043   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11044          DstTy.getSimpleVT() >= MVT::i16 &&
11045          "Unknown FP_TO_INT to lower!");
11046
11047   // These are really Legal.
11048   if (DstTy == MVT::i32 &&
11049       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11050     return std::make_pair(SDValue(), SDValue());
11051   if (Subtarget->is64Bit() &&
11052       DstTy == MVT::i64 &&
11053       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11054     return std::make_pair(SDValue(), SDValue());
11055
11056   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11057   // stack slot, or into the FTOL runtime function.
11058   MachineFunction &MF = DAG.getMachineFunction();
11059   unsigned MemSize = DstTy.getSizeInBits()/8;
11060   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11061   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11062
11063   unsigned Opc;
11064   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11065     Opc = X86ISD::WIN_FTOL;
11066   else
11067     switch (DstTy.getSimpleVT().SimpleTy) {
11068     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11069     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11070     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11071     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11072     }
11073
11074   SDValue Chain = DAG.getEntryNode();
11075   SDValue Value = Op.getOperand(0);
11076   EVT TheVT = Op.getOperand(0).getValueType();
11077   // FIXME This causes a redundant load/store if the SSE-class value is already
11078   // in memory, such as if it is on the callstack.
11079   if (isScalarFPTypeInSSEReg(TheVT)) {
11080     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11081     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11082                          MachinePointerInfo::getFixedStack(SSFI),
11083                          false, false, 0);
11084     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11085     SDValue Ops[] = {
11086       Chain, StackSlot, DAG.getValueType(TheVT)
11087     };
11088
11089     MachineMemOperand *MMO =
11090       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11091                               MachineMemOperand::MOLoad, MemSize, MemSize);
11092     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11093     Chain = Value.getValue(1);
11094     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11095     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11096   }
11097
11098   MachineMemOperand *MMO =
11099     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11100                             MachineMemOperand::MOStore, MemSize, MemSize);
11101
11102   if (Opc != X86ISD::WIN_FTOL) {
11103     // Build the FP_TO_INT*_IN_MEM
11104     SDValue Ops[] = { Chain, Value, StackSlot };
11105     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11106                                            Ops, DstTy, MMO);
11107     return std::make_pair(FIST, StackSlot);
11108   } else {
11109     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11110       DAG.getVTList(MVT::Other, MVT::Glue),
11111       Chain, Value);
11112     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11113       MVT::i32, ftol.getValue(1));
11114     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11115       MVT::i32, eax.getValue(2));
11116     SDValue Ops[] = { eax, edx };
11117     SDValue pair = IsReplace
11118       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11119       : DAG.getMergeValues(Ops, DL);
11120     return std::make_pair(pair, SDValue());
11121   }
11122 }
11123
11124 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11125                               const X86Subtarget *Subtarget) {
11126   MVT VT = Op->getSimpleValueType(0);
11127   SDValue In = Op->getOperand(0);
11128   MVT InVT = In.getSimpleValueType();
11129   SDLoc dl(Op);
11130
11131   // Optimize vectors in AVX mode:
11132   //
11133   //   v8i16 -> v8i32
11134   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11135   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11136   //   Concat upper and lower parts.
11137   //
11138   //   v4i32 -> v4i64
11139   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11140   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11141   //   Concat upper and lower parts.
11142   //
11143
11144   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11145       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11146       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11147     return SDValue();
11148
11149   if (Subtarget->hasInt256())
11150     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11151
11152   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11153   SDValue Undef = DAG.getUNDEF(InVT);
11154   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11155   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11156   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11157
11158   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11159                              VT.getVectorNumElements()/2);
11160
11161   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11162   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11163
11164   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11165 }
11166
11167 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11168                                         SelectionDAG &DAG) {
11169   MVT VT = Op->getSimpleValueType(0);
11170   SDValue In = Op->getOperand(0);
11171   MVT InVT = In.getSimpleValueType();
11172   SDLoc DL(Op);
11173   unsigned int NumElts = VT.getVectorNumElements();
11174   if (NumElts != 8 && NumElts != 16)
11175     return SDValue();
11176
11177   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11178     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11179
11180   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11182   // Now we have only mask extension
11183   assert(InVT.getVectorElementType() == MVT::i1);
11184   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11185   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11186   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11187   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11188   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11189                            MachinePointerInfo::getConstantPool(),
11190                            false, false, false, Alignment);
11191
11192   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11193   if (VT.is512BitVector())
11194     return Brcst;
11195   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11196 }
11197
11198 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11199                                SelectionDAG &DAG) {
11200   if (Subtarget->hasFp256()) {
11201     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11202     if (Res.getNode())
11203       return Res;
11204   }
11205
11206   return SDValue();
11207 }
11208
11209 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11210                                 SelectionDAG &DAG) {
11211   SDLoc DL(Op);
11212   MVT VT = Op.getSimpleValueType();
11213   SDValue In = Op.getOperand(0);
11214   MVT SVT = In.getSimpleValueType();
11215
11216   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11217     return LowerZERO_EXTEND_AVX512(Op, DAG);
11218
11219   if (Subtarget->hasFp256()) {
11220     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11221     if (Res.getNode())
11222       return Res;
11223   }
11224
11225   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11226          VT.getVectorNumElements() != SVT.getVectorNumElements());
11227   return SDValue();
11228 }
11229
11230 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11231   SDLoc DL(Op);
11232   MVT VT = Op.getSimpleValueType();
11233   SDValue In = Op.getOperand(0);
11234   MVT InVT = In.getSimpleValueType();
11235
11236   if (VT == MVT::i1) {
11237     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11238            "Invalid scalar TRUNCATE operation");
11239     if (InVT == MVT::i32)
11240       return SDValue();
11241     if (InVT.getSizeInBits() == 64)
11242       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11243     else if (InVT.getSizeInBits() < 32)
11244       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11245     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11246   }
11247   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11248          "Invalid TRUNCATE operation");
11249
11250   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11251     if (VT.getVectorElementType().getSizeInBits() >=8)
11252       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11253
11254     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11255     unsigned NumElts = InVT.getVectorNumElements();
11256     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11257     if (InVT.getSizeInBits() < 512) {
11258       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11259       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11260       InVT = ExtVT;
11261     }
11262     
11263     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11264     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11265     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11266     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11267     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11268                            MachinePointerInfo::getConstantPool(),
11269                            false, false, false, Alignment);
11270     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11271     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11272     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11273   }
11274
11275   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11276     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11277     if (Subtarget->hasInt256()) {
11278       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11279       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11280       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11281                                 ShufMask);
11282       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11283                          DAG.getIntPtrConstant(0));
11284     }
11285
11286     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11287                                DAG.getIntPtrConstant(0));
11288     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11289                                DAG.getIntPtrConstant(2));
11290     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11291     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11292     static const int ShufMask[] = {0, 2, 4, 6};
11293     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11294   }
11295
11296   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11297     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11298     if (Subtarget->hasInt256()) {
11299       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11300
11301       SmallVector<SDValue,32> pshufbMask;
11302       for (unsigned i = 0; i < 2; ++i) {
11303         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11304         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11305         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11306         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11307         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11308         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11309         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11310         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11311         for (unsigned j = 0; j < 8; ++j)
11312           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11313       }
11314       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11315       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11316       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11317
11318       static const int ShufMask[] = {0,  2,  -1,  -1};
11319       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11320                                 &ShufMask[0]);
11321       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11322                        DAG.getIntPtrConstant(0));
11323       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11324     }
11325
11326     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11327                                DAG.getIntPtrConstant(0));
11328
11329     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11330                                DAG.getIntPtrConstant(4));
11331
11332     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11333     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11334
11335     // The PSHUFB mask:
11336     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11337                                    -1, -1, -1, -1, -1, -1, -1, -1};
11338
11339     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11340     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11341     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11342
11343     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11344     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11345
11346     // The MOVLHPS Mask:
11347     static const int ShufMask2[] = {0, 1, 4, 5};
11348     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11349     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11350   }
11351
11352   // Handle truncation of V256 to V128 using shuffles.
11353   if (!VT.is128BitVector() || !InVT.is256BitVector())
11354     return SDValue();
11355
11356   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11357
11358   unsigned NumElems = VT.getVectorNumElements();
11359   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11360
11361   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11362   // Prepare truncation shuffle mask
11363   for (unsigned i = 0; i != NumElems; ++i)
11364     MaskVec[i] = i * 2;
11365   SDValue V = DAG.getVectorShuffle(NVT, DL,
11366                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11367                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11368   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11369                      DAG.getIntPtrConstant(0));
11370 }
11371
11372 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11373                                            SelectionDAG &DAG) const {
11374   assert(!Op.getSimpleValueType().isVector());
11375
11376   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11377     /*IsSigned=*/ true, /*IsReplace=*/ false);
11378   SDValue FIST = Vals.first, StackSlot = Vals.second;
11379   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11380   if (!FIST.getNode()) return Op;
11381
11382   if (StackSlot.getNode())
11383     // Load the result.
11384     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11385                        FIST, StackSlot, MachinePointerInfo(),
11386                        false, false, false, 0);
11387
11388   // The node is the result.
11389   return FIST;
11390 }
11391
11392 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11393                                            SelectionDAG &DAG) const {
11394   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11395     /*IsSigned=*/ false, /*IsReplace=*/ false);
11396   SDValue FIST = Vals.first, StackSlot = Vals.second;
11397   assert(FIST.getNode() && "Unexpected failure");
11398
11399   if (StackSlot.getNode())
11400     // Load the result.
11401     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11402                        FIST, StackSlot, MachinePointerInfo(),
11403                        false, false, false, 0);
11404
11405   // The node is the result.
11406   return FIST;
11407 }
11408
11409 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11410   SDLoc DL(Op);
11411   MVT VT = Op.getSimpleValueType();
11412   SDValue In = Op.getOperand(0);
11413   MVT SVT = In.getSimpleValueType();
11414
11415   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11416
11417   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11418                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11419                                  In, DAG.getUNDEF(SVT)));
11420 }
11421
11422 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11423   LLVMContext *Context = DAG.getContext();
11424   SDLoc dl(Op);
11425   MVT VT = Op.getSimpleValueType();
11426   MVT EltVT = VT;
11427   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11428   if (VT.isVector()) {
11429     EltVT = VT.getVectorElementType();
11430     NumElts = VT.getVectorNumElements();
11431   }
11432   Constant *C;
11433   if (EltVT == MVT::f64)
11434     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11435                                           APInt(64, ~(1ULL << 63))));
11436   else
11437     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11438                                           APInt(32, ~(1U << 31))));
11439   C = ConstantVector::getSplat(NumElts, C);
11440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11441   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11442   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11443   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11444                              MachinePointerInfo::getConstantPool(),
11445                              false, false, false, Alignment);
11446   if (VT.isVector()) {
11447     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11448     return DAG.getNode(ISD::BITCAST, dl, VT,
11449                        DAG.getNode(ISD::AND, dl, ANDVT,
11450                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11451                                                Op.getOperand(0)),
11452                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11453   }
11454   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11455 }
11456
11457 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11458   LLVMContext *Context = DAG.getContext();
11459   SDLoc dl(Op);
11460   MVT VT = Op.getSimpleValueType();
11461   MVT EltVT = VT;
11462   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11463   if (VT.isVector()) {
11464     EltVT = VT.getVectorElementType();
11465     NumElts = VT.getVectorNumElements();
11466   }
11467   Constant *C;
11468   if (EltVT == MVT::f64)
11469     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11470                                           APInt(64, 1ULL << 63)));
11471   else
11472     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11473                                           APInt(32, 1U << 31)));
11474   C = ConstantVector::getSplat(NumElts, C);
11475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11476   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11477   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11478   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11479                              MachinePointerInfo::getConstantPool(),
11480                              false, false, false, Alignment);
11481   if (VT.isVector()) {
11482     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11483     return DAG.getNode(ISD::BITCAST, dl, VT,
11484                        DAG.getNode(ISD::XOR, dl, XORVT,
11485                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11486                                                Op.getOperand(0)),
11487                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11488   }
11489
11490   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11491 }
11492
11493 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11495   LLVMContext *Context = DAG.getContext();
11496   SDValue Op0 = Op.getOperand(0);
11497   SDValue Op1 = Op.getOperand(1);
11498   SDLoc dl(Op);
11499   MVT VT = Op.getSimpleValueType();
11500   MVT SrcVT = Op1.getSimpleValueType();
11501
11502   // If second operand is smaller, extend it first.
11503   if (SrcVT.bitsLT(VT)) {
11504     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11505     SrcVT = VT;
11506   }
11507   // And if it is bigger, shrink it first.
11508   if (SrcVT.bitsGT(VT)) {
11509     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11510     SrcVT = VT;
11511   }
11512
11513   // At this point the operands and the result should have the same
11514   // type, and that won't be f80 since that is not custom lowered.
11515
11516   // First get the sign bit of second operand.
11517   SmallVector<Constant*,4> CV;
11518   if (SrcVT == MVT::f64) {
11519     const fltSemantics &Sem = APFloat::IEEEdouble;
11520     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11521     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11522   } else {
11523     const fltSemantics &Sem = APFloat::IEEEsingle;
11524     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11525     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11526     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11527     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11528   }
11529   Constant *C = ConstantVector::get(CV);
11530   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11531   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11532                               MachinePointerInfo::getConstantPool(),
11533                               false, false, false, 16);
11534   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11535
11536   // Shift sign bit right or left if the two operands have different types.
11537   if (SrcVT.bitsGT(VT)) {
11538     // Op0 is MVT::f32, Op1 is MVT::f64.
11539     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11540     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11541                           DAG.getConstant(32, MVT::i32));
11542     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11543     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11544                           DAG.getIntPtrConstant(0));
11545   }
11546
11547   // Clear first operand sign bit.
11548   CV.clear();
11549   if (VT == MVT::f64) {
11550     const fltSemantics &Sem = APFloat::IEEEdouble;
11551     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11552                                                    APInt(64, ~(1ULL << 63)))));
11553     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11554   } else {
11555     const fltSemantics &Sem = APFloat::IEEEsingle;
11556     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11557                                                    APInt(32, ~(1U << 31)))));
11558     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11559     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11560     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11561   }
11562   C = ConstantVector::get(CV);
11563   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11564   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11565                               MachinePointerInfo::getConstantPool(),
11566                               false, false, false, 16);
11567   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11568
11569   // Or the value with the sign bit.
11570   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11571 }
11572
11573 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11574   SDValue N0 = Op.getOperand(0);
11575   SDLoc dl(Op);
11576   MVT VT = Op.getSimpleValueType();
11577
11578   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11579   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11580                                   DAG.getConstant(1, VT));
11581   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11582 }
11583
11584 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11585 //
11586 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11587                                       SelectionDAG &DAG) {
11588   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11589
11590   if (!Subtarget->hasSSE41())
11591     return SDValue();
11592
11593   if (!Op->hasOneUse())
11594     return SDValue();
11595
11596   SDNode *N = Op.getNode();
11597   SDLoc DL(N);
11598
11599   SmallVector<SDValue, 8> Opnds;
11600   DenseMap<SDValue, unsigned> VecInMap;
11601   SmallVector<SDValue, 8> VecIns;
11602   EVT VT = MVT::Other;
11603
11604   // Recognize a special case where a vector is casted into wide integer to
11605   // test all 0s.
11606   Opnds.push_back(N->getOperand(0));
11607   Opnds.push_back(N->getOperand(1));
11608
11609   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11610     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11611     // BFS traverse all OR'd operands.
11612     if (I->getOpcode() == ISD::OR) {
11613       Opnds.push_back(I->getOperand(0));
11614       Opnds.push_back(I->getOperand(1));
11615       // Re-evaluate the number of nodes to be traversed.
11616       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11617       continue;
11618     }
11619
11620     // Quit if a non-EXTRACT_VECTOR_ELT
11621     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11622       return SDValue();
11623
11624     // Quit if without a constant index.
11625     SDValue Idx = I->getOperand(1);
11626     if (!isa<ConstantSDNode>(Idx))
11627       return SDValue();
11628
11629     SDValue ExtractedFromVec = I->getOperand(0);
11630     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11631     if (M == VecInMap.end()) {
11632       VT = ExtractedFromVec.getValueType();
11633       // Quit if not 128/256-bit vector.
11634       if (!VT.is128BitVector() && !VT.is256BitVector())
11635         return SDValue();
11636       // Quit if not the same type.
11637       if (VecInMap.begin() != VecInMap.end() &&
11638           VT != VecInMap.begin()->first.getValueType())
11639         return SDValue();
11640       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11641       VecIns.push_back(ExtractedFromVec);
11642     }
11643     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11644   }
11645
11646   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11647          "Not extracted from 128-/256-bit vector.");
11648
11649   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11650
11651   for (DenseMap<SDValue, unsigned>::const_iterator
11652         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11653     // Quit if not all elements are used.
11654     if (I->second != FullMask)
11655       return SDValue();
11656   }
11657
11658   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11659
11660   // Cast all vectors into TestVT for PTEST.
11661   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11662     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11663
11664   // If more than one full vectors are evaluated, OR them first before PTEST.
11665   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11666     // Each iteration will OR 2 nodes and append the result until there is only
11667     // 1 node left, i.e. the final OR'd value of all vectors.
11668     SDValue LHS = VecIns[Slot];
11669     SDValue RHS = VecIns[Slot + 1];
11670     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11671   }
11672
11673   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11674                      VecIns.back(), VecIns.back());
11675 }
11676
11677 /// \brief return true if \c Op has a use that doesn't just read flags.
11678 static bool hasNonFlagsUse(SDValue Op) {
11679   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11680        ++UI) {
11681     SDNode *User = *UI;
11682     unsigned UOpNo = UI.getOperandNo();
11683     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11684       // Look pass truncate.
11685       UOpNo = User->use_begin().getOperandNo();
11686       User = *User->use_begin();
11687     }
11688
11689     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11690         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11691       return true;
11692   }
11693   return false;
11694 }
11695
11696 /// Emit nodes that will be selected as "test Op0,Op0", or something
11697 /// equivalent.
11698 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11699                                     SelectionDAG &DAG) const {
11700   if (Op.getValueType() == MVT::i1)
11701     // KORTEST instruction should be selected
11702     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11703                        DAG.getConstant(0, Op.getValueType()));
11704
11705   // CF and OF aren't always set the way we want. Determine which
11706   // of these we need.
11707   bool NeedCF = false;
11708   bool NeedOF = false;
11709   switch (X86CC) {
11710   default: break;
11711   case X86::COND_A: case X86::COND_AE:
11712   case X86::COND_B: case X86::COND_BE:
11713     NeedCF = true;
11714     break;
11715   case X86::COND_G: case X86::COND_GE:
11716   case X86::COND_L: case X86::COND_LE:
11717   case X86::COND_O: case X86::COND_NO: {
11718     // Check if we really need to set the
11719     // Overflow flag. If NoSignedWrap is present
11720     // that is not actually needed.
11721     switch (Op->getOpcode()) {
11722     case ISD::ADD:
11723     case ISD::SUB:
11724     case ISD::MUL:
11725     case ISD::SHL: {
11726       const BinaryWithFlagsSDNode *BinNode =
11727           cast<BinaryWithFlagsSDNode>(Op.getNode());
11728       if (BinNode->hasNoSignedWrap())
11729         break;
11730     }
11731     default:
11732       NeedOF = true;
11733       break;
11734     }
11735     break;
11736   }
11737   }
11738   // See if we can use the EFLAGS value from the operand instead of
11739   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11740   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11741   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11742     // Emit a CMP with 0, which is the TEST pattern.
11743     //if (Op.getValueType() == MVT::i1)
11744     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11745     //                     DAG.getConstant(0, MVT::i1));
11746     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11747                        DAG.getConstant(0, Op.getValueType()));
11748   }
11749   unsigned Opcode = 0;
11750   unsigned NumOperands = 0;
11751
11752   // Truncate operations may prevent the merge of the SETCC instruction
11753   // and the arithmetic instruction before it. Attempt to truncate the operands
11754   // of the arithmetic instruction and use a reduced bit-width instruction.
11755   bool NeedTruncation = false;
11756   SDValue ArithOp = Op;
11757   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11758     SDValue Arith = Op->getOperand(0);
11759     // Both the trunc and the arithmetic op need to have one user each.
11760     if (Arith->hasOneUse())
11761       switch (Arith.getOpcode()) {
11762         default: break;
11763         case ISD::ADD:
11764         case ISD::SUB:
11765         case ISD::AND:
11766         case ISD::OR:
11767         case ISD::XOR: {
11768           NeedTruncation = true;
11769           ArithOp = Arith;
11770         }
11771       }
11772   }
11773
11774   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11775   // which may be the result of a CAST.  We use the variable 'Op', which is the
11776   // non-casted variable when we check for possible users.
11777   switch (ArithOp.getOpcode()) {
11778   case ISD::ADD:
11779     // Due to an isel shortcoming, be conservative if this add is likely to be
11780     // selected as part of a load-modify-store instruction. When the root node
11781     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11782     // uses of other nodes in the match, such as the ADD in this case. This
11783     // leads to the ADD being left around and reselected, with the result being
11784     // two adds in the output.  Alas, even if none our users are stores, that
11785     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11786     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11787     // climbing the DAG back to the root, and it doesn't seem to be worth the
11788     // effort.
11789     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11790          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11791       if (UI->getOpcode() != ISD::CopyToReg &&
11792           UI->getOpcode() != ISD::SETCC &&
11793           UI->getOpcode() != ISD::STORE)
11794         goto default_case;
11795
11796     if (ConstantSDNode *C =
11797         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11798       // An add of one will be selected as an INC.
11799       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11800         Opcode = X86ISD::INC;
11801         NumOperands = 1;
11802         break;
11803       }
11804
11805       // An add of negative one (subtract of one) will be selected as a DEC.
11806       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11807         Opcode = X86ISD::DEC;
11808         NumOperands = 1;
11809         break;
11810       }
11811     }
11812
11813     // Otherwise use a regular EFLAGS-setting add.
11814     Opcode = X86ISD::ADD;
11815     NumOperands = 2;
11816     break;
11817   case ISD::SHL:
11818   case ISD::SRL:
11819     // If we have a constant logical shift that's only used in a comparison
11820     // against zero turn it into an equivalent AND. This allows turning it into
11821     // a TEST instruction later.
11822     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11823         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11824       EVT VT = Op.getValueType();
11825       unsigned BitWidth = VT.getSizeInBits();
11826       unsigned ShAmt = Op->getConstantOperandVal(1);
11827       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11828         break;
11829       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11830                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11831                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11832       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11833         break;
11834       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11835                                 DAG.getConstant(Mask, VT));
11836       DAG.ReplaceAllUsesWith(Op, New);
11837       Op = New;
11838     }
11839     break;
11840
11841   case ISD::AND:
11842     // If the primary and result isn't used, don't bother using X86ISD::AND,
11843     // because a TEST instruction will be better.
11844     if (!hasNonFlagsUse(Op))
11845       break;
11846     // FALL THROUGH
11847   case ISD::SUB:
11848   case ISD::OR:
11849   case ISD::XOR:
11850     // Due to the ISEL shortcoming noted above, be conservative if this op is
11851     // likely to be selected as part of a load-modify-store instruction.
11852     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11853            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11854       if (UI->getOpcode() == ISD::STORE)
11855         goto default_case;
11856
11857     // Otherwise use a regular EFLAGS-setting instruction.
11858     switch (ArithOp.getOpcode()) {
11859     default: llvm_unreachable("unexpected operator!");
11860     case ISD::SUB: Opcode = X86ISD::SUB; break;
11861     case ISD::XOR: Opcode = X86ISD::XOR; break;
11862     case ISD::AND: Opcode = X86ISD::AND; break;
11863     case ISD::OR: {
11864       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11865         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11866         if (EFLAGS.getNode())
11867           return EFLAGS;
11868       }
11869       Opcode = X86ISD::OR;
11870       break;
11871     }
11872     }
11873
11874     NumOperands = 2;
11875     break;
11876   case X86ISD::ADD:
11877   case X86ISD::SUB:
11878   case X86ISD::INC:
11879   case X86ISD::DEC:
11880   case X86ISD::OR:
11881   case X86ISD::XOR:
11882   case X86ISD::AND:
11883     return SDValue(Op.getNode(), 1);
11884   default:
11885   default_case:
11886     break;
11887   }
11888
11889   // If we found that truncation is beneficial, perform the truncation and
11890   // update 'Op'.
11891   if (NeedTruncation) {
11892     EVT VT = Op.getValueType();
11893     SDValue WideVal = Op->getOperand(0);
11894     EVT WideVT = WideVal.getValueType();
11895     unsigned ConvertedOp = 0;
11896     // Use a target machine opcode to prevent further DAGCombine
11897     // optimizations that may separate the arithmetic operations
11898     // from the setcc node.
11899     switch (WideVal.getOpcode()) {
11900       default: break;
11901       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11902       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11903       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11904       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11905       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11906     }
11907
11908     if (ConvertedOp) {
11909       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11910       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11911         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11912         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11913         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11914       }
11915     }
11916   }
11917
11918   if (Opcode == 0)
11919     // Emit a CMP with 0, which is the TEST pattern.
11920     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11921                        DAG.getConstant(0, Op.getValueType()));
11922
11923   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11924   SmallVector<SDValue, 4> Ops;
11925   for (unsigned i = 0; i != NumOperands; ++i)
11926     Ops.push_back(Op.getOperand(i));
11927
11928   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11929   DAG.ReplaceAllUsesWith(Op, New);
11930   return SDValue(New.getNode(), 1);
11931 }
11932
11933 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11934 /// equivalent.
11935 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11936                                    SDLoc dl, SelectionDAG &DAG) const {
11937   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11938     if (C->getAPIntValue() == 0)
11939       return EmitTest(Op0, X86CC, dl, DAG);
11940
11941      if (Op0.getValueType() == MVT::i1)
11942        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11943   }
11944  
11945   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11946        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11947     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11948     // This avoids subregister aliasing issues. Keep the smaller reference 
11949     // if we're optimizing for size, however, as that'll allow better folding 
11950     // of memory operations.
11951     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11952         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11953              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11954         !Subtarget->isAtom()) {
11955       unsigned ExtendOp =
11956           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11957       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11958       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11959     }
11960     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11961     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11962     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11963                               Op0, Op1);
11964     return SDValue(Sub.getNode(), 1);
11965   }
11966   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11967 }
11968
11969 /// Convert a comparison if required by the subtarget.
11970 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11971                                                  SelectionDAG &DAG) const {
11972   // If the subtarget does not support the FUCOMI instruction, floating-point
11973   // comparisons have to be converted.
11974   if (Subtarget->hasCMov() ||
11975       Cmp.getOpcode() != X86ISD::CMP ||
11976       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11977       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11978     return Cmp;
11979
11980   // The instruction selector will select an FUCOM instruction instead of
11981   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11982   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11983   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11984   SDLoc dl(Cmp);
11985   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11986   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11987   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11988                             DAG.getConstant(8, MVT::i8));
11989   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11990   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11991 }
11992
11993 static bool isAllOnes(SDValue V) {
11994   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11995   return C && C->isAllOnesValue();
11996 }
11997
11998 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11999 /// if it's possible.
12000 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12001                                      SDLoc dl, SelectionDAG &DAG) const {
12002   SDValue Op0 = And.getOperand(0);
12003   SDValue Op1 = And.getOperand(1);
12004   if (Op0.getOpcode() == ISD::TRUNCATE)
12005     Op0 = Op0.getOperand(0);
12006   if (Op1.getOpcode() == ISD::TRUNCATE)
12007     Op1 = Op1.getOperand(0);
12008
12009   SDValue LHS, RHS;
12010   if (Op1.getOpcode() == ISD::SHL)
12011     std::swap(Op0, Op1);
12012   if (Op0.getOpcode() == ISD::SHL) {
12013     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12014       if (And00C->getZExtValue() == 1) {
12015         // If we looked past a truncate, check that it's only truncating away
12016         // known zeros.
12017         unsigned BitWidth = Op0.getValueSizeInBits();
12018         unsigned AndBitWidth = And.getValueSizeInBits();
12019         if (BitWidth > AndBitWidth) {
12020           APInt Zeros, Ones;
12021           DAG.computeKnownBits(Op0, Zeros, Ones);
12022           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12023             return SDValue();
12024         }
12025         LHS = Op1;
12026         RHS = Op0.getOperand(1);
12027       }
12028   } else if (Op1.getOpcode() == ISD::Constant) {
12029     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12030     uint64_t AndRHSVal = AndRHS->getZExtValue();
12031     SDValue AndLHS = Op0;
12032
12033     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12034       LHS = AndLHS.getOperand(0);
12035       RHS = AndLHS.getOperand(1);
12036     }
12037
12038     // Use BT if the immediate can't be encoded in a TEST instruction.
12039     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12040       LHS = AndLHS;
12041       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12042     }
12043   }
12044
12045   if (LHS.getNode()) {
12046     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12047     // instruction.  Since the shift amount is in-range-or-undefined, we know
12048     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12049     // the encoding for the i16 version is larger than the i32 version.
12050     // Also promote i16 to i32 for performance / code size reason.
12051     if (LHS.getValueType() == MVT::i8 ||
12052         LHS.getValueType() == MVT::i16)
12053       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12054
12055     // If the operand types disagree, extend the shift amount to match.  Since
12056     // BT ignores high bits (like shifts) we can use anyextend.
12057     if (LHS.getValueType() != RHS.getValueType())
12058       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12059
12060     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12061     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12062     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12063                        DAG.getConstant(Cond, MVT::i8), BT);
12064   }
12065
12066   return SDValue();
12067 }
12068
12069 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12070 /// mask CMPs.
12071 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12072                               SDValue &Op1) {
12073   unsigned SSECC;
12074   bool Swap = false;
12075
12076   // SSE Condition code mapping:
12077   //  0 - EQ
12078   //  1 - LT
12079   //  2 - LE
12080   //  3 - UNORD
12081   //  4 - NEQ
12082   //  5 - NLT
12083   //  6 - NLE
12084   //  7 - ORD
12085   switch (SetCCOpcode) {
12086   default: llvm_unreachable("Unexpected SETCC condition");
12087   case ISD::SETOEQ:
12088   case ISD::SETEQ:  SSECC = 0; break;
12089   case ISD::SETOGT:
12090   case ISD::SETGT:  Swap = true; // Fallthrough
12091   case ISD::SETLT:
12092   case ISD::SETOLT: SSECC = 1; break;
12093   case ISD::SETOGE:
12094   case ISD::SETGE:  Swap = true; // Fallthrough
12095   case ISD::SETLE:
12096   case ISD::SETOLE: SSECC = 2; break;
12097   case ISD::SETUO:  SSECC = 3; break;
12098   case ISD::SETUNE:
12099   case ISD::SETNE:  SSECC = 4; break;
12100   case ISD::SETULE: Swap = true; // Fallthrough
12101   case ISD::SETUGE: SSECC = 5; break;
12102   case ISD::SETULT: Swap = true; // Fallthrough
12103   case ISD::SETUGT: SSECC = 6; break;
12104   case ISD::SETO:   SSECC = 7; break;
12105   case ISD::SETUEQ:
12106   case ISD::SETONE: SSECC = 8; break;
12107   }
12108   if (Swap)
12109     std::swap(Op0, Op1);
12110
12111   return SSECC;
12112 }
12113
12114 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12115 // ones, and then concatenate the result back.
12116 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12117   MVT VT = Op.getSimpleValueType();
12118
12119   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12120          "Unsupported value type for operation");
12121
12122   unsigned NumElems = VT.getVectorNumElements();
12123   SDLoc dl(Op);
12124   SDValue CC = Op.getOperand(2);
12125
12126   // Extract the LHS vectors
12127   SDValue LHS = Op.getOperand(0);
12128   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12129   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12130
12131   // Extract the RHS vectors
12132   SDValue RHS = Op.getOperand(1);
12133   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12134   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12135
12136   // Issue the operation on the smaller types and concatenate the result back
12137   MVT EltVT = VT.getVectorElementType();
12138   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12139   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12140                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12141                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12142 }
12143
12144 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12145                                      const X86Subtarget *Subtarget) {
12146   SDValue Op0 = Op.getOperand(0);
12147   SDValue Op1 = Op.getOperand(1);
12148   SDValue CC = Op.getOperand(2);
12149   MVT VT = Op.getSimpleValueType();
12150   SDLoc dl(Op);
12151
12152   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12153          Op.getValueType().getScalarType() == MVT::i1 &&
12154          "Cannot set masked compare for this operation");
12155
12156   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12157   unsigned  Opc = 0;
12158   bool Unsigned = false;
12159   bool Swap = false;
12160   unsigned SSECC;
12161   switch (SetCCOpcode) {
12162   default: llvm_unreachable("Unexpected SETCC condition");
12163   case ISD::SETNE:  SSECC = 4; break;
12164   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12165   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12166   case ISD::SETLT:  Swap = true; //fall-through
12167   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12168   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12169   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12170   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12171   case ISD::SETULE: Unsigned = true; //fall-through
12172   case ISD::SETLE:  SSECC = 2; break;
12173   }
12174
12175   if (Swap)
12176     std::swap(Op0, Op1);
12177   if (Opc)
12178     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12179   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12180   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12181                      DAG.getConstant(SSECC, MVT::i8));
12182 }
12183
12184 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12185 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12186 /// return an empty value.
12187 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12188 {
12189   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12190   if (!BV)
12191     return SDValue();
12192
12193   MVT VT = Op1.getSimpleValueType();
12194   MVT EVT = VT.getVectorElementType();
12195   unsigned n = VT.getVectorNumElements();
12196   SmallVector<SDValue, 8> ULTOp1;
12197
12198   for (unsigned i = 0; i < n; ++i) {
12199     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12200     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12201       return SDValue();
12202
12203     // Avoid underflow.
12204     APInt Val = Elt->getAPIntValue();
12205     if (Val == 0)
12206       return SDValue();
12207
12208     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12209   }
12210
12211   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12212 }
12213
12214 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12215                            SelectionDAG &DAG) {
12216   SDValue Op0 = Op.getOperand(0);
12217   SDValue Op1 = Op.getOperand(1);
12218   SDValue CC = Op.getOperand(2);
12219   MVT VT = Op.getSimpleValueType();
12220   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12221   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12222   SDLoc dl(Op);
12223
12224   if (isFP) {
12225 #ifndef NDEBUG
12226     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12227     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12228 #endif
12229
12230     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12231     unsigned Opc = X86ISD::CMPP;
12232     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12233       assert(VT.getVectorNumElements() <= 16);
12234       Opc = X86ISD::CMPM;
12235     }
12236     // In the two special cases we can't handle, emit two comparisons.
12237     if (SSECC == 8) {
12238       unsigned CC0, CC1;
12239       unsigned CombineOpc;
12240       if (SetCCOpcode == ISD::SETUEQ) {
12241         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12242       } else {
12243         assert(SetCCOpcode == ISD::SETONE);
12244         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12245       }
12246
12247       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12248                                  DAG.getConstant(CC0, MVT::i8));
12249       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12250                                  DAG.getConstant(CC1, MVT::i8));
12251       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12252     }
12253     // Handle all other FP comparisons here.
12254     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12255                        DAG.getConstant(SSECC, MVT::i8));
12256   }
12257
12258   // Break 256-bit integer vector compare into smaller ones.
12259   if (VT.is256BitVector() && !Subtarget->hasInt256())
12260     return Lower256IntVSETCC(Op, DAG);
12261
12262   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12263   EVT OpVT = Op1.getValueType();
12264   if (Subtarget->hasAVX512()) {
12265     if (Op1.getValueType().is512BitVector() ||
12266         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12267       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12268
12269     // In AVX-512 architecture setcc returns mask with i1 elements,
12270     // But there is no compare instruction for i8 and i16 elements.
12271     // We are not talking about 512-bit operands in this case, these
12272     // types are illegal.
12273     if (MaskResult &&
12274         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12275          OpVT.getVectorElementType().getSizeInBits() >= 8))
12276       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12277                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12278   }
12279
12280   // We are handling one of the integer comparisons here.  Since SSE only has
12281   // GT and EQ comparisons for integer, swapping operands and multiple
12282   // operations may be required for some comparisons.
12283   unsigned Opc;
12284   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12285   bool Subus = false;
12286
12287   switch (SetCCOpcode) {
12288   default: llvm_unreachable("Unexpected SETCC condition");
12289   case ISD::SETNE:  Invert = true;
12290   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12291   case ISD::SETLT:  Swap = true;
12292   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12293   case ISD::SETGE:  Swap = true;
12294   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12295                     Invert = true; break;
12296   case ISD::SETULT: Swap = true;
12297   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12298                     FlipSigns = true; break;
12299   case ISD::SETUGE: Swap = true;
12300   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12301                     FlipSigns = true; Invert = true; break;
12302   }
12303
12304   // Special case: Use min/max operations for SETULE/SETUGE
12305   MVT VET = VT.getVectorElementType();
12306   bool hasMinMax =
12307        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12308     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12309
12310   if (hasMinMax) {
12311     switch (SetCCOpcode) {
12312     default: break;
12313     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12314     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12315     }
12316
12317     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12318   }
12319
12320   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12321   if (!MinMax && hasSubus) {
12322     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12323     // Op0 u<= Op1:
12324     //   t = psubus Op0, Op1
12325     //   pcmpeq t, <0..0>
12326     switch (SetCCOpcode) {
12327     default: break;
12328     case ISD::SETULT: {
12329       // If the comparison is against a constant we can turn this into a
12330       // setule.  With psubus, setule does not require a swap.  This is
12331       // beneficial because the constant in the register is no longer
12332       // destructed as the destination so it can be hoisted out of a loop.
12333       // Only do this pre-AVX since vpcmp* is no longer destructive.
12334       if (Subtarget->hasAVX())
12335         break;
12336       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12337       if (ULEOp1.getNode()) {
12338         Op1 = ULEOp1;
12339         Subus = true; Invert = false; Swap = false;
12340       }
12341       break;
12342     }
12343     // Psubus is better than flip-sign because it requires no inversion.
12344     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12345     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12346     }
12347
12348     if (Subus) {
12349       Opc = X86ISD::SUBUS;
12350       FlipSigns = false;
12351     }
12352   }
12353
12354   if (Swap)
12355     std::swap(Op0, Op1);
12356
12357   // Check that the operation in question is available (most are plain SSE2,
12358   // but PCMPGTQ and PCMPEQQ have different requirements).
12359   if (VT == MVT::v2i64) {
12360     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12361       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12362
12363       // First cast everything to the right type.
12364       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12365       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12366
12367       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12368       // bits of the inputs before performing those operations. The lower
12369       // compare is always unsigned.
12370       SDValue SB;
12371       if (FlipSigns) {
12372         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12373       } else {
12374         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12375         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12376         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12377                          Sign, Zero, Sign, Zero);
12378       }
12379       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12380       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12381
12382       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12383       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12384       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12385
12386       // Create masks for only the low parts/high parts of the 64 bit integers.
12387       static const int MaskHi[] = { 1, 1, 3, 3 };
12388       static const int MaskLo[] = { 0, 0, 2, 2 };
12389       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12390       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12391       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12392
12393       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12394       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12395
12396       if (Invert)
12397         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12398
12399       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12400     }
12401
12402     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12403       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12404       // pcmpeqd + pshufd + pand.
12405       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12406
12407       // First cast everything to the right type.
12408       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12409       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12410
12411       // Do the compare.
12412       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12413
12414       // Make sure the lower and upper halves are both all-ones.
12415       static const int Mask[] = { 1, 0, 3, 2 };
12416       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12417       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12418
12419       if (Invert)
12420         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12421
12422       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12423     }
12424   }
12425
12426   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12427   // bits of the inputs before performing those operations.
12428   if (FlipSigns) {
12429     EVT EltVT = VT.getVectorElementType();
12430     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12431     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12432     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12433   }
12434
12435   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12436
12437   // If the logical-not of the result is required, perform that now.
12438   if (Invert)
12439     Result = DAG.getNOT(dl, Result, VT);
12440
12441   if (MinMax)
12442     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12443
12444   if (Subus)
12445     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12446                          getZeroVector(VT, Subtarget, DAG, dl));
12447
12448   return Result;
12449 }
12450
12451 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12452
12453   MVT VT = Op.getSimpleValueType();
12454
12455   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12456
12457   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12458          && "SetCC type must be 8-bit or 1-bit integer");
12459   SDValue Op0 = Op.getOperand(0);
12460   SDValue Op1 = Op.getOperand(1);
12461   SDLoc dl(Op);
12462   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12463
12464   // Optimize to BT if possible.
12465   // Lower (X & (1 << N)) == 0 to BT(X, N).
12466   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12467   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12468   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12469       Op1.getOpcode() == ISD::Constant &&
12470       cast<ConstantSDNode>(Op1)->isNullValue() &&
12471       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12472     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12473     if (NewSetCC.getNode())
12474       return NewSetCC;
12475   }
12476
12477   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12478   // these.
12479   if (Op1.getOpcode() == ISD::Constant &&
12480       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12481        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12482       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12483
12484     // If the input is a setcc, then reuse the input setcc or use a new one with
12485     // the inverted condition.
12486     if (Op0.getOpcode() == X86ISD::SETCC) {
12487       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12488       bool Invert = (CC == ISD::SETNE) ^
12489         cast<ConstantSDNode>(Op1)->isNullValue();
12490       if (!Invert)
12491         return Op0;
12492
12493       CCode = X86::GetOppositeBranchCondition(CCode);
12494       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12495                                   DAG.getConstant(CCode, MVT::i8),
12496                                   Op0.getOperand(1));
12497       if (VT == MVT::i1)
12498         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12499       return SetCC;
12500     }
12501   }
12502   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12503       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12504       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12505
12506     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12507     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12508   }
12509
12510   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12511   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12512   if (X86CC == X86::COND_INVALID)
12513     return SDValue();
12514
12515   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12516   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12517   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12518                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12519   if (VT == MVT::i1)
12520     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12521   return SetCC;
12522 }
12523
12524 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12525 static bool isX86LogicalCmp(SDValue Op) {
12526   unsigned Opc = Op.getNode()->getOpcode();
12527   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12528       Opc == X86ISD::SAHF)
12529     return true;
12530   if (Op.getResNo() == 1 &&
12531       (Opc == X86ISD::ADD ||
12532        Opc == X86ISD::SUB ||
12533        Opc == X86ISD::ADC ||
12534        Opc == X86ISD::SBB ||
12535        Opc == X86ISD::SMUL ||
12536        Opc == X86ISD::UMUL ||
12537        Opc == X86ISD::INC ||
12538        Opc == X86ISD::DEC ||
12539        Opc == X86ISD::OR ||
12540        Opc == X86ISD::XOR ||
12541        Opc == X86ISD::AND))
12542     return true;
12543
12544   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12545     return true;
12546
12547   return false;
12548 }
12549
12550 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12551   if (V.getOpcode() != ISD::TRUNCATE)
12552     return false;
12553
12554   SDValue VOp0 = V.getOperand(0);
12555   unsigned InBits = VOp0.getValueSizeInBits();
12556   unsigned Bits = V.getValueSizeInBits();
12557   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12558 }
12559
12560 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12561   bool addTest = true;
12562   SDValue Cond  = Op.getOperand(0);
12563   SDValue Op1 = Op.getOperand(1);
12564   SDValue Op2 = Op.getOperand(2);
12565   SDLoc DL(Op);
12566   EVT VT = Op1.getValueType();
12567   SDValue CC;
12568
12569   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12570   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12571   // sequence later on.
12572   if (Cond.getOpcode() == ISD::SETCC &&
12573       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12574        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12575       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12576     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12577     int SSECC = translateX86FSETCC(
12578         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12579
12580     if (SSECC != 8) {
12581       if (Subtarget->hasAVX512()) {
12582         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12583                                   DAG.getConstant(SSECC, MVT::i8));
12584         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12585       }
12586       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12587                                 DAG.getConstant(SSECC, MVT::i8));
12588       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12589       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12590       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12591     }
12592   }
12593
12594   if (Cond.getOpcode() == ISD::SETCC) {
12595     SDValue NewCond = LowerSETCC(Cond, DAG);
12596     if (NewCond.getNode())
12597       Cond = NewCond;
12598   }
12599
12600   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12601   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12602   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12603   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12604   if (Cond.getOpcode() == X86ISD::SETCC &&
12605       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12606       isZero(Cond.getOperand(1).getOperand(1))) {
12607     SDValue Cmp = Cond.getOperand(1);
12608
12609     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12610
12611     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12612         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12613       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12614
12615       SDValue CmpOp0 = Cmp.getOperand(0);
12616       // Apply further optimizations for special cases
12617       // (select (x != 0), -1, 0) -> neg & sbb
12618       // (select (x == 0), 0, -1) -> neg & sbb
12619       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12620         if (YC->isNullValue() &&
12621             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12622           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12623           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12624                                     DAG.getConstant(0, CmpOp0.getValueType()),
12625                                     CmpOp0);
12626           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12627                                     DAG.getConstant(X86::COND_B, MVT::i8),
12628                                     SDValue(Neg.getNode(), 1));
12629           return Res;
12630         }
12631
12632       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12633                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12634       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12635
12636       SDValue Res =   // Res = 0 or -1.
12637         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12638                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12639
12640       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12641         Res = DAG.getNOT(DL, Res, Res.getValueType());
12642
12643       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12644       if (!N2C || !N2C->isNullValue())
12645         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12646       return Res;
12647     }
12648   }
12649
12650   // Look past (and (setcc_carry (cmp ...)), 1).
12651   if (Cond.getOpcode() == ISD::AND &&
12652       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12653     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12654     if (C && C->getAPIntValue() == 1)
12655       Cond = Cond.getOperand(0);
12656   }
12657
12658   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12659   // setting operand in place of the X86ISD::SETCC.
12660   unsigned CondOpcode = Cond.getOpcode();
12661   if (CondOpcode == X86ISD::SETCC ||
12662       CondOpcode == X86ISD::SETCC_CARRY) {
12663     CC = Cond.getOperand(0);
12664
12665     SDValue Cmp = Cond.getOperand(1);
12666     unsigned Opc = Cmp.getOpcode();
12667     MVT VT = Op.getSimpleValueType();
12668
12669     bool IllegalFPCMov = false;
12670     if (VT.isFloatingPoint() && !VT.isVector() &&
12671         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12672       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12673
12674     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12675         Opc == X86ISD::BT) { // FIXME
12676       Cond = Cmp;
12677       addTest = false;
12678     }
12679   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12680              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12681              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12682               Cond.getOperand(0).getValueType() != MVT::i8)) {
12683     SDValue LHS = Cond.getOperand(0);
12684     SDValue RHS = Cond.getOperand(1);
12685     unsigned X86Opcode;
12686     unsigned X86Cond;
12687     SDVTList VTs;
12688     switch (CondOpcode) {
12689     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12690     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12691     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12692     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12693     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12694     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12695     default: llvm_unreachable("unexpected overflowing operator");
12696     }
12697     if (CondOpcode == ISD::UMULO)
12698       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12699                           MVT::i32);
12700     else
12701       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12702
12703     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12704
12705     if (CondOpcode == ISD::UMULO)
12706       Cond = X86Op.getValue(2);
12707     else
12708       Cond = X86Op.getValue(1);
12709
12710     CC = DAG.getConstant(X86Cond, MVT::i8);
12711     addTest = false;
12712   }
12713
12714   if (addTest) {
12715     // Look pass the truncate if the high bits are known zero.
12716     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12717         Cond = Cond.getOperand(0);
12718
12719     // We know the result of AND is compared against zero. Try to match
12720     // it to BT.
12721     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12722       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12723       if (NewSetCC.getNode()) {
12724         CC = NewSetCC.getOperand(0);
12725         Cond = NewSetCC.getOperand(1);
12726         addTest = false;
12727       }
12728     }
12729   }
12730
12731   if (addTest) {
12732     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12733     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12734   }
12735
12736   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12737   // a <  b ?  0 : -1 -> RES = setcc_carry
12738   // a >= b ? -1 :  0 -> RES = setcc_carry
12739   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12740   if (Cond.getOpcode() == X86ISD::SUB) {
12741     Cond = ConvertCmpIfNecessary(Cond, DAG);
12742     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12743
12744     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12745         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12746       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12747                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12748       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12749         return DAG.getNOT(DL, Res, Res.getValueType());
12750       return Res;
12751     }
12752   }
12753
12754   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12755   // widen the cmov and push the truncate through. This avoids introducing a new
12756   // branch during isel and doesn't add any extensions.
12757   if (Op.getValueType() == MVT::i8 &&
12758       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12759     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12760     if (T1.getValueType() == T2.getValueType() &&
12761         // Blacklist CopyFromReg to avoid partial register stalls.
12762         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12763       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12764       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12765       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12766     }
12767   }
12768
12769   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12770   // condition is true.
12771   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12772   SDValue Ops[] = { Op2, Op1, CC, Cond };
12773   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12774 }
12775
12776 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12777   MVT VT = Op->getSimpleValueType(0);
12778   SDValue In = Op->getOperand(0);
12779   MVT InVT = In.getSimpleValueType();
12780   SDLoc dl(Op);
12781
12782   unsigned int NumElts = VT.getVectorNumElements();
12783   if (NumElts != 8 && NumElts != 16)
12784     return SDValue();
12785
12786   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12787     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12788
12789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12790   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12791
12792   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12793   Constant *C = ConstantInt::get(*DAG.getContext(),
12794     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12795
12796   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12797   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12798   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12799                           MachinePointerInfo::getConstantPool(),
12800                           false, false, false, Alignment);
12801   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12802   if (VT.is512BitVector())
12803     return Brcst;
12804   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12805 }
12806
12807 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12808                                 SelectionDAG &DAG) {
12809   MVT VT = Op->getSimpleValueType(0);
12810   SDValue In = Op->getOperand(0);
12811   MVT InVT = In.getSimpleValueType();
12812   SDLoc dl(Op);
12813
12814   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12815     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12816
12817   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12818       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12819       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12820     return SDValue();
12821
12822   if (Subtarget->hasInt256())
12823     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12824
12825   // Optimize vectors in AVX mode
12826   // Sign extend  v8i16 to v8i32 and
12827   //              v4i32 to v4i64
12828   //
12829   // Divide input vector into two parts
12830   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12831   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12832   // concat the vectors to original VT
12833
12834   unsigned NumElems = InVT.getVectorNumElements();
12835   SDValue Undef = DAG.getUNDEF(InVT);
12836
12837   SmallVector<int,8> ShufMask1(NumElems, -1);
12838   for (unsigned i = 0; i != NumElems/2; ++i)
12839     ShufMask1[i] = i;
12840
12841   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12842
12843   SmallVector<int,8> ShufMask2(NumElems, -1);
12844   for (unsigned i = 0; i != NumElems/2; ++i)
12845     ShufMask2[i] = i + NumElems/2;
12846
12847   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12848
12849   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12850                                 VT.getVectorNumElements()/2);
12851
12852   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12853   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12854
12855   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12856 }
12857
12858 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
12859 // may emit an illegal shuffle but the expansion is still better than scalar
12860 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
12861 // we'll emit a shuffle and a arithmetic shift.
12862 // TODO: It is possible to support ZExt by zeroing the undef values during
12863 // the shuffle phase or after the shuffle.
12864 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
12865                                  SelectionDAG &DAG) {
12866   MVT RegVT = Op.getSimpleValueType();
12867   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
12868   assert(RegVT.isInteger() &&
12869          "We only custom lower integer vector sext loads.");
12870
12871   // Nothing useful we can do without SSE2 shuffles.
12872   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
12873
12874   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
12875   SDLoc dl(Ld);
12876   EVT MemVT = Ld->getMemoryVT();
12877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12878   unsigned RegSz = RegVT.getSizeInBits();
12879
12880   ISD::LoadExtType Ext = Ld->getExtensionType();
12881
12882   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
12883          && "Only anyext and sext are currently implemented.");
12884   assert(MemVT != RegVT && "Cannot extend to the same type");
12885   assert(MemVT.isVector() && "Must load a vector from memory");
12886
12887   unsigned NumElems = RegVT.getVectorNumElements();
12888   unsigned MemSz = MemVT.getSizeInBits();
12889   assert(RegSz > MemSz && "Register size must be greater than the mem size");
12890
12891   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
12892     // The only way in which we have a legal 256-bit vector result but not the
12893     // integer 256-bit operations needed to directly lower a sextload is if we
12894     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
12895     // a 128-bit vector and a normal sign_extend to 256-bits that should get
12896     // correctly legalized. We do this late to allow the canonical form of
12897     // sextload to persist throughout the rest of the DAG combiner -- it wants
12898     // to fold together any extensions it can, and so will fuse a sign_extend
12899     // of an sextload into an sextload targeting a wider value.
12900     SDValue Load;
12901     if (MemSz == 128) {
12902       // Just switch this to a normal load.
12903       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
12904                                        "it must be a legal 128-bit vector "
12905                                        "type!");
12906       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
12907                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
12908                   Ld->isInvariant(), Ld->getAlignment());
12909     } else {
12910       assert(MemSz < 128 &&
12911              "Can't extend a type wider than 128 bits to a 256 bit vector!");
12912       // Do an sext load to a 128-bit vector type. We want to use the same
12913       // number of elements, but elements half as wide. This will end up being
12914       // recursively lowered by this routine, but will succeed as we definitely
12915       // have all the necessary features if we're using AVX1.
12916       EVT HalfEltVT =
12917           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
12918       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
12919       Load =
12920           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
12921                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
12922                          Ld->isNonTemporal(), Ld->getAlignment());
12923     }
12924
12925     // Replace chain users with the new chain.
12926     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
12927     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
12928
12929     // Finally, do a normal sign-extend to the desired register.
12930     return DAG.getSExtOrTrunc(Load, dl, RegVT);
12931   }
12932
12933   // All sizes must be a power of two.
12934   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
12935          "Non-power-of-two elements are not custom lowered!");
12936
12937   // Attempt to load the original value using scalar loads.
12938   // Find the largest scalar type that divides the total loaded size.
12939   MVT SclrLoadTy = MVT::i8;
12940   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
12941        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
12942     MVT Tp = (MVT::SimpleValueType)tp;
12943     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
12944       SclrLoadTy = Tp;
12945     }
12946   }
12947
12948   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
12949   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
12950       (64 <= MemSz))
12951     SclrLoadTy = MVT::f64;
12952
12953   // Calculate the number of scalar loads that we need to perform
12954   // in order to load our vector from memory.
12955   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
12956
12957   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
12958          "Can only lower sext loads with a single scalar load!");
12959
12960   unsigned loadRegZize = RegSz;
12961   if (Ext == ISD::SEXTLOAD && RegSz == 256)
12962     loadRegZize /= 2;
12963
12964   // Represent our vector as a sequence of elements which are the
12965   // largest scalar that we can load.
12966   EVT LoadUnitVecVT = EVT::getVectorVT(
12967       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
12968
12969   // Represent the data using the same element type that is stored in
12970   // memory. In practice, we ''widen'' MemVT.
12971   EVT WideVecVT =
12972       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
12973                        loadRegZize / MemVT.getScalarType().getSizeInBits());
12974
12975   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
12976          "Invalid vector type");
12977
12978   // We can't shuffle using an illegal type.
12979   assert(TLI.isTypeLegal(WideVecVT) &&
12980          "We only lower types that form legal widened vector types");
12981
12982   SmallVector<SDValue, 8> Chains;
12983   SDValue Ptr = Ld->getBasePtr();
12984   SDValue Increment =
12985       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
12986   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
12987
12988   for (unsigned i = 0; i < NumLoads; ++i) {
12989     // Perform a single load.
12990     SDValue ScalarLoad =
12991         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
12992                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
12993                     Ld->getAlignment());
12994     Chains.push_back(ScalarLoad.getValue(1));
12995     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
12996     // another round of DAGCombining.
12997     if (i == 0)
12998       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
12999     else
13000       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13001                         ScalarLoad, DAG.getIntPtrConstant(i));
13002
13003     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13004   }
13005
13006   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13007
13008   // Bitcast the loaded value to a vector of the original element type, in
13009   // the size of the target vector type.
13010   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13011   unsigned SizeRatio = RegSz / MemSz;
13012
13013   if (Ext == ISD::SEXTLOAD) {
13014     // If we have SSE4.1 we can directly emit a VSEXT node.
13015     if (Subtarget->hasSSE41()) {
13016       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13017       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13018       return Sext;
13019     }
13020
13021     // Otherwise we'll shuffle the small elements in the high bits of the
13022     // larger type and perform an arithmetic shift. If the shift is not legal
13023     // it's better to scalarize.
13024     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13025            "We can't implement an sext load without a arithmetic right shift!");
13026
13027     // Redistribute the loaded elements into the different locations.
13028     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13029     for (unsigned i = 0; i != NumElems; ++i)
13030       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13031
13032     SDValue Shuff = DAG.getVectorShuffle(
13033         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13034
13035     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13036
13037     // Build the arithmetic shift.
13038     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13039                    MemVT.getVectorElementType().getSizeInBits();
13040     Shuff =
13041         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13042
13043     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13044     return Shuff;
13045   }
13046
13047   // Redistribute the loaded elements into the different locations.
13048   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13049   for (unsigned i = 0; i != NumElems; ++i)
13050     ShuffleVec[i * SizeRatio] = i;
13051
13052   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13053                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13054
13055   // Bitcast to the requested type.
13056   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13057   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13058   return Shuff;
13059 }
13060
13061 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13062 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13063 // from the AND / OR.
13064 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13065   Opc = Op.getOpcode();
13066   if (Opc != ISD::OR && Opc != ISD::AND)
13067     return false;
13068   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13069           Op.getOperand(0).hasOneUse() &&
13070           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13071           Op.getOperand(1).hasOneUse());
13072 }
13073
13074 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13075 // 1 and that the SETCC node has a single use.
13076 static bool isXor1OfSetCC(SDValue Op) {
13077   if (Op.getOpcode() != ISD::XOR)
13078     return false;
13079   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13080   if (N1C && N1C->getAPIntValue() == 1) {
13081     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13082       Op.getOperand(0).hasOneUse();
13083   }
13084   return false;
13085 }
13086
13087 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13088   bool addTest = true;
13089   SDValue Chain = Op.getOperand(0);
13090   SDValue Cond  = Op.getOperand(1);
13091   SDValue Dest  = Op.getOperand(2);
13092   SDLoc dl(Op);
13093   SDValue CC;
13094   bool Inverted = false;
13095
13096   if (Cond.getOpcode() == ISD::SETCC) {
13097     // Check for setcc([su]{add,sub,mul}o == 0).
13098     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13099         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13100         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13101         Cond.getOperand(0).getResNo() == 1 &&
13102         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13103          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13104          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13105          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13106          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13107          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13108       Inverted = true;
13109       Cond = Cond.getOperand(0);
13110     } else {
13111       SDValue NewCond = LowerSETCC(Cond, DAG);
13112       if (NewCond.getNode())
13113         Cond = NewCond;
13114     }
13115   }
13116 #if 0
13117   // FIXME: LowerXALUO doesn't handle these!!
13118   else if (Cond.getOpcode() == X86ISD::ADD  ||
13119            Cond.getOpcode() == X86ISD::SUB  ||
13120            Cond.getOpcode() == X86ISD::SMUL ||
13121            Cond.getOpcode() == X86ISD::UMUL)
13122     Cond = LowerXALUO(Cond, DAG);
13123 #endif
13124
13125   // Look pass (and (setcc_carry (cmp ...)), 1).
13126   if (Cond.getOpcode() == ISD::AND &&
13127       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13128     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13129     if (C && C->getAPIntValue() == 1)
13130       Cond = Cond.getOperand(0);
13131   }
13132
13133   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13134   // setting operand in place of the X86ISD::SETCC.
13135   unsigned CondOpcode = Cond.getOpcode();
13136   if (CondOpcode == X86ISD::SETCC ||
13137       CondOpcode == X86ISD::SETCC_CARRY) {
13138     CC = Cond.getOperand(0);
13139
13140     SDValue Cmp = Cond.getOperand(1);
13141     unsigned Opc = Cmp.getOpcode();
13142     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13143     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13144       Cond = Cmp;
13145       addTest = false;
13146     } else {
13147       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13148       default: break;
13149       case X86::COND_O:
13150       case X86::COND_B:
13151         // These can only come from an arithmetic instruction with overflow,
13152         // e.g. SADDO, UADDO.
13153         Cond = Cond.getNode()->getOperand(1);
13154         addTest = false;
13155         break;
13156       }
13157     }
13158   }
13159   CondOpcode = Cond.getOpcode();
13160   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13161       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13162       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13163        Cond.getOperand(0).getValueType() != MVT::i8)) {
13164     SDValue LHS = Cond.getOperand(0);
13165     SDValue RHS = Cond.getOperand(1);
13166     unsigned X86Opcode;
13167     unsigned X86Cond;
13168     SDVTList VTs;
13169     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13170     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13171     // X86ISD::INC).
13172     switch (CondOpcode) {
13173     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13174     case ISD::SADDO:
13175       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13176         if (C->isOne()) {
13177           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13178           break;
13179         }
13180       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13181     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13182     case ISD::SSUBO:
13183       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13184         if (C->isOne()) {
13185           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13186           break;
13187         }
13188       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13189     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13190     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13191     default: llvm_unreachable("unexpected overflowing operator");
13192     }
13193     if (Inverted)
13194       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13195     if (CondOpcode == ISD::UMULO)
13196       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13197                           MVT::i32);
13198     else
13199       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13200
13201     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13202
13203     if (CondOpcode == ISD::UMULO)
13204       Cond = X86Op.getValue(2);
13205     else
13206       Cond = X86Op.getValue(1);
13207
13208     CC = DAG.getConstant(X86Cond, MVT::i8);
13209     addTest = false;
13210   } else {
13211     unsigned CondOpc;
13212     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13213       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13214       if (CondOpc == ISD::OR) {
13215         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13216         // two branches instead of an explicit OR instruction with a
13217         // separate test.
13218         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13219             isX86LogicalCmp(Cmp)) {
13220           CC = Cond.getOperand(0).getOperand(0);
13221           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13222                               Chain, Dest, CC, Cmp);
13223           CC = Cond.getOperand(1).getOperand(0);
13224           Cond = Cmp;
13225           addTest = false;
13226         }
13227       } else { // ISD::AND
13228         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13229         // two branches instead of an explicit AND instruction with a
13230         // separate test. However, we only do this if this block doesn't
13231         // have a fall-through edge, because this requires an explicit
13232         // jmp when the condition is false.
13233         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13234             isX86LogicalCmp(Cmp) &&
13235             Op.getNode()->hasOneUse()) {
13236           X86::CondCode CCode =
13237             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13238           CCode = X86::GetOppositeBranchCondition(CCode);
13239           CC = DAG.getConstant(CCode, MVT::i8);
13240           SDNode *User = *Op.getNode()->use_begin();
13241           // Look for an unconditional branch following this conditional branch.
13242           // We need this because we need to reverse the successors in order
13243           // to implement FCMP_OEQ.
13244           if (User->getOpcode() == ISD::BR) {
13245             SDValue FalseBB = User->getOperand(1);
13246             SDNode *NewBR =
13247               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13248             assert(NewBR == User);
13249             (void)NewBR;
13250             Dest = FalseBB;
13251
13252             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13253                                 Chain, Dest, CC, Cmp);
13254             X86::CondCode CCode =
13255               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13256             CCode = X86::GetOppositeBranchCondition(CCode);
13257             CC = DAG.getConstant(CCode, MVT::i8);
13258             Cond = Cmp;
13259             addTest = false;
13260           }
13261         }
13262       }
13263     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13264       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13265       // It should be transformed during dag combiner except when the condition
13266       // is set by a arithmetics with overflow node.
13267       X86::CondCode CCode =
13268         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13269       CCode = X86::GetOppositeBranchCondition(CCode);
13270       CC = DAG.getConstant(CCode, MVT::i8);
13271       Cond = Cond.getOperand(0).getOperand(1);
13272       addTest = false;
13273     } else if (Cond.getOpcode() == ISD::SETCC &&
13274                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13275       // For FCMP_OEQ, we can emit
13276       // two branches instead of an explicit AND instruction with a
13277       // separate test. However, we only do this if this block doesn't
13278       // have a fall-through edge, because this requires an explicit
13279       // jmp when the condition is false.
13280       if (Op.getNode()->hasOneUse()) {
13281         SDNode *User = *Op.getNode()->use_begin();
13282         // Look for an unconditional branch following this conditional branch.
13283         // We need this because we need to reverse the successors in order
13284         // to implement FCMP_OEQ.
13285         if (User->getOpcode() == ISD::BR) {
13286           SDValue FalseBB = User->getOperand(1);
13287           SDNode *NewBR =
13288             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13289           assert(NewBR == User);
13290           (void)NewBR;
13291           Dest = FalseBB;
13292
13293           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13294                                     Cond.getOperand(0), Cond.getOperand(1));
13295           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13296           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13297           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13298                               Chain, Dest, CC, Cmp);
13299           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13300           Cond = Cmp;
13301           addTest = false;
13302         }
13303       }
13304     } else if (Cond.getOpcode() == ISD::SETCC &&
13305                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13306       // For FCMP_UNE, we can emit
13307       // two branches instead of an explicit AND instruction with a
13308       // separate test. However, we only do this if this block doesn't
13309       // have a fall-through edge, because this requires an explicit
13310       // jmp when the condition is false.
13311       if (Op.getNode()->hasOneUse()) {
13312         SDNode *User = *Op.getNode()->use_begin();
13313         // Look for an unconditional branch following this conditional branch.
13314         // We need this because we need to reverse the successors in order
13315         // to implement FCMP_UNE.
13316         if (User->getOpcode() == ISD::BR) {
13317           SDValue FalseBB = User->getOperand(1);
13318           SDNode *NewBR =
13319             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13320           assert(NewBR == User);
13321           (void)NewBR;
13322
13323           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13324                                     Cond.getOperand(0), Cond.getOperand(1));
13325           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13326           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13327           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13328                               Chain, Dest, CC, Cmp);
13329           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13330           Cond = Cmp;
13331           addTest = false;
13332           Dest = FalseBB;
13333         }
13334       }
13335     }
13336   }
13337
13338   if (addTest) {
13339     // Look pass the truncate if the high bits are known zero.
13340     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13341         Cond = Cond.getOperand(0);
13342
13343     // We know the result of AND is compared against zero. Try to match
13344     // it to BT.
13345     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13346       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13347       if (NewSetCC.getNode()) {
13348         CC = NewSetCC.getOperand(0);
13349         Cond = NewSetCC.getOperand(1);
13350         addTest = false;
13351       }
13352     }
13353   }
13354
13355   if (addTest) {
13356     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13357     CC = DAG.getConstant(X86Cond, MVT::i8);
13358     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13359   }
13360   Cond = ConvertCmpIfNecessary(Cond, DAG);
13361   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13362                      Chain, Dest, CC, Cond);
13363 }
13364
13365 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13366 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13367 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13368 // that the guard pages used by the OS virtual memory manager are allocated in
13369 // correct sequence.
13370 SDValue
13371 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13372                                            SelectionDAG &DAG) const {
13373   MachineFunction &MF = DAG.getMachineFunction();
13374   bool SplitStack = MF.shouldSplitStack();
13375   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13376                SplitStack;
13377   SDLoc dl(Op);
13378
13379   if (!Lower) {
13380     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13381     SDNode* Node = Op.getNode();
13382
13383     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13384     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13385         " not tell us which reg is the stack pointer!");
13386     EVT VT = Node->getValueType(0);
13387     SDValue Tmp1 = SDValue(Node, 0);
13388     SDValue Tmp2 = SDValue(Node, 1);
13389     SDValue Tmp3 = Node->getOperand(2);
13390     SDValue Chain = Tmp1.getOperand(0);
13391
13392     // Chain the dynamic stack allocation so that it doesn't modify the stack
13393     // pointer when other instructions are using the stack.
13394     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13395         SDLoc(Node));
13396
13397     SDValue Size = Tmp2.getOperand(1);
13398     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13399     Chain = SP.getValue(1);
13400     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13401     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13402     unsigned StackAlign = TFI.getStackAlignment();
13403     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13404     if (Align > StackAlign)
13405       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13406           DAG.getConstant(-(uint64_t)Align, VT));
13407     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13408
13409     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13410         DAG.getIntPtrConstant(0, true), SDValue(),
13411         SDLoc(Node));
13412
13413     SDValue Ops[2] = { Tmp1, Tmp2 };
13414     return DAG.getMergeValues(Ops, dl);
13415   }
13416
13417   // Get the inputs.
13418   SDValue Chain = Op.getOperand(0);
13419   SDValue Size  = Op.getOperand(1);
13420   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13421   EVT VT = Op.getNode()->getValueType(0);
13422
13423   bool Is64Bit = Subtarget->is64Bit();
13424   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13425
13426   if (SplitStack) {
13427     MachineRegisterInfo &MRI = MF.getRegInfo();
13428
13429     if (Is64Bit) {
13430       // The 64 bit implementation of segmented stacks needs to clobber both r10
13431       // r11. This makes it impossible to use it along with nested parameters.
13432       const Function *F = MF.getFunction();
13433
13434       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13435            I != E; ++I)
13436         if (I->hasNestAttr())
13437           report_fatal_error("Cannot use segmented stacks with functions that "
13438                              "have nested arguments.");
13439     }
13440
13441     const TargetRegisterClass *AddrRegClass =
13442       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13443     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13444     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13445     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13446                                 DAG.getRegister(Vreg, SPTy));
13447     SDValue Ops1[2] = { Value, Chain };
13448     return DAG.getMergeValues(Ops1, dl);
13449   } else {
13450     SDValue Flag;
13451     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13452
13453     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13454     Flag = Chain.getValue(1);
13455     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13456
13457     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13458
13459     const X86RegisterInfo *RegInfo =
13460       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13461     unsigned SPReg = RegInfo->getStackRegister();
13462     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13463     Chain = SP.getValue(1);
13464
13465     if (Align) {
13466       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13467                        DAG.getConstant(-(uint64_t)Align, VT));
13468       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13469     }
13470
13471     SDValue Ops1[2] = { SP, Chain };
13472     return DAG.getMergeValues(Ops1, dl);
13473   }
13474 }
13475
13476 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13477   MachineFunction &MF = DAG.getMachineFunction();
13478   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13479
13480   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13481   SDLoc DL(Op);
13482
13483   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13484     // vastart just stores the address of the VarArgsFrameIndex slot into the
13485     // memory location argument.
13486     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13487                                    getPointerTy());
13488     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13489                         MachinePointerInfo(SV), false, false, 0);
13490   }
13491
13492   // __va_list_tag:
13493   //   gp_offset         (0 - 6 * 8)
13494   //   fp_offset         (48 - 48 + 8 * 16)
13495   //   overflow_arg_area (point to parameters coming in memory).
13496   //   reg_save_area
13497   SmallVector<SDValue, 8> MemOps;
13498   SDValue FIN = Op.getOperand(1);
13499   // Store gp_offset
13500   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13501                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13502                                                MVT::i32),
13503                                FIN, MachinePointerInfo(SV), false, false, 0);
13504   MemOps.push_back(Store);
13505
13506   // Store fp_offset
13507   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13508                     FIN, DAG.getIntPtrConstant(4));
13509   Store = DAG.getStore(Op.getOperand(0), DL,
13510                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13511                                        MVT::i32),
13512                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13513   MemOps.push_back(Store);
13514
13515   // Store ptr to overflow_arg_area
13516   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13517                     FIN, DAG.getIntPtrConstant(4));
13518   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13519                                     getPointerTy());
13520   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13521                        MachinePointerInfo(SV, 8),
13522                        false, false, 0);
13523   MemOps.push_back(Store);
13524
13525   // Store ptr to reg_save_area.
13526   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13527                     FIN, DAG.getIntPtrConstant(8));
13528   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13529                                     getPointerTy());
13530   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13531                        MachinePointerInfo(SV, 16), false, false, 0);
13532   MemOps.push_back(Store);
13533   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13534 }
13535
13536 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13537   assert(Subtarget->is64Bit() &&
13538          "LowerVAARG only handles 64-bit va_arg!");
13539   assert((Subtarget->isTargetLinux() ||
13540           Subtarget->isTargetDarwin()) &&
13541           "Unhandled target in LowerVAARG");
13542   assert(Op.getNode()->getNumOperands() == 4);
13543   SDValue Chain = Op.getOperand(0);
13544   SDValue SrcPtr = Op.getOperand(1);
13545   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13546   unsigned Align = Op.getConstantOperandVal(3);
13547   SDLoc dl(Op);
13548
13549   EVT ArgVT = Op.getNode()->getValueType(0);
13550   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13551   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13552   uint8_t ArgMode;
13553
13554   // Decide which area this value should be read from.
13555   // TODO: Implement the AMD64 ABI in its entirety. This simple
13556   // selection mechanism works only for the basic types.
13557   if (ArgVT == MVT::f80) {
13558     llvm_unreachable("va_arg for f80 not yet implemented");
13559   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13560     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13561   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13562     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13563   } else {
13564     llvm_unreachable("Unhandled argument type in LowerVAARG");
13565   }
13566
13567   if (ArgMode == 2) {
13568     // Sanity Check: Make sure using fp_offset makes sense.
13569     assert(!DAG.getTarget().Options.UseSoftFloat &&
13570            !(DAG.getMachineFunction()
13571                 .getFunction()->getAttributes()
13572                 .hasAttribute(AttributeSet::FunctionIndex,
13573                               Attribute::NoImplicitFloat)) &&
13574            Subtarget->hasSSE1());
13575   }
13576
13577   // Insert VAARG_64 node into the DAG
13578   // VAARG_64 returns two values: Variable Argument Address, Chain
13579   SmallVector<SDValue, 11> InstOps;
13580   InstOps.push_back(Chain);
13581   InstOps.push_back(SrcPtr);
13582   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13583   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13584   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13585   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13586   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13587                                           VTs, InstOps, MVT::i64,
13588                                           MachinePointerInfo(SV),
13589                                           /*Align=*/0,
13590                                           /*Volatile=*/false,
13591                                           /*ReadMem=*/true,
13592                                           /*WriteMem=*/true);
13593   Chain = VAARG.getValue(1);
13594
13595   // Load the next argument and return it
13596   return DAG.getLoad(ArgVT, dl,
13597                      Chain,
13598                      VAARG,
13599                      MachinePointerInfo(),
13600                      false, false, false, 0);
13601 }
13602
13603 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13604                            SelectionDAG &DAG) {
13605   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13606   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13607   SDValue Chain = Op.getOperand(0);
13608   SDValue DstPtr = Op.getOperand(1);
13609   SDValue SrcPtr = Op.getOperand(2);
13610   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13611   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13612   SDLoc DL(Op);
13613
13614   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13615                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13616                        false,
13617                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13618 }
13619
13620 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13621 // amount is a constant. Takes immediate version of shift as input.
13622 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13623                                           SDValue SrcOp, uint64_t ShiftAmt,
13624                                           SelectionDAG &DAG) {
13625   MVT ElementType = VT.getVectorElementType();
13626
13627   // Fold this packed shift into its first operand if ShiftAmt is 0.
13628   if (ShiftAmt == 0)
13629     return SrcOp;
13630
13631   // Check for ShiftAmt >= element width
13632   if (ShiftAmt >= ElementType.getSizeInBits()) {
13633     if (Opc == X86ISD::VSRAI)
13634       ShiftAmt = ElementType.getSizeInBits() - 1;
13635     else
13636       return DAG.getConstant(0, VT);
13637   }
13638
13639   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13640          && "Unknown target vector shift-by-constant node");
13641
13642   // Fold this packed vector shift into a build vector if SrcOp is a
13643   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13644   if (VT == SrcOp.getSimpleValueType() &&
13645       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13646     SmallVector<SDValue, 8> Elts;
13647     unsigned NumElts = SrcOp->getNumOperands();
13648     ConstantSDNode *ND;
13649
13650     switch(Opc) {
13651     default: llvm_unreachable(nullptr);
13652     case X86ISD::VSHLI:
13653       for (unsigned i=0; i!=NumElts; ++i) {
13654         SDValue CurrentOp = SrcOp->getOperand(i);
13655         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13656           Elts.push_back(CurrentOp);
13657           continue;
13658         }
13659         ND = cast<ConstantSDNode>(CurrentOp);
13660         const APInt &C = ND->getAPIntValue();
13661         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13662       }
13663       break;
13664     case X86ISD::VSRLI:
13665       for (unsigned i=0; i!=NumElts; ++i) {
13666         SDValue CurrentOp = SrcOp->getOperand(i);
13667         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13668           Elts.push_back(CurrentOp);
13669           continue;
13670         }
13671         ND = cast<ConstantSDNode>(CurrentOp);
13672         const APInt &C = ND->getAPIntValue();
13673         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13674       }
13675       break;
13676     case X86ISD::VSRAI:
13677       for (unsigned i=0; i!=NumElts; ++i) {
13678         SDValue CurrentOp = SrcOp->getOperand(i);
13679         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13680           Elts.push_back(CurrentOp);
13681           continue;
13682         }
13683         ND = cast<ConstantSDNode>(CurrentOp);
13684         const APInt &C = ND->getAPIntValue();
13685         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13686       }
13687       break;
13688     }
13689
13690     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13691   }
13692
13693   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13694 }
13695
13696 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13697 // may or may not be a constant. Takes immediate version of shift as input.
13698 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13699                                    SDValue SrcOp, SDValue ShAmt,
13700                                    SelectionDAG &DAG) {
13701   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13702
13703   // Catch shift-by-constant.
13704   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13705     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13706                                       CShAmt->getZExtValue(), DAG);
13707
13708   // Change opcode to non-immediate version
13709   switch (Opc) {
13710     default: llvm_unreachable("Unknown target vector shift node");
13711     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13712     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13713     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13714   }
13715
13716   // Need to build a vector containing shift amount
13717   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13718   SDValue ShOps[4];
13719   ShOps[0] = ShAmt;
13720   ShOps[1] = DAG.getConstant(0, MVT::i32);
13721   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13722   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13723
13724   // The return type has to be a 128-bit type with the same element
13725   // type as the input type.
13726   MVT EltVT = VT.getVectorElementType();
13727   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13728
13729   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13730   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13731 }
13732
13733 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13734   SDLoc dl(Op);
13735   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13736   switch (IntNo) {
13737   default: return SDValue();    // Don't custom lower most intrinsics.
13738   // Comparison intrinsics.
13739   case Intrinsic::x86_sse_comieq_ss:
13740   case Intrinsic::x86_sse_comilt_ss:
13741   case Intrinsic::x86_sse_comile_ss:
13742   case Intrinsic::x86_sse_comigt_ss:
13743   case Intrinsic::x86_sse_comige_ss:
13744   case Intrinsic::x86_sse_comineq_ss:
13745   case Intrinsic::x86_sse_ucomieq_ss:
13746   case Intrinsic::x86_sse_ucomilt_ss:
13747   case Intrinsic::x86_sse_ucomile_ss:
13748   case Intrinsic::x86_sse_ucomigt_ss:
13749   case Intrinsic::x86_sse_ucomige_ss:
13750   case Intrinsic::x86_sse_ucomineq_ss:
13751   case Intrinsic::x86_sse2_comieq_sd:
13752   case Intrinsic::x86_sse2_comilt_sd:
13753   case Intrinsic::x86_sse2_comile_sd:
13754   case Intrinsic::x86_sse2_comigt_sd:
13755   case Intrinsic::x86_sse2_comige_sd:
13756   case Intrinsic::x86_sse2_comineq_sd:
13757   case Intrinsic::x86_sse2_ucomieq_sd:
13758   case Intrinsic::x86_sse2_ucomilt_sd:
13759   case Intrinsic::x86_sse2_ucomile_sd:
13760   case Intrinsic::x86_sse2_ucomigt_sd:
13761   case Intrinsic::x86_sse2_ucomige_sd:
13762   case Intrinsic::x86_sse2_ucomineq_sd: {
13763     unsigned Opc;
13764     ISD::CondCode CC;
13765     switch (IntNo) {
13766     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13767     case Intrinsic::x86_sse_comieq_ss:
13768     case Intrinsic::x86_sse2_comieq_sd:
13769       Opc = X86ISD::COMI;
13770       CC = ISD::SETEQ;
13771       break;
13772     case Intrinsic::x86_sse_comilt_ss:
13773     case Intrinsic::x86_sse2_comilt_sd:
13774       Opc = X86ISD::COMI;
13775       CC = ISD::SETLT;
13776       break;
13777     case Intrinsic::x86_sse_comile_ss:
13778     case Intrinsic::x86_sse2_comile_sd:
13779       Opc = X86ISD::COMI;
13780       CC = ISD::SETLE;
13781       break;
13782     case Intrinsic::x86_sse_comigt_ss:
13783     case Intrinsic::x86_sse2_comigt_sd:
13784       Opc = X86ISD::COMI;
13785       CC = ISD::SETGT;
13786       break;
13787     case Intrinsic::x86_sse_comige_ss:
13788     case Intrinsic::x86_sse2_comige_sd:
13789       Opc = X86ISD::COMI;
13790       CC = ISD::SETGE;
13791       break;
13792     case Intrinsic::x86_sse_comineq_ss:
13793     case Intrinsic::x86_sse2_comineq_sd:
13794       Opc = X86ISD::COMI;
13795       CC = ISD::SETNE;
13796       break;
13797     case Intrinsic::x86_sse_ucomieq_ss:
13798     case Intrinsic::x86_sse2_ucomieq_sd:
13799       Opc = X86ISD::UCOMI;
13800       CC = ISD::SETEQ;
13801       break;
13802     case Intrinsic::x86_sse_ucomilt_ss:
13803     case Intrinsic::x86_sse2_ucomilt_sd:
13804       Opc = X86ISD::UCOMI;
13805       CC = ISD::SETLT;
13806       break;
13807     case Intrinsic::x86_sse_ucomile_ss:
13808     case Intrinsic::x86_sse2_ucomile_sd:
13809       Opc = X86ISD::UCOMI;
13810       CC = ISD::SETLE;
13811       break;
13812     case Intrinsic::x86_sse_ucomigt_ss:
13813     case Intrinsic::x86_sse2_ucomigt_sd:
13814       Opc = X86ISD::UCOMI;
13815       CC = ISD::SETGT;
13816       break;
13817     case Intrinsic::x86_sse_ucomige_ss:
13818     case Intrinsic::x86_sse2_ucomige_sd:
13819       Opc = X86ISD::UCOMI;
13820       CC = ISD::SETGE;
13821       break;
13822     case Intrinsic::x86_sse_ucomineq_ss:
13823     case Intrinsic::x86_sse2_ucomineq_sd:
13824       Opc = X86ISD::UCOMI;
13825       CC = ISD::SETNE;
13826       break;
13827     }
13828
13829     SDValue LHS = Op.getOperand(1);
13830     SDValue RHS = Op.getOperand(2);
13831     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13832     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13833     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13834     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13835                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13836     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13837   }
13838
13839   // Arithmetic intrinsics.
13840   case Intrinsic::x86_sse2_pmulu_dq:
13841   case Intrinsic::x86_avx2_pmulu_dq:
13842     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13843                        Op.getOperand(1), Op.getOperand(2));
13844
13845   case Intrinsic::x86_sse41_pmuldq:
13846   case Intrinsic::x86_avx2_pmul_dq:
13847     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13848                        Op.getOperand(1), Op.getOperand(2));
13849
13850   case Intrinsic::x86_sse2_pmulhu_w:
13851   case Intrinsic::x86_avx2_pmulhu_w:
13852     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13853                        Op.getOperand(1), Op.getOperand(2));
13854
13855   case Intrinsic::x86_sse2_pmulh_w:
13856   case Intrinsic::x86_avx2_pmulh_w:
13857     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13858                        Op.getOperand(1), Op.getOperand(2));
13859
13860   // SSE2/AVX2 sub with unsigned saturation intrinsics
13861   case Intrinsic::x86_sse2_psubus_b:
13862   case Intrinsic::x86_sse2_psubus_w:
13863   case Intrinsic::x86_avx2_psubus_b:
13864   case Intrinsic::x86_avx2_psubus_w:
13865     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13866                        Op.getOperand(1), Op.getOperand(2));
13867
13868   // SSE3/AVX horizontal add/sub intrinsics
13869   case Intrinsic::x86_sse3_hadd_ps:
13870   case Intrinsic::x86_sse3_hadd_pd:
13871   case Intrinsic::x86_avx_hadd_ps_256:
13872   case Intrinsic::x86_avx_hadd_pd_256:
13873   case Intrinsic::x86_sse3_hsub_ps:
13874   case Intrinsic::x86_sse3_hsub_pd:
13875   case Intrinsic::x86_avx_hsub_ps_256:
13876   case Intrinsic::x86_avx_hsub_pd_256:
13877   case Intrinsic::x86_ssse3_phadd_w_128:
13878   case Intrinsic::x86_ssse3_phadd_d_128:
13879   case Intrinsic::x86_avx2_phadd_w:
13880   case Intrinsic::x86_avx2_phadd_d:
13881   case Intrinsic::x86_ssse3_phsub_w_128:
13882   case Intrinsic::x86_ssse3_phsub_d_128:
13883   case Intrinsic::x86_avx2_phsub_w:
13884   case Intrinsic::x86_avx2_phsub_d: {
13885     unsigned Opcode;
13886     switch (IntNo) {
13887     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13888     case Intrinsic::x86_sse3_hadd_ps:
13889     case Intrinsic::x86_sse3_hadd_pd:
13890     case Intrinsic::x86_avx_hadd_ps_256:
13891     case Intrinsic::x86_avx_hadd_pd_256:
13892       Opcode = X86ISD::FHADD;
13893       break;
13894     case Intrinsic::x86_sse3_hsub_ps:
13895     case Intrinsic::x86_sse3_hsub_pd:
13896     case Intrinsic::x86_avx_hsub_ps_256:
13897     case Intrinsic::x86_avx_hsub_pd_256:
13898       Opcode = X86ISD::FHSUB;
13899       break;
13900     case Intrinsic::x86_ssse3_phadd_w_128:
13901     case Intrinsic::x86_ssse3_phadd_d_128:
13902     case Intrinsic::x86_avx2_phadd_w:
13903     case Intrinsic::x86_avx2_phadd_d:
13904       Opcode = X86ISD::HADD;
13905       break;
13906     case Intrinsic::x86_ssse3_phsub_w_128:
13907     case Intrinsic::x86_ssse3_phsub_d_128:
13908     case Intrinsic::x86_avx2_phsub_w:
13909     case Intrinsic::x86_avx2_phsub_d:
13910       Opcode = X86ISD::HSUB;
13911       break;
13912     }
13913     return DAG.getNode(Opcode, dl, Op.getValueType(),
13914                        Op.getOperand(1), Op.getOperand(2));
13915   }
13916
13917   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13918   case Intrinsic::x86_sse2_pmaxu_b:
13919   case Intrinsic::x86_sse41_pmaxuw:
13920   case Intrinsic::x86_sse41_pmaxud:
13921   case Intrinsic::x86_avx2_pmaxu_b:
13922   case Intrinsic::x86_avx2_pmaxu_w:
13923   case Intrinsic::x86_avx2_pmaxu_d:
13924   case Intrinsic::x86_sse2_pminu_b:
13925   case Intrinsic::x86_sse41_pminuw:
13926   case Intrinsic::x86_sse41_pminud:
13927   case Intrinsic::x86_avx2_pminu_b:
13928   case Intrinsic::x86_avx2_pminu_w:
13929   case Intrinsic::x86_avx2_pminu_d:
13930   case Intrinsic::x86_sse41_pmaxsb:
13931   case Intrinsic::x86_sse2_pmaxs_w:
13932   case Intrinsic::x86_sse41_pmaxsd:
13933   case Intrinsic::x86_avx2_pmaxs_b:
13934   case Intrinsic::x86_avx2_pmaxs_w:
13935   case Intrinsic::x86_avx2_pmaxs_d:
13936   case Intrinsic::x86_sse41_pminsb:
13937   case Intrinsic::x86_sse2_pmins_w:
13938   case Intrinsic::x86_sse41_pminsd:
13939   case Intrinsic::x86_avx2_pmins_b:
13940   case Intrinsic::x86_avx2_pmins_w:
13941   case Intrinsic::x86_avx2_pmins_d: {
13942     unsigned Opcode;
13943     switch (IntNo) {
13944     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13945     case Intrinsic::x86_sse2_pmaxu_b:
13946     case Intrinsic::x86_sse41_pmaxuw:
13947     case Intrinsic::x86_sse41_pmaxud:
13948     case Intrinsic::x86_avx2_pmaxu_b:
13949     case Intrinsic::x86_avx2_pmaxu_w:
13950     case Intrinsic::x86_avx2_pmaxu_d:
13951       Opcode = X86ISD::UMAX;
13952       break;
13953     case Intrinsic::x86_sse2_pminu_b:
13954     case Intrinsic::x86_sse41_pminuw:
13955     case Intrinsic::x86_sse41_pminud:
13956     case Intrinsic::x86_avx2_pminu_b:
13957     case Intrinsic::x86_avx2_pminu_w:
13958     case Intrinsic::x86_avx2_pminu_d:
13959       Opcode = X86ISD::UMIN;
13960       break;
13961     case Intrinsic::x86_sse41_pmaxsb:
13962     case Intrinsic::x86_sse2_pmaxs_w:
13963     case Intrinsic::x86_sse41_pmaxsd:
13964     case Intrinsic::x86_avx2_pmaxs_b:
13965     case Intrinsic::x86_avx2_pmaxs_w:
13966     case Intrinsic::x86_avx2_pmaxs_d:
13967       Opcode = X86ISD::SMAX;
13968       break;
13969     case Intrinsic::x86_sse41_pminsb:
13970     case Intrinsic::x86_sse2_pmins_w:
13971     case Intrinsic::x86_sse41_pminsd:
13972     case Intrinsic::x86_avx2_pmins_b:
13973     case Intrinsic::x86_avx2_pmins_w:
13974     case Intrinsic::x86_avx2_pmins_d:
13975       Opcode = X86ISD::SMIN;
13976       break;
13977     }
13978     return DAG.getNode(Opcode, dl, Op.getValueType(),
13979                        Op.getOperand(1), Op.getOperand(2));
13980   }
13981
13982   // SSE/SSE2/AVX floating point max/min intrinsics.
13983   case Intrinsic::x86_sse_max_ps:
13984   case Intrinsic::x86_sse2_max_pd:
13985   case Intrinsic::x86_avx_max_ps_256:
13986   case Intrinsic::x86_avx_max_pd_256:
13987   case Intrinsic::x86_sse_min_ps:
13988   case Intrinsic::x86_sse2_min_pd:
13989   case Intrinsic::x86_avx_min_ps_256:
13990   case Intrinsic::x86_avx_min_pd_256: {
13991     unsigned Opcode;
13992     switch (IntNo) {
13993     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13994     case Intrinsic::x86_sse_max_ps:
13995     case Intrinsic::x86_sse2_max_pd:
13996     case Intrinsic::x86_avx_max_ps_256:
13997     case Intrinsic::x86_avx_max_pd_256:
13998       Opcode = X86ISD::FMAX;
13999       break;
14000     case Intrinsic::x86_sse_min_ps:
14001     case Intrinsic::x86_sse2_min_pd:
14002     case Intrinsic::x86_avx_min_ps_256:
14003     case Intrinsic::x86_avx_min_pd_256:
14004       Opcode = X86ISD::FMIN;
14005       break;
14006     }
14007     return DAG.getNode(Opcode, dl, Op.getValueType(),
14008                        Op.getOperand(1), Op.getOperand(2));
14009   }
14010
14011   // AVX2 variable shift intrinsics
14012   case Intrinsic::x86_avx2_psllv_d:
14013   case Intrinsic::x86_avx2_psllv_q:
14014   case Intrinsic::x86_avx2_psllv_d_256:
14015   case Intrinsic::x86_avx2_psllv_q_256:
14016   case Intrinsic::x86_avx2_psrlv_d:
14017   case Intrinsic::x86_avx2_psrlv_q:
14018   case Intrinsic::x86_avx2_psrlv_d_256:
14019   case Intrinsic::x86_avx2_psrlv_q_256:
14020   case Intrinsic::x86_avx2_psrav_d:
14021   case Intrinsic::x86_avx2_psrav_d_256: {
14022     unsigned Opcode;
14023     switch (IntNo) {
14024     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14025     case Intrinsic::x86_avx2_psllv_d:
14026     case Intrinsic::x86_avx2_psllv_q:
14027     case Intrinsic::x86_avx2_psllv_d_256:
14028     case Intrinsic::x86_avx2_psllv_q_256:
14029       Opcode = ISD::SHL;
14030       break;
14031     case Intrinsic::x86_avx2_psrlv_d:
14032     case Intrinsic::x86_avx2_psrlv_q:
14033     case Intrinsic::x86_avx2_psrlv_d_256:
14034     case Intrinsic::x86_avx2_psrlv_q_256:
14035       Opcode = ISD::SRL;
14036       break;
14037     case Intrinsic::x86_avx2_psrav_d:
14038     case Intrinsic::x86_avx2_psrav_d_256:
14039       Opcode = ISD::SRA;
14040       break;
14041     }
14042     return DAG.getNode(Opcode, dl, Op.getValueType(),
14043                        Op.getOperand(1), Op.getOperand(2));
14044   }
14045
14046   case Intrinsic::x86_sse2_packssdw_128:
14047   case Intrinsic::x86_sse2_packsswb_128:
14048   case Intrinsic::x86_avx2_packssdw:
14049   case Intrinsic::x86_avx2_packsswb:
14050     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14051                        Op.getOperand(1), Op.getOperand(2));
14052
14053   case Intrinsic::x86_sse2_packuswb_128:
14054   case Intrinsic::x86_sse41_packusdw:
14055   case Intrinsic::x86_avx2_packuswb:
14056   case Intrinsic::x86_avx2_packusdw:
14057     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14058                        Op.getOperand(1), Op.getOperand(2));
14059
14060   case Intrinsic::x86_ssse3_pshuf_b_128:
14061   case Intrinsic::x86_avx2_pshuf_b:
14062     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14063                        Op.getOperand(1), Op.getOperand(2));
14064
14065   case Intrinsic::x86_sse2_pshuf_d:
14066     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14067                        Op.getOperand(1), Op.getOperand(2));
14068
14069   case Intrinsic::x86_sse2_pshufl_w:
14070     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14071                        Op.getOperand(1), Op.getOperand(2));
14072
14073   case Intrinsic::x86_sse2_pshufh_w:
14074     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14075                        Op.getOperand(1), Op.getOperand(2));
14076
14077   case Intrinsic::x86_ssse3_psign_b_128:
14078   case Intrinsic::x86_ssse3_psign_w_128:
14079   case Intrinsic::x86_ssse3_psign_d_128:
14080   case Intrinsic::x86_avx2_psign_b:
14081   case Intrinsic::x86_avx2_psign_w:
14082   case Intrinsic::x86_avx2_psign_d:
14083     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14084                        Op.getOperand(1), Op.getOperand(2));
14085
14086   case Intrinsic::x86_sse41_insertps:
14087     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14088                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14089
14090   case Intrinsic::x86_avx_vperm2f128_ps_256:
14091   case Intrinsic::x86_avx_vperm2f128_pd_256:
14092   case Intrinsic::x86_avx_vperm2f128_si_256:
14093   case Intrinsic::x86_avx2_vperm2i128:
14094     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14095                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14096
14097   case Intrinsic::x86_avx2_permd:
14098   case Intrinsic::x86_avx2_permps:
14099     // Operands intentionally swapped. Mask is last operand to intrinsic,
14100     // but second operand for node/instruction.
14101     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14102                        Op.getOperand(2), Op.getOperand(1));
14103
14104   case Intrinsic::x86_sse_sqrt_ps:
14105   case Intrinsic::x86_sse2_sqrt_pd:
14106   case Intrinsic::x86_avx_sqrt_ps_256:
14107   case Intrinsic::x86_avx_sqrt_pd_256:
14108     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14109
14110   // ptest and testp intrinsics. The intrinsic these come from are designed to
14111   // return an integer value, not just an instruction so lower it to the ptest
14112   // or testp pattern and a setcc for the result.
14113   case Intrinsic::x86_sse41_ptestz:
14114   case Intrinsic::x86_sse41_ptestc:
14115   case Intrinsic::x86_sse41_ptestnzc:
14116   case Intrinsic::x86_avx_ptestz_256:
14117   case Intrinsic::x86_avx_ptestc_256:
14118   case Intrinsic::x86_avx_ptestnzc_256:
14119   case Intrinsic::x86_avx_vtestz_ps:
14120   case Intrinsic::x86_avx_vtestc_ps:
14121   case Intrinsic::x86_avx_vtestnzc_ps:
14122   case Intrinsic::x86_avx_vtestz_pd:
14123   case Intrinsic::x86_avx_vtestc_pd:
14124   case Intrinsic::x86_avx_vtestnzc_pd:
14125   case Intrinsic::x86_avx_vtestz_ps_256:
14126   case Intrinsic::x86_avx_vtestc_ps_256:
14127   case Intrinsic::x86_avx_vtestnzc_ps_256:
14128   case Intrinsic::x86_avx_vtestz_pd_256:
14129   case Intrinsic::x86_avx_vtestc_pd_256:
14130   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14131     bool IsTestPacked = false;
14132     unsigned X86CC;
14133     switch (IntNo) {
14134     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14135     case Intrinsic::x86_avx_vtestz_ps:
14136     case Intrinsic::x86_avx_vtestz_pd:
14137     case Intrinsic::x86_avx_vtestz_ps_256:
14138     case Intrinsic::x86_avx_vtestz_pd_256:
14139       IsTestPacked = true; // Fallthrough
14140     case Intrinsic::x86_sse41_ptestz:
14141     case Intrinsic::x86_avx_ptestz_256:
14142       // ZF = 1
14143       X86CC = X86::COND_E;
14144       break;
14145     case Intrinsic::x86_avx_vtestc_ps:
14146     case Intrinsic::x86_avx_vtestc_pd:
14147     case Intrinsic::x86_avx_vtestc_ps_256:
14148     case Intrinsic::x86_avx_vtestc_pd_256:
14149       IsTestPacked = true; // Fallthrough
14150     case Intrinsic::x86_sse41_ptestc:
14151     case Intrinsic::x86_avx_ptestc_256:
14152       // CF = 1
14153       X86CC = X86::COND_B;
14154       break;
14155     case Intrinsic::x86_avx_vtestnzc_ps:
14156     case Intrinsic::x86_avx_vtestnzc_pd:
14157     case Intrinsic::x86_avx_vtestnzc_ps_256:
14158     case Intrinsic::x86_avx_vtestnzc_pd_256:
14159       IsTestPacked = true; // Fallthrough
14160     case Intrinsic::x86_sse41_ptestnzc:
14161     case Intrinsic::x86_avx_ptestnzc_256:
14162       // ZF and CF = 0
14163       X86CC = X86::COND_A;
14164       break;
14165     }
14166
14167     SDValue LHS = Op.getOperand(1);
14168     SDValue RHS = Op.getOperand(2);
14169     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14170     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14171     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14172     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14173     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14174   }
14175   case Intrinsic::x86_avx512_kortestz_w:
14176   case Intrinsic::x86_avx512_kortestc_w: {
14177     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14178     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14179     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14180     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14181     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14182     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14183     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14184   }
14185
14186   // SSE/AVX shift intrinsics
14187   case Intrinsic::x86_sse2_psll_w:
14188   case Intrinsic::x86_sse2_psll_d:
14189   case Intrinsic::x86_sse2_psll_q:
14190   case Intrinsic::x86_avx2_psll_w:
14191   case Intrinsic::x86_avx2_psll_d:
14192   case Intrinsic::x86_avx2_psll_q:
14193   case Intrinsic::x86_sse2_psrl_w:
14194   case Intrinsic::x86_sse2_psrl_d:
14195   case Intrinsic::x86_sse2_psrl_q:
14196   case Intrinsic::x86_avx2_psrl_w:
14197   case Intrinsic::x86_avx2_psrl_d:
14198   case Intrinsic::x86_avx2_psrl_q:
14199   case Intrinsic::x86_sse2_psra_w:
14200   case Intrinsic::x86_sse2_psra_d:
14201   case Intrinsic::x86_avx2_psra_w:
14202   case Intrinsic::x86_avx2_psra_d: {
14203     unsigned Opcode;
14204     switch (IntNo) {
14205     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14206     case Intrinsic::x86_sse2_psll_w:
14207     case Intrinsic::x86_sse2_psll_d:
14208     case Intrinsic::x86_sse2_psll_q:
14209     case Intrinsic::x86_avx2_psll_w:
14210     case Intrinsic::x86_avx2_psll_d:
14211     case Intrinsic::x86_avx2_psll_q:
14212       Opcode = X86ISD::VSHL;
14213       break;
14214     case Intrinsic::x86_sse2_psrl_w:
14215     case Intrinsic::x86_sse2_psrl_d:
14216     case Intrinsic::x86_sse2_psrl_q:
14217     case Intrinsic::x86_avx2_psrl_w:
14218     case Intrinsic::x86_avx2_psrl_d:
14219     case Intrinsic::x86_avx2_psrl_q:
14220       Opcode = X86ISD::VSRL;
14221       break;
14222     case Intrinsic::x86_sse2_psra_w:
14223     case Intrinsic::x86_sse2_psra_d:
14224     case Intrinsic::x86_avx2_psra_w:
14225     case Intrinsic::x86_avx2_psra_d:
14226       Opcode = X86ISD::VSRA;
14227       break;
14228     }
14229     return DAG.getNode(Opcode, dl, Op.getValueType(),
14230                        Op.getOperand(1), Op.getOperand(2));
14231   }
14232
14233   // SSE/AVX immediate shift intrinsics
14234   case Intrinsic::x86_sse2_pslli_w:
14235   case Intrinsic::x86_sse2_pslli_d:
14236   case Intrinsic::x86_sse2_pslli_q:
14237   case Intrinsic::x86_avx2_pslli_w:
14238   case Intrinsic::x86_avx2_pslli_d:
14239   case Intrinsic::x86_avx2_pslli_q:
14240   case Intrinsic::x86_sse2_psrli_w:
14241   case Intrinsic::x86_sse2_psrli_d:
14242   case Intrinsic::x86_sse2_psrli_q:
14243   case Intrinsic::x86_avx2_psrli_w:
14244   case Intrinsic::x86_avx2_psrli_d:
14245   case Intrinsic::x86_avx2_psrli_q:
14246   case Intrinsic::x86_sse2_psrai_w:
14247   case Intrinsic::x86_sse2_psrai_d:
14248   case Intrinsic::x86_avx2_psrai_w:
14249   case Intrinsic::x86_avx2_psrai_d: {
14250     unsigned Opcode;
14251     switch (IntNo) {
14252     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14253     case Intrinsic::x86_sse2_pslli_w:
14254     case Intrinsic::x86_sse2_pslli_d:
14255     case Intrinsic::x86_sse2_pslli_q:
14256     case Intrinsic::x86_avx2_pslli_w:
14257     case Intrinsic::x86_avx2_pslli_d:
14258     case Intrinsic::x86_avx2_pslli_q:
14259       Opcode = X86ISD::VSHLI;
14260       break;
14261     case Intrinsic::x86_sse2_psrli_w:
14262     case Intrinsic::x86_sse2_psrli_d:
14263     case Intrinsic::x86_sse2_psrli_q:
14264     case Intrinsic::x86_avx2_psrli_w:
14265     case Intrinsic::x86_avx2_psrli_d:
14266     case Intrinsic::x86_avx2_psrli_q:
14267       Opcode = X86ISD::VSRLI;
14268       break;
14269     case Intrinsic::x86_sse2_psrai_w:
14270     case Intrinsic::x86_sse2_psrai_d:
14271     case Intrinsic::x86_avx2_psrai_w:
14272     case Intrinsic::x86_avx2_psrai_d:
14273       Opcode = X86ISD::VSRAI;
14274       break;
14275     }
14276     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14277                                Op.getOperand(1), Op.getOperand(2), DAG);
14278   }
14279
14280   case Intrinsic::x86_sse42_pcmpistria128:
14281   case Intrinsic::x86_sse42_pcmpestria128:
14282   case Intrinsic::x86_sse42_pcmpistric128:
14283   case Intrinsic::x86_sse42_pcmpestric128:
14284   case Intrinsic::x86_sse42_pcmpistrio128:
14285   case Intrinsic::x86_sse42_pcmpestrio128:
14286   case Intrinsic::x86_sse42_pcmpistris128:
14287   case Intrinsic::x86_sse42_pcmpestris128:
14288   case Intrinsic::x86_sse42_pcmpistriz128:
14289   case Intrinsic::x86_sse42_pcmpestriz128: {
14290     unsigned Opcode;
14291     unsigned X86CC;
14292     switch (IntNo) {
14293     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14294     case Intrinsic::x86_sse42_pcmpistria128:
14295       Opcode = X86ISD::PCMPISTRI;
14296       X86CC = X86::COND_A;
14297       break;
14298     case Intrinsic::x86_sse42_pcmpestria128:
14299       Opcode = X86ISD::PCMPESTRI;
14300       X86CC = X86::COND_A;
14301       break;
14302     case Intrinsic::x86_sse42_pcmpistric128:
14303       Opcode = X86ISD::PCMPISTRI;
14304       X86CC = X86::COND_B;
14305       break;
14306     case Intrinsic::x86_sse42_pcmpestric128:
14307       Opcode = X86ISD::PCMPESTRI;
14308       X86CC = X86::COND_B;
14309       break;
14310     case Intrinsic::x86_sse42_pcmpistrio128:
14311       Opcode = X86ISD::PCMPISTRI;
14312       X86CC = X86::COND_O;
14313       break;
14314     case Intrinsic::x86_sse42_pcmpestrio128:
14315       Opcode = X86ISD::PCMPESTRI;
14316       X86CC = X86::COND_O;
14317       break;
14318     case Intrinsic::x86_sse42_pcmpistris128:
14319       Opcode = X86ISD::PCMPISTRI;
14320       X86CC = X86::COND_S;
14321       break;
14322     case Intrinsic::x86_sse42_pcmpestris128:
14323       Opcode = X86ISD::PCMPESTRI;
14324       X86CC = X86::COND_S;
14325       break;
14326     case Intrinsic::x86_sse42_pcmpistriz128:
14327       Opcode = X86ISD::PCMPISTRI;
14328       X86CC = X86::COND_E;
14329       break;
14330     case Intrinsic::x86_sse42_pcmpestriz128:
14331       Opcode = X86ISD::PCMPESTRI;
14332       X86CC = X86::COND_E;
14333       break;
14334     }
14335     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14336     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14337     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14338     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14339                                 DAG.getConstant(X86CC, MVT::i8),
14340                                 SDValue(PCMP.getNode(), 1));
14341     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14342   }
14343
14344   case Intrinsic::x86_sse42_pcmpistri128:
14345   case Intrinsic::x86_sse42_pcmpestri128: {
14346     unsigned Opcode;
14347     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14348       Opcode = X86ISD::PCMPISTRI;
14349     else
14350       Opcode = X86ISD::PCMPESTRI;
14351
14352     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14353     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14354     return DAG.getNode(Opcode, dl, VTs, NewOps);
14355   }
14356   case Intrinsic::x86_fma_vfmadd_ps:
14357   case Intrinsic::x86_fma_vfmadd_pd:
14358   case Intrinsic::x86_fma_vfmsub_ps:
14359   case Intrinsic::x86_fma_vfmsub_pd:
14360   case Intrinsic::x86_fma_vfnmadd_ps:
14361   case Intrinsic::x86_fma_vfnmadd_pd:
14362   case Intrinsic::x86_fma_vfnmsub_ps:
14363   case Intrinsic::x86_fma_vfnmsub_pd:
14364   case Intrinsic::x86_fma_vfmaddsub_ps:
14365   case Intrinsic::x86_fma_vfmaddsub_pd:
14366   case Intrinsic::x86_fma_vfmsubadd_ps:
14367   case Intrinsic::x86_fma_vfmsubadd_pd:
14368   case Intrinsic::x86_fma_vfmadd_ps_256:
14369   case Intrinsic::x86_fma_vfmadd_pd_256:
14370   case Intrinsic::x86_fma_vfmsub_ps_256:
14371   case Intrinsic::x86_fma_vfmsub_pd_256:
14372   case Intrinsic::x86_fma_vfnmadd_ps_256:
14373   case Intrinsic::x86_fma_vfnmadd_pd_256:
14374   case Intrinsic::x86_fma_vfnmsub_ps_256:
14375   case Intrinsic::x86_fma_vfnmsub_pd_256:
14376   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14377   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14378   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14379   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14380   case Intrinsic::x86_fma_vfmadd_ps_512:
14381   case Intrinsic::x86_fma_vfmadd_pd_512:
14382   case Intrinsic::x86_fma_vfmsub_ps_512:
14383   case Intrinsic::x86_fma_vfmsub_pd_512:
14384   case Intrinsic::x86_fma_vfnmadd_ps_512:
14385   case Intrinsic::x86_fma_vfnmadd_pd_512:
14386   case Intrinsic::x86_fma_vfnmsub_ps_512:
14387   case Intrinsic::x86_fma_vfnmsub_pd_512:
14388   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14389   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14390   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14391   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14392     unsigned Opc;
14393     switch (IntNo) {
14394     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14395     case Intrinsic::x86_fma_vfmadd_ps:
14396     case Intrinsic::x86_fma_vfmadd_pd:
14397     case Intrinsic::x86_fma_vfmadd_ps_256:
14398     case Intrinsic::x86_fma_vfmadd_pd_256:
14399     case Intrinsic::x86_fma_vfmadd_ps_512:
14400     case Intrinsic::x86_fma_vfmadd_pd_512:
14401       Opc = X86ISD::FMADD;
14402       break;
14403     case Intrinsic::x86_fma_vfmsub_ps:
14404     case Intrinsic::x86_fma_vfmsub_pd:
14405     case Intrinsic::x86_fma_vfmsub_ps_256:
14406     case Intrinsic::x86_fma_vfmsub_pd_256:
14407     case Intrinsic::x86_fma_vfmsub_ps_512:
14408     case Intrinsic::x86_fma_vfmsub_pd_512:
14409       Opc = X86ISD::FMSUB;
14410       break;
14411     case Intrinsic::x86_fma_vfnmadd_ps:
14412     case Intrinsic::x86_fma_vfnmadd_pd:
14413     case Intrinsic::x86_fma_vfnmadd_ps_256:
14414     case Intrinsic::x86_fma_vfnmadd_pd_256:
14415     case Intrinsic::x86_fma_vfnmadd_ps_512:
14416     case Intrinsic::x86_fma_vfnmadd_pd_512:
14417       Opc = X86ISD::FNMADD;
14418       break;
14419     case Intrinsic::x86_fma_vfnmsub_ps:
14420     case Intrinsic::x86_fma_vfnmsub_pd:
14421     case Intrinsic::x86_fma_vfnmsub_ps_256:
14422     case Intrinsic::x86_fma_vfnmsub_pd_256:
14423     case Intrinsic::x86_fma_vfnmsub_ps_512:
14424     case Intrinsic::x86_fma_vfnmsub_pd_512:
14425       Opc = X86ISD::FNMSUB;
14426       break;
14427     case Intrinsic::x86_fma_vfmaddsub_ps:
14428     case Intrinsic::x86_fma_vfmaddsub_pd:
14429     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14430     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14431     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14432     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14433       Opc = X86ISD::FMADDSUB;
14434       break;
14435     case Intrinsic::x86_fma_vfmsubadd_ps:
14436     case Intrinsic::x86_fma_vfmsubadd_pd:
14437     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14438     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14439     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14440     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14441       Opc = X86ISD::FMSUBADD;
14442       break;
14443     }
14444
14445     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14446                        Op.getOperand(2), Op.getOperand(3));
14447   }
14448   }
14449 }
14450
14451 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14452                               SDValue Src, SDValue Mask, SDValue Base,
14453                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14454                               const X86Subtarget * Subtarget) {
14455   SDLoc dl(Op);
14456   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14457   assert(C && "Invalid scale type");
14458   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14459   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14460                              Index.getSimpleValueType().getVectorNumElements());
14461   SDValue MaskInReg;
14462   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14463   if (MaskC)
14464     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14465   else
14466     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14467   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14468   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14469   SDValue Segment = DAG.getRegister(0, MVT::i32);
14470   if (Src.getOpcode() == ISD::UNDEF)
14471     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14472   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14473   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14474   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14475   return DAG.getMergeValues(RetOps, dl);
14476 }
14477
14478 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14479                                SDValue Src, SDValue Mask, SDValue Base,
14480                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14481   SDLoc dl(Op);
14482   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14483   assert(C && "Invalid scale type");
14484   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14485   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14486   SDValue Segment = DAG.getRegister(0, MVT::i32);
14487   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14488                              Index.getSimpleValueType().getVectorNumElements());
14489   SDValue MaskInReg;
14490   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14491   if (MaskC)
14492     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14493   else
14494     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14495   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14496   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14497   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14498   return SDValue(Res, 1);
14499 }
14500
14501 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14502                                SDValue Mask, SDValue Base, SDValue Index,
14503                                SDValue ScaleOp, SDValue Chain) {
14504   SDLoc dl(Op);
14505   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14506   assert(C && "Invalid scale type");
14507   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14508   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14509   SDValue Segment = DAG.getRegister(0, MVT::i32);
14510   EVT MaskVT =
14511     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14512   SDValue MaskInReg;
14513   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14514   if (MaskC)
14515     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14516   else
14517     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14518   //SDVTList VTs = DAG.getVTList(MVT::Other);
14519   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14520   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14521   return SDValue(Res, 0);
14522 }
14523
14524 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14525 // read performance monitor counters (x86_rdpmc).
14526 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14527                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14528                               SmallVectorImpl<SDValue> &Results) {
14529   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14530   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14531   SDValue LO, HI;
14532
14533   // The ECX register is used to select the index of the performance counter
14534   // to read.
14535   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14536                                    N->getOperand(2));
14537   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14538
14539   // Reads the content of a 64-bit performance counter and returns it in the
14540   // registers EDX:EAX.
14541   if (Subtarget->is64Bit()) {
14542     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14543     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14544                             LO.getValue(2));
14545   } else {
14546     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14547     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14548                             LO.getValue(2));
14549   }
14550   Chain = HI.getValue(1);
14551
14552   if (Subtarget->is64Bit()) {
14553     // The EAX register is loaded with the low-order 32 bits. The EDX register
14554     // is loaded with the supported high-order bits of the counter.
14555     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14556                               DAG.getConstant(32, MVT::i8));
14557     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14558     Results.push_back(Chain);
14559     return;
14560   }
14561
14562   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14563   SDValue Ops[] = { LO, HI };
14564   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14565   Results.push_back(Pair);
14566   Results.push_back(Chain);
14567 }
14568
14569 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14570 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14571 // also used to custom lower READCYCLECOUNTER nodes.
14572 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14573                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14574                               SmallVectorImpl<SDValue> &Results) {
14575   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14576   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14577   SDValue LO, HI;
14578
14579   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14580   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14581   // and the EAX register is loaded with the low-order 32 bits.
14582   if (Subtarget->is64Bit()) {
14583     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14584     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14585                             LO.getValue(2));
14586   } else {
14587     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14588     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14589                             LO.getValue(2));
14590   }
14591   SDValue Chain = HI.getValue(1);
14592
14593   if (Opcode == X86ISD::RDTSCP_DAG) {
14594     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14595
14596     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14597     // the ECX register. Add 'ecx' explicitly to the chain.
14598     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14599                                      HI.getValue(2));
14600     // Explicitly store the content of ECX at the location passed in input
14601     // to the 'rdtscp' intrinsic.
14602     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14603                          MachinePointerInfo(), false, false, 0);
14604   }
14605
14606   if (Subtarget->is64Bit()) {
14607     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14608     // the EAX register is loaded with the low-order 32 bits.
14609     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14610                               DAG.getConstant(32, MVT::i8));
14611     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14612     Results.push_back(Chain);
14613     return;
14614   }
14615
14616   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14617   SDValue Ops[] = { LO, HI };
14618   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14619   Results.push_back(Pair);
14620   Results.push_back(Chain);
14621 }
14622
14623 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14624                                      SelectionDAG &DAG) {
14625   SmallVector<SDValue, 2> Results;
14626   SDLoc DL(Op);
14627   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14628                           Results);
14629   return DAG.getMergeValues(Results, DL);
14630 }
14631
14632 enum IntrinsicType {
14633   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14634 };
14635
14636 struct IntrinsicData {
14637   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14638     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14639   IntrinsicType Type;
14640   unsigned      Opc0;
14641   unsigned      Opc1;
14642 };
14643
14644 std::map < unsigned, IntrinsicData> IntrMap;
14645 static void InitIntinsicsMap() {
14646   static bool Initialized = false;
14647   if (Initialized) 
14648     return;
14649   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14650                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14651   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14652                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14653   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14654                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14655   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14656                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14657   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14658                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14659   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14660                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14661   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14662                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14663   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14664                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14665   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14666                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14667
14668   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14669                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14670   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14671                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14672   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14673                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14674   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14675                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14676   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14677                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14678   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14679                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14680   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14681                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14682   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14683                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14684    
14685   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14686                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14687                                                         X86::VGATHERPF1QPSm)));
14688   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14689                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14690                                                         X86::VGATHERPF1QPDm)));
14691   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14692                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14693                                                         X86::VGATHERPF1DPDm)));
14694   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14695                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14696                                                         X86::VGATHERPF1DPSm)));
14697   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14698                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14699                                                         X86::VSCATTERPF1QPSm)));
14700   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14701                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14702                                                         X86::VSCATTERPF1QPDm)));
14703   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14704                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14705                                                         X86::VSCATTERPF1DPDm)));
14706   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14707                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14708                                                         X86::VSCATTERPF1DPSm)));
14709   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14710                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14711   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14712                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14713   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14714                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14715   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14716                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14717   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14718                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14719   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14720                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14721   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14722                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14723   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14724                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14725   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14726                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14727   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14728                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14729   Initialized = true;
14730 }
14731
14732 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14733                                       SelectionDAG &DAG) {
14734   InitIntinsicsMap();
14735   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14736   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14737   if (itr == IntrMap.end())
14738     return SDValue();
14739
14740   SDLoc dl(Op);
14741   IntrinsicData Intr = itr->second;
14742   switch(Intr.Type) {
14743   case RDSEED:
14744   case RDRAND: {
14745     // Emit the node with the right value type.
14746     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14747     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14748
14749     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14750     // Otherwise return the value from Rand, which is always 0, casted to i32.
14751     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14752                       DAG.getConstant(1, Op->getValueType(1)),
14753                       DAG.getConstant(X86::COND_B, MVT::i32),
14754                       SDValue(Result.getNode(), 1) };
14755     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14756                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14757                                   Ops);
14758
14759     // Return { result, isValid, chain }.
14760     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14761                        SDValue(Result.getNode(), 2));
14762   }
14763   case GATHER: {
14764   //gather(v1, mask, index, base, scale);
14765     SDValue Chain = Op.getOperand(0);
14766     SDValue Src   = Op.getOperand(2);
14767     SDValue Base  = Op.getOperand(3);
14768     SDValue Index = Op.getOperand(4);
14769     SDValue Mask  = Op.getOperand(5);
14770     SDValue Scale = Op.getOperand(6);
14771     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14772                           Subtarget);
14773   }
14774   case SCATTER: {
14775   //scatter(base, mask, index, v1, scale);
14776     SDValue Chain = Op.getOperand(0);
14777     SDValue Base  = Op.getOperand(2);
14778     SDValue Mask  = Op.getOperand(3);
14779     SDValue Index = Op.getOperand(4);
14780     SDValue Src   = Op.getOperand(5);
14781     SDValue Scale = Op.getOperand(6);
14782     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14783   }
14784   case PREFETCH: {
14785     SDValue Hint = Op.getOperand(6);
14786     unsigned HintVal;
14787     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14788         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14789       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14790     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14791     SDValue Chain = Op.getOperand(0);
14792     SDValue Mask  = Op.getOperand(2);
14793     SDValue Index = Op.getOperand(3);
14794     SDValue Base  = Op.getOperand(4);
14795     SDValue Scale = Op.getOperand(5);
14796     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14797   }
14798   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14799   case RDTSC: {
14800     SmallVector<SDValue, 2> Results;
14801     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14802     return DAG.getMergeValues(Results, dl);
14803   }
14804   // Read Performance Monitoring Counters.
14805   case RDPMC: {
14806     SmallVector<SDValue, 2> Results;
14807     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14808     return DAG.getMergeValues(Results, dl);
14809   }
14810   // XTEST intrinsics.
14811   case XTEST: {
14812     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14813     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14814     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14815                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14816                                 InTrans);
14817     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14818     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14819                        Ret, SDValue(InTrans.getNode(), 1));
14820   }
14821   }
14822   llvm_unreachable("Unknown Intrinsic Type");
14823 }
14824
14825 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14826                                            SelectionDAG &DAG) const {
14827   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14828   MFI->setReturnAddressIsTaken(true);
14829
14830   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14831     return SDValue();
14832
14833   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14834   SDLoc dl(Op);
14835   EVT PtrVT = getPointerTy();
14836
14837   if (Depth > 0) {
14838     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14839     const X86RegisterInfo *RegInfo =
14840       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14841     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14842     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14843                        DAG.getNode(ISD::ADD, dl, PtrVT,
14844                                    FrameAddr, Offset),
14845                        MachinePointerInfo(), false, false, false, 0);
14846   }
14847
14848   // Just load the return address.
14849   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14850   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14851                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14852 }
14853
14854 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14855   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14856   MFI->setFrameAddressIsTaken(true);
14857
14858   EVT VT = Op.getValueType();
14859   SDLoc dl(Op);  // FIXME probably not meaningful
14860   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14861   const X86RegisterInfo *RegInfo =
14862     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14863   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14864   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14865           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14866          "Invalid Frame Register!");
14867   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14868   while (Depth--)
14869     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14870                             MachinePointerInfo(),
14871                             false, false, false, 0);
14872   return FrameAddr;
14873 }
14874
14875 // FIXME? Maybe this could be a TableGen attribute on some registers and
14876 // this table could be generated automatically from RegInfo.
14877 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14878                                               EVT VT) const {
14879   unsigned Reg = StringSwitch<unsigned>(RegName)
14880                        .Case("esp", X86::ESP)
14881                        .Case("rsp", X86::RSP)
14882                        .Default(0);
14883   if (Reg)
14884     return Reg;
14885   report_fatal_error("Invalid register name global variable");
14886 }
14887
14888 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14889                                                      SelectionDAG &DAG) const {
14890   const X86RegisterInfo *RegInfo =
14891     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14892   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14893 }
14894
14895 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14896   SDValue Chain     = Op.getOperand(0);
14897   SDValue Offset    = Op.getOperand(1);
14898   SDValue Handler   = Op.getOperand(2);
14899   SDLoc dl      (Op);
14900
14901   EVT PtrVT = getPointerTy();
14902   const X86RegisterInfo *RegInfo =
14903     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14904   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14905   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14906           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14907          "Invalid Frame Register!");
14908   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14909   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14910
14911   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14912                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14913   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14914   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14915                        false, false, 0);
14916   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14917
14918   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14919                      DAG.getRegister(StoreAddrReg, PtrVT));
14920 }
14921
14922 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14923                                                SelectionDAG &DAG) const {
14924   SDLoc DL(Op);
14925   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14926                      DAG.getVTList(MVT::i32, MVT::Other),
14927                      Op.getOperand(0), Op.getOperand(1));
14928 }
14929
14930 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14931                                                 SelectionDAG &DAG) const {
14932   SDLoc DL(Op);
14933   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14934                      Op.getOperand(0), Op.getOperand(1));
14935 }
14936
14937 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14938   return Op.getOperand(0);
14939 }
14940
14941 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14942                                                 SelectionDAG &DAG) const {
14943   SDValue Root = Op.getOperand(0);
14944   SDValue Trmp = Op.getOperand(1); // trampoline
14945   SDValue FPtr = Op.getOperand(2); // nested function
14946   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14947   SDLoc dl (Op);
14948
14949   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14950   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14951
14952   if (Subtarget->is64Bit()) {
14953     SDValue OutChains[6];
14954
14955     // Large code-model.
14956     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14957     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14958
14959     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14960     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14961
14962     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14963
14964     // Load the pointer to the nested function into R11.
14965     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14966     SDValue Addr = Trmp;
14967     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14968                                 Addr, MachinePointerInfo(TrmpAddr),
14969                                 false, false, 0);
14970
14971     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14972                        DAG.getConstant(2, MVT::i64));
14973     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14974                                 MachinePointerInfo(TrmpAddr, 2),
14975                                 false, false, 2);
14976
14977     // Load the 'nest' parameter value into R10.
14978     // R10 is specified in X86CallingConv.td
14979     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14980     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14981                        DAG.getConstant(10, MVT::i64));
14982     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14983                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14984                                 false, false, 0);
14985
14986     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14987                        DAG.getConstant(12, MVT::i64));
14988     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14989                                 MachinePointerInfo(TrmpAddr, 12),
14990                                 false, false, 2);
14991
14992     // Jump to the nested function.
14993     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14994     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14995                        DAG.getConstant(20, MVT::i64));
14996     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14997                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14998                                 false, false, 0);
14999
15000     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15001     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15002                        DAG.getConstant(22, MVT::i64));
15003     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15004                                 MachinePointerInfo(TrmpAddr, 22),
15005                                 false, false, 0);
15006
15007     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15008   } else {
15009     const Function *Func =
15010       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15011     CallingConv::ID CC = Func->getCallingConv();
15012     unsigned NestReg;
15013
15014     switch (CC) {
15015     default:
15016       llvm_unreachable("Unsupported calling convention");
15017     case CallingConv::C:
15018     case CallingConv::X86_StdCall: {
15019       // Pass 'nest' parameter in ECX.
15020       // Must be kept in sync with X86CallingConv.td
15021       NestReg = X86::ECX;
15022
15023       // Check that ECX wasn't needed by an 'inreg' parameter.
15024       FunctionType *FTy = Func->getFunctionType();
15025       const AttributeSet &Attrs = Func->getAttributes();
15026
15027       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15028         unsigned InRegCount = 0;
15029         unsigned Idx = 1;
15030
15031         for (FunctionType::param_iterator I = FTy->param_begin(),
15032              E = FTy->param_end(); I != E; ++I, ++Idx)
15033           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15034             // FIXME: should only count parameters that are lowered to integers.
15035             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15036
15037         if (InRegCount > 2) {
15038           report_fatal_error("Nest register in use - reduce number of inreg"
15039                              " parameters!");
15040         }
15041       }
15042       break;
15043     }
15044     case CallingConv::X86_FastCall:
15045     case CallingConv::X86_ThisCall:
15046     case CallingConv::Fast:
15047       // Pass 'nest' parameter in EAX.
15048       // Must be kept in sync with X86CallingConv.td
15049       NestReg = X86::EAX;
15050       break;
15051     }
15052
15053     SDValue OutChains[4];
15054     SDValue Addr, Disp;
15055
15056     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15057                        DAG.getConstant(10, MVT::i32));
15058     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15059
15060     // This is storing the opcode for MOV32ri.
15061     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15062     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15063     OutChains[0] = DAG.getStore(Root, dl,
15064                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15065                                 Trmp, MachinePointerInfo(TrmpAddr),
15066                                 false, false, 0);
15067
15068     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15069                        DAG.getConstant(1, MVT::i32));
15070     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15071                                 MachinePointerInfo(TrmpAddr, 1),
15072                                 false, false, 1);
15073
15074     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15075     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15076                        DAG.getConstant(5, MVT::i32));
15077     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15078                                 MachinePointerInfo(TrmpAddr, 5),
15079                                 false, false, 1);
15080
15081     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15082                        DAG.getConstant(6, MVT::i32));
15083     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15084                                 MachinePointerInfo(TrmpAddr, 6),
15085                                 false, false, 1);
15086
15087     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15088   }
15089 }
15090
15091 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15092                                             SelectionDAG &DAG) const {
15093   /*
15094    The rounding mode is in bits 11:10 of FPSR, and has the following
15095    settings:
15096      00 Round to nearest
15097      01 Round to -inf
15098      10 Round to +inf
15099      11 Round to 0
15100
15101   FLT_ROUNDS, on the other hand, expects the following:
15102     -1 Undefined
15103      0 Round to 0
15104      1 Round to nearest
15105      2 Round to +inf
15106      3 Round to -inf
15107
15108   To perform the conversion, we do:
15109     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15110   */
15111
15112   MachineFunction &MF = DAG.getMachineFunction();
15113   const TargetMachine &TM = MF.getTarget();
15114   const TargetFrameLowering &TFI = *TM.getFrameLowering();
15115   unsigned StackAlignment = TFI.getStackAlignment();
15116   MVT VT = Op.getSimpleValueType();
15117   SDLoc DL(Op);
15118
15119   // Save FP Control Word to stack slot
15120   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15121   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15122
15123   MachineMemOperand *MMO =
15124    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15125                            MachineMemOperand::MOStore, 2, 2);
15126
15127   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15128   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15129                                           DAG.getVTList(MVT::Other),
15130                                           Ops, MVT::i16, MMO);
15131
15132   // Load FP Control Word from stack slot
15133   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15134                             MachinePointerInfo(), false, false, false, 0);
15135
15136   // Transform as necessary
15137   SDValue CWD1 =
15138     DAG.getNode(ISD::SRL, DL, MVT::i16,
15139                 DAG.getNode(ISD::AND, DL, MVT::i16,
15140                             CWD, DAG.getConstant(0x800, MVT::i16)),
15141                 DAG.getConstant(11, MVT::i8));
15142   SDValue CWD2 =
15143     DAG.getNode(ISD::SRL, DL, MVT::i16,
15144                 DAG.getNode(ISD::AND, DL, MVT::i16,
15145                             CWD, DAG.getConstant(0x400, MVT::i16)),
15146                 DAG.getConstant(9, MVT::i8));
15147
15148   SDValue RetVal =
15149     DAG.getNode(ISD::AND, DL, MVT::i16,
15150                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15151                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15152                             DAG.getConstant(1, MVT::i16)),
15153                 DAG.getConstant(3, MVT::i16));
15154
15155   return DAG.getNode((VT.getSizeInBits() < 16 ?
15156                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15157 }
15158
15159 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15160   MVT VT = Op.getSimpleValueType();
15161   EVT OpVT = VT;
15162   unsigned NumBits = VT.getSizeInBits();
15163   SDLoc dl(Op);
15164
15165   Op = Op.getOperand(0);
15166   if (VT == MVT::i8) {
15167     // Zero extend to i32 since there is not an i8 bsr.
15168     OpVT = MVT::i32;
15169     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15170   }
15171
15172   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15173   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15174   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15175
15176   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15177   SDValue Ops[] = {
15178     Op,
15179     DAG.getConstant(NumBits+NumBits-1, OpVT),
15180     DAG.getConstant(X86::COND_E, MVT::i8),
15181     Op.getValue(1)
15182   };
15183   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15184
15185   // Finally xor with NumBits-1.
15186   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15187
15188   if (VT == MVT::i8)
15189     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15190   return Op;
15191 }
15192
15193 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15194   MVT VT = Op.getSimpleValueType();
15195   EVT OpVT = VT;
15196   unsigned NumBits = VT.getSizeInBits();
15197   SDLoc dl(Op);
15198
15199   Op = Op.getOperand(0);
15200   if (VT == MVT::i8) {
15201     // Zero extend to i32 since there is not an i8 bsr.
15202     OpVT = MVT::i32;
15203     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15204   }
15205
15206   // Issue a bsr (scan bits in reverse).
15207   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15208   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15209
15210   // And xor with NumBits-1.
15211   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15212
15213   if (VT == MVT::i8)
15214     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15215   return Op;
15216 }
15217
15218 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15219   MVT VT = Op.getSimpleValueType();
15220   unsigned NumBits = VT.getSizeInBits();
15221   SDLoc dl(Op);
15222   Op = Op.getOperand(0);
15223
15224   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15225   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15226   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15227
15228   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15229   SDValue Ops[] = {
15230     Op,
15231     DAG.getConstant(NumBits, VT),
15232     DAG.getConstant(X86::COND_E, MVT::i8),
15233     Op.getValue(1)
15234   };
15235   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15236 }
15237
15238 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15239 // ones, and then concatenate the result back.
15240 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15241   MVT VT = Op.getSimpleValueType();
15242
15243   assert(VT.is256BitVector() && VT.isInteger() &&
15244          "Unsupported value type for operation");
15245
15246   unsigned NumElems = VT.getVectorNumElements();
15247   SDLoc dl(Op);
15248
15249   // Extract the LHS vectors
15250   SDValue LHS = Op.getOperand(0);
15251   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15252   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15253
15254   // Extract the RHS vectors
15255   SDValue RHS = Op.getOperand(1);
15256   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15257   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15258
15259   MVT EltVT = VT.getVectorElementType();
15260   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15261
15262   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15263                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15264                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15265 }
15266
15267 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15268   assert(Op.getSimpleValueType().is256BitVector() &&
15269          Op.getSimpleValueType().isInteger() &&
15270          "Only handle AVX 256-bit vector integer operation");
15271   return Lower256IntArith(Op, DAG);
15272 }
15273
15274 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15275   assert(Op.getSimpleValueType().is256BitVector() &&
15276          Op.getSimpleValueType().isInteger() &&
15277          "Only handle AVX 256-bit vector integer operation");
15278   return Lower256IntArith(Op, DAG);
15279 }
15280
15281 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15282                         SelectionDAG &DAG) {
15283   SDLoc dl(Op);
15284   MVT VT = Op.getSimpleValueType();
15285
15286   // Decompose 256-bit ops into smaller 128-bit ops.
15287   if (VT.is256BitVector() && !Subtarget->hasInt256())
15288     return Lower256IntArith(Op, DAG);
15289
15290   SDValue A = Op.getOperand(0);
15291   SDValue B = Op.getOperand(1);
15292
15293   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15294   if (VT == MVT::v4i32) {
15295     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15296            "Should not custom lower when pmuldq is available!");
15297
15298     // Extract the odd parts.
15299     static const int UnpackMask[] = { 1, -1, 3, -1 };
15300     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15301     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15302
15303     // Multiply the even parts.
15304     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15305     // Now multiply odd parts.
15306     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15307
15308     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15309     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15310
15311     // Merge the two vectors back together with a shuffle. This expands into 2
15312     // shuffles.
15313     static const int ShufMask[] = { 0, 4, 2, 6 };
15314     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15315   }
15316
15317   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15318          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15319
15320   //  Ahi = psrlqi(a, 32);
15321   //  Bhi = psrlqi(b, 32);
15322   //
15323   //  AloBlo = pmuludq(a, b);
15324   //  AloBhi = pmuludq(a, Bhi);
15325   //  AhiBlo = pmuludq(Ahi, b);
15326
15327   //  AloBhi = psllqi(AloBhi, 32);
15328   //  AhiBlo = psllqi(AhiBlo, 32);
15329   //  return AloBlo + AloBhi + AhiBlo;
15330
15331   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15332   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15333
15334   // Bit cast to 32-bit vectors for MULUDQ
15335   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15336                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15337   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15338   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15339   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15340   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15341
15342   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15343   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15344   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15345
15346   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15347   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15348
15349   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15350   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15351 }
15352
15353 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15354   assert(Subtarget->isTargetWin64() && "Unexpected target");
15355   EVT VT = Op.getValueType();
15356   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15357          "Unexpected return type for lowering");
15358
15359   RTLIB::Libcall LC;
15360   bool isSigned;
15361   switch (Op->getOpcode()) {
15362   default: llvm_unreachable("Unexpected request for libcall!");
15363   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15364   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15365   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15366   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15367   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15368   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15369   }
15370
15371   SDLoc dl(Op);
15372   SDValue InChain = DAG.getEntryNode();
15373
15374   TargetLowering::ArgListTy Args;
15375   TargetLowering::ArgListEntry Entry;
15376   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15377     EVT ArgVT = Op->getOperand(i).getValueType();
15378     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15379            "Unexpected argument type for lowering");
15380     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15381     Entry.Node = StackPtr;
15382     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15383                            false, false, 16);
15384     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15385     Entry.Ty = PointerType::get(ArgTy,0);
15386     Entry.isSExt = false;
15387     Entry.isZExt = false;
15388     Args.push_back(Entry);
15389   }
15390
15391   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15392                                          getPointerTy());
15393
15394   TargetLowering::CallLoweringInfo CLI(DAG);
15395   CLI.setDebugLoc(dl).setChain(InChain)
15396     .setCallee(getLibcallCallingConv(LC),
15397                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15398                Callee, std::move(Args), 0)
15399     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15400
15401   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15402   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15403 }
15404
15405 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15406                              SelectionDAG &DAG) {
15407   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15408   EVT VT = Op0.getValueType();
15409   SDLoc dl(Op);
15410
15411   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15412          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15413
15414   // PMULxD operations multiply each even value (starting at 0) of LHS with
15415   // the related value of RHS and produce a widen result.
15416   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15417   // => <2 x i64> <ae|cg>
15418   //
15419   // In other word, to have all the results, we need to perform two PMULxD:
15420   // 1. one with the even values.
15421   // 2. one with the odd values.
15422   // To achieve #2, with need to place the odd values at an even position.
15423   //
15424   // Place the odd value at an even position (basically, shift all values 1
15425   // step to the left):
15426   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15427   // <a|b|c|d> => <b|undef|d|undef>
15428   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15429   // <e|f|g|h> => <f|undef|h|undef>
15430   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15431
15432   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15433   // ints.
15434   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15435   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15436   unsigned Opcode =
15437       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15438   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15439   // => <2 x i64> <ae|cg>
15440   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15441                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15442   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15443   // => <2 x i64> <bf|dh>
15444   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15445                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15446
15447   // Shuffle it back into the right order.
15448   SDValue Highs, Lows;
15449   if (VT == MVT::v8i32) {
15450     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15451     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15452     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15453     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15454   } else {
15455     const int HighMask[] = {1, 5, 3, 7};
15456     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15457     const int LowMask[] = {1, 4, 2, 6};
15458     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15459   }
15460
15461   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15462   // unsigned multiply.
15463   if (IsSigned && !Subtarget->hasSSE41()) {
15464     SDValue ShAmt =
15465         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15466     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15467                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15468     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15469                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15470
15471     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15472     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15473   }
15474
15475   // The first result of MUL_LOHI is actually the low value, followed by the
15476   // high value.
15477   SDValue Ops[] = {Lows, Highs};
15478   return DAG.getMergeValues(Ops, dl);
15479 }
15480
15481 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15482                                          const X86Subtarget *Subtarget) {
15483   MVT VT = Op.getSimpleValueType();
15484   SDLoc dl(Op);
15485   SDValue R = Op.getOperand(0);
15486   SDValue Amt = Op.getOperand(1);
15487
15488   // Optimize shl/srl/sra with constant shift amount.
15489   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15490     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15491       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15492
15493       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15494           (Subtarget->hasInt256() &&
15495            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15496           (Subtarget->hasAVX512() &&
15497            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15498         if (Op.getOpcode() == ISD::SHL)
15499           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15500                                             DAG);
15501         if (Op.getOpcode() == ISD::SRL)
15502           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15503                                             DAG);
15504         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15505           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15506                                             DAG);
15507       }
15508
15509       if (VT == MVT::v16i8) {
15510         if (Op.getOpcode() == ISD::SHL) {
15511           // Make a large shift.
15512           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15513                                                    MVT::v8i16, R, ShiftAmt,
15514                                                    DAG);
15515           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15516           // Zero out the rightmost bits.
15517           SmallVector<SDValue, 16> V(16,
15518                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15519                                                      MVT::i8));
15520           return DAG.getNode(ISD::AND, dl, VT, SHL,
15521                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15522         }
15523         if (Op.getOpcode() == ISD::SRL) {
15524           // Make a large shift.
15525           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15526                                                    MVT::v8i16, R, ShiftAmt,
15527                                                    DAG);
15528           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15529           // Zero out the leftmost bits.
15530           SmallVector<SDValue, 16> V(16,
15531                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15532                                                      MVT::i8));
15533           return DAG.getNode(ISD::AND, dl, VT, SRL,
15534                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15535         }
15536         if (Op.getOpcode() == ISD::SRA) {
15537           if (ShiftAmt == 7) {
15538             // R s>> 7  ===  R s< 0
15539             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15540             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15541           }
15542
15543           // R s>> a === ((R u>> a) ^ m) - m
15544           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15545           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15546                                                          MVT::i8));
15547           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15548           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15549           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15550           return Res;
15551         }
15552         llvm_unreachable("Unknown shift opcode.");
15553       }
15554
15555       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15556         if (Op.getOpcode() == ISD::SHL) {
15557           // Make a large shift.
15558           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15559                                                    MVT::v16i16, R, ShiftAmt,
15560                                                    DAG);
15561           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15562           // Zero out the rightmost bits.
15563           SmallVector<SDValue, 32> V(32,
15564                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15565                                                      MVT::i8));
15566           return DAG.getNode(ISD::AND, dl, VT, SHL,
15567                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15568         }
15569         if (Op.getOpcode() == ISD::SRL) {
15570           // Make a large shift.
15571           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15572                                                    MVT::v16i16, R, ShiftAmt,
15573                                                    DAG);
15574           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15575           // Zero out the leftmost bits.
15576           SmallVector<SDValue, 32> V(32,
15577                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15578                                                      MVT::i8));
15579           return DAG.getNode(ISD::AND, dl, VT, SRL,
15580                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15581         }
15582         if (Op.getOpcode() == ISD::SRA) {
15583           if (ShiftAmt == 7) {
15584             // R s>> 7  ===  R s< 0
15585             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15586             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15587           }
15588
15589           // R s>> a === ((R u>> a) ^ m) - m
15590           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15591           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15592                                                          MVT::i8));
15593           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15594           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15595           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15596           return Res;
15597         }
15598         llvm_unreachable("Unknown shift opcode.");
15599       }
15600     }
15601   }
15602
15603   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15604   if (!Subtarget->is64Bit() &&
15605       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15606       Amt.getOpcode() == ISD::BITCAST &&
15607       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15608     Amt = Amt.getOperand(0);
15609     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15610                      VT.getVectorNumElements();
15611     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15612     uint64_t ShiftAmt = 0;
15613     for (unsigned i = 0; i != Ratio; ++i) {
15614       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15615       if (!C)
15616         return SDValue();
15617       // 6 == Log2(64)
15618       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15619     }
15620     // Check remaining shift amounts.
15621     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15622       uint64_t ShAmt = 0;
15623       for (unsigned j = 0; j != Ratio; ++j) {
15624         ConstantSDNode *C =
15625           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15626         if (!C)
15627           return SDValue();
15628         // 6 == Log2(64)
15629         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15630       }
15631       if (ShAmt != ShiftAmt)
15632         return SDValue();
15633     }
15634     switch (Op.getOpcode()) {
15635     default:
15636       llvm_unreachable("Unknown shift opcode!");
15637     case ISD::SHL:
15638       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15639                                         DAG);
15640     case ISD::SRL:
15641       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15642                                         DAG);
15643     case ISD::SRA:
15644       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15645                                         DAG);
15646     }
15647   }
15648
15649   return SDValue();
15650 }
15651
15652 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15653                                         const X86Subtarget* Subtarget) {
15654   MVT VT = Op.getSimpleValueType();
15655   SDLoc dl(Op);
15656   SDValue R = Op.getOperand(0);
15657   SDValue Amt = Op.getOperand(1);
15658
15659   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15660       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15661       (Subtarget->hasInt256() &&
15662        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15663         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15664        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15665     SDValue BaseShAmt;
15666     EVT EltVT = VT.getVectorElementType();
15667
15668     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15669       unsigned NumElts = VT.getVectorNumElements();
15670       unsigned i, j;
15671       for (i = 0; i != NumElts; ++i) {
15672         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15673           continue;
15674         break;
15675       }
15676       for (j = i; j != NumElts; ++j) {
15677         SDValue Arg = Amt.getOperand(j);
15678         if (Arg.getOpcode() == ISD::UNDEF) continue;
15679         if (Arg != Amt.getOperand(i))
15680           break;
15681       }
15682       if (i != NumElts && j == NumElts)
15683         BaseShAmt = Amt.getOperand(i);
15684     } else {
15685       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15686         Amt = Amt.getOperand(0);
15687       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15688                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15689         SDValue InVec = Amt.getOperand(0);
15690         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15691           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15692           unsigned i = 0;
15693           for (; i != NumElts; ++i) {
15694             SDValue Arg = InVec.getOperand(i);
15695             if (Arg.getOpcode() == ISD::UNDEF) continue;
15696             BaseShAmt = Arg;
15697             break;
15698           }
15699         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15700            if (ConstantSDNode *C =
15701                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15702              unsigned SplatIdx =
15703                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15704              if (C->getZExtValue() == SplatIdx)
15705                BaseShAmt = InVec.getOperand(1);
15706            }
15707         }
15708         if (!BaseShAmt.getNode())
15709           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15710                                   DAG.getIntPtrConstant(0));
15711       }
15712     }
15713
15714     if (BaseShAmt.getNode()) {
15715       if (EltVT.bitsGT(MVT::i32))
15716         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15717       else if (EltVT.bitsLT(MVT::i32))
15718         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15719
15720       switch (Op.getOpcode()) {
15721       default:
15722         llvm_unreachable("Unknown shift opcode!");
15723       case ISD::SHL:
15724         switch (VT.SimpleTy) {
15725         default: return SDValue();
15726         case MVT::v2i64:
15727         case MVT::v4i32:
15728         case MVT::v8i16:
15729         case MVT::v4i64:
15730         case MVT::v8i32:
15731         case MVT::v16i16:
15732         case MVT::v16i32:
15733         case MVT::v8i64:
15734           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15735         }
15736       case ISD::SRA:
15737         switch (VT.SimpleTy) {
15738         default: return SDValue();
15739         case MVT::v4i32:
15740         case MVT::v8i16:
15741         case MVT::v8i32:
15742         case MVT::v16i16:
15743         case MVT::v16i32:
15744         case MVT::v8i64:
15745           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15746         }
15747       case ISD::SRL:
15748         switch (VT.SimpleTy) {
15749         default: return SDValue();
15750         case MVT::v2i64:
15751         case MVT::v4i32:
15752         case MVT::v8i16:
15753         case MVT::v4i64:
15754         case MVT::v8i32:
15755         case MVT::v16i16:
15756         case MVT::v16i32:
15757         case MVT::v8i64:
15758           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15759         }
15760       }
15761     }
15762   }
15763
15764   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15765   if (!Subtarget->is64Bit() &&
15766       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15767       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15768       Amt.getOpcode() == ISD::BITCAST &&
15769       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15770     Amt = Amt.getOperand(0);
15771     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15772                      VT.getVectorNumElements();
15773     std::vector<SDValue> Vals(Ratio);
15774     for (unsigned i = 0; i != Ratio; ++i)
15775       Vals[i] = Amt.getOperand(i);
15776     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15777       for (unsigned j = 0; j != Ratio; ++j)
15778         if (Vals[j] != Amt.getOperand(i + j))
15779           return SDValue();
15780     }
15781     switch (Op.getOpcode()) {
15782     default:
15783       llvm_unreachable("Unknown shift opcode!");
15784     case ISD::SHL:
15785       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15786     case ISD::SRL:
15787       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15788     case ISD::SRA:
15789       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15790     }
15791   }
15792
15793   return SDValue();
15794 }
15795
15796 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15797                           SelectionDAG &DAG) {
15798   MVT VT = Op.getSimpleValueType();
15799   SDLoc dl(Op);
15800   SDValue R = Op.getOperand(0);
15801   SDValue Amt = Op.getOperand(1);
15802   SDValue V;
15803
15804   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15805   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15806
15807   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15808   if (V.getNode())
15809     return V;
15810
15811   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15812   if (V.getNode())
15813       return V;
15814
15815   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15816     return Op;
15817   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15818   if (Subtarget->hasInt256()) {
15819     if (Op.getOpcode() == ISD::SRL &&
15820         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15821          VT == MVT::v4i64 || VT == MVT::v8i32))
15822       return Op;
15823     if (Op.getOpcode() == ISD::SHL &&
15824         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15825          VT == MVT::v4i64 || VT == MVT::v8i32))
15826       return Op;
15827     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15828       return Op;
15829   }
15830
15831   // If possible, lower this packed shift into a vector multiply instead of
15832   // expanding it into a sequence of scalar shifts.
15833   // Do this only if the vector shift count is a constant build_vector.
15834   if (Op.getOpcode() == ISD::SHL && 
15835       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15836        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15837       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15838     SmallVector<SDValue, 8> Elts;
15839     EVT SVT = VT.getScalarType();
15840     unsigned SVTBits = SVT.getSizeInBits();
15841     const APInt &One = APInt(SVTBits, 1);
15842     unsigned NumElems = VT.getVectorNumElements();
15843
15844     for (unsigned i=0; i !=NumElems; ++i) {
15845       SDValue Op = Amt->getOperand(i);
15846       if (Op->getOpcode() == ISD::UNDEF) {
15847         Elts.push_back(Op);
15848         continue;
15849       }
15850
15851       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15852       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15853       uint64_t ShAmt = C.getZExtValue();
15854       if (ShAmt >= SVTBits) {
15855         Elts.push_back(DAG.getUNDEF(SVT));
15856         continue;
15857       }
15858       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15859     }
15860     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15861     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15862   }
15863
15864   // Lower SHL with variable shift amount.
15865   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15866     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15867
15868     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15869     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15870     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15871     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15872   }
15873
15874   // If possible, lower this shift as a sequence of two shifts by
15875   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15876   // Example:
15877   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15878   //
15879   // Could be rewritten as:
15880   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15881   //
15882   // The advantage is that the two shifts from the example would be
15883   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15884   // the vector shift into four scalar shifts plus four pairs of vector
15885   // insert/extract.
15886   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15887       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15888     unsigned TargetOpcode = X86ISD::MOVSS;
15889     bool CanBeSimplified;
15890     // The splat value for the first packed shift (the 'X' from the example).
15891     SDValue Amt1 = Amt->getOperand(0);
15892     // The splat value for the second packed shift (the 'Y' from the example).
15893     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15894                                         Amt->getOperand(2);
15895
15896     // See if it is possible to replace this node with a sequence of
15897     // two shifts followed by a MOVSS/MOVSD
15898     if (VT == MVT::v4i32) {
15899       // Check if it is legal to use a MOVSS.
15900       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15901                         Amt2 == Amt->getOperand(3);
15902       if (!CanBeSimplified) {
15903         // Otherwise, check if we can still simplify this node using a MOVSD.
15904         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15905                           Amt->getOperand(2) == Amt->getOperand(3);
15906         TargetOpcode = X86ISD::MOVSD;
15907         Amt2 = Amt->getOperand(2);
15908       }
15909     } else {
15910       // Do similar checks for the case where the machine value type
15911       // is MVT::v8i16.
15912       CanBeSimplified = Amt1 == Amt->getOperand(1);
15913       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15914         CanBeSimplified = Amt2 == Amt->getOperand(i);
15915
15916       if (!CanBeSimplified) {
15917         TargetOpcode = X86ISD::MOVSD;
15918         CanBeSimplified = true;
15919         Amt2 = Amt->getOperand(4);
15920         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15921           CanBeSimplified = Amt1 == Amt->getOperand(i);
15922         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15923           CanBeSimplified = Amt2 == Amt->getOperand(j);
15924       }
15925     }
15926     
15927     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15928         isa<ConstantSDNode>(Amt2)) {
15929       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15930       EVT CastVT = MVT::v4i32;
15931       SDValue Splat1 = 
15932         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15933       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15934       SDValue Splat2 = 
15935         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15936       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15937       if (TargetOpcode == X86ISD::MOVSD)
15938         CastVT = MVT::v2i64;
15939       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15940       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15941       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15942                                             BitCast1, DAG);
15943       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15944     }
15945   }
15946
15947   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15948     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15949
15950     // a = a << 5;
15951     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15952     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15953
15954     // Turn 'a' into a mask suitable for VSELECT
15955     SDValue VSelM = DAG.getConstant(0x80, VT);
15956     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15957     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15958
15959     SDValue CM1 = DAG.getConstant(0x0f, VT);
15960     SDValue CM2 = DAG.getConstant(0x3f, VT);
15961
15962     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15963     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15964     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15965     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15966     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15967
15968     // a += a
15969     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15970     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15971     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15972
15973     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15974     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15975     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15976     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15977     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15978
15979     // a += a
15980     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15981     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15982     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15983
15984     // return VSELECT(r, r+r, a);
15985     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15986                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15987     return R;
15988   }
15989
15990   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15991   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15992   // solution better.
15993   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15994     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15995     unsigned ExtOpc =
15996         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15997     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15998     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15999     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16000                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16001     }
16002
16003   // Decompose 256-bit shifts into smaller 128-bit shifts.
16004   if (VT.is256BitVector()) {
16005     unsigned NumElems = VT.getVectorNumElements();
16006     MVT EltVT = VT.getVectorElementType();
16007     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16008
16009     // Extract the two vectors
16010     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16011     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16012
16013     // Recreate the shift amount vectors
16014     SDValue Amt1, Amt2;
16015     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16016       // Constant shift amount
16017       SmallVector<SDValue, 4> Amt1Csts;
16018       SmallVector<SDValue, 4> Amt2Csts;
16019       for (unsigned i = 0; i != NumElems/2; ++i)
16020         Amt1Csts.push_back(Amt->getOperand(i));
16021       for (unsigned i = NumElems/2; i != NumElems; ++i)
16022         Amt2Csts.push_back(Amt->getOperand(i));
16023
16024       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16025       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16026     } else {
16027       // Variable shift amount
16028       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16029       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16030     }
16031
16032     // Issue new vector shifts for the smaller types
16033     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16034     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16035
16036     // Concatenate the result back
16037     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16038   }
16039
16040   return SDValue();
16041 }
16042
16043 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16044   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16045   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16046   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16047   // has only one use.
16048   SDNode *N = Op.getNode();
16049   SDValue LHS = N->getOperand(0);
16050   SDValue RHS = N->getOperand(1);
16051   unsigned BaseOp = 0;
16052   unsigned Cond = 0;
16053   SDLoc DL(Op);
16054   switch (Op.getOpcode()) {
16055   default: llvm_unreachable("Unknown ovf instruction!");
16056   case ISD::SADDO:
16057     // A subtract of one will be selected as a INC. Note that INC doesn't
16058     // set CF, so we can't do this for UADDO.
16059     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16060       if (C->isOne()) {
16061         BaseOp = X86ISD::INC;
16062         Cond = X86::COND_O;
16063         break;
16064       }
16065     BaseOp = X86ISD::ADD;
16066     Cond = X86::COND_O;
16067     break;
16068   case ISD::UADDO:
16069     BaseOp = X86ISD::ADD;
16070     Cond = X86::COND_B;
16071     break;
16072   case ISD::SSUBO:
16073     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16074     // set CF, so we can't do this for USUBO.
16075     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16076       if (C->isOne()) {
16077         BaseOp = X86ISD::DEC;
16078         Cond = X86::COND_O;
16079         break;
16080       }
16081     BaseOp = X86ISD::SUB;
16082     Cond = X86::COND_O;
16083     break;
16084   case ISD::USUBO:
16085     BaseOp = X86ISD::SUB;
16086     Cond = X86::COND_B;
16087     break;
16088   case ISD::SMULO:
16089     BaseOp = X86ISD::SMUL;
16090     Cond = X86::COND_O;
16091     break;
16092   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16093     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16094                                  MVT::i32);
16095     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16096
16097     SDValue SetCC =
16098       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16099                   DAG.getConstant(X86::COND_O, MVT::i32),
16100                   SDValue(Sum.getNode(), 2));
16101
16102     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16103   }
16104   }
16105
16106   // Also sets EFLAGS.
16107   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16108   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16109
16110   SDValue SetCC =
16111     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16112                 DAG.getConstant(Cond, MVT::i32),
16113                 SDValue(Sum.getNode(), 1));
16114
16115   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16116 }
16117
16118 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16119                                                   SelectionDAG &DAG) const {
16120   SDLoc dl(Op);
16121   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16122   MVT VT = Op.getSimpleValueType();
16123
16124   if (!Subtarget->hasSSE2() || !VT.isVector())
16125     return SDValue();
16126
16127   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16128                       ExtraVT.getScalarType().getSizeInBits();
16129
16130   switch (VT.SimpleTy) {
16131     default: return SDValue();
16132     case MVT::v8i32:
16133     case MVT::v16i16:
16134       if (!Subtarget->hasFp256())
16135         return SDValue();
16136       if (!Subtarget->hasInt256()) {
16137         // needs to be split
16138         unsigned NumElems = VT.getVectorNumElements();
16139
16140         // Extract the LHS vectors
16141         SDValue LHS = Op.getOperand(0);
16142         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16143         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16144
16145         MVT EltVT = VT.getVectorElementType();
16146         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16147
16148         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16149         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16150         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16151                                    ExtraNumElems/2);
16152         SDValue Extra = DAG.getValueType(ExtraVT);
16153
16154         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16155         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16156
16157         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16158       }
16159       // fall through
16160     case MVT::v4i32:
16161     case MVT::v8i16: {
16162       SDValue Op0 = Op.getOperand(0);
16163       SDValue Op00 = Op0.getOperand(0);
16164       SDValue Tmp1;
16165       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16166       if (Op0.getOpcode() == ISD::BITCAST &&
16167           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16168         // (sext (vzext x)) -> (vsext x)
16169         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16170         if (Tmp1.getNode()) {
16171           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16172           // This folding is only valid when the in-reg type is a vector of i8,
16173           // i16, or i32.
16174           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16175               ExtraEltVT == MVT::i32) {
16176             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16177             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16178                    "This optimization is invalid without a VZEXT.");
16179             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16180           }
16181           Op0 = Tmp1;
16182         }
16183       }
16184
16185       // If the above didn't work, then just use Shift-Left + Shift-Right.
16186       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16187                                         DAG);
16188       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16189                                         DAG);
16190     }
16191   }
16192 }
16193
16194 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16195                                  SelectionDAG &DAG) {
16196   SDLoc dl(Op);
16197   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16198     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16199   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16200     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16201
16202   // The only fence that needs an instruction is a sequentially-consistent
16203   // cross-thread fence.
16204   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16205     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16206     // no-sse2). There isn't any reason to disable it if the target processor
16207     // supports it.
16208     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16209       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16210
16211     SDValue Chain = Op.getOperand(0);
16212     SDValue Zero = DAG.getConstant(0, MVT::i32);
16213     SDValue Ops[] = {
16214       DAG.getRegister(X86::ESP, MVT::i32), // Base
16215       DAG.getTargetConstant(1, MVT::i8),   // Scale
16216       DAG.getRegister(0, MVT::i32),        // Index
16217       DAG.getTargetConstant(0, MVT::i32),  // Disp
16218       DAG.getRegister(0, MVT::i32),        // Segment.
16219       Zero,
16220       Chain
16221     };
16222     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16223     return SDValue(Res, 0);
16224   }
16225
16226   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16227   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16228 }
16229
16230 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16231                              SelectionDAG &DAG) {
16232   MVT T = Op.getSimpleValueType();
16233   SDLoc DL(Op);
16234   unsigned Reg = 0;
16235   unsigned size = 0;
16236   switch(T.SimpleTy) {
16237   default: llvm_unreachable("Invalid value type!");
16238   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16239   case MVT::i16: Reg = X86::AX;  size = 2; break;
16240   case MVT::i32: Reg = X86::EAX; size = 4; break;
16241   case MVT::i64:
16242     assert(Subtarget->is64Bit() && "Node not type legal!");
16243     Reg = X86::RAX; size = 8;
16244     break;
16245   }
16246   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16247                                   Op.getOperand(2), SDValue());
16248   SDValue Ops[] = { cpIn.getValue(0),
16249                     Op.getOperand(1),
16250                     Op.getOperand(3),
16251                     DAG.getTargetConstant(size, MVT::i8),
16252                     cpIn.getValue(1) };
16253   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16254   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16255   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16256                                            Ops, T, MMO);
16257
16258   SDValue cpOut =
16259     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16260   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16261                                       MVT::i32, cpOut.getValue(2));
16262   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16263                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16264
16265   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16266   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16267   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16268   return SDValue();
16269 }
16270
16271 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16272                             SelectionDAG &DAG) {
16273   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16274   MVT DstVT = Op.getSimpleValueType();
16275
16276   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16277     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16278     if (DstVT != MVT::f64)
16279       // This conversion needs to be expanded.
16280       return SDValue();
16281
16282     SDValue InVec = Op->getOperand(0);
16283     SDLoc dl(Op);
16284     unsigned NumElts = SrcVT.getVectorNumElements();
16285     EVT SVT = SrcVT.getVectorElementType();
16286
16287     // Widen the vector in input in the case of MVT::v2i32.
16288     // Example: from MVT::v2i32 to MVT::v4i32.
16289     SmallVector<SDValue, 16> Elts;
16290     for (unsigned i = 0, e = NumElts; i != e; ++i)
16291       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16292                                  DAG.getIntPtrConstant(i)));
16293
16294     // Explicitly mark the extra elements as Undef.
16295     SDValue Undef = DAG.getUNDEF(SVT);
16296     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16297       Elts.push_back(Undef);
16298
16299     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16300     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16301     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16302     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16303                        DAG.getIntPtrConstant(0));
16304   }
16305
16306   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16307          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16308   assert((DstVT == MVT::i64 ||
16309           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16310          "Unexpected custom BITCAST");
16311   // i64 <=> MMX conversions are Legal.
16312   if (SrcVT==MVT::i64 && DstVT.isVector())
16313     return Op;
16314   if (DstVT==MVT::i64 && SrcVT.isVector())
16315     return Op;
16316   // MMX <=> MMX conversions are Legal.
16317   if (SrcVT.isVector() && DstVT.isVector())
16318     return Op;
16319   // All other conversions need to be expanded.
16320   return SDValue();
16321 }
16322
16323 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16324   SDNode *Node = Op.getNode();
16325   SDLoc dl(Node);
16326   EVT T = Node->getValueType(0);
16327   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16328                               DAG.getConstant(0, T), Node->getOperand(2));
16329   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16330                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16331                        Node->getOperand(0),
16332                        Node->getOperand(1), negOp,
16333                        cast<AtomicSDNode>(Node)->getMemOperand(),
16334                        cast<AtomicSDNode>(Node)->getOrdering(),
16335                        cast<AtomicSDNode>(Node)->getSynchScope());
16336 }
16337
16338 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16339   SDNode *Node = Op.getNode();
16340   SDLoc dl(Node);
16341   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16342
16343   // Convert seq_cst store -> xchg
16344   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16345   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16346   //        (The only way to get a 16-byte store is cmpxchg16b)
16347   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16348   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16349       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16350     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16351                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16352                                  Node->getOperand(0),
16353                                  Node->getOperand(1), Node->getOperand(2),
16354                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16355                                  cast<AtomicSDNode>(Node)->getOrdering(),
16356                                  cast<AtomicSDNode>(Node)->getSynchScope());
16357     return Swap.getValue(1);
16358   }
16359   // Other atomic stores have a simple pattern.
16360   return Op;
16361 }
16362
16363 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16364   EVT VT = Op.getNode()->getSimpleValueType(0);
16365
16366   // Let legalize expand this if it isn't a legal type yet.
16367   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16368     return SDValue();
16369
16370   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16371
16372   unsigned Opc;
16373   bool ExtraOp = false;
16374   switch (Op.getOpcode()) {
16375   default: llvm_unreachable("Invalid code");
16376   case ISD::ADDC: Opc = X86ISD::ADD; break;
16377   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16378   case ISD::SUBC: Opc = X86ISD::SUB; break;
16379   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16380   }
16381
16382   if (!ExtraOp)
16383     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16384                        Op.getOperand(1));
16385   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16386                      Op.getOperand(1), Op.getOperand(2));
16387 }
16388
16389 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16390                             SelectionDAG &DAG) {
16391   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16392
16393   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16394   // which returns the values as { float, float } (in XMM0) or
16395   // { double, double } (which is returned in XMM0, XMM1).
16396   SDLoc dl(Op);
16397   SDValue Arg = Op.getOperand(0);
16398   EVT ArgVT = Arg.getValueType();
16399   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16400
16401   TargetLowering::ArgListTy Args;
16402   TargetLowering::ArgListEntry Entry;
16403
16404   Entry.Node = Arg;
16405   Entry.Ty = ArgTy;
16406   Entry.isSExt = false;
16407   Entry.isZExt = false;
16408   Args.push_back(Entry);
16409
16410   bool isF64 = ArgVT == MVT::f64;
16411   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16412   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16413   // the results are returned via SRet in memory.
16414   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16416   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16417
16418   Type *RetTy = isF64
16419     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16420     : (Type*)VectorType::get(ArgTy, 4);
16421
16422   TargetLowering::CallLoweringInfo CLI(DAG);
16423   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16424     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16425
16426   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16427
16428   if (isF64)
16429     // Returned in xmm0 and xmm1.
16430     return CallResult.first;
16431
16432   // Returned in bits 0:31 and 32:64 xmm0.
16433   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16434                                CallResult.first, DAG.getIntPtrConstant(0));
16435   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16436                                CallResult.first, DAG.getIntPtrConstant(1));
16437   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16438   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16439 }
16440
16441 /// LowerOperation - Provide custom lowering hooks for some operations.
16442 ///
16443 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16444   switch (Op.getOpcode()) {
16445   default: llvm_unreachable("Should not custom lower this!");
16446   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16447   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16448   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16449     return LowerCMP_SWAP(Op, Subtarget, DAG);
16450   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16451   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16452   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16453   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16454   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16455   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16456   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16457   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16458   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16459   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16460   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16461   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16462   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16463   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16464   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16465   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16466   case ISD::SHL_PARTS:
16467   case ISD::SRA_PARTS:
16468   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16469   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16470   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16471   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16472   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16473   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16474   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16475   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16476   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16477   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16478   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16479   case ISD::FABS:               return LowerFABS(Op, DAG);
16480   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16481   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16482   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16483   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16484   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16485   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16486   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16487   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16488   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16489   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16490   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16491   case ISD::INTRINSIC_VOID:
16492   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16493   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16494   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16495   case ISD::FRAME_TO_ARGS_OFFSET:
16496                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16497   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16498   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16499   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16500   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16501   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16502   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16503   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16504   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16505   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16506   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16507   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16508   case ISD::UMUL_LOHI:
16509   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16510   case ISD::SRA:
16511   case ISD::SRL:
16512   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16513   case ISD::SADDO:
16514   case ISD::UADDO:
16515   case ISD::SSUBO:
16516   case ISD::USUBO:
16517   case ISD::SMULO:
16518   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16519   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16520   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16521   case ISD::ADDC:
16522   case ISD::ADDE:
16523   case ISD::SUBC:
16524   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16525   case ISD::ADD:                return LowerADD(Op, DAG);
16526   case ISD::SUB:                return LowerSUB(Op, DAG);
16527   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16528   }
16529 }
16530
16531 static void ReplaceATOMIC_LOAD(SDNode *Node,
16532                                SmallVectorImpl<SDValue> &Results,
16533                                SelectionDAG &DAG) {
16534   SDLoc dl(Node);
16535   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16536
16537   // Convert wide load -> cmpxchg8b/cmpxchg16b
16538   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16539   //        (The only way to get a 16-byte load is cmpxchg16b)
16540   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16541   SDValue Zero = DAG.getConstant(0, VT);
16542   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16543   SDValue Swap =
16544       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16545                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16546                            cast<AtomicSDNode>(Node)->getMemOperand(),
16547                            cast<AtomicSDNode>(Node)->getOrdering(),
16548                            cast<AtomicSDNode>(Node)->getOrdering(),
16549                            cast<AtomicSDNode>(Node)->getSynchScope());
16550   Results.push_back(Swap.getValue(0));
16551   Results.push_back(Swap.getValue(2));
16552 }
16553
16554 /// ReplaceNodeResults - Replace a node with an illegal result type
16555 /// with a new node built out of custom code.
16556 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16557                                            SmallVectorImpl<SDValue>&Results,
16558                                            SelectionDAG &DAG) const {
16559   SDLoc dl(N);
16560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16561   switch (N->getOpcode()) {
16562   default:
16563     llvm_unreachable("Do not know how to custom type legalize this operation!");
16564   case ISD::SIGN_EXTEND_INREG:
16565   case ISD::ADDC:
16566   case ISD::ADDE:
16567   case ISD::SUBC:
16568   case ISD::SUBE:
16569     // We don't want to expand or promote these.
16570     return;
16571   case ISD::SDIV:
16572   case ISD::UDIV:
16573   case ISD::SREM:
16574   case ISD::UREM:
16575   case ISD::SDIVREM:
16576   case ISD::UDIVREM: {
16577     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16578     Results.push_back(V);
16579     return;
16580   }
16581   case ISD::FP_TO_SINT:
16582   case ISD::FP_TO_UINT: {
16583     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16584
16585     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16586       return;
16587
16588     std::pair<SDValue,SDValue> Vals =
16589         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16590     SDValue FIST = Vals.first, StackSlot = Vals.second;
16591     if (FIST.getNode()) {
16592       EVT VT = N->getValueType(0);
16593       // Return a load from the stack slot.
16594       if (StackSlot.getNode())
16595         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16596                                       MachinePointerInfo(),
16597                                       false, false, false, 0));
16598       else
16599         Results.push_back(FIST);
16600     }
16601     return;
16602   }
16603   case ISD::UINT_TO_FP: {
16604     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16605     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16606         N->getValueType(0) != MVT::v2f32)
16607       return;
16608     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16609                                  N->getOperand(0));
16610     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16611                                      MVT::f64);
16612     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16613     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16614                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16615     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16616     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16617     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16618     return;
16619   }
16620   case ISD::FP_ROUND: {
16621     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16622         return;
16623     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16624     Results.push_back(V);
16625     return;
16626   }
16627   case ISD::INTRINSIC_W_CHAIN: {
16628     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16629     switch (IntNo) {
16630     default : llvm_unreachable("Do not know how to custom type "
16631                                "legalize this intrinsic operation!");
16632     case Intrinsic::x86_rdtsc:
16633       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16634                                      Results);
16635     case Intrinsic::x86_rdtscp:
16636       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16637                                      Results);
16638     case Intrinsic::x86_rdpmc:
16639       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16640     }
16641   }
16642   case ISD::READCYCLECOUNTER: {
16643     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16644                                    Results);
16645   }
16646   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16647     EVT T = N->getValueType(0);
16648     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16649     bool Regs64bit = T == MVT::i128;
16650     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16651     SDValue cpInL, cpInH;
16652     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16653                         DAG.getConstant(0, HalfT));
16654     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16655                         DAG.getConstant(1, HalfT));
16656     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16657                              Regs64bit ? X86::RAX : X86::EAX,
16658                              cpInL, SDValue());
16659     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16660                              Regs64bit ? X86::RDX : X86::EDX,
16661                              cpInH, cpInL.getValue(1));
16662     SDValue swapInL, swapInH;
16663     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16664                           DAG.getConstant(0, HalfT));
16665     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16666                           DAG.getConstant(1, HalfT));
16667     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16668                                Regs64bit ? X86::RBX : X86::EBX,
16669                                swapInL, cpInH.getValue(1));
16670     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16671                                Regs64bit ? X86::RCX : X86::ECX,
16672                                swapInH, swapInL.getValue(1));
16673     SDValue Ops[] = { swapInH.getValue(0),
16674                       N->getOperand(1),
16675                       swapInH.getValue(1) };
16676     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16677     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16678     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16679                                   X86ISD::LCMPXCHG8_DAG;
16680     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16681     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16682                                         Regs64bit ? X86::RAX : X86::EAX,
16683                                         HalfT, Result.getValue(1));
16684     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16685                                         Regs64bit ? X86::RDX : X86::EDX,
16686                                         HalfT, cpOutL.getValue(2));
16687     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16688
16689     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16690                                         MVT::i32, cpOutH.getValue(2));
16691     SDValue Success =
16692         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16693                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16694     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16695
16696     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16697     Results.push_back(Success);
16698     Results.push_back(EFLAGS.getValue(1));
16699     return;
16700   }
16701   case ISD::ATOMIC_SWAP:
16702   case ISD::ATOMIC_LOAD_ADD:
16703   case ISD::ATOMIC_LOAD_SUB:
16704   case ISD::ATOMIC_LOAD_AND:
16705   case ISD::ATOMIC_LOAD_OR:
16706   case ISD::ATOMIC_LOAD_XOR:
16707   case ISD::ATOMIC_LOAD_NAND:
16708   case ISD::ATOMIC_LOAD_MIN:
16709   case ISD::ATOMIC_LOAD_MAX:
16710   case ISD::ATOMIC_LOAD_UMIN:
16711   case ISD::ATOMIC_LOAD_UMAX:
16712     // Delegate to generic TypeLegalization. Situations we can really handle
16713     // should have already been dealt with by X86AtomicExpand.cpp.
16714     break;
16715   case ISD::ATOMIC_LOAD: {
16716     ReplaceATOMIC_LOAD(N, Results, DAG);
16717     return;
16718   }
16719   case ISD::BITCAST: {
16720     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16721     EVT DstVT = N->getValueType(0);
16722     EVT SrcVT = N->getOperand(0)->getValueType(0);
16723
16724     if (SrcVT != MVT::f64 ||
16725         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16726       return;
16727
16728     unsigned NumElts = DstVT.getVectorNumElements();
16729     EVT SVT = DstVT.getVectorElementType();
16730     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16731     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16732                                    MVT::v2f64, N->getOperand(0));
16733     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16734
16735     if (ExperimentalVectorWideningLegalization) {
16736       // If we are legalizing vectors by widening, we already have the desired
16737       // legal vector type, just return it.
16738       Results.push_back(ToVecInt);
16739       return;
16740     }
16741
16742     SmallVector<SDValue, 8> Elts;
16743     for (unsigned i = 0, e = NumElts; i != e; ++i)
16744       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16745                                    ToVecInt, DAG.getIntPtrConstant(i)));
16746
16747     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16748   }
16749   }
16750 }
16751
16752 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16753   switch (Opcode) {
16754   default: return nullptr;
16755   case X86ISD::BSF:                return "X86ISD::BSF";
16756   case X86ISD::BSR:                return "X86ISD::BSR";
16757   case X86ISD::SHLD:               return "X86ISD::SHLD";
16758   case X86ISD::SHRD:               return "X86ISD::SHRD";
16759   case X86ISD::FAND:               return "X86ISD::FAND";
16760   case X86ISD::FANDN:              return "X86ISD::FANDN";
16761   case X86ISD::FOR:                return "X86ISD::FOR";
16762   case X86ISD::FXOR:               return "X86ISD::FXOR";
16763   case X86ISD::FSRL:               return "X86ISD::FSRL";
16764   case X86ISD::FILD:               return "X86ISD::FILD";
16765   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16766   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16767   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16768   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16769   case X86ISD::FLD:                return "X86ISD::FLD";
16770   case X86ISD::FST:                return "X86ISD::FST";
16771   case X86ISD::CALL:               return "X86ISD::CALL";
16772   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16773   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16774   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16775   case X86ISD::BT:                 return "X86ISD::BT";
16776   case X86ISD::CMP:                return "X86ISD::CMP";
16777   case X86ISD::COMI:               return "X86ISD::COMI";
16778   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16779   case X86ISD::CMPM:               return "X86ISD::CMPM";
16780   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16781   case X86ISD::SETCC:              return "X86ISD::SETCC";
16782   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16783   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16784   case X86ISD::CMOV:               return "X86ISD::CMOV";
16785   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16786   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16787   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16788   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16789   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16790   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16791   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16792   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16793   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16794   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16795   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16796   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16797   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16798   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16799   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16800   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16801   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16802   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16803   case X86ISD::HADD:               return "X86ISD::HADD";
16804   case X86ISD::HSUB:               return "X86ISD::HSUB";
16805   case X86ISD::FHADD:              return "X86ISD::FHADD";
16806   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16807   case X86ISD::UMAX:               return "X86ISD::UMAX";
16808   case X86ISD::UMIN:               return "X86ISD::UMIN";
16809   case X86ISD::SMAX:               return "X86ISD::SMAX";
16810   case X86ISD::SMIN:               return "X86ISD::SMIN";
16811   case X86ISD::FMAX:               return "X86ISD::FMAX";
16812   case X86ISD::FMIN:               return "X86ISD::FMIN";
16813   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16814   case X86ISD::FMINC:              return "X86ISD::FMINC";
16815   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16816   case X86ISD::FRCP:               return "X86ISD::FRCP";
16817   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16818   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16819   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16820   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16821   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16822   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16823   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16824   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16825   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16826   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16827   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16828   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16829   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16830   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16831   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16832   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16833   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16834   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16835   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16836   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16837   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16838   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16839   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16840   case X86ISD::VSHL:               return "X86ISD::VSHL";
16841   case X86ISD::VSRL:               return "X86ISD::VSRL";
16842   case X86ISD::VSRA:               return "X86ISD::VSRA";
16843   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16844   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16845   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16846   case X86ISD::CMPP:               return "X86ISD::CMPP";
16847   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16848   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16849   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16850   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16851   case X86ISD::ADD:                return "X86ISD::ADD";
16852   case X86ISD::SUB:                return "X86ISD::SUB";
16853   case X86ISD::ADC:                return "X86ISD::ADC";
16854   case X86ISD::SBB:                return "X86ISD::SBB";
16855   case X86ISD::SMUL:               return "X86ISD::SMUL";
16856   case X86ISD::UMUL:               return "X86ISD::UMUL";
16857   case X86ISD::INC:                return "X86ISD::INC";
16858   case X86ISD::DEC:                return "X86ISD::DEC";
16859   case X86ISD::OR:                 return "X86ISD::OR";
16860   case X86ISD::XOR:                return "X86ISD::XOR";
16861   case X86ISD::AND:                return "X86ISD::AND";
16862   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16863   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16864   case X86ISD::PTEST:              return "X86ISD::PTEST";
16865   case X86ISD::TESTP:              return "X86ISD::TESTP";
16866   case X86ISD::TESTM:              return "X86ISD::TESTM";
16867   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16868   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16869   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16870   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16871   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16872   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16873   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16874   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16875   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16876   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16877   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16878   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16879   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16880   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16881   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16882   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16883   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16884   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16885   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16886   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16887   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16888   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16889   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16890   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16891   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16892   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16893   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16894   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16895   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16896   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16897   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16898   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16899   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16900   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16901   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16902   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16903   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16904   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16905   case X86ISD::SAHF:               return "X86ISD::SAHF";
16906   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16907   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16908   case X86ISD::FMADD:              return "X86ISD::FMADD";
16909   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16910   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16911   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16912   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16913   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16914   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16915   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16916   case X86ISD::XTEST:              return "X86ISD::XTEST";
16917   }
16918 }
16919
16920 // isLegalAddressingMode - Return true if the addressing mode represented
16921 // by AM is legal for this target, for a load/store of the specified type.
16922 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16923                                               Type *Ty) const {
16924   // X86 supports extremely general addressing modes.
16925   CodeModel::Model M = getTargetMachine().getCodeModel();
16926   Reloc::Model R = getTargetMachine().getRelocationModel();
16927
16928   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16929   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16930     return false;
16931
16932   if (AM.BaseGV) {
16933     unsigned GVFlags =
16934       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16935
16936     // If a reference to this global requires an extra load, we can't fold it.
16937     if (isGlobalStubReference(GVFlags))
16938       return false;
16939
16940     // If BaseGV requires a register for the PIC base, we cannot also have a
16941     // BaseReg specified.
16942     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16943       return false;
16944
16945     // If lower 4G is not available, then we must use rip-relative addressing.
16946     if ((M != CodeModel::Small || R != Reloc::Static) &&
16947         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16948       return false;
16949   }
16950
16951   switch (AM.Scale) {
16952   case 0:
16953   case 1:
16954   case 2:
16955   case 4:
16956   case 8:
16957     // These scales always work.
16958     break;
16959   case 3:
16960   case 5:
16961   case 9:
16962     // These scales are formed with basereg+scalereg.  Only accept if there is
16963     // no basereg yet.
16964     if (AM.HasBaseReg)
16965       return false;
16966     break;
16967   default:  // Other stuff never works.
16968     return false;
16969   }
16970
16971   return true;
16972 }
16973
16974 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16975   unsigned Bits = Ty->getScalarSizeInBits();
16976
16977   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16978   // particularly cheaper than those without.
16979   if (Bits == 8)
16980     return false;
16981
16982   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16983   // variable shifts just as cheap as scalar ones.
16984   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16985     return false;
16986
16987   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16988   // fully general vector.
16989   return true;
16990 }
16991
16992 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16993   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16994     return false;
16995   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16996   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16997   return NumBits1 > NumBits2;
16998 }
16999
17000 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17001   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17002     return false;
17003
17004   if (!isTypeLegal(EVT::getEVT(Ty1)))
17005     return false;
17006
17007   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17008
17009   // Assuming the caller doesn't have a zeroext or signext return parameter,
17010   // truncation all the way down to i1 is valid.
17011   return true;
17012 }
17013
17014 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17015   return isInt<32>(Imm);
17016 }
17017
17018 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17019   // Can also use sub to handle negated immediates.
17020   return isInt<32>(Imm);
17021 }
17022
17023 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17024   if (!VT1.isInteger() || !VT2.isInteger())
17025     return false;
17026   unsigned NumBits1 = VT1.getSizeInBits();
17027   unsigned NumBits2 = VT2.getSizeInBits();
17028   return NumBits1 > NumBits2;
17029 }
17030
17031 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17032   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17033   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17034 }
17035
17036 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17037   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17038   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17039 }
17040
17041 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17042   EVT VT1 = Val.getValueType();
17043   if (isZExtFree(VT1, VT2))
17044     return true;
17045
17046   if (Val.getOpcode() != ISD::LOAD)
17047     return false;
17048
17049   if (!VT1.isSimple() || !VT1.isInteger() ||
17050       !VT2.isSimple() || !VT2.isInteger())
17051     return false;
17052
17053   switch (VT1.getSimpleVT().SimpleTy) {
17054   default: break;
17055   case MVT::i8:
17056   case MVT::i16:
17057   case MVT::i32:
17058     // X86 has 8, 16, and 32-bit zero-extending loads.
17059     return true;
17060   }
17061
17062   return false;
17063 }
17064
17065 bool
17066 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17067   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17068     return false;
17069
17070   VT = VT.getScalarType();
17071
17072   if (!VT.isSimple())
17073     return false;
17074
17075   switch (VT.getSimpleVT().SimpleTy) {
17076   case MVT::f32:
17077   case MVT::f64:
17078     return true;
17079   default:
17080     break;
17081   }
17082
17083   return false;
17084 }
17085
17086 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17087   // i16 instructions are longer (0x66 prefix) and potentially slower.
17088   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17089 }
17090
17091 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17092 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17093 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17094 /// are assumed to be legal.
17095 bool
17096 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17097                                       EVT VT) const {
17098   if (!VT.isSimple())
17099     return false;
17100
17101   MVT SVT = VT.getSimpleVT();
17102
17103   // Very little shuffling can be done for 64-bit vectors right now.
17104   if (VT.getSizeInBits() == 64)
17105     return false;
17106
17107   // If this is a single-input shuffle with no 128 bit lane crossings we can
17108   // lower it into pshufb.
17109   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17110       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17111     bool isLegal = true;
17112     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17113       if (M[I] >= (int)SVT.getVectorNumElements() ||
17114           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17115         isLegal = false;
17116         break;
17117       }
17118     }
17119     if (isLegal)
17120       return true;
17121   }
17122
17123   // FIXME: blends, shifts.
17124   return (SVT.getVectorNumElements() == 2 ||
17125           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17126           isMOVLMask(M, SVT) ||
17127           isMOVHLPSMask(M, SVT) ||
17128           isSHUFPMask(M, SVT) ||
17129           isPSHUFDMask(M, SVT) ||
17130           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17131           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17132           isPALIGNRMask(M, SVT, Subtarget) ||
17133           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17134           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17135           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17136           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17137           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17138 }
17139
17140 bool
17141 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17142                                           EVT VT) const {
17143   if (!VT.isSimple())
17144     return false;
17145
17146   MVT SVT = VT.getSimpleVT();
17147   unsigned NumElts = SVT.getVectorNumElements();
17148   // FIXME: This collection of masks seems suspect.
17149   if (NumElts == 2)
17150     return true;
17151   if (NumElts == 4 && SVT.is128BitVector()) {
17152     return (isMOVLMask(Mask, SVT)  ||
17153             isCommutedMOVLMask(Mask, SVT, true) ||
17154             isSHUFPMask(Mask, SVT) ||
17155             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17156   }
17157   return false;
17158 }
17159
17160 //===----------------------------------------------------------------------===//
17161 //                           X86 Scheduler Hooks
17162 //===----------------------------------------------------------------------===//
17163
17164 /// Utility function to emit xbegin specifying the start of an RTM region.
17165 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17166                                      const TargetInstrInfo *TII) {
17167   DebugLoc DL = MI->getDebugLoc();
17168
17169   const BasicBlock *BB = MBB->getBasicBlock();
17170   MachineFunction::iterator I = MBB;
17171   ++I;
17172
17173   // For the v = xbegin(), we generate
17174   //
17175   // thisMBB:
17176   //  xbegin sinkMBB
17177   //
17178   // mainMBB:
17179   //  eax = -1
17180   //
17181   // sinkMBB:
17182   //  v = eax
17183
17184   MachineBasicBlock *thisMBB = MBB;
17185   MachineFunction *MF = MBB->getParent();
17186   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17187   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17188   MF->insert(I, mainMBB);
17189   MF->insert(I, sinkMBB);
17190
17191   // Transfer the remainder of BB and its successor edges to sinkMBB.
17192   sinkMBB->splice(sinkMBB->begin(), MBB,
17193                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17194   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17195
17196   // thisMBB:
17197   //  xbegin sinkMBB
17198   //  # fallthrough to mainMBB
17199   //  # abortion to sinkMBB
17200   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17201   thisMBB->addSuccessor(mainMBB);
17202   thisMBB->addSuccessor(sinkMBB);
17203
17204   // mainMBB:
17205   //  EAX = -1
17206   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17207   mainMBB->addSuccessor(sinkMBB);
17208
17209   // sinkMBB:
17210   // EAX is live into the sinkMBB
17211   sinkMBB->addLiveIn(X86::EAX);
17212   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17213           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17214     .addReg(X86::EAX);
17215
17216   MI->eraseFromParent();
17217   return sinkMBB;
17218 }
17219
17220 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17221 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17222 // in the .td file.
17223 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17224                                        const TargetInstrInfo *TII) {
17225   unsigned Opc;
17226   switch (MI->getOpcode()) {
17227   default: llvm_unreachable("illegal opcode!");
17228   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17229   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17230   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17231   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17232   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17233   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17234   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17235   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17236   }
17237
17238   DebugLoc dl = MI->getDebugLoc();
17239   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17240
17241   unsigned NumArgs = MI->getNumOperands();
17242   for (unsigned i = 1; i < NumArgs; ++i) {
17243     MachineOperand &Op = MI->getOperand(i);
17244     if (!(Op.isReg() && Op.isImplicit()))
17245       MIB.addOperand(Op);
17246   }
17247   if (MI->hasOneMemOperand())
17248     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17249
17250   BuildMI(*BB, MI, dl,
17251     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17252     .addReg(X86::XMM0);
17253
17254   MI->eraseFromParent();
17255   return BB;
17256 }
17257
17258 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17259 // defs in an instruction pattern
17260 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17261                                        const TargetInstrInfo *TII) {
17262   unsigned Opc;
17263   switch (MI->getOpcode()) {
17264   default: llvm_unreachable("illegal opcode!");
17265   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17266   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17267   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17268   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17269   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17270   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17271   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17272   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17273   }
17274
17275   DebugLoc dl = MI->getDebugLoc();
17276   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17277
17278   unsigned NumArgs = MI->getNumOperands(); // remove the results
17279   for (unsigned i = 1; i < NumArgs; ++i) {
17280     MachineOperand &Op = MI->getOperand(i);
17281     if (!(Op.isReg() && Op.isImplicit()))
17282       MIB.addOperand(Op);
17283   }
17284   if (MI->hasOneMemOperand())
17285     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17286
17287   BuildMI(*BB, MI, dl,
17288     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17289     .addReg(X86::ECX);
17290
17291   MI->eraseFromParent();
17292   return BB;
17293 }
17294
17295 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17296                                        const TargetInstrInfo *TII,
17297                                        const X86Subtarget* Subtarget) {
17298   DebugLoc dl = MI->getDebugLoc();
17299
17300   // Address into RAX/EAX, other two args into ECX, EDX.
17301   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17302   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17303   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17304   for (int i = 0; i < X86::AddrNumOperands; ++i)
17305     MIB.addOperand(MI->getOperand(i));
17306
17307   unsigned ValOps = X86::AddrNumOperands;
17308   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17309     .addReg(MI->getOperand(ValOps).getReg());
17310   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17311     .addReg(MI->getOperand(ValOps+1).getReg());
17312
17313   // The instruction doesn't actually take any operands though.
17314   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17315
17316   MI->eraseFromParent(); // The pseudo is gone now.
17317   return BB;
17318 }
17319
17320 MachineBasicBlock *
17321 X86TargetLowering::EmitVAARG64WithCustomInserter(
17322                    MachineInstr *MI,
17323                    MachineBasicBlock *MBB) const {
17324   // Emit va_arg instruction on X86-64.
17325
17326   // Operands to this pseudo-instruction:
17327   // 0  ) Output        : destination address (reg)
17328   // 1-5) Input         : va_list address (addr, i64mem)
17329   // 6  ) ArgSize       : Size (in bytes) of vararg type
17330   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17331   // 8  ) Align         : Alignment of type
17332   // 9  ) EFLAGS (implicit-def)
17333
17334   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17335   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17336
17337   unsigned DestReg = MI->getOperand(0).getReg();
17338   MachineOperand &Base = MI->getOperand(1);
17339   MachineOperand &Scale = MI->getOperand(2);
17340   MachineOperand &Index = MI->getOperand(3);
17341   MachineOperand &Disp = MI->getOperand(4);
17342   MachineOperand &Segment = MI->getOperand(5);
17343   unsigned ArgSize = MI->getOperand(6).getImm();
17344   unsigned ArgMode = MI->getOperand(7).getImm();
17345   unsigned Align = MI->getOperand(8).getImm();
17346
17347   // Memory Reference
17348   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17349   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17350   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17351
17352   // Machine Information
17353   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17354   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17355   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17356   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17357   DebugLoc DL = MI->getDebugLoc();
17358
17359   // struct va_list {
17360   //   i32   gp_offset
17361   //   i32   fp_offset
17362   //   i64   overflow_area (address)
17363   //   i64   reg_save_area (address)
17364   // }
17365   // sizeof(va_list) = 24
17366   // alignment(va_list) = 8
17367
17368   unsigned TotalNumIntRegs = 6;
17369   unsigned TotalNumXMMRegs = 8;
17370   bool UseGPOffset = (ArgMode == 1);
17371   bool UseFPOffset = (ArgMode == 2);
17372   unsigned MaxOffset = TotalNumIntRegs * 8 +
17373                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17374
17375   /* Align ArgSize to a multiple of 8 */
17376   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17377   bool NeedsAlign = (Align > 8);
17378
17379   MachineBasicBlock *thisMBB = MBB;
17380   MachineBasicBlock *overflowMBB;
17381   MachineBasicBlock *offsetMBB;
17382   MachineBasicBlock *endMBB;
17383
17384   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17385   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17386   unsigned OffsetReg = 0;
17387
17388   if (!UseGPOffset && !UseFPOffset) {
17389     // If we only pull from the overflow region, we don't create a branch.
17390     // We don't need to alter control flow.
17391     OffsetDestReg = 0; // unused
17392     OverflowDestReg = DestReg;
17393
17394     offsetMBB = nullptr;
17395     overflowMBB = thisMBB;
17396     endMBB = thisMBB;
17397   } else {
17398     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17399     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17400     // If not, pull from overflow_area. (branch to overflowMBB)
17401     //
17402     //       thisMBB
17403     //         |     .
17404     //         |        .
17405     //     offsetMBB   overflowMBB
17406     //         |        .
17407     //         |     .
17408     //        endMBB
17409
17410     // Registers for the PHI in endMBB
17411     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17412     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17413
17414     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17415     MachineFunction *MF = MBB->getParent();
17416     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17417     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17418     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17419
17420     MachineFunction::iterator MBBIter = MBB;
17421     ++MBBIter;
17422
17423     // Insert the new basic blocks
17424     MF->insert(MBBIter, offsetMBB);
17425     MF->insert(MBBIter, overflowMBB);
17426     MF->insert(MBBIter, endMBB);
17427
17428     // Transfer the remainder of MBB and its successor edges to endMBB.
17429     endMBB->splice(endMBB->begin(), thisMBB,
17430                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17431     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17432
17433     // Make offsetMBB and overflowMBB successors of thisMBB
17434     thisMBB->addSuccessor(offsetMBB);
17435     thisMBB->addSuccessor(overflowMBB);
17436
17437     // endMBB is a successor of both offsetMBB and overflowMBB
17438     offsetMBB->addSuccessor(endMBB);
17439     overflowMBB->addSuccessor(endMBB);
17440
17441     // Load the offset value into a register
17442     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17443     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17444       .addOperand(Base)
17445       .addOperand(Scale)
17446       .addOperand(Index)
17447       .addDisp(Disp, UseFPOffset ? 4 : 0)
17448       .addOperand(Segment)
17449       .setMemRefs(MMOBegin, MMOEnd);
17450
17451     // Check if there is enough room left to pull this argument.
17452     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17453       .addReg(OffsetReg)
17454       .addImm(MaxOffset + 8 - ArgSizeA8);
17455
17456     // Branch to "overflowMBB" if offset >= max
17457     // Fall through to "offsetMBB" otherwise
17458     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17459       .addMBB(overflowMBB);
17460   }
17461
17462   // In offsetMBB, emit code to use the reg_save_area.
17463   if (offsetMBB) {
17464     assert(OffsetReg != 0);
17465
17466     // Read the reg_save_area address.
17467     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17468     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17469       .addOperand(Base)
17470       .addOperand(Scale)
17471       .addOperand(Index)
17472       .addDisp(Disp, 16)
17473       .addOperand(Segment)
17474       .setMemRefs(MMOBegin, MMOEnd);
17475
17476     // Zero-extend the offset
17477     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17478       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17479         .addImm(0)
17480         .addReg(OffsetReg)
17481         .addImm(X86::sub_32bit);
17482
17483     // Add the offset to the reg_save_area to get the final address.
17484     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17485       .addReg(OffsetReg64)
17486       .addReg(RegSaveReg);
17487
17488     // Compute the offset for the next argument
17489     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17490     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17491       .addReg(OffsetReg)
17492       .addImm(UseFPOffset ? 16 : 8);
17493
17494     // Store it back into the va_list.
17495     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17496       .addOperand(Base)
17497       .addOperand(Scale)
17498       .addOperand(Index)
17499       .addDisp(Disp, UseFPOffset ? 4 : 0)
17500       .addOperand(Segment)
17501       .addReg(NextOffsetReg)
17502       .setMemRefs(MMOBegin, MMOEnd);
17503
17504     // Jump to endMBB
17505     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17506       .addMBB(endMBB);
17507   }
17508
17509   //
17510   // Emit code to use overflow area
17511   //
17512
17513   // Load the overflow_area address into a register.
17514   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17515   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17516     .addOperand(Base)
17517     .addOperand(Scale)
17518     .addOperand(Index)
17519     .addDisp(Disp, 8)
17520     .addOperand(Segment)
17521     .setMemRefs(MMOBegin, MMOEnd);
17522
17523   // If we need to align it, do so. Otherwise, just copy the address
17524   // to OverflowDestReg.
17525   if (NeedsAlign) {
17526     // Align the overflow address
17527     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17528     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17529
17530     // aligned_addr = (addr + (align-1)) & ~(align-1)
17531     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17532       .addReg(OverflowAddrReg)
17533       .addImm(Align-1);
17534
17535     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17536       .addReg(TmpReg)
17537       .addImm(~(uint64_t)(Align-1));
17538   } else {
17539     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17540       .addReg(OverflowAddrReg);
17541   }
17542
17543   // Compute the next overflow address after this argument.
17544   // (the overflow address should be kept 8-byte aligned)
17545   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17546   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17547     .addReg(OverflowDestReg)
17548     .addImm(ArgSizeA8);
17549
17550   // Store the new overflow address.
17551   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17552     .addOperand(Base)
17553     .addOperand(Scale)
17554     .addOperand(Index)
17555     .addDisp(Disp, 8)
17556     .addOperand(Segment)
17557     .addReg(NextAddrReg)
17558     .setMemRefs(MMOBegin, MMOEnd);
17559
17560   // If we branched, emit the PHI to the front of endMBB.
17561   if (offsetMBB) {
17562     BuildMI(*endMBB, endMBB->begin(), DL,
17563             TII->get(X86::PHI), DestReg)
17564       .addReg(OffsetDestReg).addMBB(offsetMBB)
17565       .addReg(OverflowDestReg).addMBB(overflowMBB);
17566   }
17567
17568   // Erase the pseudo instruction
17569   MI->eraseFromParent();
17570
17571   return endMBB;
17572 }
17573
17574 MachineBasicBlock *
17575 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17576                                                  MachineInstr *MI,
17577                                                  MachineBasicBlock *MBB) const {
17578   // Emit code to save XMM registers to the stack. The ABI says that the
17579   // number of registers to save is given in %al, so it's theoretically
17580   // possible to do an indirect jump trick to avoid saving all of them,
17581   // however this code takes a simpler approach and just executes all
17582   // of the stores if %al is non-zero. It's less code, and it's probably
17583   // easier on the hardware branch predictor, and stores aren't all that
17584   // expensive anyway.
17585
17586   // Create the new basic blocks. One block contains all the XMM stores,
17587   // and one block is the final destination regardless of whether any
17588   // stores were performed.
17589   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17590   MachineFunction *F = MBB->getParent();
17591   MachineFunction::iterator MBBIter = MBB;
17592   ++MBBIter;
17593   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17594   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17595   F->insert(MBBIter, XMMSaveMBB);
17596   F->insert(MBBIter, EndMBB);
17597
17598   // Transfer the remainder of MBB and its successor edges to EndMBB.
17599   EndMBB->splice(EndMBB->begin(), MBB,
17600                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17601   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17602
17603   // The original block will now fall through to the XMM save block.
17604   MBB->addSuccessor(XMMSaveMBB);
17605   // The XMMSaveMBB will fall through to the end block.
17606   XMMSaveMBB->addSuccessor(EndMBB);
17607
17608   // Now add the instructions.
17609   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17610   DebugLoc DL = MI->getDebugLoc();
17611
17612   unsigned CountReg = MI->getOperand(0).getReg();
17613   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17614   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17615
17616   if (!Subtarget->isTargetWin64()) {
17617     // If %al is 0, branch around the XMM save block.
17618     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17619     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17620     MBB->addSuccessor(EndMBB);
17621   }
17622
17623   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17624   // that was just emitted, but clearly shouldn't be "saved".
17625   assert((MI->getNumOperands() <= 3 ||
17626           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17627           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17628          && "Expected last argument to be EFLAGS");
17629   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17630   // In the XMM save block, save all the XMM argument registers.
17631   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17632     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17633     MachineMemOperand *MMO =
17634       F->getMachineMemOperand(
17635           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17636         MachineMemOperand::MOStore,
17637         /*Size=*/16, /*Align=*/16);
17638     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17639       .addFrameIndex(RegSaveFrameIndex)
17640       .addImm(/*Scale=*/1)
17641       .addReg(/*IndexReg=*/0)
17642       .addImm(/*Disp=*/Offset)
17643       .addReg(/*Segment=*/0)
17644       .addReg(MI->getOperand(i).getReg())
17645       .addMemOperand(MMO);
17646   }
17647
17648   MI->eraseFromParent();   // The pseudo instruction is gone now.
17649
17650   return EndMBB;
17651 }
17652
17653 // The EFLAGS operand of SelectItr might be missing a kill marker
17654 // because there were multiple uses of EFLAGS, and ISel didn't know
17655 // which to mark. Figure out whether SelectItr should have had a
17656 // kill marker, and set it if it should. Returns the correct kill
17657 // marker value.
17658 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17659                                      MachineBasicBlock* BB,
17660                                      const TargetRegisterInfo* TRI) {
17661   // Scan forward through BB for a use/def of EFLAGS.
17662   MachineBasicBlock::iterator miI(std::next(SelectItr));
17663   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17664     const MachineInstr& mi = *miI;
17665     if (mi.readsRegister(X86::EFLAGS))
17666       return false;
17667     if (mi.definesRegister(X86::EFLAGS))
17668       break; // Should have kill-flag - update below.
17669   }
17670
17671   // If we hit the end of the block, check whether EFLAGS is live into a
17672   // successor.
17673   if (miI == BB->end()) {
17674     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17675                                           sEnd = BB->succ_end();
17676          sItr != sEnd; ++sItr) {
17677       MachineBasicBlock* succ = *sItr;
17678       if (succ->isLiveIn(X86::EFLAGS))
17679         return false;
17680     }
17681   }
17682
17683   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17684   // out. SelectMI should have a kill flag on EFLAGS.
17685   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17686   return true;
17687 }
17688
17689 MachineBasicBlock *
17690 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17691                                      MachineBasicBlock *BB) const {
17692   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17693   DebugLoc DL = MI->getDebugLoc();
17694
17695   // To "insert" a SELECT_CC instruction, we actually have to insert the
17696   // diamond control-flow pattern.  The incoming instruction knows the
17697   // destination vreg to set, the condition code register to branch on, the
17698   // true/false values to select between, and a branch opcode to use.
17699   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17700   MachineFunction::iterator It = BB;
17701   ++It;
17702
17703   //  thisMBB:
17704   //  ...
17705   //   TrueVal = ...
17706   //   cmpTY ccX, r1, r2
17707   //   bCC copy1MBB
17708   //   fallthrough --> copy0MBB
17709   MachineBasicBlock *thisMBB = BB;
17710   MachineFunction *F = BB->getParent();
17711   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17712   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17713   F->insert(It, copy0MBB);
17714   F->insert(It, sinkMBB);
17715
17716   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17717   // live into the sink and copy blocks.
17718   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17719   if (!MI->killsRegister(X86::EFLAGS) &&
17720       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17721     copy0MBB->addLiveIn(X86::EFLAGS);
17722     sinkMBB->addLiveIn(X86::EFLAGS);
17723   }
17724
17725   // Transfer the remainder of BB and its successor edges to sinkMBB.
17726   sinkMBB->splice(sinkMBB->begin(), BB,
17727                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17728   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17729
17730   // Add the true and fallthrough blocks as its successors.
17731   BB->addSuccessor(copy0MBB);
17732   BB->addSuccessor(sinkMBB);
17733
17734   // Create the conditional branch instruction.
17735   unsigned Opc =
17736     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17737   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17738
17739   //  copy0MBB:
17740   //   %FalseValue = ...
17741   //   # fallthrough to sinkMBB
17742   copy0MBB->addSuccessor(sinkMBB);
17743
17744   //  sinkMBB:
17745   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17746   //  ...
17747   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17748           TII->get(X86::PHI), MI->getOperand(0).getReg())
17749     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17750     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17751
17752   MI->eraseFromParent();   // The pseudo instruction is gone now.
17753   return sinkMBB;
17754 }
17755
17756 MachineBasicBlock *
17757 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17758                                         bool Is64Bit) const {
17759   MachineFunction *MF = BB->getParent();
17760   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17761   DebugLoc DL = MI->getDebugLoc();
17762   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17763
17764   assert(MF->shouldSplitStack());
17765
17766   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17767   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17768
17769   // BB:
17770   //  ... [Till the alloca]
17771   // If stacklet is not large enough, jump to mallocMBB
17772   //
17773   // bumpMBB:
17774   //  Allocate by subtracting from RSP
17775   //  Jump to continueMBB
17776   //
17777   // mallocMBB:
17778   //  Allocate by call to runtime
17779   //
17780   // continueMBB:
17781   //  ...
17782   //  [rest of original BB]
17783   //
17784
17785   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17786   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17787   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17788
17789   MachineRegisterInfo &MRI = MF->getRegInfo();
17790   const TargetRegisterClass *AddrRegClass =
17791     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17792
17793   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17794     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17795     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17796     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17797     sizeVReg = MI->getOperand(1).getReg(),
17798     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17799
17800   MachineFunction::iterator MBBIter = BB;
17801   ++MBBIter;
17802
17803   MF->insert(MBBIter, bumpMBB);
17804   MF->insert(MBBIter, mallocMBB);
17805   MF->insert(MBBIter, continueMBB);
17806
17807   continueMBB->splice(continueMBB->begin(), BB,
17808                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17809   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17810
17811   // Add code to the main basic block to check if the stack limit has been hit,
17812   // and if so, jump to mallocMBB otherwise to bumpMBB.
17813   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17814   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17815     .addReg(tmpSPVReg).addReg(sizeVReg);
17816   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17817     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17818     .addReg(SPLimitVReg);
17819   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17820
17821   // bumpMBB simply decreases the stack pointer, since we know the current
17822   // stacklet has enough space.
17823   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17824     .addReg(SPLimitVReg);
17825   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17826     .addReg(SPLimitVReg);
17827   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17828
17829   // Calls into a routine in libgcc to allocate more space from the heap.
17830   const uint32_t *RegMask =
17831     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17832   if (Is64Bit) {
17833     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17834       .addReg(sizeVReg);
17835     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17836       .addExternalSymbol("__morestack_allocate_stack_space")
17837       .addRegMask(RegMask)
17838       .addReg(X86::RDI, RegState::Implicit)
17839       .addReg(X86::RAX, RegState::ImplicitDefine);
17840   } else {
17841     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17842       .addImm(12);
17843     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17844     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17845       .addExternalSymbol("__morestack_allocate_stack_space")
17846       .addRegMask(RegMask)
17847       .addReg(X86::EAX, RegState::ImplicitDefine);
17848   }
17849
17850   if (!Is64Bit)
17851     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17852       .addImm(16);
17853
17854   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17855     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17856   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17857
17858   // Set up the CFG correctly.
17859   BB->addSuccessor(bumpMBB);
17860   BB->addSuccessor(mallocMBB);
17861   mallocMBB->addSuccessor(continueMBB);
17862   bumpMBB->addSuccessor(continueMBB);
17863
17864   // Take care of the PHI nodes.
17865   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17866           MI->getOperand(0).getReg())
17867     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17868     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17869
17870   // Delete the original pseudo instruction.
17871   MI->eraseFromParent();
17872
17873   // And we're done.
17874   return continueMBB;
17875 }
17876
17877 MachineBasicBlock *
17878 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17879                                         MachineBasicBlock *BB) const {
17880   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17881   DebugLoc DL = MI->getDebugLoc();
17882
17883   assert(!Subtarget->isTargetMacho());
17884
17885   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17886   // non-trivial part is impdef of ESP.
17887
17888   if (Subtarget->isTargetWin64()) {
17889     if (Subtarget->isTargetCygMing()) {
17890       // ___chkstk(Mingw64):
17891       // Clobbers R10, R11, RAX and EFLAGS.
17892       // Updates RSP.
17893       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17894         .addExternalSymbol("___chkstk")
17895         .addReg(X86::RAX, RegState::Implicit)
17896         .addReg(X86::RSP, RegState::Implicit)
17897         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17898         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17899         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17900     } else {
17901       // __chkstk(MSVCRT): does not update stack pointer.
17902       // Clobbers R10, R11 and EFLAGS.
17903       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17904         .addExternalSymbol("__chkstk")
17905         .addReg(X86::RAX, RegState::Implicit)
17906         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17907       // RAX has the offset to be subtracted from RSP.
17908       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17909         .addReg(X86::RSP)
17910         .addReg(X86::RAX);
17911     }
17912   } else {
17913     const char *StackProbeSymbol =
17914       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17915
17916     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17917       .addExternalSymbol(StackProbeSymbol)
17918       .addReg(X86::EAX, RegState::Implicit)
17919       .addReg(X86::ESP, RegState::Implicit)
17920       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17921       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17922       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17923   }
17924
17925   MI->eraseFromParent();   // The pseudo instruction is gone now.
17926   return BB;
17927 }
17928
17929 MachineBasicBlock *
17930 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17931                                       MachineBasicBlock *BB) const {
17932   // This is pretty easy.  We're taking the value that we received from
17933   // our load from the relocation, sticking it in either RDI (x86-64)
17934   // or EAX and doing an indirect call.  The return value will then
17935   // be in the normal return register.
17936   MachineFunction *F = BB->getParent();
17937   const X86InstrInfo *TII
17938     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17939   DebugLoc DL = MI->getDebugLoc();
17940
17941   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17942   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17943
17944   // Get a register mask for the lowered call.
17945   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17946   // proper register mask.
17947   const uint32_t *RegMask =
17948     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17949   if (Subtarget->is64Bit()) {
17950     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17951                                       TII->get(X86::MOV64rm), X86::RDI)
17952     .addReg(X86::RIP)
17953     .addImm(0).addReg(0)
17954     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17955                       MI->getOperand(3).getTargetFlags())
17956     .addReg(0);
17957     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17958     addDirectMem(MIB, X86::RDI);
17959     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17960   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17961     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17962                                       TII->get(X86::MOV32rm), X86::EAX)
17963     .addReg(0)
17964     .addImm(0).addReg(0)
17965     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17966                       MI->getOperand(3).getTargetFlags())
17967     .addReg(0);
17968     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17969     addDirectMem(MIB, X86::EAX);
17970     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17971   } else {
17972     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17973                                       TII->get(X86::MOV32rm), X86::EAX)
17974     .addReg(TII->getGlobalBaseReg(F))
17975     .addImm(0).addReg(0)
17976     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17977                       MI->getOperand(3).getTargetFlags())
17978     .addReg(0);
17979     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17980     addDirectMem(MIB, X86::EAX);
17981     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17982   }
17983
17984   MI->eraseFromParent(); // The pseudo instruction is gone now.
17985   return BB;
17986 }
17987
17988 MachineBasicBlock *
17989 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17990                                     MachineBasicBlock *MBB) const {
17991   DebugLoc DL = MI->getDebugLoc();
17992   MachineFunction *MF = MBB->getParent();
17993   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17994   MachineRegisterInfo &MRI = MF->getRegInfo();
17995
17996   const BasicBlock *BB = MBB->getBasicBlock();
17997   MachineFunction::iterator I = MBB;
17998   ++I;
17999
18000   // Memory Reference
18001   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18002   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18003
18004   unsigned DstReg;
18005   unsigned MemOpndSlot = 0;
18006
18007   unsigned CurOp = 0;
18008
18009   DstReg = MI->getOperand(CurOp++).getReg();
18010   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18011   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18012   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18013   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18014
18015   MemOpndSlot = CurOp;
18016
18017   MVT PVT = getPointerTy();
18018   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18019          "Invalid Pointer Size!");
18020
18021   // For v = setjmp(buf), we generate
18022   //
18023   // thisMBB:
18024   //  buf[LabelOffset] = restoreMBB
18025   //  SjLjSetup restoreMBB
18026   //
18027   // mainMBB:
18028   //  v_main = 0
18029   //
18030   // sinkMBB:
18031   //  v = phi(main, restore)
18032   //
18033   // restoreMBB:
18034   //  v_restore = 1
18035
18036   MachineBasicBlock *thisMBB = MBB;
18037   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18038   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18039   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18040   MF->insert(I, mainMBB);
18041   MF->insert(I, sinkMBB);
18042   MF->push_back(restoreMBB);
18043
18044   MachineInstrBuilder MIB;
18045
18046   // Transfer the remainder of BB and its successor edges to sinkMBB.
18047   sinkMBB->splice(sinkMBB->begin(), MBB,
18048                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18049   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18050
18051   // thisMBB:
18052   unsigned PtrStoreOpc = 0;
18053   unsigned LabelReg = 0;
18054   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18055   Reloc::Model RM = MF->getTarget().getRelocationModel();
18056   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18057                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18058
18059   // Prepare IP either in reg or imm.
18060   if (!UseImmLabel) {
18061     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18062     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18063     LabelReg = MRI.createVirtualRegister(PtrRC);
18064     if (Subtarget->is64Bit()) {
18065       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18066               .addReg(X86::RIP)
18067               .addImm(0)
18068               .addReg(0)
18069               .addMBB(restoreMBB)
18070               .addReg(0);
18071     } else {
18072       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18073       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18074               .addReg(XII->getGlobalBaseReg(MF))
18075               .addImm(0)
18076               .addReg(0)
18077               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18078               .addReg(0);
18079     }
18080   } else
18081     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18082   // Store IP
18083   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18084   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18085     if (i == X86::AddrDisp)
18086       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18087     else
18088       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18089   }
18090   if (!UseImmLabel)
18091     MIB.addReg(LabelReg);
18092   else
18093     MIB.addMBB(restoreMBB);
18094   MIB.setMemRefs(MMOBegin, MMOEnd);
18095   // Setup
18096   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18097           .addMBB(restoreMBB);
18098
18099   const X86RegisterInfo *RegInfo =
18100     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18101   MIB.addRegMask(RegInfo->getNoPreservedMask());
18102   thisMBB->addSuccessor(mainMBB);
18103   thisMBB->addSuccessor(restoreMBB);
18104
18105   // mainMBB:
18106   //  EAX = 0
18107   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18108   mainMBB->addSuccessor(sinkMBB);
18109
18110   // sinkMBB:
18111   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18112           TII->get(X86::PHI), DstReg)
18113     .addReg(mainDstReg).addMBB(mainMBB)
18114     .addReg(restoreDstReg).addMBB(restoreMBB);
18115
18116   // restoreMBB:
18117   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18118   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18119   restoreMBB->addSuccessor(sinkMBB);
18120
18121   MI->eraseFromParent();
18122   return sinkMBB;
18123 }
18124
18125 MachineBasicBlock *
18126 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18127                                      MachineBasicBlock *MBB) const {
18128   DebugLoc DL = MI->getDebugLoc();
18129   MachineFunction *MF = MBB->getParent();
18130   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18131   MachineRegisterInfo &MRI = MF->getRegInfo();
18132
18133   // Memory Reference
18134   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18135   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18136
18137   MVT PVT = getPointerTy();
18138   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18139          "Invalid Pointer Size!");
18140
18141   const TargetRegisterClass *RC =
18142     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18143   unsigned Tmp = MRI.createVirtualRegister(RC);
18144   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18145   const X86RegisterInfo *RegInfo =
18146     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18147   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18148   unsigned SP = RegInfo->getStackRegister();
18149
18150   MachineInstrBuilder MIB;
18151
18152   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18153   const int64_t SPOffset = 2 * PVT.getStoreSize();
18154
18155   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18156   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18157
18158   // Reload FP
18159   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18160   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18161     MIB.addOperand(MI->getOperand(i));
18162   MIB.setMemRefs(MMOBegin, MMOEnd);
18163   // Reload IP
18164   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18165   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18166     if (i == X86::AddrDisp)
18167       MIB.addDisp(MI->getOperand(i), LabelOffset);
18168     else
18169       MIB.addOperand(MI->getOperand(i));
18170   }
18171   MIB.setMemRefs(MMOBegin, MMOEnd);
18172   // Reload SP
18173   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18174   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18175     if (i == X86::AddrDisp)
18176       MIB.addDisp(MI->getOperand(i), SPOffset);
18177     else
18178       MIB.addOperand(MI->getOperand(i));
18179   }
18180   MIB.setMemRefs(MMOBegin, MMOEnd);
18181   // Jump
18182   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18183
18184   MI->eraseFromParent();
18185   return MBB;
18186 }
18187
18188 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18189 // accumulator loops. Writing back to the accumulator allows the coalescer
18190 // to remove extra copies in the loop.   
18191 MachineBasicBlock *
18192 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18193                                  MachineBasicBlock *MBB) const {
18194   MachineOperand &AddendOp = MI->getOperand(3);
18195
18196   // Bail out early if the addend isn't a register - we can't switch these.
18197   if (!AddendOp.isReg())
18198     return MBB;
18199
18200   MachineFunction &MF = *MBB->getParent();
18201   MachineRegisterInfo &MRI = MF.getRegInfo();
18202
18203   // Check whether the addend is defined by a PHI:
18204   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18205   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18206   if (!AddendDef.isPHI())
18207     return MBB;
18208
18209   // Look for the following pattern:
18210   // loop:
18211   //   %addend = phi [%entry, 0], [%loop, %result]
18212   //   ...
18213   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18214
18215   // Replace with:
18216   //   loop:
18217   //   %addend = phi [%entry, 0], [%loop, %result]
18218   //   ...
18219   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18220
18221   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18222     assert(AddendDef.getOperand(i).isReg());
18223     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18224     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18225     if (&PHISrcInst == MI) {
18226       // Found a matching instruction.
18227       unsigned NewFMAOpc = 0;
18228       switch (MI->getOpcode()) {
18229         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18230         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18231         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18232         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18233         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18234         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18235         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18236         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18237         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18238         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18239         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18240         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18241         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18242         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18243         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18244         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18245         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18246         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18247         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18248         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18249         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18250         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18251         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18252         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18253         default: llvm_unreachable("Unrecognized FMA variant.");
18254       }
18255
18256       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18257       MachineInstrBuilder MIB =
18258         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18259         .addOperand(MI->getOperand(0))
18260         .addOperand(MI->getOperand(3))
18261         .addOperand(MI->getOperand(2))
18262         .addOperand(MI->getOperand(1));
18263       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18264       MI->eraseFromParent();
18265     }
18266   }
18267
18268   return MBB;
18269 }
18270
18271 MachineBasicBlock *
18272 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18273                                                MachineBasicBlock *BB) const {
18274   switch (MI->getOpcode()) {
18275   default: llvm_unreachable("Unexpected instr type to insert");
18276   case X86::TAILJMPd64:
18277   case X86::TAILJMPr64:
18278   case X86::TAILJMPm64:
18279     llvm_unreachable("TAILJMP64 would not be touched here.");
18280   case X86::TCRETURNdi64:
18281   case X86::TCRETURNri64:
18282   case X86::TCRETURNmi64:
18283     return BB;
18284   case X86::WIN_ALLOCA:
18285     return EmitLoweredWinAlloca(MI, BB);
18286   case X86::SEG_ALLOCA_32:
18287     return EmitLoweredSegAlloca(MI, BB, false);
18288   case X86::SEG_ALLOCA_64:
18289     return EmitLoweredSegAlloca(MI, BB, true);
18290   case X86::TLSCall_32:
18291   case X86::TLSCall_64:
18292     return EmitLoweredTLSCall(MI, BB);
18293   case X86::CMOV_GR8:
18294   case X86::CMOV_FR32:
18295   case X86::CMOV_FR64:
18296   case X86::CMOV_V4F32:
18297   case X86::CMOV_V2F64:
18298   case X86::CMOV_V2I64:
18299   case X86::CMOV_V8F32:
18300   case X86::CMOV_V4F64:
18301   case X86::CMOV_V4I64:
18302   case X86::CMOV_V16F32:
18303   case X86::CMOV_V8F64:
18304   case X86::CMOV_V8I64:
18305   case X86::CMOV_GR16:
18306   case X86::CMOV_GR32:
18307   case X86::CMOV_RFP32:
18308   case X86::CMOV_RFP64:
18309   case X86::CMOV_RFP80:
18310     return EmitLoweredSelect(MI, BB);
18311
18312   case X86::FP32_TO_INT16_IN_MEM:
18313   case X86::FP32_TO_INT32_IN_MEM:
18314   case X86::FP32_TO_INT64_IN_MEM:
18315   case X86::FP64_TO_INT16_IN_MEM:
18316   case X86::FP64_TO_INT32_IN_MEM:
18317   case X86::FP64_TO_INT64_IN_MEM:
18318   case X86::FP80_TO_INT16_IN_MEM:
18319   case X86::FP80_TO_INT32_IN_MEM:
18320   case X86::FP80_TO_INT64_IN_MEM: {
18321     MachineFunction *F = BB->getParent();
18322     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18323     DebugLoc DL = MI->getDebugLoc();
18324
18325     // Change the floating point control register to use "round towards zero"
18326     // mode when truncating to an integer value.
18327     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18328     addFrameReference(BuildMI(*BB, MI, DL,
18329                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18330
18331     // Load the old value of the high byte of the control word...
18332     unsigned OldCW =
18333       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18334     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18335                       CWFrameIdx);
18336
18337     // Set the high part to be round to zero...
18338     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18339       .addImm(0xC7F);
18340
18341     // Reload the modified control word now...
18342     addFrameReference(BuildMI(*BB, MI, DL,
18343                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18344
18345     // Restore the memory image of control word to original value
18346     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18347       .addReg(OldCW);
18348
18349     // Get the X86 opcode to use.
18350     unsigned Opc;
18351     switch (MI->getOpcode()) {
18352     default: llvm_unreachable("illegal opcode!");
18353     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18354     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18355     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18356     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18357     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18358     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18359     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18360     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18361     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18362     }
18363
18364     X86AddressMode AM;
18365     MachineOperand &Op = MI->getOperand(0);
18366     if (Op.isReg()) {
18367       AM.BaseType = X86AddressMode::RegBase;
18368       AM.Base.Reg = Op.getReg();
18369     } else {
18370       AM.BaseType = X86AddressMode::FrameIndexBase;
18371       AM.Base.FrameIndex = Op.getIndex();
18372     }
18373     Op = MI->getOperand(1);
18374     if (Op.isImm())
18375       AM.Scale = Op.getImm();
18376     Op = MI->getOperand(2);
18377     if (Op.isImm())
18378       AM.IndexReg = Op.getImm();
18379     Op = MI->getOperand(3);
18380     if (Op.isGlobal()) {
18381       AM.GV = Op.getGlobal();
18382     } else {
18383       AM.Disp = Op.getImm();
18384     }
18385     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18386                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18387
18388     // Reload the original control word now.
18389     addFrameReference(BuildMI(*BB, MI, DL,
18390                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18391
18392     MI->eraseFromParent();   // The pseudo instruction is gone now.
18393     return BB;
18394   }
18395     // String/text processing lowering.
18396   case X86::PCMPISTRM128REG:
18397   case X86::VPCMPISTRM128REG:
18398   case X86::PCMPISTRM128MEM:
18399   case X86::VPCMPISTRM128MEM:
18400   case X86::PCMPESTRM128REG:
18401   case X86::VPCMPESTRM128REG:
18402   case X86::PCMPESTRM128MEM:
18403   case X86::VPCMPESTRM128MEM:
18404     assert(Subtarget->hasSSE42() &&
18405            "Target must have SSE4.2 or AVX features enabled");
18406     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18407
18408   // String/text processing lowering.
18409   case X86::PCMPISTRIREG:
18410   case X86::VPCMPISTRIREG:
18411   case X86::PCMPISTRIMEM:
18412   case X86::VPCMPISTRIMEM:
18413   case X86::PCMPESTRIREG:
18414   case X86::VPCMPESTRIREG:
18415   case X86::PCMPESTRIMEM:
18416   case X86::VPCMPESTRIMEM:
18417     assert(Subtarget->hasSSE42() &&
18418            "Target must have SSE4.2 or AVX features enabled");
18419     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18420
18421   // Thread synchronization.
18422   case X86::MONITOR:
18423     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18424
18425   // xbegin
18426   case X86::XBEGIN:
18427     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18428
18429   case X86::VASTART_SAVE_XMM_REGS:
18430     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18431
18432   case X86::VAARG_64:
18433     return EmitVAARG64WithCustomInserter(MI, BB);
18434
18435   case X86::EH_SjLj_SetJmp32:
18436   case X86::EH_SjLj_SetJmp64:
18437     return emitEHSjLjSetJmp(MI, BB);
18438
18439   case X86::EH_SjLj_LongJmp32:
18440   case X86::EH_SjLj_LongJmp64:
18441     return emitEHSjLjLongJmp(MI, BB);
18442
18443   case TargetOpcode::STACKMAP:
18444   case TargetOpcode::PATCHPOINT:
18445     return emitPatchPoint(MI, BB);
18446
18447   case X86::VFMADDPDr213r:
18448   case X86::VFMADDPSr213r:
18449   case X86::VFMADDSDr213r:
18450   case X86::VFMADDSSr213r:
18451   case X86::VFMSUBPDr213r:
18452   case X86::VFMSUBPSr213r:
18453   case X86::VFMSUBSDr213r:
18454   case X86::VFMSUBSSr213r:
18455   case X86::VFNMADDPDr213r:
18456   case X86::VFNMADDPSr213r:
18457   case X86::VFNMADDSDr213r:
18458   case X86::VFNMADDSSr213r:
18459   case X86::VFNMSUBPDr213r:
18460   case X86::VFNMSUBPSr213r:
18461   case X86::VFNMSUBSDr213r:
18462   case X86::VFNMSUBSSr213r:
18463   case X86::VFMADDPDr213rY:
18464   case X86::VFMADDPSr213rY:
18465   case X86::VFMSUBPDr213rY:
18466   case X86::VFMSUBPSr213rY:
18467   case X86::VFNMADDPDr213rY:
18468   case X86::VFNMADDPSr213rY:
18469   case X86::VFNMSUBPDr213rY:
18470   case X86::VFNMSUBPSr213rY:
18471     return emitFMA3Instr(MI, BB);
18472   }
18473 }
18474
18475 //===----------------------------------------------------------------------===//
18476 //                           X86 Optimization Hooks
18477 //===----------------------------------------------------------------------===//
18478
18479 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18480                                                       APInt &KnownZero,
18481                                                       APInt &KnownOne,
18482                                                       const SelectionDAG &DAG,
18483                                                       unsigned Depth) const {
18484   unsigned BitWidth = KnownZero.getBitWidth();
18485   unsigned Opc = Op.getOpcode();
18486   assert((Opc >= ISD::BUILTIN_OP_END ||
18487           Opc == ISD::INTRINSIC_WO_CHAIN ||
18488           Opc == ISD::INTRINSIC_W_CHAIN ||
18489           Opc == ISD::INTRINSIC_VOID) &&
18490          "Should use MaskedValueIsZero if you don't know whether Op"
18491          " is a target node!");
18492
18493   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18494   switch (Opc) {
18495   default: break;
18496   case X86ISD::ADD:
18497   case X86ISD::SUB:
18498   case X86ISD::ADC:
18499   case X86ISD::SBB:
18500   case X86ISD::SMUL:
18501   case X86ISD::UMUL:
18502   case X86ISD::INC:
18503   case X86ISD::DEC:
18504   case X86ISD::OR:
18505   case X86ISD::XOR:
18506   case X86ISD::AND:
18507     // These nodes' second result is a boolean.
18508     if (Op.getResNo() == 0)
18509       break;
18510     // Fallthrough
18511   case X86ISD::SETCC:
18512     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18513     break;
18514   case ISD::INTRINSIC_WO_CHAIN: {
18515     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18516     unsigned NumLoBits = 0;
18517     switch (IntId) {
18518     default: break;
18519     case Intrinsic::x86_sse_movmsk_ps:
18520     case Intrinsic::x86_avx_movmsk_ps_256:
18521     case Intrinsic::x86_sse2_movmsk_pd:
18522     case Intrinsic::x86_avx_movmsk_pd_256:
18523     case Intrinsic::x86_mmx_pmovmskb:
18524     case Intrinsic::x86_sse2_pmovmskb_128:
18525     case Intrinsic::x86_avx2_pmovmskb: {
18526       // High bits of movmskp{s|d}, pmovmskb are known zero.
18527       switch (IntId) {
18528         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18529         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18530         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18531         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18532         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18533         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18534         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18535         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18536       }
18537       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18538       break;
18539     }
18540     }
18541     break;
18542   }
18543   }
18544 }
18545
18546 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18547   SDValue Op,
18548   const SelectionDAG &,
18549   unsigned Depth) const {
18550   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18551   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18552     return Op.getValueType().getScalarType().getSizeInBits();
18553
18554   // Fallback case.
18555   return 1;
18556 }
18557
18558 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18559 /// node is a GlobalAddress + offset.
18560 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18561                                        const GlobalValue* &GA,
18562                                        int64_t &Offset) const {
18563   if (N->getOpcode() == X86ISD::Wrapper) {
18564     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18565       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18566       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18567       return true;
18568     }
18569   }
18570   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18571 }
18572
18573 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18574 /// same as extracting the high 128-bit part of 256-bit vector and then
18575 /// inserting the result into the low part of a new 256-bit vector
18576 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18577   EVT VT = SVOp->getValueType(0);
18578   unsigned NumElems = VT.getVectorNumElements();
18579
18580   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18581   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18582     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18583         SVOp->getMaskElt(j) >= 0)
18584       return false;
18585
18586   return true;
18587 }
18588
18589 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18590 /// same as extracting the low 128-bit part of 256-bit vector and then
18591 /// inserting the result into the high part of a new 256-bit vector
18592 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18593   EVT VT = SVOp->getValueType(0);
18594   unsigned NumElems = VT.getVectorNumElements();
18595
18596   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18597   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18598     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18599         SVOp->getMaskElt(j) >= 0)
18600       return false;
18601
18602   return true;
18603 }
18604
18605 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18606 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18607                                         TargetLowering::DAGCombinerInfo &DCI,
18608                                         const X86Subtarget* Subtarget) {
18609   SDLoc dl(N);
18610   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18611   SDValue V1 = SVOp->getOperand(0);
18612   SDValue V2 = SVOp->getOperand(1);
18613   EVT VT = SVOp->getValueType(0);
18614   unsigned NumElems = VT.getVectorNumElements();
18615
18616   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18617       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18618     //
18619     //                   0,0,0,...
18620     //                      |
18621     //    V      UNDEF    BUILD_VECTOR    UNDEF
18622     //     \      /           \           /
18623     //  CONCAT_VECTOR         CONCAT_VECTOR
18624     //         \                  /
18625     //          \                /
18626     //          RESULT: V + zero extended
18627     //
18628     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18629         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18630         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18631       return SDValue();
18632
18633     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18634       return SDValue();
18635
18636     // To match the shuffle mask, the first half of the mask should
18637     // be exactly the first vector, and all the rest a splat with the
18638     // first element of the second one.
18639     for (unsigned i = 0; i != NumElems/2; ++i)
18640       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18641           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18642         return SDValue();
18643
18644     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18645     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18646       if (Ld->hasNUsesOfValue(1, 0)) {
18647         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18648         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18649         SDValue ResNode =
18650           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18651                                   Ld->getMemoryVT(),
18652                                   Ld->getPointerInfo(),
18653                                   Ld->getAlignment(),
18654                                   false/*isVolatile*/, true/*ReadMem*/,
18655                                   false/*WriteMem*/);
18656
18657         // Make sure the newly-created LOAD is in the same position as Ld in
18658         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18659         // and update uses of Ld's output chain to use the TokenFactor.
18660         if (Ld->hasAnyUseOfValue(1)) {
18661           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18662                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18663           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18664           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18665                                  SDValue(ResNode.getNode(), 1));
18666         }
18667
18668         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18669       }
18670     }
18671
18672     // Emit a zeroed vector and insert the desired subvector on its
18673     // first half.
18674     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18675     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18676     return DCI.CombineTo(N, InsV);
18677   }
18678
18679   //===--------------------------------------------------------------------===//
18680   // Combine some shuffles into subvector extracts and inserts:
18681   //
18682
18683   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18684   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18685     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18686     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18687     return DCI.CombineTo(N, InsV);
18688   }
18689
18690   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18691   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18692     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18693     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18694     return DCI.CombineTo(N, InsV);
18695   }
18696
18697   return SDValue();
18698 }
18699
18700 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
18701 /// possible.
18702 ///
18703 /// This is the leaf of the recursive combinine below. When we have found some
18704 /// chain of single-use x86 shuffle instructions and accumulated the combined
18705 /// shuffle mask represented by them, this will try to pattern match that mask
18706 /// into either a single instruction if there is a special purpose instruction
18707 /// for this operation, or into a PSHUFB instruction which is a fully general
18708 /// instruction but should only be used to replace chains over a certain depth.
18709 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
18710                                    int Depth, SelectionDAG &DAG,
18711                                    TargetLowering::DAGCombinerInfo &DCI,
18712                                    const X86Subtarget *Subtarget) {
18713   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
18714
18715   // Find the operand that enters the chain. Note that multiple uses are OK
18716   // here, we're not going to remove the operand we find.
18717   SDValue Input = Op.getOperand(0);
18718   while (Input.getOpcode() == ISD::BITCAST)
18719     Input = Input.getOperand(0);
18720
18721   MVT VT = Input.getSimpleValueType();
18722   MVT RootVT = Root.getSimpleValueType();
18723   SDLoc DL(Root);
18724
18725   // Just remove no-op shuffle masks.
18726   if (Mask.size() == 1) {
18727     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
18728                   /*AddTo*/ true);
18729     return true;
18730   }
18731
18732   // Use the float domain if the operand type is a floatingc point type.
18733   bool FloatDomain = VT.isFloatingPoint();
18734
18735   // If we don't have access to VEX encodings, the generic PSHUF instructions
18736   // are preferable to some of the specialized forms despite requiring one more
18737   // byte to encode because they can implicitly copy.
18738   //
18739   // IF we *do* have VEX encodings, than we can use shorter, more specific
18740   // shuffle instructions freely as they can copy due to the extra register
18741   // operand.
18742   if (Subtarget->hasAVX()) {
18743     // We have both floatincg point and integer variants of shuffles that dup
18744     // either tho low or high half of the vector.
18745     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
18746       bool Lo = Mask.equals(0, 0);
18747       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
18748                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
18749       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
18750       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18751       DCI.AddToWorklist(Op.getNode());
18752       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
18753       DCI.AddToWorklist(Op.getNode());
18754       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18755                     /*AddTo*/ true);
18756       return true;
18757     }
18758
18759     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
18760
18761     // For the integer domain we have specialized instructions for duplicating
18762     // any element size from the low or high half.
18763     if (!FloatDomain &&
18764         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
18765          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
18766          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
18767          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
18768          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
18769                      15))) {
18770       bool Lo = Mask[0] == 0;
18771       MVT ShuffleVT;
18772       switch (Mask.size()) {
18773       case 4: ShuffleVT = MVT::v4i32; break;
18774       case 8: ShuffleVT = MVT::v8i32; break;
18775       case 16: ShuffleVT = MVT::v16i32; break;
18776       };
18777       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18778       DCI.AddToWorklist(Op.getNode());
18779       Op = DAG.getNode(Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL, ShuffleVT, Op,
18780                        Op);
18781       DCI.AddToWorklist(Op.getNode());
18782       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18783                     /*AddTo*/ true);
18784       return true;
18785     }
18786   }
18787
18788   // Bail if we have fewer than 3 shuffle instructions in the chain.
18789   if (Depth < 3)
18790     return false;
18791
18792   // If we have 3 or more shuffle instructions, we can replace them with
18793   // a single PSHUFB instruction profitably. Intel's manuals suggest only using
18794   // PSHUFB if doing so replacing 5 instructions, but in practice PSHUFB tends
18795   // to be *very* fast so we're more aggressive.
18796   if (Subtarget->hasSSSE3()) {
18797     SmallVector<SDValue, 16> PSHUFBMask;
18798     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
18799     int Ratio = 16 / Mask.size();
18800     for (unsigned i = 0; i < 16; ++i) {
18801       int M = Ratio * Mask[i / Ratio] + i % Ratio;
18802       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
18803     }
18804     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
18805     DCI.AddToWorklist(Op.getNode());
18806     SDValue PSHUFBMaskOp =
18807         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
18808     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
18809     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
18810     DCI.AddToWorklist(Op.getNode());
18811     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18812                   /*AddTo*/ true);
18813     return true;
18814   }
18815
18816   // Failed to find any combines.
18817   return false;
18818 }
18819
18820 /// \brief Fully generic combining of x86 shuffle instructions.
18821 ///
18822 /// This should be the last combine run over the x86 shuffle instructions. Once
18823 /// they have been fully optimized, this will recursively consdier all chains
18824 /// of single-use shuffle instructions, build a generic model of the cumulative
18825 /// shuffle operation, and check for simpler instructions which implement this
18826 /// operation. We use this primarily for two purposes:
18827 ///
18828 /// 1) Collapse generic shuffles to specialized single instructions when
18829 ///    equivalent. In most cases, this is just an encoding size win, but
18830 ///    sometimes we will collapse multiple generic shuffles into a single
18831 ///    special-purpose shuffle.
18832 /// 2) Look for sequences of shuffle instructions with 3 or more total
18833 ///    instructions, and replace them with the slightly more expensive SSSE3
18834 ///    PSHUFB instruction if available. We do this as the last combining step
18835 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
18836 ///    a suitable short sequence of other instructions. The PHUFB will either
18837 ///    use a register or have to read from memory and so is slightly (but only
18838 ///    slightly) more expensive than the other shuffle instructions.
18839 ///
18840 /// Because this is inherently a quadratic operation (for each shuffle in
18841 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
18842 /// This should never be an issue in practice as the shuffle lowering doesn't
18843 /// produce sequences of more than 8 instructions.
18844 ///
18845 /// FIXME: Currently, we don't collapse instructions *into* PSHUFB. We should,
18846 /// and we should do so more aggressively than we form PSHUFB because once we
18847 /// have a PSHUFB, we might as well do as much shuffling as we can.
18848 ///
18849 /// FIXME: We will currently miss some cases where the redundant shuffling
18850 /// would simplify under the threshold for PSHUFB formation because of
18851 /// combine-ordering. To fix this, we should do the redundant instruction
18852 /// combining in this recursive walk.
18853 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
18854                                           ArrayRef<int> IncomingMask, int Depth,
18855                                           SelectionDAG &DAG,
18856                                           TargetLowering::DAGCombinerInfo &DCI,
18857                                           const X86Subtarget *Subtarget) {
18858   // Bound the depth of our recursive combine because this is ultimately
18859   // quadratic in nature.
18860   if (Depth > 8)
18861     return false;
18862
18863   // Directly rip through bitcasts to find the underlying operand.
18864   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
18865     Op = Op.getOperand(0);
18866
18867   MVT VT = Op.getSimpleValueType();
18868   if (!VT.isVector())
18869     return false; // Bail if we hit a non-vector.
18870   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
18871   // version should be added.
18872   if (VT.getSizeInBits() != 128)
18873     return false;
18874
18875   assert(Root.getSimpleValueType().isVector() &&
18876          "Shuffles operate on vector types!");
18877   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
18878          "Can only combine shuffles of the same vector register size.");
18879
18880   if (!isTargetShuffle(Op.getOpcode()))
18881     return false;
18882   SmallVector<int, 16> OpMask;
18883   bool IsUnary;
18884   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
18885   // We only can combine unary shuffles which we can decode the mask for.
18886   if (!HaveMask || !IsUnary)
18887     return false;
18888
18889   assert(VT.getVectorNumElements() == OpMask.size() &&
18890          "Different mask size from vector size!");
18891
18892   SmallVector<int, 16> Mask;
18893   Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
18894
18895   // Merge this shuffle operation's mask into our accumulated mask. This is
18896   // a bit tricky as the shuffle may have a different size from the root.
18897   if (OpMask.size() == IncomingMask.size()) {
18898     for (int M : IncomingMask)
18899       Mask.push_back(OpMask[M]);
18900   } else if (OpMask.size() < IncomingMask.size()) {
18901     assert(IncomingMask.size() % OpMask.size() == 0 &&
18902            "The smaller number of elements must divide the larger.");
18903     int Ratio = IncomingMask.size() / OpMask.size();
18904     for (int M : IncomingMask)
18905       Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
18906   } else {
18907     assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
18908     assert(OpMask.size() % IncomingMask.size() == 0 &&
18909            "The smaller number of elements must divide the larger.");
18910     int Ratio = OpMask.size() / IncomingMask.size();
18911     for (int i = 0, e = OpMask.size(); i < e; ++i)
18912       Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
18913   }
18914
18915   // See if we can recurse into the operand to combine more things.
18916   switch (Op.getOpcode()) {
18917     case X86ISD::PSHUFD:
18918     case X86ISD::PSHUFHW:
18919     case X86ISD::PSHUFLW:
18920       if (Op.getOperand(0).hasOneUse() &&
18921           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
18922                                         DAG, DCI, Subtarget))
18923         return true;
18924       break;
18925
18926     case X86ISD::UNPCKL:
18927     case X86ISD::UNPCKH:
18928       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
18929       // We can't check for single use, we have to check that this shuffle is the only user.
18930       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
18931           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
18932                                         DAG, DCI, Subtarget))
18933           return true;
18934       break;
18935   }
18936
18937   // Minor canonicalization of the accumulated shuffle mask to make it easier
18938   // to match below. All this does is detect masks with squential pairs of
18939   // elements, and shrink them to the half-width mask. It does this in a loop
18940   // so it will reduce the size of the mask to the minimal width mask which
18941   // performs an equivalent shuffle.
18942   while (Mask.size() > 1) {
18943     SmallVector<int, 16> NewMask;
18944     for (int i = 0, e = Mask.size()/2; i < e; ++i) {
18945       if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
18946         NewMask.clear();
18947         break;
18948       }
18949       NewMask.push_back(Mask[2*i] / 2);
18950     }
18951     if (NewMask.empty())
18952       break;
18953     Mask.swap(NewMask);
18954   }
18955
18956   return combineX86ShuffleChain(Op, Root, Mask, Depth, DAG, DCI, Subtarget);
18957 }
18958
18959 /// \brief Get the PSHUF-style mask from PSHUF node.
18960 ///
18961 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18962 /// PSHUF-style masks that can be reused with such instructions.
18963 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18964   SmallVector<int, 4> Mask;
18965   bool IsUnary;
18966   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18967   (void)HaveMask;
18968   assert(HaveMask);
18969
18970   switch (N.getOpcode()) {
18971   case X86ISD::PSHUFD:
18972     return Mask;
18973   case X86ISD::PSHUFLW:
18974     Mask.resize(4);
18975     return Mask;
18976   case X86ISD::PSHUFHW:
18977     Mask.erase(Mask.begin(), Mask.begin() + 4);
18978     for (int &M : Mask)
18979       M -= 4;
18980     return Mask;
18981   default:
18982     llvm_unreachable("No valid shuffle instruction found!");
18983   }
18984 }
18985
18986 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18987 ///
18988 /// We walk up the chain and look for a combinable shuffle, skipping over
18989 /// shuffles that we could hoist this shuffle's transformation past without
18990 /// altering anything.
18991 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18992                                          SelectionDAG &DAG,
18993                                          TargetLowering::DAGCombinerInfo &DCI) {
18994   assert(N.getOpcode() == X86ISD::PSHUFD &&
18995          "Called with something other than an x86 128-bit half shuffle!");
18996   SDLoc DL(N);
18997
18998   // Walk up a single-use chain looking for a combinable shuffle.
18999   SDValue V = N.getOperand(0);
19000   for (; V.hasOneUse(); V = V.getOperand(0)) {
19001     switch (V.getOpcode()) {
19002     default:
19003       return false; // Nothing combined!
19004
19005     case ISD::BITCAST:
19006       // Skip bitcasts as we always know the type for the target specific
19007       // instructions.
19008       continue;
19009
19010     case X86ISD::PSHUFD:
19011       // Found another dword shuffle.
19012       break;
19013
19014     case X86ISD::PSHUFLW:
19015       // Check that the low words (being shuffled) are the identity in the
19016       // dword shuffle, and the high words are self-contained.
19017       if (Mask[0] != 0 || Mask[1] != 1 ||
19018           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19019         return false;
19020
19021       continue;
19022
19023     case X86ISD::PSHUFHW:
19024       // Check that the high words (being shuffled) are the identity in the
19025       // dword shuffle, and the low words are self-contained.
19026       if (Mask[2] != 2 || Mask[3] != 3 ||
19027           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19028         return false;
19029
19030       continue;
19031
19032     case X86ISD::UNPCKL:
19033     case X86ISD::UNPCKH:
19034       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19035       // shuffle into a preceding word shuffle.
19036       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19037         return false;
19038
19039       // Search for a half-shuffle which we can combine with.
19040       unsigned CombineOp =
19041           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19042       if (V.getOperand(0) != V.getOperand(1) ||
19043           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19044         return false;
19045       V = V.getOperand(0);
19046       do {
19047         switch (V.getOpcode()) {
19048         default:
19049           return false; // Nothing to combine.
19050
19051         case X86ISD::PSHUFLW:
19052         case X86ISD::PSHUFHW:
19053           if (V.getOpcode() == CombineOp)
19054             break;
19055
19056           // Fallthrough!
19057         case ISD::BITCAST:
19058           V = V.getOperand(0);
19059           continue;
19060         }
19061         break;
19062       } while (V.hasOneUse());
19063       break;
19064     }
19065     // Break out of the loop if we break out of the switch.
19066     break;
19067   }
19068
19069   if (!V.hasOneUse())
19070     // We fell out of the loop without finding a viable combining instruction.
19071     return false;
19072
19073   // Record the old value to use in RAUW-ing.
19074   SDValue Old = V;
19075
19076   // Merge this node's mask and our incoming mask.
19077   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19078   for (int &M : Mask)
19079     M = VMask[M];
19080   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19081                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19082
19083   // It is possible that one of the combinable shuffles was completely absorbed
19084   // by the other, just replace it and revisit all users in that case.
19085   if (Old.getNode() == V.getNode()) {
19086     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19087     return true;
19088   }
19089
19090   // Replace N with its operand as we're going to combine that shuffle away.
19091   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19092
19093   // Replace the combinable shuffle with the combined one, updating all users
19094   // so that we re-evaluate the chain here.
19095   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19096   return true;
19097 }
19098
19099 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19100 ///
19101 /// We walk up the chain, skipping shuffles of the other half and looking
19102 /// through shuffles which switch halves trying to find a shuffle of the same
19103 /// pair of dwords.
19104 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19105                                         SelectionDAG &DAG,
19106                                         TargetLowering::DAGCombinerInfo &DCI) {
19107   assert(
19108       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19109       "Called with something other than an x86 128-bit half shuffle!");
19110   SDLoc DL(N);
19111   unsigned CombineOpcode = N.getOpcode();
19112
19113   // Walk up a single-use chain looking for a combinable shuffle.
19114   SDValue V = N.getOperand(0);
19115   for (; V.hasOneUse(); V = V.getOperand(0)) {
19116     switch (V.getOpcode()) {
19117     default:
19118       return false; // Nothing combined!
19119
19120     case ISD::BITCAST:
19121       // Skip bitcasts as we always know the type for the target specific
19122       // instructions.
19123       continue;
19124
19125     case X86ISD::PSHUFLW:
19126     case X86ISD::PSHUFHW:
19127       if (V.getOpcode() == CombineOpcode)
19128         break;
19129
19130       // Other-half shuffles are no-ops.
19131       continue;
19132
19133     case X86ISD::PSHUFD: {
19134       // We can only handle pshufd if the half we are combining either stays in
19135       // its half, or switches to the other half. Bail if one of these isn't
19136       // true.
19137       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19138       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19139       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19140             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19141         return false;
19142
19143       // Map the mask through the pshufd and keep walking up the chain.
19144       for (int i = 0; i < 4; ++i)
19145         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19146
19147       // Switch halves if the pshufd does.
19148       CombineOpcode =
19149           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19150       continue;
19151     }
19152     }
19153     // Break out of the loop if we break out of the switch.
19154     break;
19155   }
19156
19157   if (!V.hasOneUse())
19158     // We fell out of the loop without finding a viable combining instruction.
19159     return false;
19160
19161   // Record the old value to use in RAUW-ing.
19162   SDValue Old = V;
19163
19164   // Merge this node's mask and our incoming mask (adjusted to account for all
19165   // the pshufd instructions encountered).
19166   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19167   for (int &M : Mask)
19168     M = VMask[M];
19169   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19170                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19171
19172   // Replace N with its operand as we're going to combine that shuffle away.
19173   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19174
19175   // Replace the combinable shuffle with the combined one, updating all users
19176   // so that we re-evaluate the chain here.
19177   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19178   return true;
19179 }
19180
19181 /// \brief Try to combine x86 target specific shuffles.
19182 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19183                                            TargetLowering::DAGCombinerInfo &DCI,
19184                                            const X86Subtarget *Subtarget) {
19185   SDLoc DL(N);
19186   MVT VT = N.getSimpleValueType();
19187   SmallVector<int, 4> Mask;
19188
19189   switch (N.getOpcode()) {
19190   case X86ISD::PSHUFD:
19191   case X86ISD::PSHUFLW:
19192   case X86ISD::PSHUFHW:
19193     Mask = getPSHUFShuffleMask(N);
19194     assert(Mask.size() == 4);
19195     break;
19196   default:
19197     return SDValue();
19198   }
19199
19200   // Nuke no-op shuffles that show up after combining.
19201   if (isNoopShuffleMask(Mask))
19202     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19203
19204   // Look for simplifications involving one or two shuffle instructions.
19205   SDValue V = N.getOperand(0);
19206   switch (N.getOpcode()) {
19207   default:
19208     break;
19209   case X86ISD::PSHUFLW:
19210   case X86ISD::PSHUFHW:
19211     assert(VT == MVT::v8i16);
19212     (void)VT;
19213
19214     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19215       return SDValue(); // We combined away this shuffle, so we're done.
19216
19217     // See if this reduces to a PSHUFD which is no more expensive and can
19218     // combine with more operations.
19219     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19220         areAdjacentMasksSequential(Mask)) {
19221       int DMask[] = {-1, -1, -1, -1};
19222       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19223       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19224       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19225       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19226       DCI.AddToWorklist(V.getNode());
19227       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19228                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19229       DCI.AddToWorklist(V.getNode());
19230       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19231     }
19232
19233     // Look for shuffle patterns which can be implemented as a single unpack.
19234     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19235     // only works when we have a PSHUFD followed by two half-shuffles.
19236     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19237         (V.getOpcode() == X86ISD::PSHUFLW ||
19238          V.getOpcode() == X86ISD::PSHUFHW) &&
19239         V.getOpcode() != N.getOpcode() &&
19240         V.hasOneUse()) {
19241       SDValue D = V.getOperand(0);
19242       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19243         D = D.getOperand(0);
19244       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19245         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19246         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19247         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19248         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19249         int WordMask[8];
19250         for (int i = 0; i < 4; ++i) {
19251           WordMask[i + NOffset] = Mask[i] + NOffset;
19252           WordMask[i + VOffset] = VMask[i] + VOffset;
19253         }
19254         // Map the word mask through the DWord mask.
19255         int MappedMask[8];
19256         for (int i = 0; i < 8; ++i)
19257           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19258         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19259         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19260         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19261                        std::begin(UnpackLoMask)) ||
19262             std::equal(std::begin(MappedMask), std::end(MappedMask),
19263                        std::begin(UnpackHiMask))) {
19264           // We can replace all three shuffles with an unpack.
19265           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19266           DCI.AddToWorklist(V.getNode());
19267           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19268                                                 : X86ISD::UNPCKH,
19269                              DL, MVT::v8i16, V, V);
19270         }
19271       }
19272     }
19273
19274     break;
19275
19276   case X86ISD::PSHUFD:
19277     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19278       return SDValue(); // We combined away this shuffle.
19279
19280     break;
19281   }
19282
19283   return SDValue();
19284 }
19285
19286 /// PerformShuffleCombine - Performs several different shuffle combines.
19287 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19288                                      TargetLowering::DAGCombinerInfo &DCI,
19289                                      const X86Subtarget *Subtarget) {
19290   SDLoc dl(N);
19291   SDValue N0 = N->getOperand(0);
19292   SDValue N1 = N->getOperand(1);
19293   EVT VT = N->getValueType(0);
19294
19295   // Don't create instructions with illegal types after legalize types has run.
19296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19297   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19298     return SDValue();
19299
19300   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19301   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19302       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19303     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19304
19305   // During Type Legalization, when promoting illegal vector types,
19306   // the backend might introduce new shuffle dag nodes and bitcasts.
19307   //
19308   // This code performs the following transformation:
19309   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19310   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19311   //
19312   // We do this only if both the bitcast and the BINOP dag nodes have
19313   // one use. Also, perform this transformation only if the new binary
19314   // operation is legal. This is to avoid introducing dag nodes that
19315   // potentially need to be further expanded (or custom lowered) into a
19316   // less optimal sequence of dag nodes.
19317   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19318       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19319       N0.getOpcode() == ISD::BITCAST) {
19320     SDValue BC0 = N0.getOperand(0);
19321     EVT SVT = BC0.getValueType();
19322     unsigned Opcode = BC0.getOpcode();
19323     unsigned NumElts = VT.getVectorNumElements();
19324     
19325     if (BC0.hasOneUse() && SVT.isVector() &&
19326         SVT.getVectorNumElements() * 2 == NumElts &&
19327         TLI.isOperationLegal(Opcode, VT)) {
19328       bool CanFold = false;
19329       switch (Opcode) {
19330       default : break;
19331       case ISD::ADD :
19332       case ISD::FADD :
19333       case ISD::SUB :
19334       case ISD::FSUB :
19335       case ISD::MUL :
19336       case ISD::FMUL :
19337         CanFold = true;
19338       }
19339
19340       unsigned SVTNumElts = SVT.getVectorNumElements();
19341       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19342       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19343         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19344       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19345         CanFold = SVOp->getMaskElt(i) < 0;
19346
19347       if (CanFold) {
19348         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19349         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19350         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19351         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19352       }
19353     }
19354   }
19355
19356   // Only handle 128 wide vector from here on.
19357   if (!VT.is128BitVector())
19358     return SDValue();
19359
19360   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19361   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19362   // consecutive, non-overlapping, and in the right order.
19363   SmallVector<SDValue, 16> Elts;
19364   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19365     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19366
19367   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19368   if (LD.getNode())
19369     return LD;
19370
19371   if (isTargetShuffle(N->getOpcode())) {
19372     SDValue Shuffle =
19373         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19374     if (Shuffle.getNode())
19375       return Shuffle;
19376
19377     // Try recursively combining arbitrary sequences of x86 shuffle
19378     // instructions into higher-order shuffles. We do this after combining
19379     // specific PSHUF instruction sequences into their minimal form so that we
19380     // can evaluate how many specialized shuffle instructions are involved in
19381     // a particular chain.
19382     SmallVector<int, 1> NonceMask; // Just a placeholder.
19383     NonceMask.push_back(0);
19384     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19385                                       /*Depth*/ 1, DAG, DCI, Subtarget))
19386       return SDValue(); // This routine will use CombineTo to replace N.
19387   }
19388
19389   return SDValue();
19390 }
19391
19392 /// PerformTruncateCombine - Converts truncate operation to
19393 /// a sequence of vector shuffle operations.
19394 /// It is possible when we truncate 256-bit vector to 128-bit vector
19395 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19396                                       TargetLowering::DAGCombinerInfo &DCI,
19397                                       const X86Subtarget *Subtarget)  {
19398   return SDValue();
19399 }
19400
19401 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19402 /// specific shuffle of a load can be folded into a single element load.
19403 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19404 /// shuffles have been customed lowered so we need to handle those here.
19405 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19406                                          TargetLowering::DAGCombinerInfo &DCI) {
19407   if (DCI.isBeforeLegalizeOps())
19408     return SDValue();
19409
19410   SDValue InVec = N->getOperand(0);
19411   SDValue EltNo = N->getOperand(1);
19412
19413   if (!isa<ConstantSDNode>(EltNo))
19414     return SDValue();
19415
19416   EVT VT = InVec.getValueType();
19417
19418   bool HasShuffleIntoBitcast = false;
19419   if (InVec.getOpcode() == ISD::BITCAST) {
19420     // Don't duplicate a load with other uses.
19421     if (!InVec.hasOneUse())
19422       return SDValue();
19423     EVT BCVT = InVec.getOperand(0).getValueType();
19424     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19425       return SDValue();
19426     InVec = InVec.getOperand(0);
19427     HasShuffleIntoBitcast = true;
19428   }
19429
19430   if (!isTargetShuffle(InVec.getOpcode()))
19431     return SDValue();
19432
19433   // Don't duplicate a load with other uses.
19434   if (!InVec.hasOneUse())
19435     return SDValue();
19436
19437   SmallVector<int, 16> ShuffleMask;
19438   bool UnaryShuffle;
19439   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19440                             UnaryShuffle))
19441     return SDValue();
19442
19443   // Select the input vector, guarding against out of range extract vector.
19444   unsigned NumElems = VT.getVectorNumElements();
19445   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19446   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19447   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19448                                          : InVec.getOperand(1);
19449
19450   // If inputs to shuffle are the same for both ops, then allow 2 uses
19451   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19452
19453   if (LdNode.getOpcode() == ISD::BITCAST) {
19454     // Don't duplicate a load with other uses.
19455     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19456       return SDValue();
19457
19458     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19459     LdNode = LdNode.getOperand(0);
19460   }
19461
19462   if (!ISD::isNormalLoad(LdNode.getNode()))
19463     return SDValue();
19464
19465   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19466
19467   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19468     return SDValue();
19469
19470   if (HasShuffleIntoBitcast) {
19471     // If there's a bitcast before the shuffle, check if the load type and
19472     // alignment is valid.
19473     unsigned Align = LN0->getAlignment();
19474     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19475     unsigned NewAlign = TLI.getDataLayout()->
19476       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19477
19478     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19479       return SDValue();
19480   }
19481
19482   // All checks match so transform back to vector_shuffle so that DAG combiner
19483   // can finish the job
19484   SDLoc dl(N);
19485
19486   // Create shuffle node taking into account the case that its a unary shuffle
19487   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19488   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19489                                  InVec.getOperand(0), Shuffle,
19490                                  &ShuffleMask[0]);
19491   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19492   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19493                      EltNo);
19494 }
19495
19496 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19497 /// generation and convert it from being a bunch of shuffles and extracts
19498 /// to a simple store and scalar loads to extract the elements.
19499 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19500                                          TargetLowering::DAGCombinerInfo &DCI) {
19501   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19502   if (NewOp.getNode())
19503     return NewOp;
19504
19505   SDValue InputVector = N->getOperand(0);
19506
19507   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19508   // from mmx to v2i32 has a single usage.
19509   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19510       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19511       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19512     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19513                        N->getValueType(0),
19514                        InputVector.getNode()->getOperand(0));
19515
19516   // Only operate on vectors of 4 elements, where the alternative shuffling
19517   // gets to be more expensive.
19518   if (InputVector.getValueType() != MVT::v4i32)
19519     return SDValue();
19520
19521   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19522   // single use which is a sign-extend or zero-extend, and all elements are
19523   // used.
19524   SmallVector<SDNode *, 4> Uses;
19525   unsigned ExtractedElements = 0;
19526   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19527        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19528     if (UI.getUse().getResNo() != InputVector.getResNo())
19529       return SDValue();
19530
19531     SDNode *Extract = *UI;
19532     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19533       return SDValue();
19534
19535     if (Extract->getValueType(0) != MVT::i32)
19536       return SDValue();
19537     if (!Extract->hasOneUse())
19538       return SDValue();
19539     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19540         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19541       return SDValue();
19542     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19543       return SDValue();
19544
19545     // Record which element was extracted.
19546     ExtractedElements |=
19547       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19548
19549     Uses.push_back(Extract);
19550   }
19551
19552   // If not all the elements were used, this may not be worthwhile.
19553   if (ExtractedElements != 15)
19554     return SDValue();
19555
19556   // Ok, we've now decided to do the transformation.
19557   SDLoc dl(InputVector);
19558
19559   // Store the value to a temporary stack slot.
19560   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19561   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19562                             MachinePointerInfo(), false, false, 0);
19563
19564   // Replace each use (extract) with a load of the appropriate element.
19565   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19566        UE = Uses.end(); UI != UE; ++UI) {
19567     SDNode *Extract = *UI;
19568
19569     // cOMpute the element's address.
19570     SDValue Idx = Extract->getOperand(1);
19571     unsigned EltSize =
19572         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19573     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19574     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19575     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19576
19577     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19578                                      StackPtr, OffsetVal);
19579
19580     // Load the scalar.
19581     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19582                                      ScalarAddr, MachinePointerInfo(),
19583                                      false, false, false, 0);
19584
19585     // Replace the exact with the load.
19586     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19587   }
19588
19589   // The replacement was made in place; don't return anything.
19590   return SDValue();
19591 }
19592
19593 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19594 static std::pair<unsigned, bool>
19595 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19596                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19597   if (!VT.isVector())
19598     return std::make_pair(0, false);
19599
19600   bool NeedSplit = false;
19601   switch (VT.getSimpleVT().SimpleTy) {
19602   default: return std::make_pair(0, false);
19603   case MVT::v32i8:
19604   case MVT::v16i16:
19605   case MVT::v8i32:
19606     if (!Subtarget->hasAVX2())
19607       NeedSplit = true;
19608     if (!Subtarget->hasAVX())
19609       return std::make_pair(0, false);
19610     break;
19611   case MVT::v16i8:
19612   case MVT::v8i16:
19613   case MVT::v4i32:
19614     if (!Subtarget->hasSSE2())
19615       return std::make_pair(0, false);
19616   }
19617
19618   // SSE2 has only a small subset of the operations.
19619   bool hasUnsigned = Subtarget->hasSSE41() ||
19620                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19621   bool hasSigned = Subtarget->hasSSE41() ||
19622                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19623
19624   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19625
19626   unsigned Opc = 0;
19627   // Check for x CC y ? x : y.
19628   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19629       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19630     switch (CC) {
19631     default: break;
19632     case ISD::SETULT:
19633     case ISD::SETULE:
19634       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19635     case ISD::SETUGT:
19636     case ISD::SETUGE:
19637       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19638     case ISD::SETLT:
19639     case ISD::SETLE:
19640       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19641     case ISD::SETGT:
19642     case ISD::SETGE:
19643       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19644     }
19645   // Check for x CC y ? y : x -- a min/max with reversed arms.
19646   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19647              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19648     switch (CC) {
19649     default: break;
19650     case ISD::SETULT:
19651     case ISD::SETULE:
19652       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19653     case ISD::SETUGT:
19654     case ISD::SETUGE:
19655       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19656     case ISD::SETLT:
19657     case ISD::SETLE:
19658       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19659     case ISD::SETGT:
19660     case ISD::SETGE:
19661       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19662     }
19663   }
19664
19665   return std::make_pair(Opc, NeedSplit);
19666 }
19667
19668 static SDValue
19669 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19670                                       const X86Subtarget *Subtarget) {
19671   SDLoc dl(N);
19672   SDValue Cond = N->getOperand(0);
19673   SDValue LHS = N->getOperand(1);
19674   SDValue RHS = N->getOperand(2);
19675
19676   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19677     SDValue CondSrc = Cond->getOperand(0);
19678     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19679       Cond = CondSrc->getOperand(0);
19680   }
19681
19682   MVT VT = N->getSimpleValueType(0);
19683   MVT EltVT = VT.getVectorElementType();
19684   unsigned NumElems = VT.getVectorNumElements();
19685   // There is no blend with immediate in AVX-512.
19686   if (VT.is512BitVector())
19687     return SDValue();
19688
19689   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19690     return SDValue();
19691   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19692     return SDValue();
19693
19694   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19695     return SDValue();
19696
19697   unsigned MaskValue = 0;
19698   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19699     return SDValue();
19700
19701   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19702   for (unsigned i = 0; i < NumElems; ++i) {
19703     // Be sure we emit undef where we can.
19704     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19705       ShuffleMask[i] = -1;
19706     else
19707       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19708   }
19709
19710   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19711 }
19712
19713 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19714 /// nodes.
19715 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19716                                     TargetLowering::DAGCombinerInfo &DCI,
19717                                     const X86Subtarget *Subtarget) {
19718   SDLoc DL(N);
19719   SDValue Cond = N->getOperand(0);
19720   // Get the LHS/RHS of the select.
19721   SDValue LHS = N->getOperand(1);
19722   SDValue RHS = N->getOperand(2);
19723   EVT VT = LHS.getValueType();
19724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19725
19726   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19727   // instructions match the semantics of the common C idiom x<y?x:y but not
19728   // x<=y?x:y, because of how they handle negative zero (which can be
19729   // ignored in unsafe-math mode).
19730   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19731       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19732       (Subtarget->hasSSE2() ||
19733        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19734     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19735
19736     unsigned Opcode = 0;
19737     // Check for x CC y ? x : y.
19738     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19739         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19740       switch (CC) {
19741       default: break;
19742       case ISD::SETULT:
19743         // Converting this to a min would handle NaNs incorrectly, and swapping
19744         // the operands would cause it to handle comparisons between positive
19745         // and negative zero incorrectly.
19746         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19747           if (!DAG.getTarget().Options.UnsafeFPMath &&
19748               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19749             break;
19750           std::swap(LHS, RHS);
19751         }
19752         Opcode = X86ISD::FMIN;
19753         break;
19754       case ISD::SETOLE:
19755         // Converting this to a min would handle comparisons between positive
19756         // and negative zero incorrectly.
19757         if (!DAG.getTarget().Options.UnsafeFPMath &&
19758             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19759           break;
19760         Opcode = X86ISD::FMIN;
19761         break;
19762       case ISD::SETULE:
19763         // Converting this to a min would handle both negative zeros and NaNs
19764         // incorrectly, but we can swap the operands to fix both.
19765         std::swap(LHS, RHS);
19766       case ISD::SETOLT:
19767       case ISD::SETLT:
19768       case ISD::SETLE:
19769         Opcode = X86ISD::FMIN;
19770         break;
19771
19772       case ISD::SETOGE:
19773         // Converting this to a max would handle comparisons between positive
19774         // and negative zero incorrectly.
19775         if (!DAG.getTarget().Options.UnsafeFPMath &&
19776             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19777           break;
19778         Opcode = X86ISD::FMAX;
19779         break;
19780       case ISD::SETUGT:
19781         // Converting this to a max would handle NaNs incorrectly, and swapping
19782         // the operands would cause it to handle comparisons between positive
19783         // and negative zero incorrectly.
19784         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19785           if (!DAG.getTarget().Options.UnsafeFPMath &&
19786               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19787             break;
19788           std::swap(LHS, RHS);
19789         }
19790         Opcode = X86ISD::FMAX;
19791         break;
19792       case ISD::SETUGE:
19793         // Converting this to a max would handle both negative zeros and NaNs
19794         // incorrectly, but we can swap the operands to fix both.
19795         std::swap(LHS, RHS);
19796       case ISD::SETOGT:
19797       case ISD::SETGT:
19798       case ISD::SETGE:
19799         Opcode = X86ISD::FMAX;
19800         break;
19801       }
19802     // Check for x CC y ? y : x -- a min/max with reversed arms.
19803     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19804                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19805       switch (CC) {
19806       default: break;
19807       case ISD::SETOGE:
19808         // Converting this to a min would handle comparisons between positive
19809         // and negative zero incorrectly, and swapping the operands would
19810         // cause it to handle NaNs incorrectly.
19811         if (!DAG.getTarget().Options.UnsafeFPMath &&
19812             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19813           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19814             break;
19815           std::swap(LHS, RHS);
19816         }
19817         Opcode = X86ISD::FMIN;
19818         break;
19819       case ISD::SETUGT:
19820         // Converting this to a min would handle NaNs incorrectly.
19821         if (!DAG.getTarget().Options.UnsafeFPMath &&
19822             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19823           break;
19824         Opcode = X86ISD::FMIN;
19825         break;
19826       case ISD::SETUGE:
19827         // Converting this to a min would handle both negative zeros and NaNs
19828         // incorrectly, but we can swap the operands to fix both.
19829         std::swap(LHS, RHS);
19830       case ISD::SETOGT:
19831       case ISD::SETGT:
19832       case ISD::SETGE:
19833         Opcode = X86ISD::FMIN;
19834         break;
19835
19836       case ISD::SETULT:
19837         // Converting this to a max would handle NaNs incorrectly.
19838         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19839           break;
19840         Opcode = X86ISD::FMAX;
19841         break;
19842       case ISD::SETOLE:
19843         // Converting this to a max would handle comparisons between positive
19844         // and negative zero incorrectly, and swapping the operands would
19845         // cause it to handle NaNs incorrectly.
19846         if (!DAG.getTarget().Options.UnsafeFPMath &&
19847             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19848           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19849             break;
19850           std::swap(LHS, RHS);
19851         }
19852         Opcode = X86ISD::FMAX;
19853         break;
19854       case ISD::SETULE:
19855         // Converting this to a max would handle both negative zeros and NaNs
19856         // incorrectly, but we can swap the operands to fix both.
19857         std::swap(LHS, RHS);
19858       case ISD::SETOLT:
19859       case ISD::SETLT:
19860       case ISD::SETLE:
19861         Opcode = X86ISD::FMAX;
19862         break;
19863       }
19864     }
19865
19866     if (Opcode)
19867       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19868   }
19869
19870   EVT CondVT = Cond.getValueType();
19871   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19872       CondVT.getVectorElementType() == MVT::i1) {
19873     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19874     // lowering on AVX-512. In this case we convert it to
19875     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19876     // The same situation for all 128 and 256-bit vectors of i8 and i16
19877     EVT OpVT = LHS.getValueType();
19878     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19879         (OpVT.getVectorElementType() == MVT::i8 ||
19880          OpVT.getVectorElementType() == MVT::i16)) {
19881       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19882       DCI.AddToWorklist(Cond.getNode());
19883       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19884     }
19885   }
19886   // If this is a select between two integer constants, try to do some
19887   // optimizations.
19888   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19889     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19890       // Don't do this for crazy integer types.
19891       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19892         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19893         // so that TrueC (the true value) is larger than FalseC.
19894         bool NeedsCondInvert = false;
19895
19896         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19897             // Efficiently invertible.
19898             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19899              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19900               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19901           NeedsCondInvert = true;
19902           std::swap(TrueC, FalseC);
19903         }
19904
19905         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19906         if (FalseC->getAPIntValue() == 0 &&
19907             TrueC->getAPIntValue().isPowerOf2()) {
19908           if (NeedsCondInvert) // Invert the condition if needed.
19909             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19910                                DAG.getConstant(1, Cond.getValueType()));
19911
19912           // Zero extend the condition if needed.
19913           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19914
19915           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19916           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19917                              DAG.getConstant(ShAmt, MVT::i8));
19918         }
19919
19920         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19921         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19922           if (NeedsCondInvert) // Invert the condition if needed.
19923             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19924                                DAG.getConstant(1, Cond.getValueType()));
19925
19926           // Zero extend the condition if needed.
19927           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19928                              FalseC->getValueType(0), Cond);
19929           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19930                              SDValue(FalseC, 0));
19931         }
19932
19933         // Optimize cases that will turn into an LEA instruction.  This requires
19934         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19935         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19936           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19937           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19938
19939           bool isFastMultiplier = false;
19940           if (Diff < 10) {
19941             switch ((unsigned char)Diff) {
19942               default: break;
19943               case 1:  // result = add base, cond
19944               case 2:  // result = lea base(    , cond*2)
19945               case 3:  // result = lea base(cond, cond*2)
19946               case 4:  // result = lea base(    , cond*4)
19947               case 5:  // result = lea base(cond, cond*4)
19948               case 8:  // result = lea base(    , cond*8)
19949               case 9:  // result = lea base(cond, cond*8)
19950                 isFastMultiplier = true;
19951                 break;
19952             }
19953           }
19954
19955           if (isFastMultiplier) {
19956             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19957             if (NeedsCondInvert) // Invert the condition if needed.
19958               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19959                                  DAG.getConstant(1, Cond.getValueType()));
19960
19961             // Zero extend the condition if needed.
19962             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19963                                Cond);
19964             // Scale the condition by the difference.
19965             if (Diff != 1)
19966               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19967                                  DAG.getConstant(Diff, Cond.getValueType()));
19968
19969             // Add the base if non-zero.
19970             if (FalseC->getAPIntValue() != 0)
19971               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19972                                  SDValue(FalseC, 0));
19973             return Cond;
19974           }
19975         }
19976       }
19977   }
19978
19979   // Canonicalize max and min:
19980   // (x > y) ? x : y -> (x >= y) ? x : y
19981   // (x < y) ? x : y -> (x <= y) ? x : y
19982   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19983   // the need for an extra compare
19984   // against zero. e.g.
19985   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19986   // subl   %esi, %edi
19987   // testl  %edi, %edi
19988   // movl   $0, %eax
19989   // cmovgl %edi, %eax
19990   // =>
19991   // xorl   %eax, %eax
19992   // subl   %esi, $edi
19993   // cmovsl %eax, %edi
19994   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19995       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19996       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19997     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19998     switch (CC) {
19999     default: break;
20000     case ISD::SETLT:
20001     case ISD::SETGT: {
20002       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20003       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20004                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20005       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20006     }
20007     }
20008   }
20009
20010   // Early exit check
20011   if (!TLI.isTypeLegal(VT))
20012     return SDValue();
20013
20014   // Match VSELECTs into subs with unsigned saturation.
20015   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20016       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20017       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20018        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20019     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20020
20021     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20022     // left side invert the predicate to simplify logic below.
20023     SDValue Other;
20024     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20025       Other = RHS;
20026       CC = ISD::getSetCCInverse(CC, true);
20027     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20028       Other = LHS;
20029     }
20030
20031     if (Other.getNode() && Other->getNumOperands() == 2 &&
20032         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20033       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20034       SDValue CondRHS = Cond->getOperand(1);
20035
20036       // Look for a general sub with unsigned saturation first.
20037       // x >= y ? x-y : 0 --> subus x, y
20038       // x >  y ? x-y : 0 --> subus x, y
20039       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20040           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20041         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20042
20043       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20044         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20045           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20046             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20047               // If the RHS is a constant we have to reverse the const
20048               // canonicalization.
20049               // x > C-1 ? x+-C : 0 --> subus x, C
20050               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20051                   CondRHSConst->getAPIntValue() ==
20052                       (-OpRHSConst->getAPIntValue() - 1))
20053                 return DAG.getNode(
20054                     X86ISD::SUBUS, DL, VT, OpLHS,
20055                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20056
20057           // Another special case: If C was a sign bit, the sub has been
20058           // canonicalized into a xor.
20059           // FIXME: Would it be better to use computeKnownBits to determine
20060           //        whether it's safe to decanonicalize the xor?
20061           // x s< 0 ? x^C : 0 --> subus x, C
20062           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20063               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20064               OpRHSConst->getAPIntValue().isSignBit())
20065             // Note that we have to rebuild the RHS constant here to ensure we
20066             // don't rely on particular values of undef lanes.
20067             return DAG.getNode(
20068                 X86ISD::SUBUS, DL, VT, OpLHS,
20069                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20070         }
20071     }
20072   }
20073
20074   // Try to match a min/max vector operation.
20075   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20076     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20077     unsigned Opc = ret.first;
20078     bool NeedSplit = ret.second;
20079
20080     if (Opc && NeedSplit) {
20081       unsigned NumElems = VT.getVectorNumElements();
20082       // Extract the LHS vectors
20083       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20084       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20085
20086       // Extract the RHS vectors
20087       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20088       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20089
20090       // Create min/max for each subvector
20091       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20092       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20093
20094       // Merge the result
20095       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20096     } else if (Opc)
20097       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20098   }
20099
20100   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20101   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20102       // Check if SETCC has already been promoted
20103       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20104       // Check that condition value type matches vselect operand type
20105       CondVT == VT) { 
20106
20107     assert(Cond.getValueType().isVector() &&
20108            "vector select expects a vector selector!");
20109
20110     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20111     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20112
20113     if (!TValIsAllOnes && !FValIsAllZeros) {
20114       // Try invert the condition if true value is not all 1s and false value
20115       // is not all 0s.
20116       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20117       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20118
20119       if (TValIsAllZeros || FValIsAllOnes) {
20120         SDValue CC = Cond.getOperand(2);
20121         ISD::CondCode NewCC =
20122           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20123                                Cond.getOperand(0).getValueType().isInteger());
20124         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20125         std::swap(LHS, RHS);
20126         TValIsAllOnes = FValIsAllOnes;
20127         FValIsAllZeros = TValIsAllZeros;
20128       }
20129     }
20130
20131     if (TValIsAllOnes || FValIsAllZeros) {
20132       SDValue Ret;
20133
20134       if (TValIsAllOnes && FValIsAllZeros)
20135         Ret = Cond;
20136       else if (TValIsAllOnes)
20137         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20138                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20139       else if (FValIsAllZeros)
20140         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20141                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20142
20143       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20144     }
20145   }
20146
20147   // Try to fold this VSELECT into a MOVSS/MOVSD
20148   if (N->getOpcode() == ISD::VSELECT &&
20149       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20150     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20151         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20152       bool CanFold = false;
20153       unsigned NumElems = Cond.getNumOperands();
20154       SDValue A = LHS;
20155       SDValue B = RHS;
20156       
20157       if (isZero(Cond.getOperand(0))) {
20158         CanFold = true;
20159
20160         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20161         // fold (vselect <0,-1> -> (movsd A, B)
20162         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20163           CanFold = isAllOnes(Cond.getOperand(i));
20164       } else if (isAllOnes(Cond.getOperand(0))) {
20165         CanFold = true;
20166         std::swap(A, B);
20167
20168         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20169         // fold (vselect <-1,0> -> (movsd B, A)
20170         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20171           CanFold = isZero(Cond.getOperand(i));
20172       }
20173
20174       if (CanFold) {
20175         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20176           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20177         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20178       }
20179
20180       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20181         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20182         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20183         //                             (v2i64 (bitcast B)))))
20184         //
20185         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20186         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20187         //                             (v2f64 (bitcast B)))))
20188         //
20189         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20190         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20191         //                             (v2i64 (bitcast A)))))
20192         //
20193         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20194         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20195         //                             (v2f64 (bitcast A)))))
20196
20197         CanFold = (isZero(Cond.getOperand(0)) &&
20198                    isZero(Cond.getOperand(1)) &&
20199                    isAllOnes(Cond.getOperand(2)) &&
20200                    isAllOnes(Cond.getOperand(3)));
20201
20202         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20203             isAllOnes(Cond.getOperand(1)) &&
20204             isZero(Cond.getOperand(2)) &&
20205             isZero(Cond.getOperand(3))) {
20206           CanFold = true;
20207           std::swap(LHS, RHS);
20208         }
20209
20210         if (CanFold) {
20211           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20212           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20213           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20214           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20215                                                 NewB, DAG);
20216           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20217         }
20218       }
20219     }
20220   }
20221
20222   // If we know that this node is legal then we know that it is going to be
20223   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20224   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20225   // to simplify previous instructions.
20226   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20227       !DCI.isBeforeLegalize() &&
20228       // We explicitly check against v8i16 and v16i16 because, although
20229       // they're marked as Custom, they might only be legal when Cond is a
20230       // build_vector of constants. This will be taken care in a later
20231       // condition.
20232       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20233        VT != MVT::v8i16)) {
20234     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20235
20236     // Don't optimize vector selects that map to mask-registers.
20237     if (BitWidth == 1)
20238       return SDValue();
20239
20240     // Check all uses of that condition operand to check whether it will be
20241     // consumed by non-BLEND instructions, which may depend on all bits are set
20242     // properly.
20243     for (SDNode::use_iterator I = Cond->use_begin(),
20244                               E = Cond->use_end(); I != E; ++I)
20245       if (I->getOpcode() != ISD::VSELECT)
20246         // TODO: Add other opcodes eventually lowered into BLEND.
20247         return SDValue();
20248
20249     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20250     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20251
20252     APInt KnownZero, KnownOne;
20253     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20254                                           DCI.isBeforeLegalizeOps());
20255     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20256         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20257       DCI.CommitTargetLoweringOpt(TLO);
20258   }
20259
20260   // We should generate an X86ISD::BLENDI from a vselect if its argument
20261   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20262   // constants. This specific pattern gets generated when we split a
20263   // selector for a 512 bit vector in a machine without AVX512 (but with
20264   // 256-bit vectors), during legalization:
20265   //
20266   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20267   //
20268   // Iff we find this pattern and the build_vectors are built from
20269   // constants, we translate the vselect into a shuffle_vector that we
20270   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20271   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20272     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20273     if (Shuffle.getNode())
20274       return Shuffle;
20275   }
20276
20277   return SDValue();
20278 }
20279
20280 // Check whether a boolean test is testing a boolean value generated by
20281 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20282 // code.
20283 //
20284 // Simplify the following patterns:
20285 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20286 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20287 // to (Op EFLAGS Cond)
20288 //
20289 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20290 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20291 // to (Op EFLAGS !Cond)
20292 //
20293 // where Op could be BRCOND or CMOV.
20294 //
20295 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20296   // Quit if not CMP and SUB with its value result used.
20297   if (Cmp.getOpcode() != X86ISD::CMP &&
20298       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20299       return SDValue();
20300
20301   // Quit if not used as a boolean value.
20302   if (CC != X86::COND_E && CC != X86::COND_NE)
20303     return SDValue();
20304
20305   // Check CMP operands. One of them should be 0 or 1 and the other should be
20306   // an SetCC or extended from it.
20307   SDValue Op1 = Cmp.getOperand(0);
20308   SDValue Op2 = Cmp.getOperand(1);
20309
20310   SDValue SetCC;
20311   const ConstantSDNode* C = nullptr;
20312   bool needOppositeCond = (CC == X86::COND_E);
20313   bool checkAgainstTrue = false; // Is it a comparison against 1?
20314
20315   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20316     SetCC = Op2;
20317   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20318     SetCC = Op1;
20319   else // Quit if all operands are not constants.
20320     return SDValue();
20321
20322   if (C->getZExtValue() == 1) {
20323     needOppositeCond = !needOppositeCond;
20324     checkAgainstTrue = true;
20325   } else if (C->getZExtValue() != 0)
20326     // Quit if the constant is neither 0 or 1.
20327     return SDValue();
20328
20329   bool truncatedToBoolWithAnd = false;
20330   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20331   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20332          SetCC.getOpcode() == ISD::TRUNCATE ||
20333          SetCC.getOpcode() == ISD::AND) {
20334     if (SetCC.getOpcode() == ISD::AND) {
20335       int OpIdx = -1;
20336       ConstantSDNode *CS;
20337       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20338           CS->getZExtValue() == 1)
20339         OpIdx = 1;
20340       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20341           CS->getZExtValue() == 1)
20342         OpIdx = 0;
20343       if (OpIdx == -1)
20344         break;
20345       SetCC = SetCC.getOperand(OpIdx);
20346       truncatedToBoolWithAnd = true;
20347     } else
20348       SetCC = SetCC.getOperand(0);
20349   }
20350
20351   switch (SetCC.getOpcode()) {
20352   case X86ISD::SETCC_CARRY:
20353     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20354     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20355     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20356     // truncated to i1 using 'and'.
20357     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20358       break;
20359     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20360            "Invalid use of SETCC_CARRY!");
20361     // FALL THROUGH
20362   case X86ISD::SETCC:
20363     // Set the condition code or opposite one if necessary.
20364     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20365     if (needOppositeCond)
20366       CC = X86::GetOppositeBranchCondition(CC);
20367     return SetCC.getOperand(1);
20368   case X86ISD::CMOV: {
20369     // Check whether false/true value has canonical one, i.e. 0 or 1.
20370     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20371     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20372     // Quit if true value is not a constant.
20373     if (!TVal)
20374       return SDValue();
20375     // Quit if false value is not a constant.
20376     if (!FVal) {
20377       SDValue Op = SetCC.getOperand(0);
20378       // Skip 'zext' or 'trunc' node.
20379       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20380           Op.getOpcode() == ISD::TRUNCATE)
20381         Op = Op.getOperand(0);
20382       // A special case for rdrand/rdseed, where 0 is set if false cond is
20383       // found.
20384       if ((Op.getOpcode() != X86ISD::RDRAND &&
20385            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20386         return SDValue();
20387     }
20388     // Quit if false value is not the constant 0 or 1.
20389     bool FValIsFalse = true;
20390     if (FVal && FVal->getZExtValue() != 0) {
20391       if (FVal->getZExtValue() != 1)
20392         return SDValue();
20393       // If FVal is 1, opposite cond is needed.
20394       needOppositeCond = !needOppositeCond;
20395       FValIsFalse = false;
20396     }
20397     // Quit if TVal is not the constant opposite of FVal.
20398     if (FValIsFalse && TVal->getZExtValue() != 1)
20399       return SDValue();
20400     if (!FValIsFalse && TVal->getZExtValue() != 0)
20401       return SDValue();
20402     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20403     if (needOppositeCond)
20404       CC = X86::GetOppositeBranchCondition(CC);
20405     return SetCC.getOperand(3);
20406   }
20407   }
20408
20409   return SDValue();
20410 }
20411
20412 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20413 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20414                                   TargetLowering::DAGCombinerInfo &DCI,
20415                                   const X86Subtarget *Subtarget) {
20416   SDLoc DL(N);
20417
20418   // If the flag operand isn't dead, don't touch this CMOV.
20419   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20420     return SDValue();
20421
20422   SDValue FalseOp = N->getOperand(0);
20423   SDValue TrueOp = N->getOperand(1);
20424   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20425   SDValue Cond = N->getOperand(3);
20426
20427   if (CC == X86::COND_E || CC == X86::COND_NE) {
20428     switch (Cond.getOpcode()) {
20429     default: break;
20430     case X86ISD::BSR:
20431     case X86ISD::BSF:
20432       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20433       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20434         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20435     }
20436   }
20437
20438   SDValue Flags;
20439
20440   Flags = checkBoolTestSetCCCombine(Cond, CC);
20441   if (Flags.getNode() &&
20442       // Extra check as FCMOV only supports a subset of X86 cond.
20443       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20444     SDValue Ops[] = { FalseOp, TrueOp,
20445                       DAG.getConstant(CC, MVT::i8), Flags };
20446     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20447   }
20448
20449   // If this is a select between two integer constants, try to do some
20450   // optimizations.  Note that the operands are ordered the opposite of SELECT
20451   // operands.
20452   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20453     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20454       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20455       // larger than FalseC (the false value).
20456       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20457         CC = X86::GetOppositeBranchCondition(CC);
20458         std::swap(TrueC, FalseC);
20459         std::swap(TrueOp, FalseOp);
20460       }
20461
20462       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20463       // This is efficient for any integer data type (including i8/i16) and
20464       // shift amount.
20465       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20466         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20467                            DAG.getConstant(CC, MVT::i8), Cond);
20468
20469         // Zero extend the condition if needed.
20470         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20471
20472         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20473         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20474                            DAG.getConstant(ShAmt, MVT::i8));
20475         if (N->getNumValues() == 2)  // Dead flag value?
20476           return DCI.CombineTo(N, Cond, SDValue());
20477         return Cond;
20478       }
20479
20480       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20481       // for any integer data type, including i8/i16.
20482       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20483         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20484                            DAG.getConstant(CC, MVT::i8), Cond);
20485
20486         // Zero extend the condition if needed.
20487         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20488                            FalseC->getValueType(0), Cond);
20489         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20490                            SDValue(FalseC, 0));
20491
20492         if (N->getNumValues() == 2)  // Dead flag value?
20493           return DCI.CombineTo(N, Cond, SDValue());
20494         return Cond;
20495       }
20496
20497       // Optimize cases that will turn into an LEA instruction.  This requires
20498       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20499       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20500         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20501         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20502
20503         bool isFastMultiplier = false;
20504         if (Diff < 10) {
20505           switch ((unsigned char)Diff) {
20506           default: break;
20507           case 1:  // result = add base, cond
20508           case 2:  // result = lea base(    , cond*2)
20509           case 3:  // result = lea base(cond, cond*2)
20510           case 4:  // result = lea base(    , cond*4)
20511           case 5:  // result = lea base(cond, cond*4)
20512           case 8:  // result = lea base(    , cond*8)
20513           case 9:  // result = lea base(cond, cond*8)
20514             isFastMultiplier = true;
20515             break;
20516           }
20517         }
20518
20519         if (isFastMultiplier) {
20520           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20521           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20522                              DAG.getConstant(CC, MVT::i8), Cond);
20523           // Zero extend the condition if needed.
20524           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20525                              Cond);
20526           // Scale the condition by the difference.
20527           if (Diff != 1)
20528             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20529                                DAG.getConstant(Diff, Cond.getValueType()));
20530
20531           // Add the base if non-zero.
20532           if (FalseC->getAPIntValue() != 0)
20533             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20534                                SDValue(FalseC, 0));
20535           if (N->getNumValues() == 2)  // Dead flag value?
20536             return DCI.CombineTo(N, Cond, SDValue());
20537           return Cond;
20538         }
20539       }
20540     }
20541   }
20542
20543   // Handle these cases:
20544   //   (select (x != c), e, c) -> select (x != c), e, x),
20545   //   (select (x == c), c, e) -> select (x == c), x, e)
20546   // where the c is an integer constant, and the "select" is the combination
20547   // of CMOV and CMP.
20548   //
20549   // The rationale for this change is that the conditional-move from a constant
20550   // needs two instructions, however, conditional-move from a register needs
20551   // only one instruction.
20552   //
20553   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20554   //  some instruction-combining opportunities. This opt needs to be
20555   //  postponed as late as possible.
20556   //
20557   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20558     // the DCI.xxxx conditions are provided to postpone the optimization as
20559     // late as possible.
20560
20561     ConstantSDNode *CmpAgainst = nullptr;
20562     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20563         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20564         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20565
20566       if (CC == X86::COND_NE &&
20567           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20568         CC = X86::GetOppositeBranchCondition(CC);
20569         std::swap(TrueOp, FalseOp);
20570       }
20571
20572       if (CC == X86::COND_E &&
20573           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20574         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20575                           DAG.getConstant(CC, MVT::i8), Cond };
20576         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20577       }
20578     }
20579   }
20580
20581   return SDValue();
20582 }
20583
20584 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20585                                                 const X86Subtarget *Subtarget) {
20586   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20587   switch (IntNo) {
20588   default: return SDValue();
20589   // SSE/AVX/AVX2 blend intrinsics.
20590   case Intrinsic::x86_avx2_pblendvb:
20591   case Intrinsic::x86_avx2_pblendw:
20592   case Intrinsic::x86_avx2_pblendd_128:
20593   case Intrinsic::x86_avx2_pblendd_256:
20594     // Don't try to simplify this intrinsic if we don't have AVX2.
20595     if (!Subtarget->hasAVX2())
20596       return SDValue();
20597     // FALL-THROUGH
20598   case Intrinsic::x86_avx_blend_pd_256:
20599   case Intrinsic::x86_avx_blend_ps_256:
20600   case Intrinsic::x86_avx_blendv_pd_256:
20601   case Intrinsic::x86_avx_blendv_ps_256:
20602     // Don't try to simplify this intrinsic if we don't have AVX.
20603     if (!Subtarget->hasAVX())
20604       return SDValue();
20605     // FALL-THROUGH
20606   case Intrinsic::x86_sse41_pblendw:
20607   case Intrinsic::x86_sse41_blendpd:
20608   case Intrinsic::x86_sse41_blendps:
20609   case Intrinsic::x86_sse41_blendvps:
20610   case Intrinsic::x86_sse41_blendvpd:
20611   case Intrinsic::x86_sse41_pblendvb: {
20612     SDValue Op0 = N->getOperand(1);
20613     SDValue Op1 = N->getOperand(2);
20614     SDValue Mask = N->getOperand(3);
20615
20616     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20617     if (!Subtarget->hasSSE41())
20618       return SDValue();
20619
20620     // fold (blend A, A, Mask) -> A
20621     if (Op0 == Op1)
20622       return Op0;
20623     // fold (blend A, B, allZeros) -> A
20624     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20625       return Op0;
20626     // fold (blend A, B, allOnes) -> B
20627     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20628       return Op1;
20629     
20630     // Simplify the case where the mask is a constant i32 value.
20631     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20632       if (C->isNullValue())
20633         return Op0;
20634       if (C->isAllOnesValue())
20635         return Op1;
20636     }
20637
20638     return SDValue();
20639   }
20640
20641   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20642   case Intrinsic::x86_sse2_psrai_w:
20643   case Intrinsic::x86_sse2_psrai_d:
20644   case Intrinsic::x86_avx2_psrai_w:
20645   case Intrinsic::x86_avx2_psrai_d:
20646   case Intrinsic::x86_sse2_psra_w:
20647   case Intrinsic::x86_sse2_psra_d:
20648   case Intrinsic::x86_avx2_psra_w:
20649   case Intrinsic::x86_avx2_psra_d: {
20650     SDValue Op0 = N->getOperand(1);
20651     SDValue Op1 = N->getOperand(2);
20652     EVT VT = Op0.getValueType();
20653     assert(VT.isVector() && "Expected a vector type!");
20654
20655     if (isa<BuildVectorSDNode>(Op1))
20656       Op1 = Op1.getOperand(0);
20657
20658     if (!isa<ConstantSDNode>(Op1))
20659       return SDValue();
20660
20661     EVT SVT = VT.getVectorElementType();
20662     unsigned SVTBits = SVT.getSizeInBits();
20663
20664     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20665     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20666     uint64_t ShAmt = C.getZExtValue();
20667
20668     // Don't try to convert this shift into a ISD::SRA if the shift
20669     // count is bigger than or equal to the element size.
20670     if (ShAmt >= SVTBits)
20671       return SDValue();
20672
20673     // Trivial case: if the shift count is zero, then fold this
20674     // into the first operand.
20675     if (ShAmt == 0)
20676       return Op0;
20677
20678     // Replace this packed shift intrinsic with a target independent
20679     // shift dag node.
20680     SDValue Splat = DAG.getConstant(C, VT);
20681     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20682   }
20683   }
20684 }
20685
20686 /// PerformMulCombine - Optimize a single multiply with constant into two
20687 /// in order to implement it with two cheaper instructions, e.g.
20688 /// LEA + SHL, LEA + LEA.
20689 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20690                                  TargetLowering::DAGCombinerInfo &DCI) {
20691   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20692     return SDValue();
20693
20694   EVT VT = N->getValueType(0);
20695   if (VT != MVT::i64)
20696     return SDValue();
20697
20698   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20699   if (!C)
20700     return SDValue();
20701   uint64_t MulAmt = C->getZExtValue();
20702   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20703     return SDValue();
20704
20705   uint64_t MulAmt1 = 0;
20706   uint64_t MulAmt2 = 0;
20707   if ((MulAmt % 9) == 0) {
20708     MulAmt1 = 9;
20709     MulAmt2 = MulAmt / 9;
20710   } else if ((MulAmt % 5) == 0) {
20711     MulAmt1 = 5;
20712     MulAmt2 = MulAmt / 5;
20713   } else if ((MulAmt % 3) == 0) {
20714     MulAmt1 = 3;
20715     MulAmt2 = MulAmt / 3;
20716   }
20717   if (MulAmt2 &&
20718       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20719     SDLoc DL(N);
20720
20721     if (isPowerOf2_64(MulAmt2) &&
20722         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20723       // If second multiplifer is pow2, issue it first. We want the multiply by
20724       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20725       // is an add.
20726       std::swap(MulAmt1, MulAmt2);
20727
20728     SDValue NewMul;
20729     if (isPowerOf2_64(MulAmt1))
20730       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20731                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20732     else
20733       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20734                            DAG.getConstant(MulAmt1, VT));
20735
20736     if (isPowerOf2_64(MulAmt2))
20737       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20738                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20739     else
20740       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20741                            DAG.getConstant(MulAmt2, VT));
20742
20743     // Do not add new nodes to DAG combiner worklist.
20744     DCI.CombineTo(N, NewMul, false);
20745   }
20746   return SDValue();
20747 }
20748
20749 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20750   SDValue N0 = N->getOperand(0);
20751   SDValue N1 = N->getOperand(1);
20752   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20753   EVT VT = N0.getValueType();
20754
20755   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20756   // since the result of setcc_c is all zero's or all ones.
20757   if (VT.isInteger() && !VT.isVector() &&
20758       N1C && N0.getOpcode() == ISD::AND &&
20759       N0.getOperand(1).getOpcode() == ISD::Constant) {
20760     SDValue N00 = N0.getOperand(0);
20761     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20762         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20763           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20764          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20765       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20766       APInt ShAmt = N1C->getAPIntValue();
20767       Mask = Mask.shl(ShAmt);
20768       if (Mask != 0)
20769         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20770                            N00, DAG.getConstant(Mask, VT));
20771     }
20772   }
20773
20774   // Hardware support for vector shifts is sparse which makes us scalarize the
20775   // vector operations in many cases. Also, on sandybridge ADD is faster than
20776   // shl.
20777   // (shl V, 1) -> add V,V
20778   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20779     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20780       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20781       // We shift all of the values by one. In many cases we do not have
20782       // hardware support for this operation. This is better expressed as an ADD
20783       // of two values.
20784       if (N1SplatC->getZExtValue() == 1)
20785         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20786     }
20787
20788   return SDValue();
20789 }
20790
20791 /// \brief Returns a vector of 0s if the node in input is a vector logical
20792 /// shift by a constant amount which is known to be bigger than or equal
20793 /// to the vector element size in bits.
20794 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20795                                       const X86Subtarget *Subtarget) {
20796   EVT VT = N->getValueType(0);
20797
20798   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20799       (!Subtarget->hasInt256() ||
20800        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20801     return SDValue();
20802
20803   SDValue Amt = N->getOperand(1);
20804   SDLoc DL(N);
20805   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20806     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20807       APInt ShiftAmt = AmtSplat->getAPIntValue();
20808       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20809
20810       // SSE2/AVX2 logical shifts always return a vector of 0s
20811       // if the shift amount is bigger than or equal to
20812       // the element size. The constant shift amount will be
20813       // encoded as a 8-bit immediate.
20814       if (ShiftAmt.trunc(8).uge(MaxAmount))
20815         return getZeroVector(VT, Subtarget, DAG, DL);
20816     }
20817
20818   return SDValue();
20819 }
20820
20821 /// PerformShiftCombine - Combine shifts.
20822 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20823                                    TargetLowering::DAGCombinerInfo &DCI,
20824                                    const X86Subtarget *Subtarget) {
20825   if (N->getOpcode() == ISD::SHL) {
20826     SDValue V = PerformSHLCombine(N, DAG);
20827     if (V.getNode()) return V;
20828   }
20829
20830   if (N->getOpcode() != ISD::SRA) {
20831     // Try to fold this logical shift into a zero vector.
20832     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20833     if (V.getNode()) return V;
20834   }
20835
20836   return SDValue();
20837 }
20838
20839 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20840 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20841 // and friends.  Likewise for OR -> CMPNEQSS.
20842 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20843                             TargetLowering::DAGCombinerInfo &DCI,
20844                             const X86Subtarget *Subtarget) {
20845   unsigned opcode;
20846
20847   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20848   // we're requiring SSE2 for both.
20849   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20850     SDValue N0 = N->getOperand(0);
20851     SDValue N1 = N->getOperand(1);
20852     SDValue CMP0 = N0->getOperand(1);
20853     SDValue CMP1 = N1->getOperand(1);
20854     SDLoc DL(N);
20855
20856     // The SETCCs should both refer to the same CMP.
20857     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20858       return SDValue();
20859
20860     SDValue CMP00 = CMP0->getOperand(0);
20861     SDValue CMP01 = CMP0->getOperand(1);
20862     EVT     VT    = CMP00.getValueType();
20863
20864     if (VT == MVT::f32 || VT == MVT::f64) {
20865       bool ExpectingFlags = false;
20866       // Check for any users that want flags:
20867       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20868            !ExpectingFlags && UI != UE; ++UI)
20869         switch (UI->getOpcode()) {
20870         default:
20871         case ISD::BR_CC:
20872         case ISD::BRCOND:
20873         case ISD::SELECT:
20874           ExpectingFlags = true;
20875           break;
20876         case ISD::CopyToReg:
20877         case ISD::SIGN_EXTEND:
20878         case ISD::ZERO_EXTEND:
20879         case ISD::ANY_EXTEND:
20880           break;
20881         }
20882
20883       if (!ExpectingFlags) {
20884         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20885         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20886
20887         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20888           X86::CondCode tmp = cc0;
20889           cc0 = cc1;
20890           cc1 = tmp;
20891         }
20892
20893         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20894             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20895           // FIXME: need symbolic constants for these magic numbers.
20896           // See X86ATTInstPrinter.cpp:printSSECC().
20897           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20898           if (Subtarget->hasAVX512()) {
20899             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20900                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20901             if (N->getValueType(0) != MVT::i1)
20902               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20903                                  FSetCC);
20904             return FSetCC;
20905           }
20906           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20907                                               CMP00.getValueType(), CMP00, CMP01,
20908                                               DAG.getConstant(x86cc, MVT::i8));
20909
20910           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20911           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20912
20913           if (is64BitFP && !Subtarget->is64Bit()) {
20914             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20915             // 64-bit integer, since that's not a legal type. Since
20916             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20917             // bits, but can do this little dance to extract the lowest 32 bits
20918             // and work with those going forward.
20919             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20920                                            OnesOrZeroesF);
20921             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20922                                            Vector64);
20923             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20924                                         Vector32, DAG.getIntPtrConstant(0));
20925             IntVT = MVT::i32;
20926           }
20927
20928           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20929           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20930                                       DAG.getConstant(1, IntVT));
20931           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20932           return OneBitOfTruth;
20933         }
20934       }
20935     }
20936   }
20937   return SDValue();
20938 }
20939
20940 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20941 /// so it can be folded inside ANDNP.
20942 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20943   EVT VT = N->getValueType(0);
20944
20945   // Match direct AllOnes for 128 and 256-bit vectors
20946   if (ISD::isBuildVectorAllOnes(N))
20947     return true;
20948
20949   // Look through a bit convert.
20950   if (N->getOpcode() == ISD::BITCAST)
20951     N = N->getOperand(0).getNode();
20952
20953   // Sometimes the operand may come from a insert_subvector building a 256-bit
20954   // allones vector
20955   if (VT.is256BitVector() &&
20956       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20957     SDValue V1 = N->getOperand(0);
20958     SDValue V2 = N->getOperand(1);
20959
20960     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20961         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20962         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20963         ISD::isBuildVectorAllOnes(V2.getNode()))
20964       return true;
20965   }
20966
20967   return false;
20968 }
20969
20970 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20971 // register. In most cases we actually compare or select YMM-sized registers
20972 // and mixing the two types creates horrible code. This method optimizes
20973 // some of the transition sequences.
20974 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20975                                  TargetLowering::DAGCombinerInfo &DCI,
20976                                  const X86Subtarget *Subtarget) {
20977   EVT VT = N->getValueType(0);
20978   if (!VT.is256BitVector())
20979     return SDValue();
20980
20981   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20982           N->getOpcode() == ISD::ZERO_EXTEND ||
20983           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20984
20985   SDValue Narrow = N->getOperand(0);
20986   EVT NarrowVT = Narrow->getValueType(0);
20987   if (!NarrowVT.is128BitVector())
20988     return SDValue();
20989
20990   if (Narrow->getOpcode() != ISD::XOR &&
20991       Narrow->getOpcode() != ISD::AND &&
20992       Narrow->getOpcode() != ISD::OR)
20993     return SDValue();
20994
20995   SDValue N0  = Narrow->getOperand(0);
20996   SDValue N1  = Narrow->getOperand(1);
20997   SDLoc DL(Narrow);
20998
20999   // The Left side has to be a trunc.
21000   if (N0.getOpcode() != ISD::TRUNCATE)
21001     return SDValue();
21002
21003   // The type of the truncated inputs.
21004   EVT WideVT = N0->getOperand(0)->getValueType(0);
21005   if (WideVT != VT)
21006     return SDValue();
21007
21008   // The right side has to be a 'trunc' or a constant vector.
21009   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21010   ConstantSDNode *RHSConstSplat = nullptr;
21011   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21012     RHSConstSplat = RHSBV->getConstantSplatNode();
21013   if (!RHSTrunc && !RHSConstSplat)
21014     return SDValue();
21015
21016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21017
21018   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21019     return SDValue();
21020
21021   // Set N0 and N1 to hold the inputs to the new wide operation.
21022   N0 = N0->getOperand(0);
21023   if (RHSConstSplat) {
21024     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21025                      SDValue(RHSConstSplat, 0));
21026     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21027     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21028   } else if (RHSTrunc) {
21029     N1 = N1->getOperand(0);
21030   }
21031
21032   // Generate the wide operation.
21033   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21034   unsigned Opcode = N->getOpcode();
21035   switch (Opcode) {
21036   case ISD::ANY_EXTEND:
21037     return Op;
21038   case ISD::ZERO_EXTEND: {
21039     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21040     APInt Mask = APInt::getAllOnesValue(InBits);
21041     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21042     return DAG.getNode(ISD::AND, DL, VT,
21043                        Op, DAG.getConstant(Mask, VT));
21044   }
21045   case ISD::SIGN_EXTEND:
21046     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21047                        Op, DAG.getValueType(NarrowVT));
21048   default:
21049     llvm_unreachable("Unexpected opcode");
21050   }
21051 }
21052
21053 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21054                                  TargetLowering::DAGCombinerInfo &DCI,
21055                                  const X86Subtarget *Subtarget) {
21056   EVT VT = N->getValueType(0);
21057   if (DCI.isBeforeLegalizeOps())
21058     return SDValue();
21059
21060   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21061   if (R.getNode())
21062     return R;
21063
21064   // Create BEXTR instructions
21065   // BEXTR is ((X >> imm) & (2**size-1))
21066   if (VT == MVT::i32 || VT == MVT::i64) {
21067     SDValue N0 = N->getOperand(0);
21068     SDValue N1 = N->getOperand(1);
21069     SDLoc DL(N);
21070
21071     // Check for BEXTR.
21072     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21073         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21074       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21075       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21076       if (MaskNode && ShiftNode) {
21077         uint64_t Mask = MaskNode->getZExtValue();
21078         uint64_t Shift = ShiftNode->getZExtValue();
21079         if (isMask_64(Mask)) {
21080           uint64_t MaskSize = CountPopulation_64(Mask);
21081           if (Shift + MaskSize <= VT.getSizeInBits())
21082             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21083                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21084         }
21085       }
21086     } // BEXTR
21087
21088     return SDValue();
21089   }
21090
21091   // Want to form ANDNP nodes:
21092   // 1) In the hopes of then easily combining them with OR and AND nodes
21093   //    to form PBLEND/PSIGN.
21094   // 2) To match ANDN packed intrinsics
21095   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21096     return SDValue();
21097
21098   SDValue N0 = N->getOperand(0);
21099   SDValue N1 = N->getOperand(1);
21100   SDLoc DL(N);
21101
21102   // Check LHS for vnot
21103   if (N0.getOpcode() == ISD::XOR &&
21104       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21105       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21106     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21107
21108   // Check RHS for vnot
21109   if (N1.getOpcode() == ISD::XOR &&
21110       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21111       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21112     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21113
21114   return SDValue();
21115 }
21116
21117 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21118                                 TargetLowering::DAGCombinerInfo &DCI,
21119                                 const X86Subtarget *Subtarget) {
21120   if (DCI.isBeforeLegalizeOps())
21121     return SDValue();
21122
21123   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21124   if (R.getNode())
21125     return R;
21126
21127   SDValue N0 = N->getOperand(0);
21128   SDValue N1 = N->getOperand(1);
21129   EVT VT = N->getValueType(0);
21130
21131   // look for psign/blend
21132   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21133     if (!Subtarget->hasSSSE3() ||
21134         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21135       return SDValue();
21136
21137     // Canonicalize pandn to RHS
21138     if (N0.getOpcode() == X86ISD::ANDNP)
21139       std::swap(N0, N1);
21140     // or (and (m, y), (pandn m, x))
21141     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21142       SDValue Mask = N1.getOperand(0);
21143       SDValue X    = N1.getOperand(1);
21144       SDValue Y;
21145       if (N0.getOperand(0) == Mask)
21146         Y = N0.getOperand(1);
21147       if (N0.getOperand(1) == Mask)
21148         Y = N0.getOperand(0);
21149
21150       // Check to see if the mask appeared in both the AND and ANDNP and
21151       if (!Y.getNode())
21152         return SDValue();
21153
21154       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21155       // Look through mask bitcast.
21156       if (Mask.getOpcode() == ISD::BITCAST)
21157         Mask = Mask.getOperand(0);
21158       if (X.getOpcode() == ISD::BITCAST)
21159         X = X.getOperand(0);
21160       if (Y.getOpcode() == ISD::BITCAST)
21161         Y = Y.getOperand(0);
21162
21163       EVT MaskVT = Mask.getValueType();
21164
21165       // Validate that the Mask operand is a vector sra node.
21166       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21167       // there is no psrai.b
21168       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21169       unsigned SraAmt = ~0;
21170       if (Mask.getOpcode() == ISD::SRA) {
21171         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21172           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21173             SraAmt = AmtConst->getZExtValue();
21174       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21175         SDValue SraC = Mask.getOperand(1);
21176         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21177       }
21178       if ((SraAmt + 1) != EltBits)
21179         return SDValue();
21180
21181       SDLoc DL(N);
21182
21183       // Now we know we at least have a plendvb with the mask val.  See if
21184       // we can form a psignb/w/d.
21185       // psign = x.type == y.type == mask.type && y = sub(0, x);
21186       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21187           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21188           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21189         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21190                "Unsupported VT for PSIGN");
21191         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21192         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21193       }
21194       // PBLENDVB only available on SSE 4.1
21195       if (!Subtarget->hasSSE41())
21196         return SDValue();
21197
21198       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21199
21200       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21201       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21202       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21203       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21204       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21205     }
21206   }
21207
21208   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21209     return SDValue();
21210
21211   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21212   MachineFunction &MF = DAG.getMachineFunction();
21213   bool OptForSize = MF.getFunction()->getAttributes().
21214     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21215
21216   // SHLD/SHRD instructions have lower register pressure, but on some
21217   // platforms they have higher latency than the equivalent
21218   // series of shifts/or that would otherwise be generated.
21219   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21220   // have higher latencies and we are not optimizing for size.
21221   if (!OptForSize && Subtarget->isSHLDSlow())
21222     return SDValue();
21223
21224   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21225     std::swap(N0, N1);
21226   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21227     return SDValue();
21228   if (!N0.hasOneUse() || !N1.hasOneUse())
21229     return SDValue();
21230
21231   SDValue ShAmt0 = N0.getOperand(1);
21232   if (ShAmt0.getValueType() != MVT::i8)
21233     return SDValue();
21234   SDValue ShAmt1 = N1.getOperand(1);
21235   if (ShAmt1.getValueType() != MVT::i8)
21236     return SDValue();
21237   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21238     ShAmt0 = ShAmt0.getOperand(0);
21239   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21240     ShAmt1 = ShAmt1.getOperand(0);
21241
21242   SDLoc DL(N);
21243   unsigned Opc = X86ISD::SHLD;
21244   SDValue Op0 = N0.getOperand(0);
21245   SDValue Op1 = N1.getOperand(0);
21246   if (ShAmt0.getOpcode() == ISD::SUB) {
21247     Opc = X86ISD::SHRD;
21248     std::swap(Op0, Op1);
21249     std::swap(ShAmt0, ShAmt1);
21250   }
21251
21252   unsigned Bits = VT.getSizeInBits();
21253   if (ShAmt1.getOpcode() == ISD::SUB) {
21254     SDValue Sum = ShAmt1.getOperand(0);
21255     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21256       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21257       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21258         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21259       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21260         return DAG.getNode(Opc, DL, VT,
21261                            Op0, Op1,
21262                            DAG.getNode(ISD::TRUNCATE, DL,
21263                                        MVT::i8, ShAmt0));
21264     }
21265   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21266     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21267     if (ShAmt0C &&
21268         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21269       return DAG.getNode(Opc, DL, VT,
21270                          N0.getOperand(0), N1.getOperand(0),
21271                          DAG.getNode(ISD::TRUNCATE, DL,
21272                                        MVT::i8, ShAmt0));
21273   }
21274
21275   return SDValue();
21276 }
21277
21278 // Generate NEG and CMOV for integer abs.
21279 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21280   EVT VT = N->getValueType(0);
21281
21282   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21283   // 8-bit integer abs to NEG and CMOV.
21284   if (VT.isInteger() && VT.getSizeInBits() == 8)
21285     return SDValue();
21286
21287   SDValue N0 = N->getOperand(0);
21288   SDValue N1 = N->getOperand(1);
21289   SDLoc DL(N);
21290
21291   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21292   // and change it to SUB and CMOV.
21293   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21294       N0.getOpcode() == ISD::ADD &&
21295       N0.getOperand(1) == N1 &&
21296       N1.getOpcode() == ISD::SRA &&
21297       N1.getOperand(0) == N0.getOperand(0))
21298     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21299       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21300         // Generate SUB & CMOV.
21301         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21302                                   DAG.getConstant(0, VT), N0.getOperand(0));
21303
21304         SDValue Ops[] = { N0.getOperand(0), Neg,
21305                           DAG.getConstant(X86::COND_GE, MVT::i8),
21306                           SDValue(Neg.getNode(), 1) };
21307         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21308       }
21309   return SDValue();
21310 }
21311
21312 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21313 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21314                                  TargetLowering::DAGCombinerInfo &DCI,
21315                                  const X86Subtarget *Subtarget) {
21316   if (DCI.isBeforeLegalizeOps())
21317     return SDValue();
21318
21319   if (Subtarget->hasCMov()) {
21320     SDValue RV = performIntegerAbsCombine(N, DAG);
21321     if (RV.getNode())
21322       return RV;
21323   }
21324
21325   return SDValue();
21326 }
21327
21328 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21329 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21330                                   TargetLowering::DAGCombinerInfo &DCI,
21331                                   const X86Subtarget *Subtarget) {
21332   LoadSDNode *Ld = cast<LoadSDNode>(N);
21333   EVT RegVT = Ld->getValueType(0);
21334   EVT MemVT = Ld->getMemoryVT();
21335   SDLoc dl(Ld);
21336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21337
21338   // On Sandybridge unaligned 256bit loads are inefficient.
21339   ISD::LoadExtType Ext = Ld->getExtensionType();
21340   unsigned Alignment = Ld->getAlignment();
21341   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21342   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21343       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21344     unsigned NumElems = RegVT.getVectorNumElements();
21345     if (NumElems < 2)
21346       return SDValue();
21347
21348     SDValue Ptr = Ld->getBasePtr();
21349     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21350
21351     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21352                                   NumElems/2);
21353     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21354                                 Ld->getPointerInfo(), Ld->isVolatile(),
21355                                 Ld->isNonTemporal(), Ld->isInvariant(),
21356                                 Alignment);
21357     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21358     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21359                                 Ld->getPointerInfo(), Ld->isVolatile(),
21360                                 Ld->isNonTemporal(), Ld->isInvariant(),
21361                                 std::min(16U, Alignment));
21362     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21363                              Load1.getValue(1),
21364                              Load2.getValue(1));
21365
21366     SDValue NewVec = DAG.getUNDEF(RegVT);
21367     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21368     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21369     return DCI.CombineTo(N, NewVec, TF, true);
21370   }
21371
21372   return SDValue();
21373 }
21374
21375 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21376 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21377                                    const X86Subtarget *Subtarget) {
21378   StoreSDNode *St = cast<StoreSDNode>(N);
21379   EVT VT = St->getValue().getValueType();
21380   EVT StVT = St->getMemoryVT();
21381   SDLoc dl(St);
21382   SDValue StoredVal = St->getOperand(1);
21383   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21384
21385   // If we are saving a concatenation of two XMM registers, perform two stores.
21386   // On Sandy Bridge, 256-bit memory operations are executed by two
21387   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21388   // memory  operation.
21389   unsigned Alignment = St->getAlignment();
21390   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21391   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21392       StVT == VT && !IsAligned) {
21393     unsigned NumElems = VT.getVectorNumElements();
21394     if (NumElems < 2)
21395       return SDValue();
21396
21397     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21398     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21399
21400     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21401     SDValue Ptr0 = St->getBasePtr();
21402     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21403
21404     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21405                                 St->getPointerInfo(), St->isVolatile(),
21406                                 St->isNonTemporal(), Alignment);
21407     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21408                                 St->getPointerInfo(), St->isVolatile(),
21409                                 St->isNonTemporal(),
21410                                 std::min(16U, Alignment));
21411     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21412   }
21413
21414   // Optimize trunc store (of multiple scalars) to shuffle and store.
21415   // First, pack all of the elements in one place. Next, store to memory
21416   // in fewer chunks.
21417   if (St->isTruncatingStore() && VT.isVector()) {
21418     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21419     unsigned NumElems = VT.getVectorNumElements();
21420     assert(StVT != VT && "Cannot truncate to the same type");
21421     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21422     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21423
21424     // From, To sizes and ElemCount must be pow of two
21425     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21426     // We are going to use the original vector elt for storing.
21427     // Accumulated smaller vector elements must be a multiple of the store size.
21428     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21429
21430     unsigned SizeRatio  = FromSz / ToSz;
21431
21432     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21433
21434     // Create a type on which we perform the shuffle
21435     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21436             StVT.getScalarType(), NumElems*SizeRatio);
21437
21438     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21439
21440     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21441     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21442     for (unsigned i = 0; i != NumElems; ++i)
21443       ShuffleVec[i] = i * SizeRatio;
21444
21445     // Can't shuffle using an illegal type.
21446     if (!TLI.isTypeLegal(WideVecVT))
21447       return SDValue();
21448
21449     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21450                                          DAG.getUNDEF(WideVecVT),
21451                                          &ShuffleVec[0]);
21452     // At this point all of the data is stored at the bottom of the
21453     // register. We now need to save it to mem.
21454
21455     // Find the largest store unit
21456     MVT StoreType = MVT::i8;
21457     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21458          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21459       MVT Tp = (MVT::SimpleValueType)tp;
21460       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21461         StoreType = Tp;
21462     }
21463
21464     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21465     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21466         (64 <= NumElems * ToSz))
21467       StoreType = MVT::f64;
21468
21469     // Bitcast the original vector into a vector of store-size units
21470     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21471             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21472     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21473     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21474     SmallVector<SDValue, 8> Chains;
21475     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21476                                         TLI.getPointerTy());
21477     SDValue Ptr = St->getBasePtr();
21478
21479     // Perform one or more big stores into memory.
21480     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21481       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21482                                    StoreType, ShuffWide,
21483                                    DAG.getIntPtrConstant(i));
21484       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21485                                 St->getPointerInfo(), St->isVolatile(),
21486                                 St->isNonTemporal(), St->getAlignment());
21487       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21488       Chains.push_back(Ch);
21489     }
21490
21491     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21492   }
21493
21494   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21495   // the FP state in cases where an emms may be missing.
21496   // A preferable solution to the general problem is to figure out the right
21497   // places to insert EMMS.  This qualifies as a quick hack.
21498
21499   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21500   if (VT.getSizeInBits() != 64)
21501     return SDValue();
21502
21503   const Function *F = DAG.getMachineFunction().getFunction();
21504   bool NoImplicitFloatOps = F->getAttributes().
21505     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21506   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21507                      && Subtarget->hasSSE2();
21508   if ((VT.isVector() ||
21509        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21510       isa<LoadSDNode>(St->getValue()) &&
21511       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21512       St->getChain().hasOneUse() && !St->isVolatile()) {
21513     SDNode* LdVal = St->getValue().getNode();
21514     LoadSDNode *Ld = nullptr;
21515     int TokenFactorIndex = -1;
21516     SmallVector<SDValue, 8> Ops;
21517     SDNode* ChainVal = St->getChain().getNode();
21518     // Must be a store of a load.  We currently handle two cases:  the load
21519     // is a direct child, and it's under an intervening TokenFactor.  It is
21520     // possible to dig deeper under nested TokenFactors.
21521     if (ChainVal == LdVal)
21522       Ld = cast<LoadSDNode>(St->getChain());
21523     else if (St->getValue().hasOneUse() &&
21524              ChainVal->getOpcode() == ISD::TokenFactor) {
21525       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21526         if (ChainVal->getOperand(i).getNode() == LdVal) {
21527           TokenFactorIndex = i;
21528           Ld = cast<LoadSDNode>(St->getValue());
21529         } else
21530           Ops.push_back(ChainVal->getOperand(i));
21531       }
21532     }
21533
21534     if (!Ld || !ISD::isNormalLoad(Ld))
21535       return SDValue();
21536
21537     // If this is not the MMX case, i.e. we are just turning i64 load/store
21538     // into f64 load/store, avoid the transformation if there are multiple
21539     // uses of the loaded value.
21540     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21541       return SDValue();
21542
21543     SDLoc LdDL(Ld);
21544     SDLoc StDL(N);
21545     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21546     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21547     // pair instead.
21548     if (Subtarget->is64Bit() || F64IsLegal) {
21549       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21550       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21551                                   Ld->getPointerInfo(), Ld->isVolatile(),
21552                                   Ld->isNonTemporal(), Ld->isInvariant(),
21553                                   Ld->getAlignment());
21554       SDValue NewChain = NewLd.getValue(1);
21555       if (TokenFactorIndex != -1) {
21556         Ops.push_back(NewChain);
21557         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21558       }
21559       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21560                           St->getPointerInfo(),
21561                           St->isVolatile(), St->isNonTemporal(),
21562                           St->getAlignment());
21563     }
21564
21565     // Otherwise, lower to two pairs of 32-bit loads / stores.
21566     SDValue LoAddr = Ld->getBasePtr();
21567     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21568                                  DAG.getConstant(4, MVT::i32));
21569
21570     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21571                                Ld->getPointerInfo(),
21572                                Ld->isVolatile(), Ld->isNonTemporal(),
21573                                Ld->isInvariant(), Ld->getAlignment());
21574     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21575                                Ld->getPointerInfo().getWithOffset(4),
21576                                Ld->isVolatile(), Ld->isNonTemporal(),
21577                                Ld->isInvariant(),
21578                                MinAlign(Ld->getAlignment(), 4));
21579
21580     SDValue NewChain = LoLd.getValue(1);
21581     if (TokenFactorIndex != -1) {
21582       Ops.push_back(LoLd);
21583       Ops.push_back(HiLd);
21584       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21585     }
21586
21587     LoAddr = St->getBasePtr();
21588     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21589                          DAG.getConstant(4, MVT::i32));
21590
21591     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21592                                 St->getPointerInfo(),
21593                                 St->isVolatile(), St->isNonTemporal(),
21594                                 St->getAlignment());
21595     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21596                                 St->getPointerInfo().getWithOffset(4),
21597                                 St->isVolatile(),
21598                                 St->isNonTemporal(),
21599                                 MinAlign(St->getAlignment(), 4));
21600     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21601   }
21602   return SDValue();
21603 }
21604
21605 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21606 /// and return the operands for the horizontal operation in LHS and RHS.  A
21607 /// horizontal operation performs the binary operation on successive elements
21608 /// of its first operand, then on successive elements of its second operand,
21609 /// returning the resulting values in a vector.  For example, if
21610 ///   A = < float a0, float a1, float a2, float a3 >
21611 /// and
21612 ///   B = < float b0, float b1, float b2, float b3 >
21613 /// then the result of doing a horizontal operation on A and B is
21614 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21615 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21616 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21617 /// set to A, RHS to B, and the routine returns 'true'.
21618 /// Note that the binary operation should have the property that if one of the
21619 /// operands is UNDEF then the result is UNDEF.
21620 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21621   // Look for the following pattern: if
21622   //   A = < float a0, float a1, float a2, float a3 >
21623   //   B = < float b0, float b1, float b2, float b3 >
21624   // and
21625   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21626   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21627   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21628   // which is A horizontal-op B.
21629
21630   // At least one of the operands should be a vector shuffle.
21631   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21632       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21633     return false;
21634
21635   MVT VT = LHS.getSimpleValueType();
21636
21637   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21638          "Unsupported vector type for horizontal add/sub");
21639
21640   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21641   // operate independently on 128-bit lanes.
21642   unsigned NumElts = VT.getVectorNumElements();
21643   unsigned NumLanes = VT.getSizeInBits()/128;
21644   unsigned NumLaneElts = NumElts / NumLanes;
21645   assert((NumLaneElts % 2 == 0) &&
21646          "Vector type should have an even number of elements in each lane");
21647   unsigned HalfLaneElts = NumLaneElts/2;
21648
21649   // View LHS in the form
21650   //   LHS = VECTOR_SHUFFLE A, B, LMask
21651   // If LHS is not a shuffle then pretend it is the shuffle
21652   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21653   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21654   // type VT.
21655   SDValue A, B;
21656   SmallVector<int, 16> LMask(NumElts);
21657   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21658     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21659       A = LHS.getOperand(0);
21660     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21661       B = LHS.getOperand(1);
21662     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21663     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21664   } else {
21665     if (LHS.getOpcode() != ISD::UNDEF)
21666       A = LHS;
21667     for (unsigned i = 0; i != NumElts; ++i)
21668       LMask[i] = i;
21669   }
21670
21671   // Likewise, view RHS in the form
21672   //   RHS = VECTOR_SHUFFLE C, D, RMask
21673   SDValue C, D;
21674   SmallVector<int, 16> RMask(NumElts);
21675   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21676     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21677       C = RHS.getOperand(0);
21678     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21679       D = RHS.getOperand(1);
21680     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21681     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21682   } else {
21683     if (RHS.getOpcode() != ISD::UNDEF)
21684       C = RHS;
21685     for (unsigned i = 0; i != NumElts; ++i)
21686       RMask[i] = i;
21687   }
21688
21689   // Check that the shuffles are both shuffling the same vectors.
21690   if (!(A == C && B == D) && !(A == D && B == C))
21691     return false;
21692
21693   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21694   if (!A.getNode() && !B.getNode())
21695     return false;
21696
21697   // If A and B occur in reverse order in RHS, then "swap" them (which means
21698   // rewriting the mask).
21699   if (A != C)
21700     CommuteVectorShuffleMask(RMask, NumElts);
21701
21702   // At this point LHS and RHS are equivalent to
21703   //   LHS = VECTOR_SHUFFLE A, B, LMask
21704   //   RHS = VECTOR_SHUFFLE A, B, RMask
21705   // Check that the masks correspond to performing a horizontal operation.
21706   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21707     for (unsigned i = 0; i != NumLaneElts; ++i) {
21708       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21709
21710       // Ignore any UNDEF components.
21711       if (LIdx < 0 || RIdx < 0 ||
21712           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21713           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21714         continue;
21715
21716       // Check that successive elements are being operated on.  If not, this is
21717       // not a horizontal operation.
21718       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21719       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21720       if (!(LIdx == Index && RIdx == Index + 1) &&
21721           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21722         return false;
21723     }
21724   }
21725
21726   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21727   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21728   return true;
21729 }
21730
21731 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21732 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21733                                   const X86Subtarget *Subtarget) {
21734   EVT VT = N->getValueType(0);
21735   SDValue LHS = N->getOperand(0);
21736   SDValue RHS = N->getOperand(1);
21737
21738   // Try to synthesize horizontal adds from adds of shuffles.
21739   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21740        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21741       isHorizontalBinOp(LHS, RHS, true))
21742     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21743   return SDValue();
21744 }
21745
21746 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21747 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21748                                   const X86Subtarget *Subtarget) {
21749   EVT VT = N->getValueType(0);
21750   SDValue LHS = N->getOperand(0);
21751   SDValue RHS = N->getOperand(1);
21752
21753   // Try to synthesize horizontal subs from subs of shuffles.
21754   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21755        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21756       isHorizontalBinOp(LHS, RHS, false))
21757     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21758   return SDValue();
21759 }
21760
21761 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21762 /// X86ISD::FXOR nodes.
21763 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21764   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21765   // F[X]OR(0.0, x) -> x
21766   // F[X]OR(x, 0.0) -> x
21767   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21768     if (C->getValueAPF().isPosZero())
21769       return N->getOperand(1);
21770   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21771     if (C->getValueAPF().isPosZero())
21772       return N->getOperand(0);
21773   return SDValue();
21774 }
21775
21776 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21777 /// X86ISD::FMAX nodes.
21778 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21779   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21780
21781   // Only perform optimizations if UnsafeMath is used.
21782   if (!DAG.getTarget().Options.UnsafeFPMath)
21783     return SDValue();
21784
21785   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21786   // into FMINC and FMAXC, which are Commutative operations.
21787   unsigned NewOp = 0;
21788   switch (N->getOpcode()) {
21789     default: llvm_unreachable("unknown opcode");
21790     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21791     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21792   }
21793
21794   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21795                      N->getOperand(0), N->getOperand(1));
21796 }
21797
21798 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21799 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21800   // FAND(0.0, x) -> 0.0
21801   // FAND(x, 0.0) -> 0.0
21802   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21803     if (C->getValueAPF().isPosZero())
21804       return N->getOperand(0);
21805   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21806     if (C->getValueAPF().isPosZero())
21807       return N->getOperand(1);
21808   return SDValue();
21809 }
21810
21811 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21812 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21813   // FANDN(x, 0.0) -> 0.0
21814   // FANDN(0.0, x) -> x
21815   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21816     if (C->getValueAPF().isPosZero())
21817       return N->getOperand(1);
21818   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21819     if (C->getValueAPF().isPosZero())
21820       return N->getOperand(1);
21821   return SDValue();
21822 }
21823
21824 static SDValue PerformBTCombine(SDNode *N,
21825                                 SelectionDAG &DAG,
21826                                 TargetLowering::DAGCombinerInfo &DCI) {
21827   // BT ignores high bits in the bit index operand.
21828   SDValue Op1 = N->getOperand(1);
21829   if (Op1.hasOneUse()) {
21830     unsigned BitWidth = Op1.getValueSizeInBits();
21831     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21832     APInt KnownZero, KnownOne;
21833     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21834                                           !DCI.isBeforeLegalizeOps());
21835     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21836     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21837         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21838       DCI.CommitTargetLoweringOpt(TLO);
21839   }
21840   return SDValue();
21841 }
21842
21843 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21844   SDValue Op = N->getOperand(0);
21845   if (Op.getOpcode() == ISD::BITCAST)
21846     Op = Op.getOperand(0);
21847   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21848   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21849       VT.getVectorElementType().getSizeInBits() ==
21850       OpVT.getVectorElementType().getSizeInBits()) {
21851     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21852   }
21853   return SDValue();
21854 }
21855
21856 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21857                                                const X86Subtarget *Subtarget) {
21858   EVT VT = N->getValueType(0);
21859   if (!VT.isVector())
21860     return SDValue();
21861
21862   SDValue N0 = N->getOperand(0);
21863   SDValue N1 = N->getOperand(1);
21864   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21865   SDLoc dl(N);
21866
21867   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21868   // both SSE and AVX2 since there is no sign-extended shift right
21869   // operation on a vector with 64-bit elements.
21870   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21871   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21872   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21873       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21874     SDValue N00 = N0.getOperand(0);
21875
21876     // EXTLOAD has a better solution on AVX2,
21877     // it may be replaced with X86ISD::VSEXT node.
21878     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21879       if (!ISD::isNormalLoad(N00.getNode()))
21880         return SDValue();
21881
21882     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21883         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21884                                   N00, N1);
21885       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21886     }
21887   }
21888   return SDValue();
21889 }
21890
21891 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21892                                   TargetLowering::DAGCombinerInfo &DCI,
21893                                   const X86Subtarget *Subtarget) {
21894   if (!DCI.isBeforeLegalizeOps())
21895     return SDValue();
21896
21897   if (!Subtarget->hasFp256())
21898     return SDValue();
21899
21900   EVT VT = N->getValueType(0);
21901   if (VT.isVector() && VT.getSizeInBits() == 256) {
21902     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21903     if (R.getNode())
21904       return R;
21905   }
21906
21907   return SDValue();
21908 }
21909
21910 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21911                                  const X86Subtarget* Subtarget) {
21912   SDLoc dl(N);
21913   EVT VT = N->getValueType(0);
21914
21915   // Let legalize expand this if it isn't a legal type yet.
21916   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21917     return SDValue();
21918
21919   EVT ScalarVT = VT.getScalarType();
21920   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21921       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21922     return SDValue();
21923
21924   SDValue A = N->getOperand(0);
21925   SDValue B = N->getOperand(1);
21926   SDValue C = N->getOperand(2);
21927
21928   bool NegA = (A.getOpcode() == ISD::FNEG);
21929   bool NegB = (B.getOpcode() == ISD::FNEG);
21930   bool NegC = (C.getOpcode() == ISD::FNEG);
21931
21932   // Negative multiplication when NegA xor NegB
21933   bool NegMul = (NegA != NegB);
21934   if (NegA)
21935     A = A.getOperand(0);
21936   if (NegB)
21937     B = B.getOperand(0);
21938   if (NegC)
21939     C = C.getOperand(0);
21940
21941   unsigned Opcode;
21942   if (!NegMul)
21943     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21944   else
21945     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21946
21947   return DAG.getNode(Opcode, dl, VT, A, B, C);
21948 }
21949
21950 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21951                                   TargetLowering::DAGCombinerInfo &DCI,
21952                                   const X86Subtarget *Subtarget) {
21953   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21954   //           (and (i32 x86isd::setcc_carry), 1)
21955   // This eliminates the zext. This transformation is necessary because
21956   // ISD::SETCC is always legalized to i8.
21957   SDLoc dl(N);
21958   SDValue N0 = N->getOperand(0);
21959   EVT VT = N->getValueType(0);
21960
21961   if (N0.getOpcode() == ISD::AND &&
21962       N0.hasOneUse() &&
21963       N0.getOperand(0).hasOneUse()) {
21964     SDValue N00 = N0.getOperand(0);
21965     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21966       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21967       if (!C || C->getZExtValue() != 1)
21968         return SDValue();
21969       return DAG.getNode(ISD::AND, dl, VT,
21970                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21971                                      N00.getOperand(0), N00.getOperand(1)),
21972                          DAG.getConstant(1, VT));
21973     }
21974   }
21975
21976   if (N0.getOpcode() == ISD::TRUNCATE &&
21977       N0.hasOneUse() &&
21978       N0.getOperand(0).hasOneUse()) {
21979     SDValue N00 = N0.getOperand(0);
21980     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21981       return DAG.getNode(ISD::AND, dl, VT,
21982                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21983                                      N00.getOperand(0), N00.getOperand(1)),
21984                          DAG.getConstant(1, VT));
21985     }
21986   }
21987   if (VT.is256BitVector()) {
21988     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21989     if (R.getNode())
21990       return R;
21991   }
21992
21993   return SDValue();
21994 }
21995
21996 // Optimize x == -y --> x+y == 0
21997 //          x != -y --> x+y != 0
21998 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21999                                       const X86Subtarget* Subtarget) {
22000   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22001   SDValue LHS = N->getOperand(0);
22002   SDValue RHS = N->getOperand(1);
22003   EVT VT = N->getValueType(0);
22004   SDLoc DL(N);
22005
22006   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22007     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22008       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22009         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22010                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22011         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22012                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22013       }
22014   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22015     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22016       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22017         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22018                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22019         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22020                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22021       }
22022
22023   if (VT.getScalarType() == MVT::i1) {
22024     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22025       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22026     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22027     if (!IsSEXT0 && !IsVZero0)
22028       return SDValue();
22029     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22030       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22031     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22032
22033     if (!IsSEXT1 && !IsVZero1)
22034       return SDValue();
22035
22036     if (IsSEXT0 && IsVZero1) {
22037       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22038       if (CC == ISD::SETEQ)
22039         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22040       return LHS.getOperand(0);
22041     }
22042     if (IsSEXT1 && IsVZero0) {
22043       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22044       if (CC == ISD::SETEQ)
22045         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22046       return RHS.getOperand(0);
22047     }
22048   }
22049
22050   return SDValue();
22051 }
22052
22053 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22054                                       const X86Subtarget *Subtarget) {
22055   SDLoc dl(N);
22056   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22057   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22058          "X86insertps is only defined for v4x32");
22059
22060   SDValue Ld = N->getOperand(1);
22061   if (MayFoldLoad(Ld)) {
22062     // Extract the countS bits from the immediate so we can get the proper
22063     // address when narrowing the vector load to a specific element.
22064     // When the second source op is a memory address, interps doesn't use
22065     // countS and just gets an f32 from that address.
22066     unsigned DestIndex =
22067         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22068     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22069   } else
22070     return SDValue();
22071
22072   // Create this as a scalar to vector to match the instruction pattern.
22073   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22074   // countS bits are ignored when loading from memory on insertps, which
22075   // means we don't need to explicitly set them to 0.
22076   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22077                      LoadScalarToVector, N->getOperand(2));
22078 }
22079
22080 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22081 // as "sbb reg,reg", since it can be extended without zext and produces
22082 // an all-ones bit which is more useful than 0/1 in some cases.
22083 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22084                                MVT VT) {
22085   if (VT == MVT::i8)
22086     return DAG.getNode(ISD::AND, DL, VT,
22087                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22088                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22089                        DAG.getConstant(1, VT));
22090   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22091   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22092                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22093                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22094 }
22095
22096 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22097 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22098                                    TargetLowering::DAGCombinerInfo &DCI,
22099                                    const X86Subtarget *Subtarget) {
22100   SDLoc DL(N);
22101   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22102   SDValue EFLAGS = N->getOperand(1);
22103
22104   if (CC == X86::COND_A) {
22105     // Try to convert COND_A into COND_B in an attempt to facilitate
22106     // materializing "setb reg".
22107     //
22108     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22109     // cannot take an immediate as its first operand.
22110     //
22111     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22112         EFLAGS.getValueType().isInteger() &&
22113         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22114       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22115                                    EFLAGS.getNode()->getVTList(),
22116                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22117       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22118       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22119     }
22120   }
22121
22122   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22123   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22124   // cases.
22125   if (CC == X86::COND_B)
22126     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22127
22128   SDValue Flags;
22129
22130   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22131   if (Flags.getNode()) {
22132     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22133     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22134   }
22135
22136   return SDValue();
22137 }
22138
22139 // Optimize branch condition evaluation.
22140 //
22141 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22142                                     TargetLowering::DAGCombinerInfo &DCI,
22143                                     const X86Subtarget *Subtarget) {
22144   SDLoc DL(N);
22145   SDValue Chain = N->getOperand(0);
22146   SDValue Dest = N->getOperand(1);
22147   SDValue EFLAGS = N->getOperand(3);
22148   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22149
22150   SDValue Flags;
22151
22152   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22153   if (Flags.getNode()) {
22154     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22155     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22156                        Flags);
22157   }
22158
22159   return SDValue();
22160 }
22161
22162 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22163                                                          SelectionDAG &DAG) {
22164   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22165   // optimize away operation when it's from a constant.
22166   //
22167   // The general transformation is:
22168   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22169   //       AND(VECTOR_CMP(x,y), constant2)
22170   //    constant2 = UNARYOP(constant)
22171
22172   // Early exit if this isn't a vector operation, the operand of the
22173   // unary operation isn't a bitwise AND, or if the sizes of the operations
22174   // aren't the same.
22175   EVT VT = N->getValueType(0);
22176   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22177       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22178       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22179     return SDValue();
22180
22181   // Now check that the other operand of the AND is a constant. We could
22182   // make the transformation for non-constant splats as well, but it's unclear
22183   // that would be a benefit as it would not eliminate any operations, just
22184   // perform one more step in scalar code before moving to the vector unit.
22185   if (BuildVectorSDNode *BV =
22186           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22187     // Bail out if the vector isn't a constant.
22188     if (!BV->isConstant())
22189       return SDValue();
22190
22191     // Everything checks out. Build up the new and improved node.
22192     SDLoc DL(N);
22193     EVT IntVT = BV->getValueType(0);
22194     // Create a new constant of the appropriate type for the transformed
22195     // DAG.
22196     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22197     // The AND node needs bitcasts to/from an integer vector type around it.
22198     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22199     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22200                                  N->getOperand(0)->getOperand(0), MaskConst);
22201     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22202     return Res;
22203   }
22204
22205   return SDValue();
22206 }
22207
22208 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22209                                         const X86TargetLowering *XTLI) {
22210   // First try to optimize away the conversion entirely when it's
22211   // conditionally from a constant. Vectors only.
22212   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22213   if (Res != SDValue())
22214     return Res;
22215
22216   // Now move on to more general possibilities.
22217   SDValue Op0 = N->getOperand(0);
22218   EVT InVT = Op0->getValueType(0);
22219
22220   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22221   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22222     SDLoc dl(N);
22223     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22224     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22225     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22226   }
22227
22228   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22229   // a 32-bit target where SSE doesn't support i64->FP operations.
22230   if (Op0.getOpcode() == ISD::LOAD) {
22231     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22232     EVT VT = Ld->getValueType(0);
22233     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22234         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22235         !XTLI->getSubtarget()->is64Bit() &&
22236         VT == MVT::i64) {
22237       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22238                                           Ld->getChain(), Op0, DAG);
22239       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22240       return FILDChain;
22241     }
22242   }
22243   return SDValue();
22244 }
22245
22246 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22247 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22248                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22249   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22250   // the result is either zero or one (depending on the input carry bit).
22251   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22252   if (X86::isZeroNode(N->getOperand(0)) &&
22253       X86::isZeroNode(N->getOperand(1)) &&
22254       // We don't have a good way to replace an EFLAGS use, so only do this when
22255       // dead right now.
22256       SDValue(N, 1).use_empty()) {
22257     SDLoc DL(N);
22258     EVT VT = N->getValueType(0);
22259     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22260     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22261                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22262                                            DAG.getConstant(X86::COND_B,MVT::i8),
22263                                            N->getOperand(2)),
22264                                DAG.getConstant(1, VT));
22265     return DCI.CombineTo(N, Res1, CarryOut);
22266   }
22267
22268   return SDValue();
22269 }
22270
22271 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22272 //      (add Y, (setne X, 0)) -> sbb -1, Y
22273 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22274 //      (sub (setne X, 0), Y) -> adc -1, Y
22275 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22276   SDLoc DL(N);
22277
22278   // Look through ZExts.
22279   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22280   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22281     return SDValue();
22282
22283   SDValue SetCC = Ext.getOperand(0);
22284   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22285     return SDValue();
22286
22287   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22288   if (CC != X86::COND_E && CC != X86::COND_NE)
22289     return SDValue();
22290
22291   SDValue Cmp = SetCC.getOperand(1);
22292   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22293       !X86::isZeroNode(Cmp.getOperand(1)) ||
22294       !Cmp.getOperand(0).getValueType().isInteger())
22295     return SDValue();
22296
22297   SDValue CmpOp0 = Cmp.getOperand(0);
22298   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22299                                DAG.getConstant(1, CmpOp0.getValueType()));
22300
22301   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22302   if (CC == X86::COND_NE)
22303     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22304                        DL, OtherVal.getValueType(), OtherVal,
22305                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22306   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22307                      DL, OtherVal.getValueType(), OtherVal,
22308                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22309 }
22310
22311 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22312 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22313                                  const X86Subtarget *Subtarget) {
22314   EVT VT = N->getValueType(0);
22315   SDValue Op0 = N->getOperand(0);
22316   SDValue Op1 = N->getOperand(1);
22317
22318   // Try to synthesize horizontal adds from adds of shuffles.
22319   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22320        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22321       isHorizontalBinOp(Op0, Op1, true))
22322     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22323
22324   return OptimizeConditionalInDecrement(N, DAG);
22325 }
22326
22327 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22328                                  const X86Subtarget *Subtarget) {
22329   SDValue Op0 = N->getOperand(0);
22330   SDValue Op1 = N->getOperand(1);
22331
22332   // X86 can't encode an immediate LHS of a sub. See if we can push the
22333   // negation into a preceding instruction.
22334   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22335     // If the RHS of the sub is a XOR with one use and a constant, invert the
22336     // immediate. Then add one to the LHS of the sub so we can turn
22337     // X-Y -> X+~Y+1, saving one register.
22338     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22339         isa<ConstantSDNode>(Op1.getOperand(1))) {
22340       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22341       EVT VT = Op0.getValueType();
22342       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22343                                    Op1.getOperand(0),
22344                                    DAG.getConstant(~XorC, VT));
22345       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22346                          DAG.getConstant(C->getAPIntValue()+1, VT));
22347     }
22348   }
22349
22350   // Try to synthesize horizontal adds from adds of shuffles.
22351   EVT VT = N->getValueType(0);
22352   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22353        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22354       isHorizontalBinOp(Op0, Op1, true))
22355     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22356
22357   return OptimizeConditionalInDecrement(N, DAG);
22358 }
22359
22360 /// performVZEXTCombine - Performs build vector combines
22361 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22362                                         TargetLowering::DAGCombinerInfo &DCI,
22363                                         const X86Subtarget *Subtarget) {
22364   // (vzext (bitcast (vzext (x)) -> (vzext x)
22365   SDValue In = N->getOperand(0);
22366   while (In.getOpcode() == ISD::BITCAST)
22367     In = In.getOperand(0);
22368
22369   if (In.getOpcode() != X86ISD::VZEXT)
22370     return SDValue();
22371
22372   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22373                      In.getOperand(0));
22374 }
22375
22376 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22377                                              DAGCombinerInfo &DCI) const {
22378   SelectionDAG &DAG = DCI.DAG;
22379   switch (N->getOpcode()) {
22380   default: break;
22381   case ISD::EXTRACT_VECTOR_ELT:
22382     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22383   case ISD::VSELECT:
22384   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22385   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22386   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22387   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22388   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22389   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22390   case ISD::SHL:
22391   case ISD::SRA:
22392   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22393   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22394   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22395   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22396   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22397   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22398   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22399   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22400   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22401   case X86ISD::FXOR:
22402   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22403   case X86ISD::FMIN:
22404   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22405   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22406   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22407   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22408   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22409   case ISD::ANY_EXTEND:
22410   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22411   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22412   case ISD::SIGN_EXTEND_INREG:
22413     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22414   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22415   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22416   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22417   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22418   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22419   case X86ISD::SHUFP:       // Handle all target specific shuffles
22420   case X86ISD::PALIGNR:
22421   case X86ISD::UNPCKH:
22422   case X86ISD::UNPCKL:
22423   case X86ISD::MOVHLPS:
22424   case X86ISD::MOVLHPS:
22425   case X86ISD::PSHUFD:
22426   case X86ISD::PSHUFHW:
22427   case X86ISD::PSHUFLW:
22428   case X86ISD::MOVSS:
22429   case X86ISD::MOVSD:
22430   case X86ISD::VPERMILP:
22431   case X86ISD::VPERM2X128:
22432   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22433   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22434   case ISD::INTRINSIC_WO_CHAIN:
22435     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22436   case X86ISD::INSERTPS:
22437     return PerformINSERTPSCombine(N, DAG, Subtarget);
22438   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22439   }
22440
22441   return SDValue();
22442 }
22443
22444 /// isTypeDesirableForOp - Return true if the target has native support for
22445 /// the specified value type and it is 'desirable' to use the type for the
22446 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22447 /// instruction encodings are longer and some i16 instructions are slow.
22448 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22449   if (!isTypeLegal(VT))
22450     return false;
22451   if (VT != MVT::i16)
22452     return true;
22453
22454   switch (Opc) {
22455   default:
22456     return true;
22457   case ISD::LOAD:
22458   case ISD::SIGN_EXTEND:
22459   case ISD::ZERO_EXTEND:
22460   case ISD::ANY_EXTEND:
22461   case ISD::SHL:
22462   case ISD::SRL:
22463   case ISD::SUB:
22464   case ISD::ADD:
22465   case ISD::MUL:
22466   case ISD::AND:
22467   case ISD::OR:
22468   case ISD::XOR:
22469     return false;
22470   }
22471 }
22472
22473 /// IsDesirableToPromoteOp - This method query the target whether it is
22474 /// beneficial for dag combiner to promote the specified node. If true, it
22475 /// should return the desired promotion type by reference.
22476 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22477   EVT VT = Op.getValueType();
22478   if (VT != MVT::i16)
22479     return false;
22480
22481   bool Promote = false;
22482   bool Commute = false;
22483   switch (Op.getOpcode()) {
22484   default: break;
22485   case ISD::LOAD: {
22486     LoadSDNode *LD = cast<LoadSDNode>(Op);
22487     // If the non-extending load has a single use and it's not live out, then it
22488     // might be folded.
22489     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22490                                                      Op.hasOneUse()*/) {
22491       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22492              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22493         // The only case where we'd want to promote LOAD (rather then it being
22494         // promoted as an operand is when it's only use is liveout.
22495         if (UI->getOpcode() != ISD::CopyToReg)
22496           return false;
22497       }
22498     }
22499     Promote = true;
22500     break;
22501   }
22502   case ISD::SIGN_EXTEND:
22503   case ISD::ZERO_EXTEND:
22504   case ISD::ANY_EXTEND:
22505     Promote = true;
22506     break;
22507   case ISD::SHL:
22508   case ISD::SRL: {
22509     SDValue N0 = Op.getOperand(0);
22510     // Look out for (store (shl (load), x)).
22511     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22512       return false;
22513     Promote = true;
22514     break;
22515   }
22516   case ISD::ADD:
22517   case ISD::MUL:
22518   case ISD::AND:
22519   case ISD::OR:
22520   case ISD::XOR:
22521     Commute = true;
22522     // fallthrough
22523   case ISD::SUB: {
22524     SDValue N0 = Op.getOperand(0);
22525     SDValue N1 = Op.getOperand(1);
22526     if (!Commute && MayFoldLoad(N1))
22527       return false;
22528     // Avoid disabling potential load folding opportunities.
22529     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22530       return false;
22531     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22532       return false;
22533     Promote = true;
22534   }
22535   }
22536
22537   PVT = MVT::i32;
22538   return Promote;
22539 }
22540
22541 //===----------------------------------------------------------------------===//
22542 //                           X86 Inline Assembly Support
22543 //===----------------------------------------------------------------------===//
22544
22545 namespace {
22546   // Helper to match a string separated by whitespace.
22547   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22548     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22549
22550     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22551       StringRef piece(*args[i]);
22552       if (!s.startswith(piece)) // Check if the piece matches.
22553         return false;
22554
22555       s = s.substr(piece.size());
22556       StringRef::size_type pos = s.find_first_not_of(" \t");
22557       if (pos == 0) // We matched a prefix.
22558         return false;
22559
22560       s = s.substr(pos);
22561     }
22562
22563     return s.empty();
22564   }
22565   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22566 }
22567
22568 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22569
22570   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22571     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22572         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22573         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22574
22575       if (AsmPieces.size() == 3)
22576         return true;
22577       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22578         return true;
22579     }
22580   }
22581   return false;
22582 }
22583
22584 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22585   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22586
22587   std::string AsmStr = IA->getAsmString();
22588
22589   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22590   if (!Ty || Ty->getBitWidth() % 16 != 0)
22591     return false;
22592
22593   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22594   SmallVector<StringRef, 4> AsmPieces;
22595   SplitString(AsmStr, AsmPieces, ";\n");
22596
22597   switch (AsmPieces.size()) {
22598   default: return false;
22599   case 1:
22600     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22601     // we will turn this bswap into something that will be lowered to logical
22602     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22603     // lower so don't worry about this.
22604     // bswap $0
22605     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22606         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22607         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22608         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22609         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22610         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22611       // No need to check constraints, nothing other than the equivalent of
22612       // "=r,0" would be valid here.
22613       return IntrinsicLowering::LowerToByteSwap(CI);
22614     }
22615
22616     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22617     if (CI->getType()->isIntegerTy(16) &&
22618         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22619         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22620          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22621       AsmPieces.clear();
22622       const std::string &ConstraintsStr = IA->getConstraintString();
22623       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22624       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22625       if (clobbersFlagRegisters(AsmPieces))
22626         return IntrinsicLowering::LowerToByteSwap(CI);
22627     }
22628     break;
22629   case 3:
22630     if (CI->getType()->isIntegerTy(32) &&
22631         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22632         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22633         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22634         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22635       AsmPieces.clear();
22636       const std::string &ConstraintsStr = IA->getConstraintString();
22637       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22638       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22639       if (clobbersFlagRegisters(AsmPieces))
22640         return IntrinsicLowering::LowerToByteSwap(CI);
22641     }
22642
22643     if (CI->getType()->isIntegerTy(64)) {
22644       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22645       if (Constraints.size() >= 2 &&
22646           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22647           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22648         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22649         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22650             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22651             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22652           return IntrinsicLowering::LowerToByteSwap(CI);
22653       }
22654     }
22655     break;
22656   }
22657   return false;
22658 }
22659
22660 /// getConstraintType - Given a constraint letter, return the type of
22661 /// constraint it is for this target.
22662 X86TargetLowering::ConstraintType
22663 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22664   if (Constraint.size() == 1) {
22665     switch (Constraint[0]) {
22666     case 'R':
22667     case 'q':
22668     case 'Q':
22669     case 'f':
22670     case 't':
22671     case 'u':
22672     case 'y':
22673     case 'x':
22674     case 'Y':
22675     case 'l':
22676       return C_RegisterClass;
22677     case 'a':
22678     case 'b':
22679     case 'c':
22680     case 'd':
22681     case 'S':
22682     case 'D':
22683     case 'A':
22684       return C_Register;
22685     case 'I':
22686     case 'J':
22687     case 'K':
22688     case 'L':
22689     case 'M':
22690     case 'N':
22691     case 'G':
22692     case 'C':
22693     case 'e':
22694     case 'Z':
22695       return C_Other;
22696     default:
22697       break;
22698     }
22699   }
22700   return TargetLowering::getConstraintType(Constraint);
22701 }
22702
22703 /// Examine constraint type and operand type and determine a weight value.
22704 /// This object must already have been set up with the operand type
22705 /// and the current alternative constraint selected.
22706 TargetLowering::ConstraintWeight
22707   X86TargetLowering::getSingleConstraintMatchWeight(
22708     AsmOperandInfo &info, const char *constraint) const {
22709   ConstraintWeight weight = CW_Invalid;
22710   Value *CallOperandVal = info.CallOperandVal;
22711     // If we don't have a value, we can't do a match,
22712     // but allow it at the lowest weight.
22713   if (!CallOperandVal)
22714     return CW_Default;
22715   Type *type = CallOperandVal->getType();
22716   // Look at the constraint type.
22717   switch (*constraint) {
22718   default:
22719     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22720   case 'R':
22721   case 'q':
22722   case 'Q':
22723   case 'a':
22724   case 'b':
22725   case 'c':
22726   case 'd':
22727   case 'S':
22728   case 'D':
22729   case 'A':
22730     if (CallOperandVal->getType()->isIntegerTy())
22731       weight = CW_SpecificReg;
22732     break;
22733   case 'f':
22734   case 't':
22735   case 'u':
22736     if (type->isFloatingPointTy())
22737       weight = CW_SpecificReg;
22738     break;
22739   case 'y':
22740     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22741       weight = CW_SpecificReg;
22742     break;
22743   case 'x':
22744   case 'Y':
22745     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22746         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22747       weight = CW_Register;
22748     break;
22749   case 'I':
22750     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22751       if (C->getZExtValue() <= 31)
22752         weight = CW_Constant;
22753     }
22754     break;
22755   case 'J':
22756     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22757       if (C->getZExtValue() <= 63)
22758         weight = CW_Constant;
22759     }
22760     break;
22761   case 'K':
22762     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22763       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22764         weight = CW_Constant;
22765     }
22766     break;
22767   case 'L':
22768     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22769       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22770         weight = CW_Constant;
22771     }
22772     break;
22773   case 'M':
22774     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22775       if (C->getZExtValue() <= 3)
22776         weight = CW_Constant;
22777     }
22778     break;
22779   case 'N':
22780     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22781       if (C->getZExtValue() <= 0xff)
22782         weight = CW_Constant;
22783     }
22784     break;
22785   case 'G':
22786   case 'C':
22787     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22788       weight = CW_Constant;
22789     }
22790     break;
22791   case 'e':
22792     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22793       if ((C->getSExtValue() >= -0x80000000LL) &&
22794           (C->getSExtValue() <= 0x7fffffffLL))
22795         weight = CW_Constant;
22796     }
22797     break;
22798   case 'Z':
22799     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22800       if (C->getZExtValue() <= 0xffffffff)
22801         weight = CW_Constant;
22802     }
22803     break;
22804   }
22805   return weight;
22806 }
22807
22808 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22809 /// with another that has more specific requirements based on the type of the
22810 /// corresponding operand.
22811 const char *X86TargetLowering::
22812 LowerXConstraint(EVT ConstraintVT) const {
22813   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22814   // 'f' like normal targets.
22815   if (ConstraintVT.isFloatingPoint()) {
22816     if (Subtarget->hasSSE2())
22817       return "Y";
22818     if (Subtarget->hasSSE1())
22819       return "x";
22820   }
22821
22822   return TargetLowering::LowerXConstraint(ConstraintVT);
22823 }
22824
22825 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22826 /// vector.  If it is invalid, don't add anything to Ops.
22827 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22828                                                      std::string &Constraint,
22829                                                      std::vector<SDValue>&Ops,
22830                                                      SelectionDAG &DAG) const {
22831   SDValue Result;
22832
22833   // Only support length 1 constraints for now.
22834   if (Constraint.length() > 1) return;
22835
22836   char ConstraintLetter = Constraint[0];
22837   switch (ConstraintLetter) {
22838   default: break;
22839   case 'I':
22840     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22841       if (C->getZExtValue() <= 31) {
22842         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22843         break;
22844       }
22845     }
22846     return;
22847   case 'J':
22848     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22849       if (C->getZExtValue() <= 63) {
22850         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22851         break;
22852       }
22853     }
22854     return;
22855   case 'K':
22856     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22857       if (isInt<8>(C->getSExtValue())) {
22858         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22859         break;
22860       }
22861     }
22862     return;
22863   case 'N':
22864     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22865       if (C->getZExtValue() <= 255) {
22866         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22867         break;
22868       }
22869     }
22870     return;
22871   case 'e': {
22872     // 32-bit signed value
22873     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22874       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22875                                            C->getSExtValue())) {
22876         // Widen to 64 bits here to get it sign extended.
22877         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22878         break;
22879       }
22880     // FIXME gcc accepts some relocatable values here too, but only in certain
22881     // memory models; it's complicated.
22882     }
22883     return;
22884   }
22885   case 'Z': {
22886     // 32-bit unsigned value
22887     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22888       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22889                                            C->getZExtValue())) {
22890         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22891         break;
22892       }
22893     }
22894     // FIXME gcc accepts some relocatable values here too, but only in certain
22895     // memory models; it's complicated.
22896     return;
22897   }
22898   case 'i': {
22899     // Literal immediates are always ok.
22900     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22901       // Widen to 64 bits here to get it sign extended.
22902       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22903       break;
22904     }
22905
22906     // In any sort of PIC mode addresses need to be computed at runtime by
22907     // adding in a register or some sort of table lookup.  These can't
22908     // be used as immediates.
22909     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22910       return;
22911
22912     // If we are in non-pic codegen mode, we allow the address of a global (with
22913     // an optional displacement) to be used with 'i'.
22914     GlobalAddressSDNode *GA = nullptr;
22915     int64_t Offset = 0;
22916
22917     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22918     while (1) {
22919       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22920         Offset += GA->getOffset();
22921         break;
22922       } else if (Op.getOpcode() == ISD::ADD) {
22923         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22924           Offset += C->getZExtValue();
22925           Op = Op.getOperand(0);
22926           continue;
22927         }
22928       } else if (Op.getOpcode() == ISD::SUB) {
22929         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22930           Offset += -C->getZExtValue();
22931           Op = Op.getOperand(0);
22932           continue;
22933         }
22934       }
22935
22936       // Otherwise, this isn't something we can handle, reject it.
22937       return;
22938     }
22939
22940     const GlobalValue *GV = GA->getGlobal();
22941     // If we require an extra load to get this address, as in PIC mode, we
22942     // can't accept it.
22943     if (isGlobalStubReference(
22944             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22945       return;
22946
22947     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22948                                         GA->getValueType(0), Offset);
22949     break;
22950   }
22951   }
22952
22953   if (Result.getNode()) {
22954     Ops.push_back(Result);
22955     return;
22956   }
22957   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22958 }
22959
22960 std::pair<unsigned, const TargetRegisterClass*>
22961 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22962                                                 MVT VT) const {
22963   // First, see if this is a constraint that directly corresponds to an LLVM
22964   // register class.
22965   if (Constraint.size() == 1) {
22966     // GCC Constraint Letters
22967     switch (Constraint[0]) {
22968     default: break;
22969       // TODO: Slight differences here in allocation order and leaving
22970       // RIP in the class. Do they matter any more here than they do
22971       // in the normal allocation?
22972     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22973       if (Subtarget->is64Bit()) {
22974         if (VT == MVT::i32 || VT == MVT::f32)
22975           return std::make_pair(0U, &X86::GR32RegClass);
22976         if (VT == MVT::i16)
22977           return std::make_pair(0U, &X86::GR16RegClass);
22978         if (VT == MVT::i8 || VT == MVT::i1)
22979           return std::make_pair(0U, &X86::GR8RegClass);
22980         if (VT == MVT::i64 || VT == MVT::f64)
22981           return std::make_pair(0U, &X86::GR64RegClass);
22982         break;
22983       }
22984       // 32-bit fallthrough
22985     case 'Q':   // Q_REGS
22986       if (VT == MVT::i32 || VT == MVT::f32)
22987         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22988       if (VT == MVT::i16)
22989         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22990       if (VT == MVT::i8 || VT == MVT::i1)
22991         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22992       if (VT == MVT::i64)
22993         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22994       break;
22995     case 'r':   // GENERAL_REGS
22996     case 'l':   // INDEX_REGS
22997       if (VT == MVT::i8 || VT == MVT::i1)
22998         return std::make_pair(0U, &X86::GR8RegClass);
22999       if (VT == MVT::i16)
23000         return std::make_pair(0U, &X86::GR16RegClass);
23001       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23002         return std::make_pair(0U, &X86::GR32RegClass);
23003       return std::make_pair(0U, &X86::GR64RegClass);
23004     case 'R':   // LEGACY_REGS
23005       if (VT == MVT::i8 || VT == MVT::i1)
23006         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23007       if (VT == MVT::i16)
23008         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23009       if (VT == MVT::i32 || !Subtarget->is64Bit())
23010         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23011       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23012     case 'f':  // FP Stack registers.
23013       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23014       // value to the correct fpstack register class.
23015       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23016         return std::make_pair(0U, &X86::RFP32RegClass);
23017       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23018         return std::make_pair(0U, &X86::RFP64RegClass);
23019       return std::make_pair(0U, &X86::RFP80RegClass);
23020     case 'y':   // MMX_REGS if MMX allowed.
23021       if (!Subtarget->hasMMX()) break;
23022       return std::make_pair(0U, &X86::VR64RegClass);
23023     case 'Y':   // SSE_REGS if SSE2 allowed
23024       if (!Subtarget->hasSSE2()) break;
23025       // FALL THROUGH.
23026     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23027       if (!Subtarget->hasSSE1()) break;
23028
23029       switch (VT.SimpleTy) {
23030       default: break;
23031       // Scalar SSE types.
23032       case MVT::f32:
23033       case MVT::i32:
23034         return std::make_pair(0U, &X86::FR32RegClass);
23035       case MVT::f64:
23036       case MVT::i64:
23037         return std::make_pair(0U, &X86::FR64RegClass);
23038       // Vector types.
23039       case MVT::v16i8:
23040       case MVT::v8i16:
23041       case MVT::v4i32:
23042       case MVT::v2i64:
23043       case MVT::v4f32:
23044       case MVT::v2f64:
23045         return std::make_pair(0U, &X86::VR128RegClass);
23046       // AVX types.
23047       case MVT::v32i8:
23048       case MVT::v16i16:
23049       case MVT::v8i32:
23050       case MVT::v4i64:
23051       case MVT::v8f32:
23052       case MVT::v4f64:
23053         return std::make_pair(0U, &X86::VR256RegClass);
23054       case MVT::v8f64:
23055       case MVT::v16f32:
23056       case MVT::v16i32:
23057       case MVT::v8i64:
23058         return std::make_pair(0U, &X86::VR512RegClass);
23059       }
23060       break;
23061     }
23062   }
23063
23064   // Use the default implementation in TargetLowering to convert the register
23065   // constraint into a member of a register class.
23066   std::pair<unsigned, const TargetRegisterClass*> Res;
23067   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23068
23069   // Not found as a standard register?
23070   if (!Res.second) {
23071     // Map st(0) -> st(7) -> ST0
23072     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23073         tolower(Constraint[1]) == 's' &&
23074         tolower(Constraint[2]) == 't' &&
23075         Constraint[3] == '(' &&
23076         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23077         Constraint[5] == ')' &&
23078         Constraint[6] == '}') {
23079
23080       Res.first = X86::ST0+Constraint[4]-'0';
23081       Res.second = &X86::RFP80RegClass;
23082       return Res;
23083     }
23084
23085     // GCC allows "st(0)" to be called just plain "st".
23086     if (StringRef("{st}").equals_lower(Constraint)) {
23087       Res.first = X86::ST0;
23088       Res.second = &X86::RFP80RegClass;
23089       return Res;
23090     }
23091
23092     // flags -> EFLAGS
23093     if (StringRef("{flags}").equals_lower(Constraint)) {
23094       Res.first = X86::EFLAGS;
23095       Res.second = &X86::CCRRegClass;
23096       return Res;
23097     }
23098
23099     // 'A' means EAX + EDX.
23100     if (Constraint == "A") {
23101       Res.first = X86::EAX;
23102       Res.second = &X86::GR32_ADRegClass;
23103       return Res;
23104     }
23105     return Res;
23106   }
23107
23108   // Otherwise, check to see if this is a register class of the wrong value
23109   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23110   // turn into {ax},{dx}.
23111   if (Res.second->hasType(VT))
23112     return Res;   // Correct type already, nothing to do.
23113
23114   // All of the single-register GCC register classes map their values onto
23115   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23116   // really want an 8-bit or 32-bit register, map to the appropriate register
23117   // class and return the appropriate register.
23118   if (Res.second == &X86::GR16RegClass) {
23119     if (VT == MVT::i8 || VT == MVT::i1) {
23120       unsigned DestReg = 0;
23121       switch (Res.first) {
23122       default: break;
23123       case X86::AX: DestReg = X86::AL; break;
23124       case X86::DX: DestReg = X86::DL; break;
23125       case X86::CX: DestReg = X86::CL; break;
23126       case X86::BX: DestReg = X86::BL; break;
23127       }
23128       if (DestReg) {
23129         Res.first = DestReg;
23130         Res.second = &X86::GR8RegClass;
23131       }
23132     } else if (VT == MVT::i32 || VT == MVT::f32) {
23133       unsigned DestReg = 0;
23134       switch (Res.first) {
23135       default: break;
23136       case X86::AX: DestReg = X86::EAX; break;
23137       case X86::DX: DestReg = X86::EDX; break;
23138       case X86::CX: DestReg = X86::ECX; break;
23139       case X86::BX: DestReg = X86::EBX; break;
23140       case X86::SI: DestReg = X86::ESI; break;
23141       case X86::DI: DestReg = X86::EDI; break;
23142       case X86::BP: DestReg = X86::EBP; break;
23143       case X86::SP: DestReg = X86::ESP; break;
23144       }
23145       if (DestReg) {
23146         Res.first = DestReg;
23147         Res.second = &X86::GR32RegClass;
23148       }
23149     } else if (VT == MVT::i64 || VT == MVT::f64) {
23150       unsigned DestReg = 0;
23151       switch (Res.first) {
23152       default: break;
23153       case X86::AX: DestReg = X86::RAX; break;
23154       case X86::DX: DestReg = X86::RDX; break;
23155       case X86::CX: DestReg = X86::RCX; break;
23156       case X86::BX: DestReg = X86::RBX; break;
23157       case X86::SI: DestReg = X86::RSI; break;
23158       case X86::DI: DestReg = X86::RDI; break;
23159       case X86::BP: DestReg = X86::RBP; break;
23160       case X86::SP: DestReg = X86::RSP; break;
23161       }
23162       if (DestReg) {
23163         Res.first = DestReg;
23164         Res.second = &X86::GR64RegClass;
23165       }
23166     }
23167   } else if (Res.second == &X86::FR32RegClass ||
23168              Res.second == &X86::FR64RegClass ||
23169              Res.second == &X86::VR128RegClass ||
23170              Res.second == &X86::VR256RegClass ||
23171              Res.second == &X86::FR32XRegClass ||
23172              Res.second == &X86::FR64XRegClass ||
23173              Res.second == &X86::VR128XRegClass ||
23174              Res.second == &X86::VR256XRegClass ||
23175              Res.second == &X86::VR512RegClass) {
23176     // Handle references to XMM physical registers that got mapped into the
23177     // wrong class.  This can happen with constraints like {xmm0} where the
23178     // target independent register mapper will just pick the first match it can
23179     // find, ignoring the required type.
23180
23181     if (VT == MVT::f32 || VT == MVT::i32)
23182       Res.second = &X86::FR32RegClass;
23183     else if (VT == MVT::f64 || VT == MVT::i64)
23184       Res.second = &X86::FR64RegClass;
23185     else if (X86::VR128RegClass.hasType(VT))
23186       Res.second = &X86::VR128RegClass;
23187     else if (X86::VR256RegClass.hasType(VT))
23188       Res.second = &X86::VR256RegClass;
23189     else if (X86::VR512RegClass.hasType(VT))
23190       Res.second = &X86::VR512RegClass;
23191   }
23192
23193   return Res;
23194 }
23195
23196 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23197                                             Type *Ty) const {
23198   // Scaling factors are not free at all.
23199   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23200   // will take 2 allocations in the out of order engine instead of 1
23201   // for plain addressing mode, i.e. inst (reg1).
23202   // E.g.,
23203   // vaddps (%rsi,%drx), %ymm0, %ymm1
23204   // Requires two allocations (one for the load, one for the computation)
23205   // whereas:
23206   // vaddps (%rsi), %ymm0, %ymm1
23207   // Requires just 1 allocation, i.e., freeing allocations for other operations
23208   // and having less micro operations to execute.
23209   //
23210   // For some X86 architectures, this is even worse because for instance for
23211   // stores, the complex addressing mode forces the instruction to use the
23212   // "load" ports instead of the dedicated "store" port.
23213   // E.g., on Haswell:
23214   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23215   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23216   if (isLegalAddressingMode(AM, Ty))
23217     // Scale represents reg2 * scale, thus account for 1
23218     // as soon as we use a second register.
23219     return AM.Scale != 0;
23220   return -1;
23221 }
23222
23223 bool X86TargetLowering::isTargetFTOL() const {
23224   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23225 }