musttail: Forward regparms of variadic functions on x86_64
[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 "X86IntrinsicsInfo.h"
53 #include <bitset>
54 #include <numeric>
55 #include <cctype>
56 using namespace llvm;
57
58 #define DEBUG_TYPE "x86-isel"
59
60 STATISTIC(NumTailCalls, "Number of tail calls");
61
62 static cl::opt<bool> ExperimentalVectorWideningLegalization(
63     "x86-experimental-vector-widening-legalization", cl::init(false),
64     cl::desc("Enable an experimental vector type legalization through widening "
65              "rather than promotion."),
66     cl::Hidden);
67
68 static cl::opt<bool> ExperimentalVectorShuffleLowering(
69     "x86-experimental-vector-shuffle-lowering", cl::init(false),
70     cl::desc("Enable an experimental vector shuffle lowering code path."),
71     cl::Hidden);
72
73 // Forward declarations.
74 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
75                        SDValue V2);
76
77 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
78                                 SelectionDAG &DAG, SDLoc dl,
79                                 unsigned vectorWidth) {
80   assert((vectorWidth == 128 || vectorWidth == 256) &&
81          "Unsupported vector width");
82   EVT VT = Vec.getValueType();
83   EVT ElVT = VT.getVectorElementType();
84   unsigned Factor = VT.getSizeInBits()/vectorWidth;
85   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
86                                   VT.getVectorNumElements()/Factor);
87
88   // Extract from UNDEF is UNDEF.
89   if (Vec.getOpcode() == ISD::UNDEF)
90     return DAG.getUNDEF(ResultVT);
91
92   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
93   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94
95   // This is the index of the first element of the vectorWidth-bit chunk
96   // we want.
97   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
98                                * ElemsPerChunk);
99
100   // If the input is a buildvector just emit a smaller one.
101   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
102     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
103                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
104                                     ElemsPerChunk));
105
106   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
107   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                VecIdx);
109
110   return Result;
111
112 }
113 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
114 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
115 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
116 /// instructions or a simple subregister reference. Idx is an index in the
117 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
118 /// lowering EXTRACT_VECTOR_ELT operations easier.
119 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
120                                    SelectionDAG &DAG, SDLoc dl) {
121   assert((Vec.getValueType().is256BitVector() ||
122           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
124 }
125
126 /// Generate a DAG to grab 256-bits from a 512-bit vector.
127 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
128                                    SelectionDAG &DAG, SDLoc dl) {
129   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
131 }
132
133 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
134                                unsigned IdxVal, SelectionDAG &DAG,
135                                SDLoc dl, unsigned vectorWidth) {
136   assert((vectorWidth == 128 || vectorWidth == 256) &&
137          "Unsupported vector width");
138   // Inserting UNDEF is Result
139   if (Vec.getOpcode() == ISD::UNDEF)
140     return Result;
141   EVT VT = Vec.getValueType();
142   EVT ElVT = VT.getVectorElementType();
143   EVT ResultVT = Result.getValueType();
144
145   // Insert the relevant vectorWidth bits.
146   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147
148   // This is the index of the first element of the vectorWidth-bit chunk
149   // we want.
150   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
151                                * ElemsPerChunk);
152
153   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
154   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                      VecIdx);
156 }
157 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
158 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
159 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
160 /// simple superregister reference.  Idx is an index in the 128 bits
161 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
162 /// lowering INSERT_VECTOR_ELT operations easier.
163 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
164                                   unsigned IdxVal, SelectionDAG &DAG,
165                                   SDLoc dl) {
166   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
167   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
168 }
169
170 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
171                                   unsigned IdxVal, SelectionDAG &DAG,
172                                   SDLoc dl) {
173   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
174   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
175 }
176
177 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
178 /// instructions. This is used because creating CONCAT_VECTOR nodes of
179 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
180 /// large BUILD_VECTORS.
181 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
182                                    unsigned NumElems, SelectionDAG &DAG,
183                                    SDLoc dl) {
184   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
186 }
187
188 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
189                                    unsigned NumElems, SelectionDAG &DAG,
190                                    SDLoc dl) {
191   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
193 }
194
195 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
196   if (TT.isOSBinFormatMachO()) {
197     if (TT.getArch() == Triple::x86_64)
198       return new X86_64MachoTargetObjectFile();
199     return new TargetLoweringObjectFileMachO();
200   }
201
202   if (TT.isOSLinux())
203     return new X86LinuxTargetObjectFile();
204   if (TT.isOSBinFormatELF())
205     return new TargetLoweringObjectFileELF();
206   if (TT.isKnownWindowsMSVCEnvironment())
207     return new X86WindowsTargetObjectFile();
208   if (TT.isOSBinFormatCOFF())
209     return new TargetLoweringObjectFileCOFF();
210   llvm_unreachable("unknown subtarget type");
211 }
212
213 // FIXME: This should stop caching the target machine as soon as
214 // we can remove resetOperationActions et al.
215 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
216   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
217   Subtarget = &TM.getSubtarget<X86Subtarget>();
218   X86ScalarSSEf64 = Subtarget->hasSSE2();
219   X86ScalarSSEf32 = Subtarget->hasSSE1();
220   TD = getDataLayout();
221
222   resetOperationActions();
223 }
224
225 void X86TargetLowering::resetOperationActions() {
226   const TargetMachine &TM = getTargetMachine();
227   static bool FirstTimeThrough = true;
228
229   // If none of the target options have changed, then we don't need to reset the
230   // operation actions.
231   if (!FirstTimeThrough && TO == TM.Options) return;
232
233   if (!FirstTimeThrough) {
234     // Reinitialize the actions.
235     initActions();
236     FirstTimeThrough = false;
237   }
238
239   TO = TM.Options;
240
241   // Set up the TargetLowering object.
242   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243
244   // X86 is weird, it always uses i8 for shift amounts and setcc results.
245   setBooleanContents(ZeroOrOneBooleanContent);
246   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
247   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248
249   // For 64-bit since we have so many registers use the ILP scheduler, for
250   // 32-bit code use the register pressure specific scheduling.
251   // For Atom, always use ILP scheduling.
252   if (Subtarget->isAtom())
253     setSchedulingPreference(Sched::ILP);
254   else if (Subtarget->is64Bit())
255     setSchedulingPreference(Sched::ILP);
256   else
257     setSchedulingPreference(Sched::RegPressure);
258   const X86RegisterInfo *RegInfo =
259       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
260   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261
262   // Bypass expensive divides on Atom when compiling with O2
263   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
264     addBypassSlowDiv(32, 8);
265     if (Subtarget->is64Bit())
266       addBypassSlowDiv(64, 16);
267   }
268
269   if (Subtarget->isTargetKnownWindowsMSVC()) {
270     // Setup Windows compiler runtime calls.
271     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
272     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
273     setLibcallName(RTLIB::SREM_I64, "_allrem");
274     setLibcallName(RTLIB::UREM_I64, "_aullrem");
275     setLibcallName(RTLIB::MUL_I64, "_allmul");
276     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
280     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281
282     // The _ftol2 runtime function has an unusual calling conv, which
283     // is modeled by a special pseudo-instruction.
284     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
287     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
288   }
289
290   if (Subtarget->isTargetDarwin()) {
291     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
292     setUseUnderscoreSetJmp(false);
293     setUseUnderscoreLongJmp(false);
294   } else if (Subtarget->isTargetWindowsGNU()) {
295     // MS runtime is weird: it exports _setjmp, but longjmp!
296     setUseUnderscoreSetJmp(true);
297     setUseUnderscoreLongJmp(false);
298   } else {
299     setUseUnderscoreSetJmp(true);
300     setUseUnderscoreLongJmp(true);
301   }
302
303   // Set up the register classes.
304   addRegisterClass(MVT::i8, &X86::GR8RegClass);
305   addRegisterClass(MVT::i16, &X86::GR16RegClass);
306   addRegisterClass(MVT::i32, &X86::GR32RegClass);
307   if (Subtarget->is64Bit())
308     addRegisterClass(MVT::i64, &X86::GR64RegClass);
309
310   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311
312   // We don't accept any truncstore of integer registers.
313   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
315   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
316   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
317   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
318   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
319
320   // SETOEQ and SETUNE require checking two conditions.
321   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
323   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
326   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327
328   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329   // operation.
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
332   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
333
334   if (Subtarget->is64Bit()) {
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
336     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
337   } else if (!TM.Options.UseSoftFloat) {
338     // We have an algorithm for SSE2->double, and we turn this into a
339     // 64-bit FILD followed by conditional FADD for other targets.
340     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
341     // We have an algorithm for SSE2, and we turn this into a 64-bit
342     // FILD for other targets.
343     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
344   }
345
346   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347   // this operation.
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
349   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
350
351   if (!TM.Options.UseSoftFloat) {
352     // SSE has no i16 to fp conversion, only i32
353     if (X86ScalarSSEf32) {
354       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
355       // f32 and f64 cases are Legal, f80 case is not
356       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
357     } else {
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
359       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
360     }
361   } else {
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
363     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
364   }
365
366   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
367   // are Legal, f80 is custom lowered.
368   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
369   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
370
371   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372   // this operation.
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
374   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
375
376   if (X86ScalarSSEf32) {
377     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
378     // f32 and f64 cases are Legal, f80 case is not
379     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
380   } else {
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
382     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
383   }
384
385   // Handle FP_TO_UINT by promoting the destination to a larger signed
386   // conversion.
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
389   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
390
391   if (Subtarget->is64Bit()) {
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
393     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
394   } else if (!TM.Options.UseSoftFloat) {
395     // Since AVX is a superset of SSE3, only check for SSE here.
396     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
397       // Expand FP_TO_UINT into a select.
398       // FIXME: We would like to use a Custom expander here eventually to do
399       // the optimal thing for SSE vs. the default expansion in the legalizer.
400       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
401     else
402       // With SSE3 we can use fisttpll to convert to a signed i64; without
403       // SSE, we're stuck with a fistpll.
404       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
405   }
406
407   if (isTargetFTOL()) {
408     // Use the _ftol2 runtime function, which has a pseudo-instruction
409     // to handle its weird calling convention.
410     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
411   }
412
413   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
414   if (!X86ScalarSSEf64) {
415     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
416     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
417     if (Subtarget->is64Bit()) {
418       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
419       // Without SSE, i64->f64 goes through memory.
420       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
421     }
422   }
423
424   // Scalar integer divide and remainder are lowered to use operations that
425   // produce two results, to match the available instructions. This exposes
426   // the two-result form to trivial CSE, which is able to combine x/y and x%y
427   // into a single instruction.
428   //
429   // Scalar integer multiply-high is also lowered to use two-result
430   // operations, to match the available instructions. However, plain multiply
431   // (low) operations are left as Legal, as there are single-result
432   // instructions for this in x86. Using the two-result multiply instructions
433   // when both high and low results are needed must be arranged by dagcombine.
434   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435     MVT VT = IntVTs[i];
436     setOperationAction(ISD::MULHS, VT, Expand);
437     setOperationAction(ISD::MULHU, VT, Expand);
438     setOperationAction(ISD::SDIV, VT, Expand);
439     setOperationAction(ISD::UDIV, VT, Expand);
440     setOperationAction(ISD::SREM, VT, Expand);
441     setOperationAction(ISD::UREM, VT, Expand);
442
443     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
444     setOperationAction(ISD::ADDC, VT, Custom);
445     setOperationAction(ISD::ADDE, VT, Custom);
446     setOperationAction(ISD::SUBC, VT, Custom);
447     setOperationAction(ISD::SUBE, VT, Custom);
448   }
449
450   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
451   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
452   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
458   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
465   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
466   if (Subtarget->is64Bit())
467     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
470   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
471   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
474   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
475   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
476
477   // Promote the i8 variants and force them on up to i32 which has a shorter
478   // encoding.
479   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
480   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
481   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
482   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
483   if (Subtarget->hasBMI()) {
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
485     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
486     if (Subtarget->is64Bit())
487       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488   } else {
489     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
490     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
491     if (Subtarget->is64Bit())
492       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
493   }
494
495   if (Subtarget->hasLZCNT()) {
496     // When promoting the i8 variants, force them to i32 for a shorter
497     // encoding.
498     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
499     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
500     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
501     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506   } else {
507     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
509     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
512     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
513     if (Subtarget->is64Bit()) {
514       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
515       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
516     }
517   }
518
519   // Special handling for half-precision floating point conversions.
520   // If we don't have F16C support, then lower half float conversions
521   // into library calls.
522   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
523     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
524     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
525   }
526
527   // There's never any support for operations beyond MVT::f32.
528   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
529   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
531   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532
533   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
536   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537
538   if (Subtarget->hasPOPCNT()) {
539     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
540   } else {
541     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
543     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
544     if (Subtarget->is64Bit())
545       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
546   }
547
548   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
549
550   if (!Subtarget->hasMOVBE())
551     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
552
553   // These should be promoted to a larger select which is supported.
554   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
555   // X86 wants to expand cmov itself.
556   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
561   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
567   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
568   if (Subtarget->is64Bit()) {
569     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
570     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
571   }
572   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
573   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
574   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
575   // support continuation, user-level threading, and etc.. As a result, no
576   // other SjLj exception interfaces are implemented and please don't build
577   // your own exception handling based on them.
578   // LLVM/Clang supports zero-cost DWARF exception handling.
579   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
580   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
581
582   // Darwin ABI issue.
583   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
584   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
586   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
587   if (Subtarget->is64Bit())
588     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
589   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
590   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
591   if (Subtarget->is64Bit()) {
592     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
593     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
594     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
595     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
596     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
597   }
598   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
599   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
601   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
602   if (Subtarget->is64Bit()) {
603     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
605     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
606   }
607
608   if (Subtarget->hasSSE1())
609     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
610
611   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
612
613   // Expand certain atomics
614   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615     MVT VT = IntVTs[i];
616     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
617     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
618     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
619   }
620
621   if (Subtarget->hasCmpxchg16b()) {
622     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
623   }
624
625   // FIXME - use subtarget debug flags
626   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
627       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
628     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
629   }
630
631   if (Subtarget->is64Bit()) {
632     setExceptionPointerRegister(X86::RAX);
633     setExceptionSelectorRegister(X86::RDX);
634   } else {
635     setExceptionPointerRegister(X86::EAX);
636     setExceptionSelectorRegister(X86::EDX);
637   }
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
639   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640
641   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
642   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643
644   setOperationAction(ISD::TRAP, MVT::Other, Legal);
645   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646
647   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
648   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
649   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
650   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
651     // TargetInfo::X86_64ABIBuiltinVaList
652     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
653     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
654   } else {
655     // TargetInfo::CharPtrBuiltinVaList
656     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
657     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
658   }
659
660   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
661   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
662
663   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), 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 mean 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     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1022     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1027
1028     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1029     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1030     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1031     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1032     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1033     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1034
1035     if (Subtarget->is64Bit()) {
1036       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1037       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1038     }
1039
1040     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1041     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1042       MVT VT = (MVT::SimpleValueType)i;
1043
1044       // Do not attempt to promote non-128-bit vectors
1045       if (!VT.is128BitVector())
1046         continue;
1047
1048       setOperationAction(ISD::AND,    VT, Promote);
1049       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1050       setOperationAction(ISD::OR,     VT, Promote);
1051       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1052       setOperationAction(ISD::XOR,    VT, Promote);
1053       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1054       setOperationAction(ISD::LOAD,   VT, Promote);
1055       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1056       setOperationAction(ISD::SELECT, VT, Promote);
1057       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1058     }
1059
1060     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1061
1062     // Custom lower v2i64 and v2f64 selects.
1063     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1064     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1065     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1066     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1067
1068     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1069     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1070
1071     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1073     // As there is no 64-bit GPR available, we need build a special custom
1074     // sequence to convert from v2i32 to v2f32.
1075     if (!Subtarget->is64Bit())
1076       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1077
1078     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1079     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1080
1081     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1082
1083     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1084     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1086   }
1087
1088   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1089     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1090     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1091     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1094     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1095     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1096     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1099
1100     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1101     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1102     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1105     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1106     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1107     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1110
1111     // FIXME: Do we need to handle scalar-to-vector here?
1112     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1113
1114     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1115     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1119     // There is no BLENDI for byte vectors. We don't need to custom lower
1120     // some vselects for now.
1121     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1122
1123     // SSE41 brings specific instructions for doing vector sign extend even in
1124     // cases where we don't have SRA.
1125     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1128
1129     // i8 and i16 vectors are custom because the source register and source
1130     // source memory operand types are not the same width.  f32 vectors are
1131     // custom since the immediate controlling the insert encodes additional
1132     // information.
1133     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1137
1138     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1142
1143     // FIXME: these should be Legal, but that's only for the case where
1144     // the index is constant.  For now custom expand to deal with that.
1145     if (Subtarget->is64Bit()) {
1146       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1147       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1148     }
1149   }
1150
1151   if (Subtarget->hasSSE2()) {
1152     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1153     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1154
1155     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1156     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1157
1158     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1159     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1160
1161     // In the customized shift lowering, the legal cases in AVX2 will be
1162     // recognized.
1163     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1164     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1165
1166     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1167     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1168
1169     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1170   }
1171
1172   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1173     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1174     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1175     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1179
1180     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1181     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1183
1184     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1185     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1189     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1190     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1195     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1196
1197     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1198     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1202     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1203     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1208     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1209
1210     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1211     // even though v8i16 is a legal type.
1212     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1213     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1215
1216     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1218     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1219
1220     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1222
1223     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1224
1225     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1226     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1227
1228     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1229     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1230
1231     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1232     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1233
1234     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1235     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1238
1239     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1240     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1242
1243     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1244     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1247
1248     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1251     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1254     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1257     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1260
1261     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1262       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1263       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1268     }
1269
1270     if (Subtarget->hasInt256()) {
1271       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1272       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1275
1276       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1277       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1280
1281       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1282       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1283       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1284       // Don't lower v32i8 because there is no 128-bit byte mul
1285
1286       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1287       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1289       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1290
1291       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1292       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1293     } else {
1294       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1295       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1298
1299       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1300       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1303
1304       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1305       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1307       // Don't lower v32i8 because there is no 128-bit byte mul
1308     }
1309
1310     // In the customized shift lowering, the legal cases in AVX2 will be
1311     // recognized.
1312     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1313     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1314
1315     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1316     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1317
1318     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1319
1320     // Custom lower several nodes for 256-bit types.
1321     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1322              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1323       MVT VT = (MVT::SimpleValueType)i;
1324
1325       // Extract subvector is special because the value type
1326       // (result) is 128-bit but the source is 256-bit wide.
1327       if (VT.is128BitVector())
1328         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1329
1330       // Do not attempt to custom lower other non-256-bit vectors
1331       if (!VT.is256BitVector())
1332         continue;
1333
1334       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1335       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1336       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1337       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1338       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1339       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1340       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1341     }
1342
1343     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1344     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1345       MVT VT = (MVT::SimpleValueType)i;
1346
1347       // Do not attempt to promote non-256-bit vectors
1348       if (!VT.is256BitVector())
1349         continue;
1350
1351       setOperationAction(ISD::AND,    VT, Promote);
1352       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1353       setOperationAction(ISD::OR,     VT, Promote);
1354       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1355       setOperationAction(ISD::XOR,    VT, Promote);
1356       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1357       setOperationAction(ISD::LOAD,   VT, Promote);
1358       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1359       setOperationAction(ISD::SELECT, VT, Promote);
1360       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1361     }
1362   }
1363
1364   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1365     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1366     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1369
1370     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1371     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1372     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1373
1374     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1375     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1376     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1377     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1378     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1379     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1385
1386     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1387     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1391     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1392
1393     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1394     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1398     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1399     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1400     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1401
1402     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1403     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1405     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1406     if (Subtarget->is64Bit()) {
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1408       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1411     }
1412     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1413     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1416     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1417     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1420     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1421     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1422
1423     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1424     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1429     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1431     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1436
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1443
1444     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1445     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1446
1447     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1448
1449     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1451     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1455     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1458
1459     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1461
1462     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1463     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1464
1465     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1468     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1469
1470     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1474     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1475
1476     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1482
1483     if (Subtarget->hasCDI()) {
1484       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1485       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1486     }
1487
1488     // Custom lower several nodes.
1489     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1490              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1491       MVT VT = (MVT::SimpleValueType)i;
1492
1493       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1494       // Extract subvector is special because the value type
1495       // (result) is 256/128-bit but the source is 512-bit wide.
1496       if (VT.is128BitVector() || VT.is256BitVector())
1497         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1498
1499       if (VT.getVectorElementType() == MVT::i1)
1500         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1501
1502       // Do not attempt to custom lower other non-512-bit vectors
1503       if (!VT.is512BitVector())
1504         continue;
1505
1506       if ( EltSize >= 32) {
1507         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1508         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1509         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1510         setOperationAction(ISD::VSELECT,             VT, Legal);
1511         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1512         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1513         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1514       }
1515     }
1516     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517       MVT VT = (MVT::SimpleValueType)i;
1518
1519       // Do not attempt to promote non-256-bit vectors
1520       if (!VT.is512BitVector())
1521         continue;
1522
1523       setOperationAction(ISD::SELECT, VT, Promote);
1524       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1525     }
1526   }// has  AVX-512
1527
1528   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1531
1532     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1533     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1534
1535     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1536     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1537     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1538     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1539
1540     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1541       const MVT VT = (MVT::SimpleValueType)i;
1542
1543       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1544
1545       // Do not attempt to promote non-256-bit vectors
1546       if (!VT.is512BitVector())
1547         continue;
1548
1549       if ( EltSize < 32) {
1550         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1551         setOperationAction(ISD::VSELECT,             VT, Legal);
1552       }
1553     }
1554   }
1555
1556   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1557     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1558     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1559
1560     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1561     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1562   }
1563
1564   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1565   // of this type with custom code.
1566   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1567            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1568     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1569                        Custom);
1570   }
1571
1572   // We want to custom lower some of our intrinsics.
1573   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1574   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1575   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1576   if (!Subtarget->is64Bit())
1577     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1578
1579   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1580   // handle type legalization for these operations here.
1581   //
1582   // FIXME: We really should do custom legalization for addition and
1583   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1584   // than generic legalization for 64-bit multiplication-with-overflow, though.
1585   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1586     // Add/Sub/Mul with overflow operations are custom lowered.
1587     MVT VT = IntVTs[i];
1588     setOperationAction(ISD::SADDO, VT, Custom);
1589     setOperationAction(ISD::UADDO, VT, Custom);
1590     setOperationAction(ISD::SSUBO, VT, Custom);
1591     setOperationAction(ISD::USUBO, VT, Custom);
1592     setOperationAction(ISD::SMULO, VT, Custom);
1593     setOperationAction(ISD::UMULO, VT, Custom);
1594   }
1595
1596   // There are no 8-bit 3-address imul/mul instructions
1597   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1598   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1599
1600   if (!Subtarget->is64Bit()) {
1601     // These libcalls are not available in 32-bit.
1602     setLibcallName(RTLIB::SHL_I128, nullptr);
1603     setLibcallName(RTLIB::SRL_I128, nullptr);
1604     setLibcallName(RTLIB::SRA_I128, nullptr);
1605   }
1606
1607   // Combine sin / cos into one node or libcall if possible.
1608   if (Subtarget->hasSinCos()) {
1609     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1610     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1611     if (Subtarget->isTargetDarwin()) {
1612       // For MacOSX, we don't want to the normal expansion of a libcall to
1613       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1614       // traffic.
1615       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1616       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1617     }
1618   }
1619
1620   if (Subtarget->isTargetWin64()) {
1621     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1622     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1623     setOperationAction(ISD::SREM, MVT::i128, Custom);
1624     setOperationAction(ISD::UREM, MVT::i128, Custom);
1625     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1626     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1627   }
1628
1629   // We have target-specific dag combine patterns for the following nodes:
1630   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1631   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1632   setTargetDAGCombine(ISD::VSELECT);
1633   setTargetDAGCombine(ISD::SELECT);
1634   setTargetDAGCombine(ISD::SHL);
1635   setTargetDAGCombine(ISD::SRA);
1636   setTargetDAGCombine(ISD::SRL);
1637   setTargetDAGCombine(ISD::OR);
1638   setTargetDAGCombine(ISD::AND);
1639   setTargetDAGCombine(ISD::ADD);
1640   setTargetDAGCombine(ISD::FADD);
1641   setTargetDAGCombine(ISD::FSUB);
1642   setTargetDAGCombine(ISD::FMA);
1643   setTargetDAGCombine(ISD::SUB);
1644   setTargetDAGCombine(ISD::LOAD);
1645   setTargetDAGCombine(ISD::STORE);
1646   setTargetDAGCombine(ISD::ZERO_EXTEND);
1647   setTargetDAGCombine(ISD::ANY_EXTEND);
1648   setTargetDAGCombine(ISD::SIGN_EXTEND);
1649   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1650   setTargetDAGCombine(ISD::TRUNCATE);
1651   setTargetDAGCombine(ISD::SINT_TO_FP);
1652   setTargetDAGCombine(ISD::SETCC);
1653   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1654   setTargetDAGCombine(ISD::BUILD_VECTOR);
1655   if (Subtarget->is64Bit())
1656     setTargetDAGCombine(ISD::MUL);
1657   setTargetDAGCombine(ISD::XOR);
1658
1659   computeRegisterProperties();
1660
1661   // On Darwin, -Os means optimize for size without hurting performance,
1662   // do not reduce the limit.
1663   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1664   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1665   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1666   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1667   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1668   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1669   setPrefLoopAlignment(4); // 2^4 bytes.
1670
1671   // Predictable cmov don't hurt on atom because it's in-order.
1672   PredictableSelectIsExpensive = !Subtarget->isAtom();
1673
1674   setPrefFunctionAlignment(4); // 2^4 bytes.
1675
1676   InitIntrinsicTables();
1677 }
1678
1679 // This has so far only been implemented for 64-bit MachO.
1680 bool X86TargetLowering::useLoadStackGuardNode() const {
1681   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1682          Subtarget->is64Bit();
1683 }
1684
1685 TargetLoweringBase::LegalizeTypeAction
1686 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1687   if (ExperimentalVectorWideningLegalization &&
1688       VT.getVectorNumElements() != 1 &&
1689       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1690     return TypeWidenVector;
1691
1692   return TargetLoweringBase::getPreferredVectorAction(VT);
1693 }
1694
1695 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1696   if (!VT.isVector())
1697     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1698
1699   const unsigned NumElts = VT.getVectorNumElements();
1700   const EVT EltVT = VT.getVectorElementType();
1701   if (VT.is512BitVector()) {
1702     if (Subtarget->hasAVX512())
1703       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1704           EltVT == MVT::f32 || EltVT == MVT::f64)
1705         switch(NumElts) {
1706         case  8: return MVT::v8i1;
1707         case 16: return MVT::v16i1;
1708       }
1709     if (Subtarget->hasBWI())
1710       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1711         switch(NumElts) {
1712         case 32: return MVT::v32i1;
1713         case 64: return MVT::v64i1;
1714       }
1715   }
1716
1717   if (VT.is256BitVector() || VT.is128BitVector()) {
1718     if (Subtarget->hasVLX())
1719       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1720           EltVT == MVT::f32 || EltVT == MVT::f64)
1721         switch(NumElts) {
1722         case 2: return MVT::v2i1;
1723         case 4: return MVT::v4i1;
1724         case 8: return MVT::v8i1;
1725       }
1726     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1727       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1728         switch(NumElts) {
1729         case  8: return MVT::v8i1;
1730         case 16: return MVT::v16i1;
1731         case 32: return MVT::v32i1;
1732       }
1733   }
1734
1735   return VT.changeVectorElementTypeToInteger();
1736 }
1737
1738 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1739 /// the desired ByVal argument alignment.
1740 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1741   if (MaxAlign == 16)
1742     return;
1743   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1744     if (VTy->getBitWidth() == 128)
1745       MaxAlign = 16;
1746   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1747     unsigned EltAlign = 0;
1748     getMaxByValAlign(ATy->getElementType(), EltAlign);
1749     if (EltAlign > MaxAlign)
1750       MaxAlign = EltAlign;
1751   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1752     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1753       unsigned EltAlign = 0;
1754       getMaxByValAlign(STy->getElementType(i), EltAlign);
1755       if (EltAlign > MaxAlign)
1756         MaxAlign = EltAlign;
1757       if (MaxAlign == 16)
1758         break;
1759     }
1760   }
1761 }
1762
1763 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1764 /// function arguments in the caller parameter area. For X86, aggregates
1765 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1766 /// are at 4-byte boundaries.
1767 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1768   if (Subtarget->is64Bit()) {
1769     // Max of 8 and alignment of type.
1770     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1771     if (TyAlign > 8)
1772       return TyAlign;
1773     return 8;
1774   }
1775
1776   unsigned Align = 4;
1777   if (Subtarget->hasSSE1())
1778     getMaxByValAlign(Ty, Align);
1779   return Align;
1780 }
1781
1782 /// getOptimalMemOpType - Returns the target specific optimal type for load
1783 /// and store operations as a result of memset, memcpy, and memmove
1784 /// lowering. If DstAlign is zero that means it's safe to destination
1785 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1786 /// means there isn't a need to check it against alignment requirement,
1787 /// probably because the source does not need to be loaded. If 'IsMemset' is
1788 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1789 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1790 /// source is constant so it does not need to be loaded.
1791 /// It returns EVT::Other if the type should be determined using generic
1792 /// target-independent logic.
1793 EVT
1794 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1795                                        unsigned DstAlign, unsigned SrcAlign,
1796                                        bool IsMemset, bool ZeroMemset,
1797                                        bool MemcpyStrSrc,
1798                                        MachineFunction &MF) const {
1799   const Function *F = MF.getFunction();
1800   if ((!IsMemset || ZeroMemset) &&
1801       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1802                                        Attribute::NoImplicitFloat)) {
1803     if (Size >= 16 &&
1804         (Subtarget->isUnalignedMemAccessFast() ||
1805          ((DstAlign == 0 || DstAlign >= 16) &&
1806           (SrcAlign == 0 || SrcAlign >= 16)))) {
1807       if (Size >= 32) {
1808         if (Subtarget->hasInt256())
1809           return MVT::v8i32;
1810         if (Subtarget->hasFp256())
1811           return MVT::v8f32;
1812       }
1813       if (Subtarget->hasSSE2())
1814         return MVT::v4i32;
1815       if (Subtarget->hasSSE1())
1816         return MVT::v4f32;
1817     } else if (!MemcpyStrSrc && Size >= 8 &&
1818                !Subtarget->is64Bit() &&
1819                Subtarget->hasSSE2()) {
1820       // Do not use f64 to lower memcpy if source is string constant. It's
1821       // better to use i32 to avoid the loads.
1822       return MVT::f64;
1823     }
1824   }
1825   if (Subtarget->is64Bit() && Size >= 8)
1826     return MVT::i64;
1827   return MVT::i32;
1828 }
1829
1830 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1831   if (VT == MVT::f32)
1832     return X86ScalarSSEf32;
1833   else if (VT == MVT::f64)
1834     return X86ScalarSSEf64;
1835   return true;
1836 }
1837
1838 bool
1839 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1840                                                   unsigned,
1841                                                   unsigned,
1842                                                   bool *Fast) const {
1843   if (Fast)
1844     *Fast = Subtarget->isUnalignedMemAccessFast();
1845   return true;
1846 }
1847
1848 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1849 /// current function.  The returned value is a member of the
1850 /// MachineJumpTableInfo::JTEntryKind enum.
1851 unsigned X86TargetLowering::getJumpTableEncoding() const {
1852   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1853   // symbol.
1854   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1855       Subtarget->isPICStyleGOT())
1856     return MachineJumpTableInfo::EK_Custom32;
1857
1858   // Otherwise, use the normal jump table encoding heuristics.
1859   return TargetLowering::getJumpTableEncoding();
1860 }
1861
1862 const MCExpr *
1863 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1864                                              const MachineBasicBlock *MBB,
1865                                              unsigned uid,MCContext &Ctx) const{
1866   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1867          Subtarget->isPICStyleGOT());
1868   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1869   // entries.
1870   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1871                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1872 }
1873
1874 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1875 /// jumptable.
1876 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1877                                                     SelectionDAG &DAG) const {
1878   if (!Subtarget->is64Bit())
1879     // This doesn't have SDLoc associated with it, but is not really the
1880     // same as a Register.
1881     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1882   return Table;
1883 }
1884
1885 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1886 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1887 /// MCExpr.
1888 const MCExpr *X86TargetLowering::
1889 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1890                              MCContext &Ctx) const {
1891   // X86-64 uses RIP relative addressing based on the jump table label.
1892   if (Subtarget->isPICStyleRIPRel())
1893     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1894
1895   // Otherwise, the reference is relative to the PIC base.
1896   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1897 }
1898
1899 // FIXME: Why this routine is here? Move to RegInfo!
1900 std::pair<const TargetRegisterClass*, uint8_t>
1901 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1902   const TargetRegisterClass *RRC = nullptr;
1903   uint8_t Cost = 1;
1904   switch (VT.SimpleTy) {
1905   default:
1906     return TargetLowering::findRepresentativeClass(VT);
1907   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1908     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1909     break;
1910   case MVT::x86mmx:
1911     RRC = &X86::VR64RegClass;
1912     break;
1913   case MVT::f32: case MVT::f64:
1914   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1915   case MVT::v4f32: case MVT::v2f64:
1916   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1917   case MVT::v4f64:
1918     RRC = &X86::VR128RegClass;
1919     break;
1920   }
1921   return std::make_pair(RRC, Cost);
1922 }
1923
1924 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1925                                                unsigned &Offset) const {
1926   if (!Subtarget->isTargetLinux())
1927     return false;
1928
1929   if (Subtarget->is64Bit()) {
1930     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1931     Offset = 0x28;
1932     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1933       AddressSpace = 256;
1934     else
1935       AddressSpace = 257;
1936   } else {
1937     // %gs:0x14 on i386
1938     Offset = 0x14;
1939     AddressSpace = 256;
1940   }
1941   return true;
1942 }
1943
1944 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1945                                             unsigned DestAS) const {
1946   assert(SrcAS != DestAS && "Expected different address spaces!");
1947
1948   return SrcAS < 256 && DestAS < 256;
1949 }
1950
1951 //===----------------------------------------------------------------------===//
1952 //               Return Value Calling Convention Implementation
1953 //===----------------------------------------------------------------------===//
1954
1955 #include "X86GenCallingConv.inc"
1956
1957 bool
1958 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1959                                   MachineFunction &MF, bool isVarArg,
1960                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1961                         LLVMContext &Context) const {
1962   SmallVector<CCValAssign, 16> RVLocs;
1963   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1964   return CCInfo.CheckReturn(Outs, RetCC_X86);
1965 }
1966
1967 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1968   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1969   return ScratchRegs;
1970 }
1971
1972 SDValue
1973 X86TargetLowering::LowerReturn(SDValue Chain,
1974                                CallingConv::ID CallConv, bool isVarArg,
1975                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                const SmallVectorImpl<SDValue> &OutVals,
1977                                SDLoc dl, SelectionDAG &DAG) const {
1978   MachineFunction &MF = DAG.getMachineFunction();
1979   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1980
1981   SmallVector<CCValAssign, 16> RVLocs;
1982   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1983   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1984
1985   SDValue Flag;
1986   SmallVector<SDValue, 6> RetOps;
1987   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1988   // Operand #1 = Bytes To Pop
1989   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1990                    MVT::i16));
1991
1992   // Copy the result values into the output registers.
1993   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1994     CCValAssign &VA = RVLocs[i];
1995     assert(VA.isRegLoc() && "Can only return in registers!");
1996     SDValue ValToCopy = OutVals[i];
1997     EVT ValVT = ValToCopy.getValueType();
1998
1999     // Promote values to the appropriate types
2000     if (VA.getLocInfo() == CCValAssign::SExt)
2001       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2002     else if (VA.getLocInfo() == CCValAssign::ZExt)
2003       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2004     else if (VA.getLocInfo() == CCValAssign::AExt)
2005       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2006     else if (VA.getLocInfo() == CCValAssign::BCvt)
2007       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2008
2009     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2010            "Unexpected FP-extend for return value.");  
2011
2012     // If this is x86-64, and we disabled SSE, we can't return FP values,
2013     // or SSE or MMX vectors.
2014     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2015          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2016           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2017       report_fatal_error("SSE register return with SSE disabled");
2018     }
2019     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2020     // llvm-gcc has never done it right and no one has noticed, so this
2021     // should be OK for now.
2022     if (ValVT == MVT::f64 &&
2023         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2024       report_fatal_error("SSE2 register return with SSE2 disabled");
2025
2026     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2027     // the RET instruction and handled by the FP Stackifier.
2028     if (VA.getLocReg() == X86::FP0 ||
2029         VA.getLocReg() == X86::FP1) {
2030       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2031       // change the value to the FP stack register class.
2032       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2033         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2034       RetOps.push_back(ValToCopy);
2035       // Don't emit a copytoreg.
2036       continue;
2037     }
2038
2039     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2040     // which is returned in RAX / RDX.
2041     if (Subtarget->is64Bit()) {
2042       if (ValVT == MVT::x86mmx) {
2043         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2044           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2045           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2046                                   ValToCopy);
2047           // If we don't have SSE2 available, convert to v4f32 so the generated
2048           // register is legal.
2049           if (!Subtarget->hasSSE2())
2050             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2051         }
2052       }
2053     }
2054
2055     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2056     Flag = Chain.getValue(1);
2057     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2058   }
2059
2060   // The x86-64 ABIs require that for returning structs by value we copy
2061   // the sret argument into %rax/%eax (depending on ABI) for the return.
2062   // Win32 requires us to put the sret argument to %eax as well.
2063   // We saved the argument into a virtual register in the entry block,
2064   // so now we copy the value out and into %rax/%eax.
2065   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2066       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2067     MachineFunction &MF = DAG.getMachineFunction();
2068     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2069     unsigned Reg = FuncInfo->getSRetReturnReg();
2070     assert(Reg &&
2071            "SRetReturnReg should have been set in LowerFormalArguments().");
2072     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2073
2074     unsigned RetValReg
2075         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2076           X86::RAX : X86::EAX;
2077     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2078     Flag = Chain.getValue(1);
2079
2080     // RAX/EAX now acts like a return value.
2081     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2082   }
2083
2084   RetOps[0] = Chain;  // Update chain.
2085
2086   // Add the flag if we have it.
2087   if (Flag.getNode())
2088     RetOps.push_back(Flag);
2089
2090   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2091 }
2092
2093 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2094   if (N->getNumValues() != 1)
2095     return false;
2096   if (!N->hasNUsesOfValue(1, 0))
2097     return false;
2098
2099   SDValue TCChain = Chain;
2100   SDNode *Copy = *N->use_begin();
2101   if (Copy->getOpcode() == ISD::CopyToReg) {
2102     // If the copy has a glue operand, we conservatively assume it isn't safe to
2103     // perform a tail call.
2104     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2105       return false;
2106     TCChain = Copy->getOperand(0);
2107   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2108     return false;
2109
2110   bool HasRet = false;
2111   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2112        UI != UE; ++UI) {
2113     if (UI->getOpcode() != X86ISD::RET_FLAG)
2114       return false;
2115     // If we are returning more than one value, we can definitely
2116     // not make a tail call see PR19530
2117     if (UI->getNumOperands() > 4)
2118       return false;
2119     if (UI->getNumOperands() == 4 &&
2120         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2121       return false;
2122     HasRet = true;
2123   }
2124
2125   if (!HasRet)
2126     return false;
2127
2128   Chain = TCChain;
2129   return true;
2130 }
2131
2132 EVT
2133 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2134                                             ISD::NodeType ExtendKind) const {
2135   MVT ReturnMVT;
2136   // TODO: Is this also valid on 32-bit?
2137   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2138     ReturnMVT = MVT::i8;
2139   else
2140     ReturnMVT = MVT::i32;
2141
2142   EVT MinVT = getRegisterType(Context, ReturnMVT);
2143   return VT.bitsLT(MinVT) ? MinVT : VT;
2144 }
2145
2146 /// LowerCallResult - Lower the result values of a call into the
2147 /// appropriate copies out of appropriate physical registers.
2148 ///
2149 SDValue
2150 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2151                                    CallingConv::ID CallConv, bool isVarArg,
2152                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2153                                    SDLoc dl, SelectionDAG &DAG,
2154                                    SmallVectorImpl<SDValue> &InVals) const {
2155
2156   // Assign locations to each value returned by this call.
2157   SmallVector<CCValAssign, 16> RVLocs;
2158   bool Is64Bit = Subtarget->is64Bit();
2159   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2160                  *DAG.getContext());
2161   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2162
2163   // Copy all of the result registers out of their specified physreg.
2164   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2165     CCValAssign &VA = RVLocs[i];
2166     EVT CopyVT = VA.getValVT();
2167
2168     // If this is x86-64, and we disabled SSE, we can't return FP values
2169     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2170         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2171       report_fatal_error("SSE register return with SSE disabled");
2172     }
2173
2174     // If we prefer to use the value in xmm registers, copy it out as f80 and
2175     // use a truncate to move it from fp stack reg to xmm reg.
2176     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2177         isScalarFPTypeInSSEReg(VA.getValVT()))
2178       CopyVT = MVT::f80;
2179
2180     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2181                                CopyVT, InFlag).getValue(1);
2182     SDValue Val = Chain.getValue(0);
2183
2184     if (CopyVT != VA.getValVT())
2185       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2186                         // This truncation won't change the value.
2187                         DAG.getIntPtrConstant(1));
2188
2189     InFlag = Chain.getValue(2);
2190     InVals.push_back(Val);
2191   }
2192
2193   return Chain;
2194 }
2195
2196 //===----------------------------------------------------------------------===//
2197 //                C & StdCall & Fast Calling Convention implementation
2198 //===----------------------------------------------------------------------===//
2199 //  StdCall calling convention seems to be standard for many Windows' API
2200 //  routines and around. It differs from C calling convention just a little:
2201 //  callee should clean up the stack, not caller. Symbols should be also
2202 //  decorated in some fancy way :) It doesn't support any vector arguments.
2203 //  For info on fast calling convention see Fast Calling Convention (tail call)
2204 //  implementation LowerX86_32FastCCCallTo.
2205
2206 /// CallIsStructReturn - Determines whether a call uses struct return
2207 /// semantics.
2208 enum StructReturnType {
2209   NotStructReturn,
2210   RegStructReturn,
2211   StackStructReturn
2212 };
2213 static StructReturnType
2214 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2215   if (Outs.empty())
2216     return NotStructReturn;
2217
2218   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2219   if (!Flags.isSRet())
2220     return NotStructReturn;
2221   if (Flags.isInReg())
2222     return RegStructReturn;
2223   return StackStructReturn;
2224 }
2225
2226 /// ArgsAreStructReturn - Determines whether a function uses struct
2227 /// return semantics.
2228 static StructReturnType
2229 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2230   if (Ins.empty())
2231     return NotStructReturn;
2232
2233   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2234   if (!Flags.isSRet())
2235     return NotStructReturn;
2236   if (Flags.isInReg())
2237     return RegStructReturn;
2238   return StackStructReturn;
2239 }
2240
2241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2242 /// by "Src" to address "Dst" with size and alignment information specified by
2243 /// the specific parameter attribute. The copy will be passed as a byval
2244 /// function parameter.
2245 static SDValue
2246 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2247                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2248                           SDLoc dl) {
2249   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2250
2251   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2252                        /*isVolatile*/false, /*AlwaysInline=*/true,
2253                        MachinePointerInfo(), MachinePointerInfo());
2254 }
2255
2256 /// IsTailCallConvention - Return true if the calling convention is one that
2257 /// supports tail call optimization.
2258 static bool IsTailCallConvention(CallingConv::ID CC) {
2259   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2260           CC == CallingConv::HiPE);
2261 }
2262
2263 /// \brief Return true if the calling convention is a C calling convention.
2264 static bool IsCCallConvention(CallingConv::ID CC) {
2265   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2266           CC == CallingConv::X86_64_SysV);
2267 }
2268
2269 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2270   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2271     return false;
2272
2273   CallSite CS(CI);
2274   CallingConv::ID CalleeCC = CS.getCallingConv();
2275   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2276     return false;
2277
2278   return true;
2279 }
2280
2281 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2282 /// a tailcall target by changing its ABI.
2283 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2284                                    bool GuaranteedTailCallOpt) {
2285   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2286 }
2287
2288 SDValue
2289 X86TargetLowering::LowerMemArgument(SDValue Chain,
2290                                     CallingConv::ID CallConv,
2291                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2292                                     SDLoc dl, SelectionDAG &DAG,
2293                                     const CCValAssign &VA,
2294                                     MachineFrameInfo *MFI,
2295                                     unsigned i) const {
2296   // Create the nodes corresponding to a load from this parameter slot.
2297   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2298   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2299       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2300   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2301   EVT ValVT;
2302
2303   // If value is passed by pointer we have address passed instead of the value
2304   // itself.
2305   if (VA.getLocInfo() == CCValAssign::Indirect)
2306     ValVT = VA.getLocVT();
2307   else
2308     ValVT = VA.getValVT();
2309
2310   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2311   // changed with more analysis.
2312   // In case of tail call optimization mark all arguments mutable. Since they
2313   // could be overwritten by lowering of arguments in case of a tail call.
2314   if (Flags.isByVal()) {
2315     unsigned Bytes = Flags.getByValSize();
2316     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2317     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2318     return DAG.getFrameIndex(FI, getPointerTy());
2319   } else {
2320     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2321                                     VA.getLocMemOffset(), isImmutable);
2322     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2323     return DAG.getLoad(ValVT, dl, Chain, FIN,
2324                        MachinePointerInfo::getFixedStack(FI),
2325                        false, false, false, 0);
2326   }
2327 }
2328
2329 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2330                                                 const X86Subtarget *Subtarget) {
2331   assert(Subtarget->is64Bit());
2332
2333   if (Subtarget->isCallingConvWin64(CallConv)) {
2334     static const MCPhysReg GPR64ArgRegsWin64[] = {
2335       X86::RCX, X86::RDX, X86::R8,  X86::R9
2336     };
2337     return GPR64ArgRegsWin64;
2338   }
2339
2340   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2341     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2342   };
2343   return GPR64ArgRegs64Bit;
2344 }
2345
2346 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2347                                                 CallingConv::ID CallConv,
2348                                                 const X86Subtarget *Subtarget) {
2349   assert(Subtarget->is64Bit());
2350   if (Subtarget->isCallingConvWin64(CallConv)) {
2351     // The XMM registers which might contain var arg parameters are shadowed
2352     // in their paired GPR.  So we only need to save the GPR to their home
2353     // slots.
2354     return None;
2355   }
2356
2357   const Function *Fn = MF.getFunction();
2358   bool NoImplicitFloatOps = Fn->getAttributes().
2359       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2360   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2361          "SSE register cannot be used when SSE is disabled!");
2362   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2363       !Subtarget->hasSSE1())
2364     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2365     // registers.
2366     return None;
2367
2368   static const MCPhysReg XMMArgRegs64Bit[] = {
2369     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2370     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2371   };
2372   return XMMArgRegs64Bit;
2373 }
2374
2375 SDValue
2376 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2377                                         CallingConv::ID CallConv,
2378                                         bool isVarArg,
2379                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2380                                         SDLoc dl,
2381                                         SelectionDAG &DAG,
2382                                         SmallVectorImpl<SDValue> &InVals)
2383                                           const {
2384   MachineFunction &MF = DAG.getMachineFunction();
2385   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2386
2387   const Function* Fn = MF.getFunction();
2388   if (Fn->hasExternalLinkage() &&
2389       Subtarget->isTargetCygMing() &&
2390       Fn->getName() == "main")
2391     FuncInfo->setForceFramePointer(true);
2392
2393   MachineFrameInfo *MFI = MF.getFrameInfo();
2394   bool Is64Bit = Subtarget->is64Bit();
2395   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2396
2397   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2398          "Var args not supported with calling convention fastcc, ghc or hipe");
2399
2400   // Assign locations to all of the incoming arguments.
2401   SmallVector<CCValAssign, 16> ArgLocs;
2402   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2403
2404   // Allocate shadow area for Win64
2405   if (IsWin64)
2406     CCInfo.AllocateStack(32, 8);
2407
2408   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2409
2410   unsigned LastVal = ~0U;
2411   SDValue ArgValue;
2412   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2413     CCValAssign &VA = ArgLocs[i];
2414     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2415     // places.
2416     assert(VA.getValNo() != LastVal &&
2417            "Don't support value assigned to multiple locs yet");
2418     (void)LastVal;
2419     LastVal = VA.getValNo();
2420
2421     if (VA.isRegLoc()) {
2422       EVT RegVT = VA.getLocVT();
2423       const TargetRegisterClass *RC;
2424       if (RegVT == MVT::i32)
2425         RC = &X86::GR32RegClass;
2426       else if (Is64Bit && RegVT == MVT::i64)
2427         RC = &X86::GR64RegClass;
2428       else if (RegVT == MVT::f32)
2429         RC = &X86::FR32RegClass;
2430       else if (RegVT == MVT::f64)
2431         RC = &X86::FR64RegClass;
2432       else if (RegVT.is512BitVector())
2433         RC = &X86::VR512RegClass;
2434       else if (RegVT.is256BitVector())
2435         RC = &X86::VR256RegClass;
2436       else if (RegVT.is128BitVector())
2437         RC = &X86::VR128RegClass;
2438       else if (RegVT == MVT::x86mmx)
2439         RC = &X86::VR64RegClass;
2440       else if (RegVT == MVT::i1)
2441         RC = &X86::VK1RegClass;
2442       else if (RegVT == MVT::v8i1)
2443         RC = &X86::VK8RegClass;
2444       else if (RegVT == MVT::v16i1)
2445         RC = &X86::VK16RegClass;
2446       else if (RegVT == MVT::v32i1)
2447         RC = &X86::VK32RegClass;
2448       else if (RegVT == MVT::v64i1)
2449         RC = &X86::VK64RegClass;
2450       else
2451         llvm_unreachable("Unknown argument type!");
2452
2453       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2454       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2455
2456       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2457       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2458       // right size.
2459       if (VA.getLocInfo() == CCValAssign::SExt)
2460         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2461                                DAG.getValueType(VA.getValVT()));
2462       else if (VA.getLocInfo() == CCValAssign::ZExt)
2463         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2464                                DAG.getValueType(VA.getValVT()));
2465       else if (VA.getLocInfo() == CCValAssign::BCvt)
2466         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2467
2468       if (VA.isExtInLoc()) {
2469         // Handle MMX values passed in XMM regs.
2470         if (RegVT.isVector())
2471           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2472         else
2473           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2474       }
2475     } else {
2476       assert(VA.isMemLoc());
2477       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2478     }
2479
2480     // If value is passed via pointer - do a load.
2481     if (VA.getLocInfo() == CCValAssign::Indirect)
2482       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2483                              MachinePointerInfo(), false, false, false, 0);
2484
2485     InVals.push_back(ArgValue);
2486   }
2487
2488   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2489     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2490       // The x86-64 ABIs require that for returning structs by value we copy
2491       // the sret argument into %rax/%eax (depending on ABI) for the return.
2492       // Win32 requires us to put the sret argument to %eax as well.
2493       // Save the argument into a virtual register so that we can access it
2494       // from the return points.
2495       if (Ins[i].Flags.isSRet()) {
2496         unsigned Reg = FuncInfo->getSRetReturnReg();
2497         if (!Reg) {
2498           MVT PtrTy = getPointerTy();
2499           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2500           FuncInfo->setSRetReturnReg(Reg);
2501         }
2502         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2503         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2504         break;
2505       }
2506     }
2507   }
2508
2509   unsigned StackSize = CCInfo.getNextStackOffset();
2510   // Align stack specially for tail calls.
2511   if (FuncIsMadeTailCallSafe(CallConv,
2512                              MF.getTarget().Options.GuaranteedTailCallOpt))
2513     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2514
2515   // If the function takes variable number of arguments, make a frame index for
2516   // the start of the first vararg value... for expansion of llvm.va_start. We
2517   // can skip this if there are no va_start calls.
2518   if (MFI->hasVAStart() &&
2519       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2520                    CallConv != CallingConv::X86_ThisCall))) {
2521     FuncInfo->setVarArgsFrameIndex(
2522         MFI->CreateFixedObject(1, StackSize, true));
2523   }
2524
2525   // 64-bit calling conventions support varargs and register parameters, so we
2526   // have to do extra work to spill them in the prologue or forward them to
2527   // musttail calls.
2528   if (Is64Bit && isVarArg &&
2529       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2530     // Find the first unallocated argument registers.
2531     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2532     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2533     unsigned NumIntRegs =
2534         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2535     unsigned NumXMMRegs =
2536         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2537     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2538            "SSE register cannot be used when SSE is disabled!");
2539
2540     // Gather all the live in physical registers.
2541     SmallVector<SDValue, 6> LiveGPRs;
2542     SmallVector<SDValue, 8> LiveXMMRegs;
2543     SDValue ALVal;
2544     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2545       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2546       LiveGPRs.push_back(
2547           DAG.getCopyFromReg(DAG.getEntryNode(), dl, GPR, MVT::i64));
2548     }
2549     if (!ArgXMMs.empty()) {
2550       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2551       ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2552       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2553         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2554         LiveXMMRegs.push_back(
2555             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2556       }
2557     }
2558
2559     // Store them to the va_list returned by va_start.
2560     if (MFI->hasVAStart()) {
2561       if (IsWin64) {
2562         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2563         // Get to the caller-allocated home save location.  Add 8 to account
2564         // for the return address.
2565         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2566         FuncInfo->setRegSaveFrameIndex(
2567           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2568         // Fixup to set vararg frame on shadow area (4 x i64).
2569         if (NumIntRegs < 4)
2570           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2571       } else {
2572         // For X86-64, if there are vararg parameters that are passed via
2573         // registers, then we must store them to their spots on the stack so
2574         // they may be loaded by deferencing the result of va_next.
2575         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2576         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2577         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2578             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2579       }
2580
2581       // Store the integer parameter registers.
2582       SmallVector<SDValue, 8> MemOps;
2583       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2584                                         getPointerTy());
2585       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2586       for (SDValue Val : LiveGPRs) {
2587         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2588                                   DAG.getIntPtrConstant(Offset));
2589         SDValue Store =
2590           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2591                        MachinePointerInfo::getFixedStack(
2592                          FuncInfo->getRegSaveFrameIndex(), Offset),
2593                        false, false, 0);
2594         MemOps.push_back(Store);
2595         Offset += 8;
2596       }
2597
2598       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2599         // Now store the XMM (fp + vector) parameter registers.
2600         SmallVector<SDValue, 12> SaveXMMOps;
2601         SaveXMMOps.push_back(Chain);
2602         SaveXMMOps.push_back(ALVal);
2603         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2604                                FuncInfo->getRegSaveFrameIndex()));
2605         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2606                                FuncInfo->getVarArgsFPOffset()));
2607         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2608                           LiveXMMRegs.end());
2609         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2610                                      MVT::Other, SaveXMMOps));
2611       }
2612
2613       if (!MemOps.empty())
2614         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2615     } else {
2616       // TODO: Save virtual registers away some where so we can do
2617       // getCopyFromReg in the musttail call lowering bb.
2618       assert(MFI->hasMustTailInVarArgFunc());
2619       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2620       typedef X86MachineFunctionInfo::Forward Forward;
2621
2622       // Add all GPRs, al, and XMMs to the list of forwards.
2623       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2624         unsigned VReg =
2625             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2626         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2627         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2628       }
2629
2630       if (!ArgXMMs.empty()) {
2631         unsigned ALVReg =
2632             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2633         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2634         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2635
2636         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2637           unsigned VReg =
2638               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2639           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2640           Forwards.push_back(
2641               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2642         }
2643       }
2644     }
2645   }
2646
2647   // Some CCs need callee pop.
2648   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2649                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2650     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2651   } else {
2652     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2653     // If this is an sret function, the return should pop the hidden pointer.
2654     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2655         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2656         argsAreStructReturn(Ins) == StackStructReturn)
2657       FuncInfo->setBytesToPopOnReturn(4);
2658   }
2659
2660   if (!Is64Bit) {
2661     // RegSaveFrameIndex is X86-64 only.
2662     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2663     if (CallConv == CallingConv::X86_FastCall ||
2664         CallConv == CallingConv::X86_ThisCall)
2665       // fastcc functions can't have varargs.
2666       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2667   }
2668
2669   FuncInfo->setArgumentStackSize(StackSize);
2670
2671   return Chain;
2672 }
2673
2674 SDValue
2675 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2676                                     SDValue StackPtr, SDValue Arg,
2677                                     SDLoc dl, SelectionDAG &DAG,
2678                                     const CCValAssign &VA,
2679                                     ISD::ArgFlagsTy Flags) const {
2680   unsigned LocMemOffset = VA.getLocMemOffset();
2681   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2682   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2683   if (Flags.isByVal())
2684     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2685
2686   return DAG.getStore(Chain, dl, Arg, PtrOff,
2687                       MachinePointerInfo::getStack(LocMemOffset),
2688                       false, false, 0);
2689 }
2690
2691 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2692 /// optimization is performed and it is required.
2693 SDValue
2694 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2695                                            SDValue &OutRetAddr, SDValue Chain,
2696                                            bool IsTailCall, bool Is64Bit,
2697                                            int FPDiff, SDLoc dl) const {
2698   // Adjust the Return address stack slot.
2699   EVT VT = getPointerTy();
2700   OutRetAddr = getReturnAddressFrameIndex(DAG);
2701
2702   // Load the "old" Return address.
2703   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2704                            false, false, false, 0);
2705   return SDValue(OutRetAddr.getNode(), 1);
2706 }
2707
2708 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2709 /// optimization is performed and it is required (FPDiff!=0).
2710 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2711                                         SDValue Chain, SDValue RetAddrFrIdx,
2712                                         EVT PtrVT, unsigned SlotSize,
2713                                         int FPDiff, SDLoc dl) {
2714   // Store the return address to the appropriate stack slot.
2715   if (!FPDiff) return Chain;
2716   // Calculate the new stack slot for the return address.
2717   int NewReturnAddrFI =
2718     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2719                                          false);
2720   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2721   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2722                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2723                        false, false, 0);
2724   return Chain;
2725 }
2726
2727 SDValue
2728 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2729                              SmallVectorImpl<SDValue> &InVals) const {
2730   SelectionDAG &DAG                     = CLI.DAG;
2731   SDLoc &dl                             = CLI.DL;
2732   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2733   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2734   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2735   SDValue Chain                         = CLI.Chain;
2736   SDValue Callee                        = CLI.Callee;
2737   CallingConv::ID CallConv              = CLI.CallConv;
2738   bool &isTailCall                      = CLI.IsTailCall;
2739   bool isVarArg                         = CLI.IsVarArg;
2740
2741   MachineFunction &MF = DAG.getMachineFunction();
2742   bool Is64Bit        = Subtarget->is64Bit();
2743   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2744   StructReturnType SR = callIsStructReturn(Outs);
2745   bool IsSibcall      = false;
2746   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2747
2748   if (MF.getTarget().Options.DisableTailCalls)
2749     isTailCall = false;
2750
2751   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2752   if (IsMustTail) {
2753     // Force this to be a tail call.  The verifier rules are enough to ensure
2754     // that we can lower this successfully without moving the return address
2755     // around.
2756     isTailCall = true;
2757   } else if (isTailCall) {
2758     // Check if it's really possible to do a tail call.
2759     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2760                     isVarArg, SR != NotStructReturn,
2761                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2762                     Outs, OutVals, Ins, DAG);
2763
2764     // Sibcalls are automatically detected tailcalls which do not require
2765     // ABI changes.
2766     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2767       IsSibcall = true;
2768
2769     if (isTailCall)
2770       ++NumTailCalls;
2771   }
2772
2773   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2774          "Var args not supported with calling convention fastcc, ghc or hipe");
2775
2776   // Analyze operands of the call, assigning locations to each operand.
2777   SmallVector<CCValAssign, 16> ArgLocs;
2778   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2779
2780   // Allocate shadow area for Win64
2781   if (IsWin64)
2782     CCInfo.AllocateStack(32, 8);
2783
2784   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2785
2786   // Get a count of how many bytes are to be pushed on the stack.
2787   unsigned NumBytes = CCInfo.getNextStackOffset();
2788   if (IsSibcall)
2789     // This is a sibcall. The memory operands are available in caller's
2790     // own caller's stack.
2791     NumBytes = 0;
2792   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2793            IsTailCallConvention(CallConv))
2794     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2795
2796   int FPDiff = 0;
2797   if (isTailCall && !IsSibcall && !IsMustTail) {
2798     // Lower arguments at fp - stackoffset + fpdiff.
2799     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2800
2801     FPDiff = NumBytesCallerPushed - NumBytes;
2802
2803     // Set the delta of movement of the returnaddr stackslot.
2804     // But only set if delta is greater than previous delta.
2805     if (FPDiff < X86Info->getTCReturnAddrDelta())
2806       X86Info->setTCReturnAddrDelta(FPDiff);
2807   }
2808
2809   unsigned NumBytesToPush = NumBytes;
2810   unsigned NumBytesToPop = NumBytes;
2811
2812   // If we have an inalloca argument, all stack space has already been allocated
2813   // for us and be right at the top of the stack.  We don't support multiple
2814   // arguments passed in memory when using inalloca.
2815   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2816     NumBytesToPush = 0;
2817     if (!ArgLocs.back().isMemLoc())
2818       report_fatal_error("cannot use inalloca attribute on a register "
2819                          "parameter");
2820     if (ArgLocs.back().getLocMemOffset() != 0)
2821       report_fatal_error("any parameter with the inalloca attribute must be "
2822                          "the only memory argument");
2823   }
2824
2825   if (!IsSibcall)
2826     Chain = DAG.getCALLSEQ_START(
2827         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2828
2829   SDValue RetAddrFrIdx;
2830   // Load return address for tail calls.
2831   if (isTailCall && FPDiff)
2832     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2833                                     Is64Bit, FPDiff, dl);
2834
2835   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2836   SmallVector<SDValue, 8> MemOpChains;
2837   SDValue StackPtr;
2838
2839   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2840   // of tail call optimization arguments are handle later.
2841   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2842       DAG.getSubtarget().getRegisterInfo());
2843   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2844     // Skip inalloca arguments, they have already been written.
2845     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2846     if (Flags.isInAlloca())
2847       continue;
2848
2849     CCValAssign &VA = ArgLocs[i];
2850     EVT RegVT = VA.getLocVT();
2851     SDValue Arg = OutVals[i];
2852     bool isByVal = Flags.isByVal();
2853
2854     // Promote the value if needed.
2855     switch (VA.getLocInfo()) {
2856     default: llvm_unreachable("Unknown loc info!");
2857     case CCValAssign::Full: break;
2858     case CCValAssign::SExt:
2859       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2860       break;
2861     case CCValAssign::ZExt:
2862       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2863       break;
2864     case CCValAssign::AExt:
2865       if (RegVT.is128BitVector()) {
2866         // Special case: passing MMX values in XMM registers.
2867         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2868         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2869         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2870       } else
2871         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2872       break;
2873     case CCValAssign::BCvt:
2874       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2875       break;
2876     case CCValAssign::Indirect: {
2877       // Store the argument.
2878       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2879       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2880       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2881                            MachinePointerInfo::getFixedStack(FI),
2882                            false, false, 0);
2883       Arg = SpillSlot;
2884       break;
2885     }
2886     }
2887
2888     if (VA.isRegLoc()) {
2889       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2890       if (isVarArg && IsWin64) {
2891         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2892         // shadow reg if callee is a varargs function.
2893         unsigned ShadowReg = 0;
2894         switch (VA.getLocReg()) {
2895         case X86::XMM0: ShadowReg = X86::RCX; break;
2896         case X86::XMM1: ShadowReg = X86::RDX; break;
2897         case X86::XMM2: ShadowReg = X86::R8; break;
2898         case X86::XMM3: ShadowReg = X86::R9; break;
2899         }
2900         if (ShadowReg)
2901           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2902       }
2903     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2904       assert(VA.isMemLoc());
2905       if (!StackPtr.getNode())
2906         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2907                                       getPointerTy());
2908       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2909                                              dl, DAG, VA, Flags));
2910     }
2911   }
2912
2913   if (!MemOpChains.empty())
2914     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2915
2916   if (Subtarget->isPICStyleGOT()) {
2917     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2918     // GOT pointer.
2919     if (!isTailCall) {
2920       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2921                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2922     } else {
2923       // If we are tail calling and generating PIC/GOT style code load the
2924       // address of the callee into ECX. The value in ecx is used as target of
2925       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2926       // for tail calls on PIC/GOT architectures. Normally we would just put the
2927       // address of GOT into ebx and then call target@PLT. But for tail calls
2928       // ebx would be restored (since ebx is callee saved) before jumping to the
2929       // target@PLT.
2930
2931       // Note: The actual moving to ECX is done further down.
2932       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2933       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2934           !G->getGlobal()->hasProtectedVisibility())
2935         Callee = LowerGlobalAddress(Callee, DAG);
2936       else if (isa<ExternalSymbolSDNode>(Callee))
2937         Callee = LowerExternalSymbol(Callee, DAG);
2938     }
2939   }
2940
2941   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2942     // From AMD64 ABI document:
2943     // For calls that may call functions that use varargs or stdargs
2944     // (prototype-less calls or calls to functions containing ellipsis (...) in
2945     // the declaration) %al is used as hidden argument to specify the number
2946     // of SSE registers used. The contents of %al do not need to match exactly
2947     // the number of registers, but must be an ubound on the number of SSE
2948     // registers used and is in the range 0 - 8 inclusive.
2949
2950     // Count the number of XMM registers allocated.
2951     static const MCPhysReg XMMArgRegs[] = {
2952       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2953       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2954     };
2955     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2956     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2957            && "SSE registers cannot be used when SSE is disabled");
2958
2959     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2960                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2961   }
2962
2963   if (Is64Bit && isVarArg && IsMustTail) {
2964     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2965     for (const auto &F : Forwards) {
2966       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2967       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2968     }
2969   }
2970
2971   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2972   // don't need this because the eligibility check rejects calls that require
2973   // shuffling arguments passed in memory.
2974   if (!IsSibcall && isTailCall) {
2975     // Force all the incoming stack arguments to be loaded from the stack
2976     // before any new outgoing arguments are stored to the stack, because the
2977     // outgoing stack slots may alias the incoming argument stack slots, and
2978     // the alias isn't otherwise explicit. This is slightly more conservative
2979     // than necessary, because it means that each store effectively depends
2980     // on every argument instead of just those arguments it would clobber.
2981     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2982
2983     SmallVector<SDValue, 8> MemOpChains2;
2984     SDValue FIN;
2985     int FI = 0;
2986     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2987       CCValAssign &VA = ArgLocs[i];
2988       if (VA.isRegLoc())
2989         continue;
2990       assert(VA.isMemLoc());
2991       SDValue Arg = OutVals[i];
2992       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2993       // Skip inalloca arguments.  They don't require any work.
2994       if (Flags.isInAlloca())
2995         continue;
2996       // Create frame index.
2997       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2998       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2999       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3000       FIN = DAG.getFrameIndex(FI, getPointerTy());
3001
3002       if (Flags.isByVal()) {
3003         // Copy relative to framepointer.
3004         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3005         if (!StackPtr.getNode())
3006           StackPtr = DAG.getCopyFromReg(Chain, dl,
3007                                         RegInfo->getStackRegister(),
3008                                         getPointerTy());
3009         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3010
3011         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3012                                                          ArgChain,
3013                                                          Flags, DAG, dl));
3014       } else {
3015         // Store relative to framepointer.
3016         MemOpChains2.push_back(
3017           DAG.getStore(ArgChain, dl, Arg, FIN,
3018                        MachinePointerInfo::getFixedStack(FI),
3019                        false, false, 0));
3020       }
3021     }
3022
3023     if (!MemOpChains2.empty())
3024       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3025
3026     // Store the return address to the appropriate stack slot.
3027     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3028                                      getPointerTy(), RegInfo->getSlotSize(),
3029                                      FPDiff, dl);
3030   }
3031
3032   // Build a sequence of copy-to-reg nodes chained together with token chain
3033   // and flag operands which copy the outgoing args into registers.
3034   SDValue InFlag;
3035   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3036     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3037                              RegsToPass[i].second, InFlag);
3038     InFlag = Chain.getValue(1);
3039   }
3040
3041   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3042     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3043     // In the 64-bit large code model, we have to make all calls
3044     // through a register, since the call instruction's 32-bit
3045     // pc-relative offset may not be large enough to hold the whole
3046     // address.
3047   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3048     // If the callee is a GlobalAddress node (quite common, every direct call
3049     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3050     // it.
3051
3052     // We should use extra load for direct calls to dllimported functions in
3053     // non-JIT mode.
3054     const GlobalValue *GV = G->getGlobal();
3055     if (!GV->hasDLLImportStorageClass()) {
3056       unsigned char OpFlags = 0;
3057       bool ExtraLoad = false;
3058       unsigned WrapperKind = ISD::DELETED_NODE;
3059
3060       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3061       // external symbols most go through the PLT in PIC mode.  If the symbol
3062       // has hidden or protected visibility, or if it is static or local, then
3063       // we don't need to use the PLT - we can directly call it.
3064       if (Subtarget->isTargetELF() &&
3065           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3066           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3067         OpFlags = X86II::MO_PLT;
3068       } else if (Subtarget->isPICStyleStubAny() &&
3069                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3070                  (!Subtarget->getTargetTriple().isMacOSX() ||
3071                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3072         // PC-relative references to external symbols should go through $stub,
3073         // unless we're building with the leopard linker or later, which
3074         // automatically synthesizes these stubs.
3075         OpFlags = X86II::MO_DARWIN_STUB;
3076       } else if (Subtarget->isPICStyleRIPRel() &&
3077                  isa<Function>(GV) &&
3078                  cast<Function>(GV)->getAttributes().
3079                    hasAttribute(AttributeSet::FunctionIndex,
3080                                 Attribute::NonLazyBind)) {
3081         // If the function is marked as non-lazy, generate an indirect call
3082         // which loads from the GOT directly. This avoids runtime overhead
3083         // at the cost of eager binding (and one extra byte of encoding).
3084         OpFlags = X86II::MO_GOTPCREL;
3085         WrapperKind = X86ISD::WrapperRIP;
3086         ExtraLoad = true;
3087       }
3088
3089       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3090                                           G->getOffset(), OpFlags);
3091
3092       // Add a wrapper if needed.
3093       if (WrapperKind != ISD::DELETED_NODE)
3094         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3095       // Add extra indirection if needed.
3096       if (ExtraLoad)
3097         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3098                              MachinePointerInfo::getGOT(),
3099                              false, false, false, 0);
3100     }
3101   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3102     unsigned char OpFlags = 0;
3103
3104     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3105     // external symbols should go through the PLT.
3106     if (Subtarget->isTargetELF() &&
3107         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3108       OpFlags = X86II::MO_PLT;
3109     } else if (Subtarget->isPICStyleStubAny() &&
3110                (!Subtarget->getTargetTriple().isMacOSX() ||
3111                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3112       // PC-relative references to external symbols should go through $stub,
3113       // unless we're building with the leopard linker or later, which
3114       // automatically synthesizes these stubs.
3115       OpFlags = X86II::MO_DARWIN_STUB;
3116     }
3117
3118     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3119                                          OpFlags);
3120   }
3121
3122   // Returns a chain & a flag for retval copy to use.
3123   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3124   SmallVector<SDValue, 8> Ops;
3125
3126   if (!IsSibcall && isTailCall) {
3127     Chain = DAG.getCALLSEQ_END(Chain,
3128                                DAG.getIntPtrConstant(NumBytesToPop, true),
3129                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3130     InFlag = Chain.getValue(1);
3131   }
3132
3133   Ops.push_back(Chain);
3134   Ops.push_back(Callee);
3135
3136   if (isTailCall)
3137     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3138
3139   // Add argument registers to the end of the list so that they are known live
3140   // into the call.
3141   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3142     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3143                                   RegsToPass[i].second.getValueType()));
3144
3145   // Add a register mask operand representing the call-preserved registers.
3146   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3147   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3148   assert(Mask && "Missing call preserved mask for calling convention");
3149   Ops.push_back(DAG.getRegisterMask(Mask));
3150
3151   if (InFlag.getNode())
3152     Ops.push_back(InFlag);
3153
3154   if (isTailCall) {
3155     // We used to do:
3156     //// If this is the first return lowered for this function, add the regs
3157     //// to the liveout set for the function.
3158     // This isn't right, although it's probably harmless on x86; liveouts
3159     // should be computed from returns not tail calls.  Consider a void
3160     // function making a tail call to a function returning int.
3161     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3162   }
3163
3164   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3165   InFlag = Chain.getValue(1);
3166
3167   // Create the CALLSEQ_END node.
3168   unsigned NumBytesForCalleeToPop;
3169   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3170                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3171     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3172   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3173            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3174            SR == StackStructReturn)
3175     // If this is a call to a struct-return function, the callee
3176     // pops the hidden struct pointer, so we have to push it back.
3177     // This is common for Darwin/X86, Linux & Mingw32 targets.
3178     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3179     NumBytesForCalleeToPop = 4;
3180   else
3181     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3182
3183   // Returns a flag for retval copy to use.
3184   if (!IsSibcall) {
3185     Chain = DAG.getCALLSEQ_END(Chain,
3186                                DAG.getIntPtrConstant(NumBytesToPop, true),
3187                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3188                                                      true),
3189                                InFlag, dl);
3190     InFlag = Chain.getValue(1);
3191   }
3192
3193   // Handle result values, copying them out of physregs into vregs that we
3194   // return.
3195   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3196                          Ins, dl, DAG, InVals);
3197 }
3198
3199 //===----------------------------------------------------------------------===//
3200 //                Fast Calling Convention (tail call) implementation
3201 //===----------------------------------------------------------------------===//
3202
3203 //  Like std call, callee cleans arguments, convention except that ECX is
3204 //  reserved for storing the tail called function address. Only 2 registers are
3205 //  free for argument passing (inreg). Tail call optimization is performed
3206 //  provided:
3207 //                * tailcallopt is enabled
3208 //                * caller/callee are fastcc
3209 //  On X86_64 architecture with GOT-style position independent code only local
3210 //  (within module) calls are supported at the moment.
3211 //  To keep the stack aligned according to platform abi the function
3212 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3213 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3214 //  If a tail called function callee has more arguments than the caller the
3215 //  caller needs to make sure that there is room to move the RETADDR to. This is
3216 //  achieved by reserving an area the size of the argument delta right after the
3217 //  original RETADDR, but before the saved framepointer or the spilled registers
3218 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3219 //  stack layout:
3220 //    arg1
3221 //    arg2
3222 //    RETADDR
3223 //    [ new RETADDR
3224 //      move area ]
3225 //    (possible EBP)
3226 //    ESI
3227 //    EDI
3228 //    local1 ..
3229
3230 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3231 /// for a 16 byte align requirement.
3232 unsigned
3233 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3234                                                SelectionDAG& DAG) const {
3235   MachineFunction &MF = DAG.getMachineFunction();
3236   const TargetMachine &TM = MF.getTarget();
3237   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3238       TM.getSubtargetImpl()->getRegisterInfo());
3239   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3240   unsigned StackAlignment = TFI.getStackAlignment();
3241   uint64_t AlignMask = StackAlignment - 1;
3242   int64_t Offset = StackSize;
3243   unsigned SlotSize = RegInfo->getSlotSize();
3244   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3245     // Number smaller than 12 so just add the difference.
3246     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3247   } else {
3248     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3249     Offset = ((~AlignMask) & Offset) + StackAlignment +
3250       (StackAlignment-SlotSize);
3251   }
3252   return Offset;
3253 }
3254
3255 /// MatchingStackOffset - Return true if the given stack call argument is
3256 /// already available in the same position (relatively) of the caller's
3257 /// incoming argument stack.
3258 static
3259 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3260                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3261                          const X86InstrInfo *TII) {
3262   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3263   int FI = INT_MAX;
3264   if (Arg.getOpcode() == ISD::CopyFromReg) {
3265     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3266     if (!TargetRegisterInfo::isVirtualRegister(VR))
3267       return false;
3268     MachineInstr *Def = MRI->getVRegDef(VR);
3269     if (!Def)
3270       return false;
3271     if (!Flags.isByVal()) {
3272       if (!TII->isLoadFromStackSlot(Def, FI))
3273         return false;
3274     } else {
3275       unsigned Opcode = Def->getOpcode();
3276       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3277           Def->getOperand(1).isFI()) {
3278         FI = Def->getOperand(1).getIndex();
3279         Bytes = Flags.getByValSize();
3280       } else
3281         return false;
3282     }
3283   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3284     if (Flags.isByVal())
3285       // ByVal argument is passed in as a pointer but it's now being
3286       // dereferenced. e.g.
3287       // define @foo(%struct.X* %A) {
3288       //   tail call @bar(%struct.X* byval %A)
3289       // }
3290       return false;
3291     SDValue Ptr = Ld->getBasePtr();
3292     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3293     if (!FINode)
3294       return false;
3295     FI = FINode->getIndex();
3296   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3297     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3298     FI = FINode->getIndex();
3299     Bytes = Flags.getByValSize();
3300   } else
3301     return false;
3302
3303   assert(FI != INT_MAX);
3304   if (!MFI->isFixedObjectIndex(FI))
3305     return false;
3306   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3307 }
3308
3309 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3310 /// for tail call optimization. Targets which want to do tail call
3311 /// optimization should implement this function.
3312 bool
3313 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3314                                                      CallingConv::ID CalleeCC,
3315                                                      bool isVarArg,
3316                                                      bool isCalleeStructRet,
3317                                                      bool isCallerStructRet,
3318                                                      Type *RetTy,
3319                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3320                                     const SmallVectorImpl<SDValue> &OutVals,
3321                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3322                                                      SelectionDAG &DAG) const {
3323   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3324     return false;
3325
3326   // If -tailcallopt is specified, make fastcc functions tail-callable.
3327   const MachineFunction &MF = DAG.getMachineFunction();
3328   const Function *CallerF = MF.getFunction();
3329
3330   // If the function return type is x86_fp80 and the callee return type is not,
3331   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3332   // perform a tailcall optimization here.
3333   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3334     return false;
3335
3336   CallingConv::ID CallerCC = CallerF->getCallingConv();
3337   bool CCMatch = CallerCC == CalleeCC;
3338   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3339   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3340
3341   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3342     if (IsTailCallConvention(CalleeCC) && CCMatch)
3343       return true;
3344     return false;
3345   }
3346
3347   // Look for obvious safe cases to perform tail call optimization that do not
3348   // require ABI changes. This is what gcc calls sibcall.
3349
3350   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3351   // emit a special epilogue.
3352   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3353       DAG.getSubtarget().getRegisterInfo());
3354   if (RegInfo->needsStackRealignment(MF))
3355     return false;
3356
3357   // Also avoid sibcall optimization if either caller or callee uses struct
3358   // return semantics.
3359   if (isCalleeStructRet || isCallerStructRet)
3360     return false;
3361
3362   // An stdcall/thiscall caller is expected to clean up its arguments; the
3363   // callee isn't going to do that.
3364   // FIXME: this is more restrictive than needed. We could produce a tailcall
3365   // when the stack adjustment matches. For example, with a thiscall that takes
3366   // only one argument.
3367   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3368                    CallerCC == CallingConv::X86_ThisCall))
3369     return false;
3370
3371   // Do not sibcall optimize vararg calls unless all arguments are passed via
3372   // registers.
3373   if (isVarArg && !Outs.empty()) {
3374
3375     // Optimizing for varargs on Win64 is unlikely to be safe without
3376     // additional testing.
3377     if (IsCalleeWin64 || IsCallerWin64)
3378       return false;
3379
3380     SmallVector<CCValAssign, 16> ArgLocs;
3381     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3382                    *DAG.getContext());
3383
3384     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3385     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3386       if (!ArgLocs[i].isRegLoc())
3387         return false;
3388   }
3389
3390   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3391   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3392   // this into a sibcall.
3393   bool Unused = false;
3394   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3395     if (!Ins[i].Used) {
3396       Unused = true;
3397       break;
3398     }
3399   }
3400   if (Unused) {
3401     SmallVector<CCValAssign, 16> RVLocs;
3402     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3403                    *DAG.getContext());
3404     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3405     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3406       CCValAssign &VA = RVLocs[i];
3407       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3408         return false;
3409     }
3410   }
3411
3412   // If the calling conventions do not match, then we'd better make sure the
3413   // results are returned in the same way as what the caller expects.
3414   if (!CCMatch) {
3415     SmallVector<CCValAssign, 16> RVLocs1;
3416     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3417                     *DAG.getContext());
3418     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3419
3420     SmallVector<CCValAssign, 16> RVLocs2;
3421     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3422                     *DAG.getContext());
3423     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3424
3425     if (RVLocs1.size() != RVLocs2.size())
3426       return false;
3427     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3428       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3429         return false;
3430       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3431         return false;
3432       if (RVLocs1[i].isRegLoc()) {
3433         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3434           return false;
3435       } else {
3436         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3437           return false;
3438       }
3439     }
3440   }
3441
3442   // If the callee takes no arguments then go on to check the results of the
3443   // call.
3444   if (!Outs.empty()) {
3445     // Check if stack adjustment is needed. For now, do not do this if any
3446     // argument is passed on the stack.
3447     SmallVector<CCValAssign, 16> ArgLocs;
3448     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3449                    *DAG.getContext());
3450
3451     // Allocate shadow area for Win64
3452     if (IsCalleeWin64)
3453       CCInfo.AllocateStack(32, 8);
3454
3455     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3456     if (CCInfo.getNextStackOffset()) {
3457       MachineFunction &MF = DAG.getMachineFunction();
3458       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3459         return false;
3460
3461       // Check if the arguments are already laid out in the right way as
3462       // the caller's fixed stack objects.
3463       MachineFrameInfo *MFI = MF.getFrameInfo();
3464       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3465       const X86InstrInfo *TII =
3466           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3467       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3468         CCValAssign &VA = ArgLocs[i];
3469         SDValue Arg = OutVals[i];
3470         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3471         if (VA.getLocInfo() == CCValAssign::Indirect)
3472           return false;
3473         if (!VA.isRegLoc()) {
3474           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3475                                    MFI, MRI, TII))
3476             return false;
3477         }
3478       }
3479     }
3480
3481     // If the tailcall address may be in a register, then make sure it's
3482     // possible to register allocate for it. In 32-bit, the call address can
3483     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3484     // callee-saved registers are restored. These happen to be the same
3485     // registers used to pass 'inreg' arguments so watch out for those.
3486     if (!Subtarget->is64Bit() &&
3487         ((!isa<GlobalAddressSDNode>(Callee) &&
3488           !isa<ExternalSymbolSDNode>(Callee)) ||
3489          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3490       unsigned NumInRegs = 0;
3491       // In PIC we need an extra register to formulate the address computation
3492       // for the callee.
3493       unsigned MaxInRegs =
3494         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3495
3496       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3497         CCValAssign &VA = ArgLocs[i];
3498         if (!VA.isRegLoc())
3499           continue;
3500         unsigned Reg = VA.getLocReg();
3501         switch (Reg) {
3502         default: break;
3503         case X86::EAX: case X86::EDX: case X86::ECX:
3504           if (++NumInRegs == MaxInRegs)
3505             return false;
3506           break;
3507         }
3508       }
3509     }
3510   }
3511
3512   return true;
3513 }
3514
3515 FastISel *
3516 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3517                                   const TargetLibraryInfo *libInfo) const {
3518   return X86::createFastISel(funcInfo, libInfo);
3519 }
3520
3521 //===----------------------------------------------------------------------===//
3522 //                           Other Lowering Hooks
3523 //===----------------------------------------------------------------------===//
3524
3525 static bool MayFoldLoad(SDValue Op) {
3526   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3527 }
3528
3529 static bool MayFoldIntoStore(SDValue Op) {
3530   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3531 }
3532
3533 static bool isTargetShuffle(unsigned Opcode) {
3534   switch(Opcode) {
3535   default: return false;
3536   case X86ISD::PSHUFB:
3537   case X86ISD::PSHUFD:
3538   case X86ISD::PSHUFHW:
3539   case X86ISD::PSHUFLW:
3540   case X86ISD::SHUFP:
3541   case X86ISD::PALIGNR:
3542   case X86ISD::MOVLHPS:
3543   case X86ISD::MOVLHPD:
3544   case X86ISD::MOVHLPS:
3545   case X86ISD::MOVLPS:
3546   case X86ISD::MOVLPD:
3547   case X86ISD::MOVSHDUP:
3548   case X86ISD::MOVSLDUP:
3549   case X86ISD::MOVDDUP:
3550   case X86ISD::MOVSS:
3551   case X86ISD::MOVSD:
3552   case X86ISD::UNPCKL:
3553   case X86ISD::UNPCKH:
3554   case X86ISD::VPERMILP:
3555   case X86ISD::VPERM2X128:
3556   case X86ISD::VPERMI:
3557     return true;
3558   }
3559 }
3560
3561 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3562                                     SDValue V1, SelectionDAG &DAG) {
3563   switch(Opc) {
3564   default: llvm_unreachable("Unknown x86 shuffle node");
3565   case X86ISD::MOVSHDUP:
3566   case X86ISD::MOVSLDUP:
3567   case X86ISD::MOVDDUP:
3568     return DAG.getNode(Opc, dl, VT, V1);
3569   }
3570 }
3571
3572 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3573                                     SDValue V1, unsigned TargetMask,
3574                                     SelectionDAG &DAG) {
3575   switch(Opc) {
3576   default: llvm_unreachable("Unknown x86 shuffle node");
3577   case X86ISD::PSHUFD:
3578   case X86ISD::PSHUFHW:
3579   case X86ISD::PSHUFLW:
3580   case X86ISD::VPERMILP:
3581   case X86ISD::VPERMI:
3582     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3583   }
3584 }
3585
3586 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3587                                     SDValue V1, SDValue V2, unsigned TargetMask,
3588                                     SelectionDAG &DAG) {
3589   switch(Opc) {
3590   default: llvm_unreachable("Unknown x86 shuffle node");
3591   case X86ISD::PALIGNR:
3592   case X86ISD::VALIGN:
3593   case X86ISD::SHUFP:
3594   case X86ISD::VPERM2X128:
3595     return DAG.getNode(Opc, dl, VT, V1, V2,
3596                        DAG.getConstant(TargetMask, MVT::i8));
3597   }
3598 }
3599
3600 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3601                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3602   switch(Opc) {
3603   default: llvm_unreachable("Unknown x86 shuffle node");
3604   case X86ISD::MOVLHPS:
3605   case X86ISD::MOVLHPD:
3606   case X86ISD::MOVHLPS:
3607   case X86ISD::MOVLPS:
3608   case X86ISD::MOVLPD:
3609   case X86ISD::MOVSS:
3610   case X86ISD::MOVSD:
3611   case X86ISD::UNPCKL:
3612   case X86ISD::UNPCKH:
3613     return DAG.getNode(Opc, dl, VT, V1, V2);
3614   }
3615 }
3616
3617 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3618   MachineFunction &MF = DAG.getMachineFunction();
3619   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3620       DAG.getSubtarget().getRegisterInfo());
3621   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3622   int ReturnAddrIndex = FuncInfo->getRAIndex();
3623
3624   if (ReturnAddrIndex == 0) {
3625     // Set up a frame object for the return address.
3626     unsigned SlotSize = RegInfo->getSlotSize();
3627     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3628                                                            -(int64_t)SlotSize,
3629                                                            false);
3630     FuncInfo->setRAIndex(ReturnAddrIndex);
3631   }
3632
3633   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3634 }
3635
3636 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3637                                        bool hasSymbolicDisplacement) {
3638   // Offset should fit into 32 bit immediate field.
3639   if (!isInt<32>(Offset))
3640     return false;
3641
3642   // If we don't have a symbolic displacement - we don't have any extra
3643   // restrictions.
3644   if (!hasSymbolicDisplacement)
3645     return true;
3646
3647   // FIXME: Some tweaks might be needed for medium code model.
3648   if (M != CodeModel::Small && M != CodeModel::Kernel)
3649     return false;
3650
3651   // For small code model we assume that latest object is 16MB before end of 31
3652   // bits boundary. We may also accept pretty large negative constants knowing
3653   // that all objects are in the positive half of address space.
3654   if (M == CodeModel::Small && Offset < 16*1024*1024)
3655     return true;
3656
3657   // For kernel code model we know that all object resist in the negative half
3658   // of 32bits address space. We may not accept negative offsets, since they may
3659   // be just off and we may accept pretty large positive ones.
3660   if (M == CodeModel::Kernel && Offset > 0)
3661     return true;
3662
3663   return false;
3664 }
3665
3666 /// isCalleePop - Determines whether the callee is required to pop its
3667 /// own arguments. Callee pop is necessary to support tail calls.
3668 bool X86::isCalleePop(CallingConv::ID CallingConv,
3669                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3670   switch (CallingConv) {
3671   default:
3672     return false;
3673   case CallingConv::X86_StdCall:
3674   case CallingConv::X86_FastCall:
3675   case CallingConv::X86_ThisCall:
3676     return !is64Bit;
3677   case CallingConv::Fast:
3678   case CallingConv::GHC:
3679   case CallingConv::HiPE:
3680     if (IsVarArg)
3681       return false;
3682     return TailCallOpt;
3683   }
3684 }
3685
3686 /// \brief Return true if the condition is an unsigned comparison operation.
3687 static bool isX86CCUnsigned(unsigned X86CC) {
3688   switch (X86CC) {
3689   default: llvm_unreachable("Invalid integer condition!");
3690   case X86::COND_E:     return true;
3691   case X86::COND_G:     return false;
3692   case X86::COND_GE:    return false;
3693   case X86::COND_L:     return false;
3694   case X86::COND_LE:    return false;
3695   case X86::COND_NE:    return true;
3696   case X86::COND_B:     return true;
3697   case X86::COND_A:     return true;
3698   case X86::COND_BE:    return true;
3699   case X86::COND_AE:    return true;
3700   }
3701   llvm_unreachable("covered switch fell through?!");
3702 }
3703
3704 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3705 /// specific condition code, returning the condition code and the LHS/RHS of the
3706 /// comparison to make.
3707 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3708                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3709   if (!isFP) {
3710     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3711       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3712         // X > -1   -> X == 0, jump !sign.
3713         RHS = DAG.getConstant(0, RHS.getValueType());
3714         return X86::COND_NS;
3715       }
3716       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3717         // X < 0   -> X == 0, jump on sign.
3718         return X86::COND_S;
3719       }
3720       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3721         // X < 1   -> X <= 0
3722         RHS = DAG.getConstant(0, RHS.getValueType());
3723         return X86::COND_LE;
3724       }
3725     }
3726
3727     switch (SetCCOpcode) {
3728     default: llvm_unreachable("Invalid integer condition!");
3729     case ISD::SETEQ:  return X86::COND_E;
3730     case ISD::SETGT:  return X86::COND_G;
3731     case ISD::SETGE:  return X86::COND_GE;
3732     case ISD::SETLT:  return X86::COND_L;
3733     case ISD::SETLE:  return X86::COND_LE;
3734     case ISD::SETNE:  return X86::COND_NE;
3735     case ISD::SETULT: return X86::COND_B;
3736     case ISD::SETUGT: return X86::COND_A;
3737     case ISD::SETULE: return X86::COND_BE;
3738     case ISD::SETUGE: return X86::COND_AE;
3739     }
3740   }
3741
3742   // First determine if it is required or is profitable to flip the operands.
3743
3744   // If LHS is a foldable load, but RHS is not, flip the condition.
3745   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3746       !ISD::isNON_EXTLoad(RHS.getNode())) {
3747     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3748     std::swap(LHS, RHS);
3749   }
3750
3751   switch (SetCCOpcode) {
3752   default: break;
3753   case ISD::SETOLT:
3754   case ISD::SETOLE:
3755   case ISD::SETUGT:
3756   case ISD::SETUGE:
3757     std::swap(LHS, RHS);
3758     break;
3759   }
3760
3761   // On a floating point condition, the flags are set as follows:
3762   // ZF  PF  CF   op
3763   //  0 | 0 | 0 | X > Y
3764   //  0 | 0 | 1 | X < Y
3765   //  1 | 0 | 0 | X == Y
3766   //  1 | 1 | 1 | unordered
3767   switch (SetCCOpcode) {
3768   default: llvm_unreachable("Condcode should be pre-legalized away");
3769   case ISD::SETUEQ:
3770   case ISD::SETEQ:   return X86::COND_E;
3771   case ISD::SETOLT:              // flipped
3772   case ISD::SETOGT:
3773   case ISD::SETGT:   return X86::COND_A;
3774   case ISD::SETOLE:              // flipped
3775   case ISD::SETOGE:
3776   case ISD::SETGE:   return X86::COND_AE;
3777   case ISD::SETUGT:              // flipped
3778   case ISD::SETULT:
3779   case ISD::SETLT:   return X86::COND_B;
3780   case ISD::SETUGE:              // flipped
3781   case ISD::SETULE:
3782   case ISD::SETLE:   return X86::COND_BE;
3783   case ISD::SETONE:
3784   case ISD::SETNE:   return X86::COND_NE;
3785   case ISD::SETUO:   return X86::COND_P;
3786   case ISD::SETO:    return X86::COND_NP;
3787   case ISD::SETOEQ:
3788   case ISD::SETUNE:  return X86::COND_INVALID;
3789   }
3790 }
3791
3792 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3793 /// code. Current x86 isa includes the following FP cmov instructions:
3794 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3795 static bool hasFPCMov(unsigned X86CC) {
3796   switch (X86CC) {
3797   default:
3798     return false;
3799   case X86::COND_B:
3800   case X86::COND_BE:
3801   case X86::COND_E:
3802   case X86::COND_P:
3803   case X86::COND_A:
3804   case X86::COND_AE:
3805   case X86::COND_NE:
3806   case X86::COND_NP:
3807     return true;
3808   }
3809 }
3810
3811 /// isFPImmLegal - Returns true if the target can instruction select the
3812 /// specified FP immediate natively. If false, the legalizer will
3813 /// materialize the FP immediate as a load from a constant pool.
3814 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3815   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3816     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3817       return true;
3818   }
3819   return false;
3820 }
3821
3822 /// \brief Returns true if it is beneficial to convert a load of a constant
3823 /// to just the constant itself.
3824 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3825                                                           Type *Ty) const {
3826   assert(Ty->isIntegerTy());
3827
3828   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3829   if (BitSize == 0 || BitSize > 64)
3830     return false;
3831   return true;
3832 }
3833
3834 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3835 /// the specified range (L, H].
3836 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3837   return (Val < 0) || (Val >= Low && Val < Hi);
3838 }
3839
3840 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3841 /// specified value.
3842 static bool isUndefOrEqual(int Val, int CmpVal) {
3843   return (Val < 0 || Val == CmpVal);
3844 }
3845
3846 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3847 /// from position Pos and ending in Pos+Size, falls within the specified
3848 /// sequential range (L, L+Pos]. or is undef.
3849 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3850                                        unsigned Pos, unsigned Size, int Low) {
3851   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3852     if (!isUndefOrEqual(Mask[i], Low))
3853       return false;
3854   return true;
3855 }
3856
3857 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3858 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3859 /// the second operand.
3860 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3861   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3862     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3863   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3864     return (Mask[0] < 2 && Mask[1] < 2);
3865   return false;
3866 }
3867
3868 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3869 /// is suitable for input to PSHUFHW.
3870 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3871   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3872     return false;
3873
3874   // Lower quadword copied in order or undef.
3875   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3876     return false;
3877
3878   // Upper quadword shuffled.
3879   for (unsigned i = 4; i != 8; ++i)
3880     if (!isUndefOrInRange(Mask[i], 4, 8))
3881       return false;
3882
3883   if (VT == MVT::v16i16) {
3884     // Lower quadword copied in order or undef.
3885     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3886       return false;
3887
3888     // Upper quadword shuffled.
3889     for (unsigned i = 12; i != 16; ++i)
3890       if (!isUndefOrInRange(Mask[i], 12, 16))
3891         return false;
3892   }
3893
3894   return true;
3895 }
3896
3897 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3898 /// is suitable for input to PSHUFLW.
3899 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3900   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3901     return false;
3902
3903   // Upper quadword copied in order.
3904   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3905     return false;
3906
3907   // Lower quadword shuffled.
3908   for (unsigned i = 0; i != 4; ++i)
3909     if (!isUndefOrInRange(Mask[i], 0, 4))
3910       return false;
3911
3912   if (VT == MVT::v16i16) {
3913     // Upper quadword copied in order.
3914     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3915       return false;
3916
3917     // Lower quadword shuffled.
3918     for (unsigned i = 8; i != 12; ++i)
3919       if (!isUndefOrInRange(Mask[i], 8, 12))
3920         return false;
3921   }
3922
3923   return true;
3924 }
3925
3926 /// \brief Return true if the mask specifies a shuffle of elements that is
3927 /// suitable for input to intralane (palignr) or interlane (valign) vector
3928 /// right-shift.
3929 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3930   unsigned NumElts = VT.getVectorNumElements();
3931   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3932   unsigned NumLaneElts = NumElts/NumLanes;
3933
3934   // Do not handle 64-bit element shuffles with palignr.
3935   if (NumLaneElts == 2)
3936     return false;
3937
3938   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3939     unsigned i;
3940     for (i = 0; i != NumLaneElts; ++i) {
3941       if (Mask[i+l] >= 0)
3942         break;
3943     }
3944
3945     // Lane is all undef, go to next lane
3946     if (i == NumLaneElts)
3947       continue;
3948
3949     int Start = Mask[i+l];
3950
3951     // Make sure its in this lane in one of the sources
3952     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3953         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3954       return false;
3955
3956     // If not lane 0, then we must match lane 0
3957     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3958       return false;
3959
3960     // Correct second source to be contiguous with first source
3961     if (Start >= (int)NumElts)
3962       Start -= NumElts - NumLaneElts;
3963
3964     // Make sure we're shifting in the right direction.
3965     if (Start <= (int)(i+l))
3966       return false;
3967
3968     Start -= i;
3969
3970     // Check the rest of the elements to see if they are consecutive.
3971     for (++i; i != NumLaneElts; ++i) {
3972       int Idx = Mask[i+l];
3973
3974       // Make sure its in this lane
3975       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3976           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3977         return false;
3978
3979       // If not lane 0, then we must match lane 0
3980       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3981         return false;
3982
3983       if (Idx >= (int)NumElts)
3984         Idx -= NumElts - NumLaneElts;
3985
3986       if (!isUndefOrEqual(Idx, Start+i))
3987         return false;
3988
3989     }
3990   }
3991
3992   return true;
3993 }
3994
3995 /// \brief Return true if the node specifies a shuffle of elements that is
3996 /// suitable for input to PALIGNR.
3997 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3998                           const X86Subtarget *Subtarget) {
3999   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4000       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4001       VT.is512BitVector())
4002     // FIXME: Add AVX512BW.
4003     return false;
4004
4005   return isAlignrMask(Mask, VT, false);
4006 }
4007
4008 /// \brief Return true if the node specifies a shuffle of elements that is
4009 /// suitable for input to VALIGN.
4010 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4011                           const X86Subtarget *Subtarget) {
4012   // FIXME: Add AVX512VL.
4013   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4014     return false;
4015   return isAlignrMask(Mask, VT, true);
4016 }
4017
4018 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4019 /// the two vector operands have swapped position.
4020 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4021                                      unsigned NumElems) {
4022   for (unsigned i = 0; i != NumElems; ++i) {
4023     int idx = Mask[i];
4024     if (idx < 0)
4025       continue;
4026     else if (idx < (int)NumElems)
4027       Mask[i] = idx + NumElems;
4028     else
4029       Mask[i] = idx - NumElems;
4030   }
4031 }
4032
4033 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4034 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4035 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4036 /// reverse of what x86 shuffles want.
4037 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4038
4039   unsigned NumElems = VT.getVectorNumElements();
4040   unsigned NumLanes = VT.getSizeInBits()/128;
4041   unsigned NumLaneElems = NumElems/NumLanes;
4042
4043   if (NumLaneElems != 2 && NumLaneElems != 4)
4044     return false;
4045
4046   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4047   bool symetricMaskRequired =
4048     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4049
4050   // VSHUFPSY divides the resulting vector into 4 chunks.
4051   // The sources are also splitted into 4 chunks, and each destination
4052   // chunk must come from a different source chunk.
4053   //
4054   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4055   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4056   //
4057   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4058   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4059   //
4060   // VSHUFPDY divides the resulting vector into 4 chunks.
4061   // The sources are also splitted into 4 chunks, and each destination
4062   // chunk must come from a different source chunk.
4063   //
4064   //  SRC1 =>      X3       X2       X1       X0
4065   //  SRC2 =>      Y3       Y2       Y1       Y0
4066   //
4067   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4068   //
4069   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4070   unsigned HalfLaneElems = NumLaneElems/2;
4071   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4072     for (unsigned i = 0; i != NumLaneElems; ++i) {
4073       int Idx = Mask[i+l];
4074       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4075       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4076         return false;
4077       // For VSHUFPSY, the mask of the second half must be the same as the
4078       // first but with the appropriate offsets. This works in the same way as
4079       // VPERMILPS works with masks.
4080       if (!symetricMaskRequired || Idx < 0)
4081         continue;
4082       if (MaskVal[i] < 0) {
4083         MaskVal[i] = Idx - l;
4084         continue;
4085       }
4086       if ((signed)(Idx - l) != MaskVal[i])
4087         return false;
4088     }
4089   }
4090
4091   return true;
4092 }
4093
4094 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4095 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4096 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4097   if (!VT.is128BitVector())
4098     return false;
4099
4100   unsigned NumElems = VT.getVectorNumElements();
4101
4102   if (NumElems != 4)
4103     return false;
4104
4105   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4106   return isUndefOrEqual(Mask[0], 6) &&
4107          isUndefOrEqual(Mask[1], 7) &&
4108          isUndefOrEqual(Mask[2], 2) &&
4109          isUndefOrEqual(Mask[3], 3);
4110 }
4111
4112 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4113 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4114 /// <2, 3, 2, 3>
4115 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4116   if (!VT.is128BitVector())
4117     return false;
4118
4119   unsigned NumElems = VT.getVectorNumElements();
4120
4121   if (NumElems != 4)
4122     return false;
4123
4124   return isUndefOrEqual(Mask[0], 2) &&
4125          isUndefOrEqual(Mask[1], 3) &&
4126          isUndefOrEqual(Mask[2], 2) &&
4127          isUndefOrEqual(Mask[3], 3);
4128 }
4129
4130 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4131 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4132 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4133   if (!VT.is128BitVector())
4134     return false;
4135
4136   unsigned NumElems = VT.getVectorNumElements();
4137
4138   if (NumElems != 2 && NumElems != 4)
4139     return false;
4140
4141   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4142     if (!isUndefOrEqual(Mask[i], i + NumElems))
4143       return false;
4144
4145   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4146     if (!isUndefOrEqual(Mask[i], i))
4147       return false;
4148
4149   return true;
4150 }
4151
4152 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4153 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4154 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4155   if (!VT.is128BitVector())
4156     return false;
4157
4158   unsigned NumElems = VT.getVectorNumElements();
4159
4160   if (NumElems != 2 && NumElems != 4)
4161     return false;
4162
4163   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4164     if (!isUndefOrEqual(Mask[i], i))
4165       return false;
4166
4167   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4168     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4169       return false;
4170
4171   return true;
4172 }
4173
4174 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4175 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4176 /// i. e: If all but one element come from the same vector.
4177 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4178   // TODO: Deal with AVX's VINSERTPS
4179   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4180     return false;
4181
4182   unsigned CorrectPosV1 = 0;
4183   unsigned CorrectPosV2 = 0;
4184   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4185     if (Mask[i] == -1) {
4186       ++CorrectPosV1;
4187       ++CorrectPosV2;
4188       continue;
4189     }
4190
4191     if (Mask[i] == i)
4192       ++CorrectPosV1;
4193     else if (Mask[i] == i + 4)
4194       ++CorrectPosV2;
4195   }
4196
4197   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4198     // We have 3 elements (undefs count as elements from any vector) from one
4199     // vector, and one from another.
4200     return true;
4201
4202   return false;
4203 }
4204
4205 //
4206 // Some special combinations that can be optimized.
4207 //
4208 static
4209 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4210                                SelectionDAG &DAG) {
4211   MVT VT = SVOp->getSimpleValueType(0);
4212   SDLoc dl(SVOp);
4213
4214   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4215     return SDValue();
4216
4217   ArrayRef<int> Mask = SVOp->getMask();
4218
4219   // These are the special masks that may be optimized.
4220   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4221   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4222   bool MatchEvenMask = true;
4223   bool MatchOddMask  = true;
4224   for (int i=0; i<8; ++i) {
4225     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4226       MatchEvenMask = false;
4227     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4228       MatchOddMask = false;
4229   }
4230
4231   if (!MatchEvenMask && !MatchOddMask)
4232     return SDValue();
4233
4234   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4235
4236   SDValue Op0 = SVOp->getOperand(0);
4237   SDValue Op1 = SVOp->getOperand(1);
4238
4239   if (MatchEvenMask) {
4240     // Shift the second operand right to 32 bits.
4241     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4242     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4243   } else {
4244     // Shift the first operand left to 32 bits.
4245     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4246     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4247   }
4248   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4249   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4250 }
4251
4252 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4253 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4254 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4255                          bool HasInt256, bool V2IsSplat = false) {
4256
4257   assert(VT.getSizeInBits() >= 128 &&
4258          "Unsupported vector type for unpckl");
4259
4260   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4261   unsigned NumLanes;
4262   unsigned NumOf256BitLanes;
4263   unsigned NumElts = VT.getVectorNumElements();
4264   if (VT.is256BitVector()) {
4265     if (NumElts != 4 && NumElts != 8 &&
4266         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4267     return false;
4268     NumLanes = 2;
4269     NumOf256BitLanes = 1;
4270   } else if (VT.is512BitVector()) {
4271     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4272            "Unsupported vector type for unpckh");
4273     NumLanes = 2;
4274     NumOf256BitLanes = 2;
4275   } else {
4276     NumLanes = 1;
4277     NumOf256BitLanes = 1;
4278   }
4279
4280   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4281   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4282
4283   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4284     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4285       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4286         int BitI  = Mask[l256*NumEltsInStride+l+i];
4287         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4288         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4289           return false;
4290         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4291           return false;
4292         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4293           return false;
4294       }
4295     }
4296   }
4297   return true;
4298 }
4299
4300 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4301 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4302 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4303                          bool HasInt256, bool V2IsSplat = false) {
4304   assert(VT.getSizeInBits() >= 128 &&
4305          "Unsupported vector type for unpckh");
4306
4307   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4308   unsigned NumLanes;
4309   unsigned NumOf256BitLanes;
4310   unsigned NumElts = VT.getVectorNumElements();
4311   if (VT.is256BitVector()) {
4312     if (NumElts != 4 && NumElts != 8 &&
4313         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4314     return false;
4315     NumLanes = 2;
4316     NumOf256BitLanes = 1;
4317   } else if (VT.is512BitVector()) {
4318     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4319            "Unsupported vector type for unpckh");
4320     NumLanes = 2;
4321     NumOf256BitLanes = 2;
4322   } else {
4323     NumLanes = 1;
4324     NumOf256BitLanes = 1;
4325   }
4326
4327   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4328   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4329
4330   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4331     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4332       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4333         int BitI  = Mask[l256*NumEltsInStride+l+i];
4334         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4335         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4336           return false;
4337         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4338           return false;
4339         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4340           return false;
4341       }
4342     }
4343   }
4344   return true;
4345 }
4346
4347 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4348 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4349 /// <0, 0, 1, 1>
4350 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4351   unsigned NumElts = VT.getVectorNumElements();
4352   bool Is256BitVec = VT.is256BitVector();
4353
4354   if (VT.is512BitVector())
4355     return false;
4356   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4357          "Unsupported vector type for unpckh");
4358
4359   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4360       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4361     return false;
4362
4363   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4364   // FIXME: Need a better way to get rid of this, there's no latency difference
4365   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4366   // the former later. We should also remove the "_undef" special mask.
4367   if (NumElts == 4 && Is256BitVec)
4368     return false;
4369
4370   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4371   // independently on 128-bit lanes.
4372   unsigned NumLanes = VT.getSizeInBits()/128;
4373   unsigned NumLaneElts = NumElts/NumLanes;
4374
4375   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4376     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4377       int BitI  = Mask[l+i];
4378       int BitI1 = Mask[l+i+1];
4379
4380       if (!isUndefOrEqual(BitI, j))
4381         return false;
4382       if (!isUndefOrEqual(BitI1, j))
4383         return false;
4384     }
4385   }
4386
4387   return true;
4388 }
4389
4390 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4391 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4392 /// <2, 2, 3, 3>
4393 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4394   unsigned NumElts = VT.getVectorNumElements();
4395
4396   if (VT.is512BitVector())
4397     return false;
4398
4399   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4400          "Unsupported vector type for unpckh");
4401
4402   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4403       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4404     return false;
4405
4406   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4407   // independently on 128-bit lanes.
4408   unsigned NumLanes = VT.getSizeInBits()/128;
4409   unsigned NumLaneElts = NumElts/NumLanes;
4410
4411   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4412     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4413       int BitI  = Mask[l+i];
4414       int BitI1 = Mask[l+i+1];
4415       if (!isUndefOrEqual(BitI, j))
4416         return false;
4417       if (!isUndefOrEqual(BitI1, j))
4418         return false;
4419     }
4420   }
4421   return true;
4422 }
4423
4424 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4425 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4426 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4427   if (!VT.is512BitVector())
4428     return false;
4429
4430   unsigned NumElts = VT.getVectorNumElements();
4431   unsigned HalfSize = NumElts/2;
4432   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4433     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4434       *Imm = 1;
4435       return true;
4436     }
4437   }
4438   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4439     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4440       *Imm = 0;
4441       return true;
4442     }
4443   }
4444   return false;
4445 }
4446
4447 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4448 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4449 /// MOVSD, and MOVD, i.e. setting the lowest element.
4450 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4451   if (VT.getVectorElementType().getSizeInBits() < 32)
4452     return false;
4453   if (!VT.is128BitVector())
4454     return false;
4455
4456   unsigned NumElts = VT.getVectorNumElements();
4457
4458   if (!isUndefOrEqual(Mask[0], NumElts))
4459     return false;
4460
4461   for (unsigned i = 1; i != NumElts; ++i)
4462     if (!isUndefOrEqual(Mask[i], i))
4463       return false;
4464
4465   return true;
4466 }
4467
4468 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4469 /// as permutations between 128-bit chunks or halves. As an example: this
4470 /// shuffle bellow:
4471 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4472 /// The first half comes from the second half of V1 and the second half from the
4473 /// the second half of V2.
4474 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4475   if (!HasFp256 || !VT.is256BitVector())
4476     return false;
4477
4478   // The shuffle result is divided into half A and half B. In total the two
4479   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4480   // B must come from C, D, E or F.
4481   unsigned HalfSize = VT.getVectorNumElements()/2;
4482   bool MatchA = false, MatchB = false;
4483
4484   // Check if A comes from one of C, D, E, F.
4485   for (unsigned Half = 0; Half != 4; ++Half) {
4486     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4487       MatchA = true;
4488       break;
4489     }
4490   }
4491
4492   // Check if B comes from one of C, D, E, F.
4493   for (unsigned Half = 0; Half != 4; ++Half) {
4494     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4495       MatchB = true;
4496       break;
4497     }
4498   }
4499
4500   return MatchA && MatchB;
4501 }
4502
4503 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4504 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4505 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4506   MVT VT = SVOp->getSimpleValueType(0);
4507
4508   unsigned HalfSize = VT.getVectorNumElements()/2;
4509
4510   unsigned FstHalf = 0, SndHalf = 0;
4511   for (unsigned i = 0; i < HalfSize; ++i) {
4512     if (SVOp->getMaskElt(i) > 0) {
4513       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4514       break;
4515     }
4516   }
4517   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4518     if (SVOp->getMaskElt(i) > 0) {
4519       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4520       break;
4521     }
4522   }
4523
4524   return (FstHalf | (SndHalf << 4));
4525 }
4526
4527 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4528 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4529   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4530   if (EltSize < 32)
4531     return false;
4532
4533   unsigned NumElts = VT.getVectorNumElements();
4534   Imm8 = 0;
4535   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4536     for (unsigned i = 0; i != NumElts; ++i) {
4537       if (Mask[i] < 0)
4538         continue;
4539       Imm8 |= Mask[i] << (i*2);
4540     }
4541     return true;
4542   }
4543
4544   unsigned LaneSize = 4;
4545   SmallVector<int, 4> MaskVal(LaneSize, -1);
4546
4547   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4548     for (unsigned i = 0; i != LaneSize; ++i) {
4549       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4550         return false;
4551       if (Mask[i+l] < 0)
4552         continue;
4553       if (MaskVal[i] < 0) {
4554         MaskVal[i] = Mask[i+l] - l;
4555         Imm8 |= MaskVal[i] << (i*2);
4556         continue;
4557       }
4558       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4559         return false;
4560     }
4561   }
4562   return true;
4563 }
4564
4565 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4566 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4567 /// Note that VPERMIL mask matching is different depending whether theunderlying
4568 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4569 /// to the same elements of the low, but to the higher half of the source.
4570 /// In VPERMILPD the two lanes could be shuffled independently of each other
4571 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4572 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4573   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4574   if (VT.getSizeInBits() < 256 || EltSize < 32)
4575     return false;
4576   bool symetricMaskRequired = (EltSize == 32);
4577   unsigned NumElts = VT.getVectorNumElements();
4578
4579   unsigned NumLanes = VT.getSizeInBits()/128;
4580   unsigned LaneSize = NumElts/NumLanes;
4581   // 2 or 4 elements in one lane
4582
4583   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4584   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4585     for (unsigned i = 0; i != LaneSize; ++i) {
4586       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4587         return false;
4588       if (symetricMaskRequired) {
4589         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4590           ExpectedMaskVal[i] = Mask[i+l] - l;
4591           continue;
4592         }
4593         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4594           return false;
4595       }
4596     }
4597   }
4598   return true;
4599 }
4600
4601 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4602 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4603 /// element of vector 2 and the other elements to come from vector 1 in order.
4604 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4605                                bool V2IsSplat = false, bool V2IsUndef = false) {
4606   if (!VT.is128BitVector())
4607     return false;
4608
4609   unsigned NumOps = VT.getVectorNumElements();
4610   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4611     return false;
4612
4613   if (!isUndefOrEqual(Mask[0], 0))
4614     return false;
4615
4616   for (unsigned i = 1; i != NumOps; ++i)
4617     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4618           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4619           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4620       return false;
4621
4622   return true;
4623 }
4624
4625 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4626 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4627 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4628 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4629                            const X86Subtarget *Subtarget) {
4630   if (!Subtarget->hasSSE3())
4631     return false;
4632
4633   unsigned NumElems = VT.getVectorNumElements();
4634
4635   if ((VT.is128BitVector() && NumElems != 4) ||
4636       (VT.is256BitVector() && NumElems != 8) ||
4637       (VT.is512BitVector() && NumElems != 16))
4638     return false;
4639
4640   // "i+1" is the value the indexed mask element must have
4641   for (unsigned i = 0; i != NumElems; i += 2)
4642     if (!isUndefOrEqual(Mask[i], i+1) ||
4643         !isUndefOrEqual(Mask[i+1], i+1))
4644       return false;
4645
4646   return true;
4647 }
4648
4649 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4650 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4651 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4652 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4653                            const X86Subtarget *Subtarget) {
4654   if (!Subtarget->hasSSE3())
4655     return false;
4656
4657   unsigned NumElems = VT.getVectorNumElements();
4658
4659   if ((VT.is128BitVector() && NumElems != 4) ||
4660       (VT.is256BitVector() && NumElems != 8) ||
4661       (VT.is512BitVector() && NumElems != 16))
4662     return false;
4663
4664   // "i" is the value the indexed mask element must have
4665   for (unsigned i = 0; i != NumElems; i += 2)
4666     if (!isUndefOrEqual(Mask[i], i) ||
4667         !isUndefOrEqual(Mask[i+1], i))
4668       return false;
4669
4670   return true;
4671 }
4672
4673 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4674 /// specifies a shuffle of elements that is suitable for input to 256-bit
4675 /// version of MOVDDUP.
4676 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4677   if (!HasFp256 || !VT.is256BitVector())
4678     return false;
4679
4680   unsigned NumElts = VT.getVectorNumElements();
4681   if (NumElts != 4)
4682     return false;
4683
4684   for (unsigned i = 0; i != NumElts/2; ++i)
4685     if (!isUndefOrEqual(Mask[i], 0))
4686       return false;
4687   for (unsigned i = NumElts/2; i != NumElts; ++i)
4688     if (!isUndefOrEqual(Mask[i], NumElts/2))
4689       return false;
4690   return true;
4691 }
4692
4693 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4694 /// specifies a shuffle of elements that is suitable for input to 128-bit
4695 /// version of MOVDDUP.
4696 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4697   if (!VT.is128BitVector())
4698     return false;
4699
4700   unsigned e = VT.getVectorNumElements() / 2;
4701   for (unsigned i = 0; i != e; ++i)
4702     if (!isUndefOrEqual(Mask[i], i))
4703       return false;
4704   for (unsigned i = 0; i != e; ++i)
4705     if (!isUndefOrEqual(Mask[e+i], i))
4706       return false;
4707   return true;
4708 }
4709
4710 /// isVEXTRACTIndex - Return true if the specified
4711 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4712 /// suitable for instruction that extract 128 or 256 bit vectors
4713 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4714   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4715   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4716     return false;
4717
4718   // The index should be aligned on a vecWidth-bit boundary.
4719   uint64_t Index =
4720     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4721
4722   MVT VT = N->getSimpleValueType(0);
4723   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4724   bool Result = (Index * ElSize) % vecWidth == 0;
4725
4726   return Result;
4727 }
4728
4729 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4730 /// operand specifies a subvector insert that is suitable for input to
4731 /// insertion of 128 or 256-bit subvectors
4732 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4733   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4734   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4735     return false;
4736   // The index should be aligned on a vecWidth-bit boundary.
4737   uint64_t Index =
4738     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4739
4740   MVT VT = N->getSimpleValueType(0);
4741   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4742   bool Result = (Index * ElSize) % vecWidth == 0;
4743
4744   return Result;
4745 }
4746
4747 bool X86::isVINSERT128Index(SDNode *N) {
4748   return isVINSERTIndex(N, 128);
4749 }
4750
4751 bool X86::isVINSERT256Index(SDNode *N) {
4752   return isVINSERTIndex(N, 256);
4753 }
4754
4755 bool X86::isVEXTRACT128Index(SDNode *N) {
4756   return isVEXTRACTIndex(N, 128);
4757 }
4758
4759 bool X86::isVEXTRACT256Index(SDNode *N) {
4760   return isVEXTRACTIndex(N, 256);
4761 }
4762
4763 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4764 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4765 /// Handles 128-bit and 256-bit.
4766 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4767   MVT VT = N->getSimpleValueType(0);
4768
4769   assert((VT.getSizeInBits() >= 128) &&
4770          "Unsupported vector type for PSHUF/SHUFP");
4771
4772   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4773   // independently on 128-bit lanes.
4774   unsigned NumElts = VT.getVectorNumElements();
4775   unsigned NumLanes = VT.getSizeInBits()/128;
4776   unsigned NumLaneElts = NumElts/NumLanes;
4777
4778   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4779          "Only supports 2, 4 or 8 elements per lane");
4780
4781   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4782   unsigned Mask = 0;
4783   for (unsigned i = 0; i != NumElts; ++i) {
4784     int Elt = N->getMaskElt(i);
4785     if (Elt < 0) continue;
4786     Elt &= NumLaneElts - 1;
4787     unsigned ShAmt = (i << Shift) % 8;
4788     Mask |= Elt << ShAmt;
4789   }
4790
4791   return Mask;
4792 }
4793
4794 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4795 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4796 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4797   MVT VT = N->getSimpleValueType(0);
4798
4799   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4800          "Unsupported vector type for PSHUFHW");
4801
4802   unsigned NumElts = VT.getVectorNumElements();
4803
4804   unsigned Mask = 0;
4805   for (unsigned l = 0; l != NumElts; l += 8) {
4806     // 8 nodes per lane, but we only care about the last 4.
4807     for (unsigned i = 0; i < 4; ++i) {
4808       int Elt = N->getMaskElt(l+i+4);
4809       if (Elt < 0) continue;
4810       Elt &= 0x3; // only 2-bits.
4811       Mask |= Elt << (i * 2);
4812     }
4813   }
4814
4815   return Mask;
4816 }
4817
4818 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4819 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4820 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4821   MVT VT = N->getSimpleValueType(0);
4822
4823   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4824          "Unsupported vector type for PSHUFHW");
4825
4826   unsigned NumElts = VT.getVectorNumElements();
4827
4828   unsigned Mask = 0;
4829   for (unsigned l = 0; l != NumElts; l += 8) {
4830     // 8 nodes per lane, but we only care about the first 4.
4831     for (unsigned i = 0; i < 4; ++i) {
4832       int Elt = N->getMaskElt(l+i);
4833       if (Elt < 0) continue;
4834       Elt &= 0x3; // only 2-bits
4835       Mask |= Elt << (i * 2);
4836     }
4837   }
4838
4839   return Mask;
4840 }
4841
4842 /// \brief Return the appropriate immediate to shuffle the specified
4843 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4844 /// VALIGN (if Interlane is true) instructions.
4845 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4846                                            bool InterLane) {
4847   MVT VT = SVOp->getSimpleValueType(0);
4848   unsigned EltSize = InterLane ? 1 :
4849     VT.getVectorElementType().getSizeInBits() >> 3;
4850
4851   unsigned NumElts = VT.getVectorNumElements();
4852   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4853   unsigned NumLaneElts = NumElts/NumLanes;
4854
4855   int Val = 0;
4856   unsigned i;
4857   for (i = 0; i != NumElts; ++i) {
4858     Val = SVOp->getMaskElt(i);
4859     if (Val >= 0)
4860       break;
4861   }
4862   if (Val >= (int)NumElts)
4863     Val -= NumElts - NumLaneElts;
4864
4865   assert(Val - i > 0 && "PALIGNR imm should be positive");
4866   return (Val - i) * EltSize;
4867 }
4868
4869 /// \brief Return the appropriate immediate to shuffle the specified
4870 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4871 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4872   return getShuffleAlignrImmediate(SVOp, false);
4873 }
4874
4875 /// \brief Return the appropriate immediate to shuffle the specified
4876 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4877 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4878   return getShuffleAlignrImmediate(SVOp, true);
4879 }
4880
4881
4882 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4883   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4884   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4885     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4886
4887   uint64_t Index =
4888     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4889
4890   MVT VecVT = N->getOperand(0).getSimpleValueType();
4891   MVT ElVT = VecVT.getVectorElementType();
4892
4893   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4894   return Index / NumElemsPerChunk;
4895 }
4896
4897 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4898   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4899   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4900     llvm_unreachable("Illegal insert subvector for VINSERT");
4901
4902   uint64_t Index =
4903     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4904
4905   MVT VecVT = N->getSimpleValueType(0);
4906   MVT ElVT = VecVT.getVectorElementType();
4907
4908   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4909   return Index / NumElemsPerChunk;
4910 }
4911
4912 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4913 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4914 /// and VINSERTI128 instructions.
4915 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4916   return getExtractVEXTRACTImmediate(N, 128);
4917 }
4918
4919 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4920 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4921 /// and VINSERTI64x4 instructions.
4922 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4923   return getExtractVEXTRACTImmediate(N, 256);
4924 }
4925
4926 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4927 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4928 /// and VINSERTI128 instructions.
4929 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4930   return getInsertVINSERTImmediate(N, 128);
4931 }
4932
4933 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4934 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4935 /// and VINSERTI64x4 instructions.
4936 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4937   return getInsertVINSERTImmediate(N, 256);
4938 }
4939
4940 /// isZero - Returns true if Elt is a constant integer zero
4941 static bool isZero(SDValue V) {
4942   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4943   return C && C->isNullValue();
4944 }
4945
4946 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4947 /// constant +0.0.
4948 bool X86::isZeroNode(SDValue Elt) {
4949   if (isZero(Elt))
4950     return true;
4951   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4952     return CFP->getValueAPF().isPosZero();
4953   return false;
4954 }
4955
4956 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4957 /// match movhlps. The lower half elements should come from upper half of
4958 /// V1 (and in order), and the upper half elements should come from the upper
4959 /// half of V2 (and in order).
4960 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4961   if (!VT.is128BitVector())
4962     return false;
4963   if (VT.getVectorNumElements() != 4)
4964     return false;
4965   for (unsigned i = 0, e = 2; i != e; ++i)
4966     if (!isUndefOrEqual(Mask[i], i+2))
4967       return false;
4968   for (unsigned i = 2; i != 4; ++i)
4969     if (!isUndefOrEqual(Mask[i], i+4))
4970       return false;
4971   return true;
4972 }
4973
4974 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4975 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4976 /// required.
4977 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4978   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4979     return false;
4980   N = N->getOperand(0).getNode();
4981   if (!ISD::isNON_EXTLoad(N))
4982     return false;
4983   if (LD)
4984     *LD = cast<LoadSDNode>(N);
4985   return true;
4986 }
4987
4988 // Test whether the given value is a vector value which will be legalized
4989 // into a load.
4990 static bool WillBeConstantPoolLoad(SDNode *N) {
4991   if (N->getOpcode() != ISD::BUILD_VECTOR)
4992     return false;
4993
4994   // Check for any non-constant elements.
4995   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4996     switch (N->getOperand(i).getNode()->getOpcode()) {
4997     case ISD::UNDEF:
4998     case ISD::ConstantFP:
4999     case ISD::Constant:
5000       break;
5001     default:
5002       return false;
5003     }
5004
5005   // Vectors of all-zeros and all-ones are materialized with special
5006   // instructions rather than being loaded.
5007   return !ISD::isBuildVectorAllZeros(N) &&
5008          !ISD::isBuildVectorAllOnes(N);
5009 }
5010
5011 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5012 /// match movlp{s|d}. The lower half elements should come from lower half of
5013 /// V1 (and in order), and the upper half elements should come from the upper
5014 /// half of V2 (and in order). And since V1 will become the source of the
5015 /// MOVLP, it must be either a vector load or a scalar load to vector.
5016 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5017                                ArrayRef<int> Mask, MVT VT) {
5018   if (!VT.is128BitVector())
5019     return false;
5020
5021   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5022     return false;
5023   // Is V2 is a vector load, don't do this transformation. We will try to use
5024   // load folding shufps op.
5025   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5026     return false;
5027
5028   unsigned NumElems = VT.getVectorNumElements();
5029
5030   if (NumElems != 2 && NumElems != 4)
5031     return false;
5032   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5033     if (!isUndefOrEqual(Mask[i], i))
5034       return false;
5035   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5036     if (!isUndefOrEqual(Mask[i], i+NumElems))
5037       return false;
5038   return true;
5039 }
5040
5041 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5042 /// to an zero vector.
5043 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5044 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5045   SDValue V1 = N->getOperand(0);
5046   SDValue V2 = N->getOperand(1);
5047   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5048   for (unsigned i = 0; i != NumElems; ++i) {
5049     int Idx = N->getMaskElt(i);
5050     if (Idx >= (int)NumElems) {
5051       unsigned Opc = V2.getOpcode();
5052       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5053         continue;
5054       if (Opc != ISD::BUILD_VECTOR ||
5055           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5056         return false;
5057     } else if (Idx >= 0) {
5058       unsigned Opc = V1.getOpcode();
5059       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5060         continue;
5061       if (Opc != ISD::BUILD_VECTOR ||
5062           !X86::isZeroNode(V1.getOperand(Idx)))
5063         return false;
5064     }
5065   }
5066   return true;
5067 }
5068
5069 /// getZeroVector - Returns a vector of specified type with all zero elements.
5070 ///
5071 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5072                              SelectionDAG &DAG, SDLoc dl) {
5073   assert(VT.isVector() && "Expected a vector type");
5074
5075   // Always build SSE zero vectors as <4 x i32> bitcasted
5076   // to their dest type. This ensures they get CSE'd.
5077   SDValue Vec;
5078   if (VT.is128BitVector()) {  // SSE
5079     if (Subtarget->hasSSE2()) {  // SSE2
5080       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5081       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5082     } else { // SSE1
5083       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5084       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5085     }
5086   } else if (VT.is256BitVector()) { // AVX
5087     if (Subtarget->hasInt256()) { // AVX2
5088       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5089       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5090       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5091     } else {
5092       // 256-bit logic and arithmetic instructions in AVX are all
5093       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5094       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5095       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5096       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5097     }
5098   } else if (VT.is512BitVector()) { // AVX-512
5099       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5100       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5101                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5102       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5103   } else if (VT.getScalarType() == MVT::i1) {
5104     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5105     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5106     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5107     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5108   } else
5109     llvm_unreachable("Unexpected vector type");
5110
5111   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5112 }
5113
5114 /// getOnesVector - Returns a vector of specified type with all bits set.
5115 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5116 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5117 /// Then bitcast to their original type, ensuring they get CSE'd.
5118 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5119                              SDLoc dl) {
5120   assert(VT.isVector() && "Expected a vector type");
5121
5122   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5123   SDValue Vec;
5124   if (VT.is256BitVector()) {
5125     if (HasInt256) { // AVX2
5126       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5127       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5128     } else { // AVX
5129       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5130       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5131     }
5132   } else if (VT.is128BitVector()) {
5133     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5134   } else
5135     llvm_unreachable("Unexpected vector type");
5136
5137   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5138 }
5139
5140 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5141 /// that point to V2 points to its first element.
5142 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5143   for (unsigned i = 0; i != NumElems; ++i) {
5144     if (Mask[i] > (int)NumElems) {
5145       Mask[i] = NumElems;
5146     }
5147   }
5148 }
5149
5150 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5151 /// operation of specified width.
5152 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5153                        SDValue V2) {
5154   unsigned NumElems = VT.getVectorNumElements();
5155   SmallVector<int, 8> Mask;
5156   Mask.push_back(NumElems);
5157   for (unsigned i = 1; i != NumElems; ++i)
5158     Mask.push_back(i);
5159   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5160 }
5161
5162 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5163 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5164                           SDValue V2) {
5165   unsigned NumElems = VT.getVectorNumElements();
5166   SmallVector<int, 8> Mask;
5167   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5168     Mask.push_back(i);
5169     Mask.push_back(i + NumElems);
5170   }
5171   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5172 }
5173
5174 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5175 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5176                           SDValue V2) {
5177   unsigned NumElems = VT.getVectorNumElements();
5178   SmallVector<int, 8> Mask;
5179   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5180     Mask.push_back(i + Half);
5181     Mask.push_back(i + NumElems + Half);
5182   }
5183   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5184 }
5185
5186 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5187 // a generic shuffle instruction because the target has no such instructions.
5188 // Generate shuffles which repeat i16 and i8 several times until they can be
5189 // represented by v4f32 and then be manipulated by target suported shuffles.
5190 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5191   MVT VT = V.getSimpleValueType();
5192   int NumElems = VT.getVectorNumElements();
5193   SDLoc dl(V);
5194
5195   while (NumElems > 4) {
5196     if (EltNo < NumElems/2) {
5197       V = getUnpackl(DAG, dl, VT, V, V);
5198     } else {
5199       V = getUnpackh(DAG, dl, VT, V, V);
5200       EltNo -= NumElems/2;
5201     }
5202     NumElems >>= 1;
5203   }
5204   return V;
5205 }
5206
5207 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5208 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5209   MVT VT = V.getSimpleValueType();
5210   SDLoc dl(V);
5211
5212   if (VT.is128BitVector()) {
5213     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5214     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5215     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5216                              &SplatMask[0]);
5217   } else if (VT.is256BitVector()) {
5218     // To use VPERMILPS to splat scalars, the second half of indicies must
5219     // refer to the higher part, which is a duplication of the lower one,
5220     // because VPERMILPS can only handle in-lane permutations.
5221     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5222                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5223
5224     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5225     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5226                              &SplatMask[0]);
5227   } else
5228     llvm_unreachable("Vector size not supported");
5229
5230   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5231 }
5232
5233 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5234 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5235   MVT SrcVT = SV->getSimpleValueType(0);
5236   SDValue V1 = SV->getOperand(0);
5237   SDLoc dl(SV);
5238
5239   int EltNo = SV->getSplatIndex();
5240   int NumElems = SrcVT.getVectorNumElements();
5241   bool Is256BitVec = SrcVT.is256BitVector();
5242
5243   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5244          "Unknown how to promote splat for type");
5245
5246   // Extract the 128-bit part containing the splat element and update
5247   // the splat element index when it refers to the higher register.
5248   if (Is256BitVec) {
5249     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5250     if (EltNo >= NumElems/2)
5251       EltNo -= NumElems/2;
5252   }
5253
5254   // All i16 and i8 vector types can't be used directly by a generic shuffle
5255   // instruction because the target has no such instruction. Generate shuffles
5256   // which repeat i16 and i8 several times until they fit in i32, and then can
5257   // be manipulated by target suported shuffles.
5258   MVT EltVT = SrcVT.getVectorElementType();
5259   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5260     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5261
5262   // Recreate the 256-bit vector and place the same 128-bit vector
5263   // into the low and high part. This is necessary because we want
5264   // to use VPERM* to shuffle the vectors
5265   if (Is256BitVec) {
5266     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5267   }
5268
5269   return getLegalSplat(DAG, V1, EltNo);
5270 }
5271
5272 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5273 /// vector of zero or undef vector.  This produces a shuffle where the low
5274 /// element of V2 is swizzled into the zero/undef vector, landing at element
5275 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5276 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5277                                            bool IsZero,
5278                                            const X86Subtarget *Subtarget,
5279                                            SelectionDAG &DAG) {
5280   MVT VT = V2.getSimpleValueType();
5281   SDValue V1 = IsZero
5282     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5283   unsigned NumElems = VT.getVectorNumElements();
5284   SmallVector<int, 16> MaskVec;
5285   for (unsigned i = 0; i != NumElems; ++i)
5286     // If this is the insertion idx, put the low elt of V2 here.
5287     MaskVec.push_back(i == Idx ? NumElems : i);
5288   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5289 }
5290
5291 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5292 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5293 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5294 /// shuffles which use a single input multiple times, and in those cases it will
5295 /// adjust the mask to only have indices within that single input.
5296 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5297                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5298   unsigned NumElems = VT.getVectorNumElements();
5299   SDValue ImmN;
5300
5301   IsUnary = false;
5302   bool IsFakeUnary = false;
5303   switch(N->getOpcode()) {
5304   case X86ISD::SHUFP:
5305     ImmN = N->getOperand(N->getNumOperands()-1);
5306     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5307     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5308     break;
5309   case X86ISD::UNPCKH:
5310     DecodeUNPCKHMask(VT, Mask);
5311     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5312     break;
5313   case X86ISD::UNPCKL:
5314     DecodeUNPCKLMask(VT, Mask);
5315     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5316     break;
5317   case X86ISD::MOVHLPS:
5318     DecodeMOVHLPSMask(NumElems, Mask);
5319     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5320     break;
5321   case X86ISD::MOVLHPS:
5322     DecodeMOVLHPSMask(NumElems, Mask);
5323     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5324     break;
5325   case X86ISD::PALIGNR:
5326     ImmN = N->getOperand(N->getNumOperands()-1);
5327     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5328     break;
5329   case X86ISD::PSHUFD:
5330   case X86ISD::VPERMILP:
5331     ImmN = N->getOperand(N->getNumOperands()-1);
5332     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5333     IsUnary = true;
5334     break;
5335   case X86ISD::PSHUFHW:
5336     ImmN = N->getOperand(N->getNumOperands()-1);
5337     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5338     IsUnary = true;
5339     break;
5340   case X86ISD::PSHUFLW:
5341     ImmN = N->getOperand(N->getNumOperands()-1);
5342     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5343     IsUnary = true;
5344     break;
5345   case X86ISD::PSHUFB: {
5346     IsUnary = true;
5347     SDValue MaskNode = N->getOperand(1);
5348     while (MaskNode->getOpcode() == ISD::BITCAST)
5349       MaskNode = MaskNode->getOperand(0);
5350
5351     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5352       // If we have a build-vector, then things are easy.
5353       EVT VT = MaskNode.getValueType();
5354       assert(VT.isVector() &&
5355              "Can't produce a non-vector with a build_vector!");
5356       if (!VT.isInteger())
5357         return false;
5358
5359       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5360
5361       SmallVector<uint64_t, 32> RawMask;
5362       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5363         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5364         if (!CN)
5365           return false;
5366         APInt MaskElement = CN->getAPIntValue();
5367
5368         // We now have to decode the element which could be any integer size and
5369         // extract each byte of it.
5370         for (int j = 0; j < NumBytesPerElement; ++j) {
5371           // Note that this is x86 and so always little endian: the low byte is
5372           // the first byte of the mask.
5373           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5374           MaskElement = MaskElement.lshr(8);
5375         }
5376       }
5377       DecodePSHUFBMask(RawMask, Mask);
5378       break;
5379     }
5380
5381     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5382     if (!MaskLoad)
5383       return false;
5384
5385     SDValue Ptr = MaskLoad->getBasePtr();
5386     if (Ptr->getOpcode() == X86ISD::Wrapper)
5387       Ptr = Ptr->getOperand(0);
5388
5389     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5390     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5391       return false;
5392
5393     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5394       // FIXME: Support AVX-512 here.
5395       if (!C->getType()->isVectorTy() ||
5396           (C->getNumElements() != 16 && C->getNumElements() != 32))
5397         return false;
5398
5399       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5400       DecodePSHUFBMask(C, Mask);
5401       break;
5402     }
5403
5404     return false;
5405   }
5406   case X86ISD::VPERMI:
5407     ImmN = N->getOperand(N->getNumOperands()-1);
5408     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5409     IsUnary = true;
5410     break;
5411   case X86ISD::MOVSS:
5412   case X86ISD::MOVSD: {
5413     // The index 0 always comes from the first element of the second source,
5414     // this is why MOVSS and MOVSD are used in the first place. The other
5415     // elements come from the other positions of the first source vector
5416     Mask.push_back(NumElems);
5417     for (unsigned i = 1; i != NumElems; ++i) {
5418       Mask.push_back(i);
5419     }
5420     break;
5421   }
5422   case X86ISD::VPERM2X128:
5423     ImmN = N->getOperand(N->getNumOperands()-1);
5424     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5425     if (Mask.empty()) return false;
5426     break;
5427   case X86ISD::MOVDDUP:
5428   case X86ISD::MOVLHPD:
5429   case X86ISD::MOVLPD:
5430   case X86ISD::MOVLPS:
5431   case X86ISD::MOVSHDUP:
5432   case X86ISD::MOVSLDUP:
5433     // Not yet implemented
5434     return false;
5435   default: llvm_unreachable("unknown target shuffle node");
5436   }
5437
5438   // If we have a fake unary shuffle, the shuffle mask is spread across two
5439   // inputs that are actually the same node. Re-map the mask to always point
5440   // into the first input.
5441   if (IsFakeUnary)
5442     for (int &M : Mask)
5443       if (M >= (int)Mask.size())
5444         M -= Mask.size();
5445
5446   return true;
5447 }
5448
5449 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5450 /// element of the result of the vector shuffle.
5451 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5452                                    unsigned Depth) {
5453   if (Depth == 6)
5454     return SDValue();  // Limit search depth.
5455
5456   SDValue V = SDValue(N, 0);
5457   EVT VT = V.getValueType();
5458   unsigned Opcode = V.getOpcode();
5459
5460   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5461   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5462     int Elt = SV->getMaskElt(Index);
5463
5464     if (Elt < 0)
5465       return DAG.getUNDEF(VT.getVectorElementType());
5466
5467     unsigned NumElems = VT.getVectorNumElements();
5468     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5469                                          : SV->getOperand(1);
5470     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5471   }
5472
5473   // Recurse into target specific vector shuffles to find scalars.
5474   if (isTargetShuffle(Opcode)) {
5475     MVT ShufVT = V.getSimpleValueType();
5476     unsigned NumElems = ShufVT.getVectorNumElements();
5477     SmallVector<int, 16> ShuffleMask;
5478     bool IsUnary;
5479
5480     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5481       return SDValue();
5482
5483     int Elt = ShuffleMask[Index];
5484     if (Elt < 0)
5485       return DAG.getUNDEF(ShufVT.getVectorElementType());
5486
5487     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5488                                          : N->getOperand(1);
5489     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5490                                Depth+1);
5491   }
5492
5493   // Actual nodes that may contain scalar elements
5494   if (Opcode == ISD::BITCAST) {
5495     V = V.getOperand(0);
5496     EVT SrcVT = V.getValueType();
5497     unsigned NumElems = VT.getVectorNumElements();
5498
5499     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5500       return SDValue();
5501   }
5502
5503   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5504     return (Index == 0) ? V.getOperand(0)
5505                         : DAG.getUNDEF(VT.getVectorElementType());
5506
5507   if (V.getOpcode() == ISD::BUILD_VECTOR)
5508     return V.getOperand(Index);
5509
5510   return SDValue();
5511 }
5512
5513 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5514 /// shuffle operation which come from a consecutively from a zero. The
5515 /// search can start in two different directions, from left or right.
5516 /// We count undefs as zeros until PreferredNum is reached.
5517 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5518                                          unsigned NumElems, bool ZerosFromLeft,
5519                                          SelectionDAG &DAG,
5520                                          unsigned PreferredNum = -1U) {
5521   unsigned NumZeros = 0;
5522   for (unsigned i = 0; i != NumElems; ++i) {
5523     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5524     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5525     if (!Elt.getNode())
5526       break;
5527
5528     if (X86::isZeroNode(Elt))
5529       ++NumZeros;
5530     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5531       NumZeros = std::min(NumZeros + 1, PreferredNum);
5532     else
5533       break;
5534   }
5535
5536   return NumZeros;
5537 }
5538
5539 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5540 /// correspond consecutively to elements from one of the vector operands,
5541 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5542 static
5543 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5544                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5545                               unsigned NumElems, unsigned &OpNum) {
5546   bool SeenV1 = false;
5547   bool SeenV2 = false;
5548
5549   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5550     int Idx = SVOp->getMaskElt(i);
5551     // Ignore undef indicies
5552     if (Idx < 0)
5553       continue;
5554
5555     if (Idx < (int)NumElems)
5556       SeenV1 = true;
5557     else
5558       SeenV2 = true;
5559
5560     // Only accept consecutive elements from the same vector
5561     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5562       return false;
5563   }
5564
5565   OpNum = SeenV1 ? 0 : 1;
5566   return true;
5567 }
5568
5569 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5570 /// logical left shift of a vector.
5571 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5572                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5573   unsigned NumElems =
5574     SVOp->getSimpleValueType(0).getVectorNumElements();
5575   unsigned NumZeros = getNumOfConsecutiveZeros(
5576       SVOp, NumElems, false /* check zeros from right */, DAG,
5577       SVOp->getMaskElt(0));
5578   unsigned OpSrc;
5579
5580   if (!NumZeros)
5581     return false;
5582
5583   // Considering the elements in the mask that are not consecutive zeros,
5584   // check if they consecutively come from only one of the source vectors.
5585   //
5586   //               V1 = {X, A, B, C}     0
5587   //                         \  \  \    /
5588   //   vector_shuffle V1, V2 <1, 2, 3, X>
5589   //
5590   if (!isShuffleMaskConsecutive(SVOp,
5591             0,                   // Mask Start Index
5592             NumElems-NumZeros,   // Mask End Index(exclusive)
5593             NumZeros,            // Where to start looking in the src vector
5594             NumElems,            // Number of elements in vector
5595             OpSrc))              // Which source operand ?
5596     return false;
5597
5598   isLeft = false;
5599   ShAmt = NumZeros;
5600   ShVal = SVOp->getOperand(OpSrc);
5601   return true;
5602 }
5603
5604 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5605 /// logical left shift of a vector.
5606 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5607                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5608   unsigned NumElems =
5609     SVOp->getSimpleValueType(0).getVectorNumElements();
5610   unsigned NumZeros = getNumOfConsecutiveZeros(
5611       SVOp, NumElems, true /* check zeros from left */, DAG,
5612       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5613   unsigned OpSrc;
5614
5615   if (!NumZeros)
5616     return false;
5617
5618   // Considering the elements in the mask that are not consecutive zeros,
5619   // check if they consecutively come from only one of the source vectors.
5620   //
5621   //                           0    { A, B, X, X } = V2
5622   //                          / \    /  /
5623   //   vector_shuffle V1, V2 <X, X, 4, 5>
5624   //
5625   if (!isShuffleMaskConsecutive(SVOp,
5626             NumZeros,     // Mask Start Index
5627             NumElems,     // Mask End Index(exclusive)
5628             0,            // Where to start looking in the src vector
5629             NumElems,     // Number of elements in vector
5630             OpSrc))       // Which source operand ?
5631     return false;
5632
5633   isLeft = true;
5634   ShAmt = NumZeros;
5635   ShVal = SVOp->getOperand(OpSrc);
5636   return true;
5637 }
5638
5639 /// isVectorShift - Returns true if the shuffle can be implemented as a
5640 /// logical left or right shift of a vector.
5641 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5642                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5643   // Although the logic below support any bitwidth size, there are no
5644   // shift instructions which handle more than 128-bit vectors.
5645   if (!SVOp->getSimpleValueType(0).is128BitVector())
5646     return false;
5647
5648   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5649       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5650     return true;
5651
5652   return false;
5653 }
5654
5655 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5656 ///
5657 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5658                                        unsigned NumNonZero, unsigned NumZero,
5659                                        SelectionDAG &DAG,
5660                                        const X86Subtarget* Subtarget,
5661                                        const TargetLowering &TLI) {
5662   if (NumNonZero > 8)
5663     return SDValue();
5664
5665   SDLoc dl(Op);
5666   SDValue V;
5667   bool First = true;
5668   for (unsigned i = 0; i < 16; ++i) {
5669     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5670     if (ThisIsNonZero && First) {
5671       if (NumZero)
5672         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5673       else
5674         V = DAG.getUNDEF(MVT::v8i16);
5675       First = false;
5676     }
5677
5678     if ((i & 1) != 0) {
5679       SDValue ThisElt, LastElt;
5680       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5681       if (LastIsNonZero) {
5682         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5683                               MVT::i16, Op.getOperand(i-1));
5684       }
5685       if (ThisIsNonZero) {
5686         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5687         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5688                               ThisElt, DAG.getConstant(8, MVT::i8));
5689         if (LastIsNonZero)
5690           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5691       } else
5692         ThisElt = LastElt;
5693
5694       if (ThisElt.getNode())
5695         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5696                         DAG.getIntPtrConstant(i/2));
5697     }
5698   }
5699
5700   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5701 }
5702
5703 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5704 ///
5705 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5706                                      unsigned NumNonZero, unsigned NumZero,
5707                                      SelectionDAG &DAG,
5708                                      const X86Subtarget* Subtarget,
5709                                      const TargetLowering &TLI) {
5710   if (NumNonZero > 4)
5711     return SDValue();
5712
5713   SDLoc dl(Op);
5714   SDValue V;
5715   bool First = true;
5716   for (unsigned i = 0; i < 8; ++i) {
5717     bool isNonZero = (NonZeros & (1 << i)) != 0;
5718     if (isNonZero) {
5719       if (First) {
5720         if (NumZero)
5721           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5722         else
5723           V = DAG.getUNDEF(MVT::v8i16);
5724         First = false;
5725       }
5726       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5727                       MVT::v8i16, V, Op.getOperand(i),
5728                       DAG.getIntPtrConstant(i));
5729     }
5730   }
5731
5732   return V;
5733 }
5734
5735 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5736 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5737                                      unsigned NonZeros, unsigned NumNonZero,
5738                                      unsigned NumZero, SelectionDAG &DAG,
5739                                      const X86Subtarget *Subtarget,
5740                                      const TargetLowering &TLI) {
5741   // We know there's at least one non-zero element
5742   unsigned FirstNonZeroIdx = 0;
5743   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5744   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5745          X86::isZeroNode(FirstNonZero)) {
5746     ++FirstNonZeroIdx;
5747     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5748   }
5749
5750   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5751       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5752     return SDValue();
5753
5754   SDValue V = FirstNonZero.getOperand(0);
5755   MVT VVT = V.getSimpleValueType();
5756   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5757     return SDValue();
5758
5759   unsigned FirstNonZeroDst =
5760       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5761   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5762   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5763   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5764
5765   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5766     SDValue Elem = Op.getOperand(Idx);
5767     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5768       continue;
5769
5770     // TODO: What else can be here? Deal with it.
5771     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5772       return SDValue();
5773
5774     // TODO: Some optimizations are still possible here
5775     // ex: Getting one element from a vector, and the rest from another.
5776     if (Elem.getOperand(0) != V)
5777       return SDValue();
5778
5779     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5780     if (Dst == Idx)
5781       ++CorrectIdx;
5782     else if (IncorrectIdx == -1U) {
5783       IncorrectIdx = Idx;
5784       IncorrectDst = Dst;
5785     } else
5786       // There was already one element with an incorrect index.
5787       // We can't optimize this case to an insertps.
5788       return SDValue();
5789   }
5790
5791   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5792     SDLoc dl(Op);
5793     EVT VT = Op.getSimpleValueType();
5794     unsigned ElementMoveMask = 0;
5795     if (IncorrectIdx == -1U)
5796       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5797     else
5798       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5799
5800     SDValue InsertpsMask =
5801         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5802     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5803   }
5804
5805   return SDValue();
5806 }
5807
5808 /// getVShift - Return a vector logical shift node.
5809 ///
5810 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5811                          unsigned NumBits, SelectionDAG &DAG,
5812                          const TargetLowering &TLI, SDLoc dl) {
5813   assert(VT.is128BitVector() && "Unknown type for VShift");
5814   EVT ShVT = MVT::v2i64;
5815   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5816   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5817   return DAG.getNode(ISD::BITCAST, dl, VT,
5818                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5819                              DAG.getConstant(NumBits,
5820                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5821 }
5822
5823 static SDValue
5824 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5825
5826   // Check if the scalar load can be widened into a vector load. And if
5827   // the address is "base + cst" see if the cst can be "absorbed" into
5828   // the shuffle mask.
5829   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5830     SDValue Ptr = LD->getBasePtr();
5831     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5832       return SDValue();
5833     EVT PVT = LD->getValueType(0);
5834     if (PVT != MVT::i32 && PVT != MVT::f32)
5835       return SDValue();
5836
5837     int FI = -1;
5838     int64_t Offset = 0;
5839     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5840       FI = FINode->getIndex();
5841       Offset = 0;
5842     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5843                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5844       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5845       Offset = Ptr.getConstantOperandVal(1);
5846       Ptr = Ptr.getOperand(0);
5847     } else {
5848       return SDValue();
5849     }
5850
5851     // FIXME: 256-bit vector instructions don't require a strict alignment,
5852     // improve this code to support it better.
5853     unsigned RequiredAlign = VT.getSizeInBits()/8;
5854     SDValue Chain = LD->getChain();
5855     // Make sure the stack object alignment is at least 16 or 32.
5856     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5857     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5858       if (MFI->isFixedObjectIndex(FI)) {
5859         // Can't change the alignment. FIXME: It's possible to compute
5860         // the exact stack offset and reference FI + adjust offset instead.
5861         // If someone *really* cares about this. That's the way to implement it.
5862         return SDValue();
5863       } else {
5864         MFI->setObjectAlignment(FI, RequiredAlign);
5865       }
5866     }
5867
5868     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5869     // Ptr + (Offset & ~15).
5870     if (Offset < 0)
5871       return SDValue();
5872     if ((Offset % RequiredAlign) & 3)
5873       return SDValue();
5874     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5875     if (StartOffset)
5876       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5877                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5878
5879     int EltNo = (Offset - StartOffset) >> 2;
5880     unsigned NumElems = VT.getVectorNumElements();
5881
5882     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5883     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5884                              LD->getPointerInfo().getWithOffset(StartOffset),
5885                              false, false, false, 0);
5886
5887     SmallVector<int, 8> Mask;
5888     for (unsigned i = 0; i != NumElems; ++i)
5889       Mask.push_back(EltNo);
5890
5891     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5892   }
5893
5894   return SDValue();
5895 }
5896
5897 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5898 /// vector of type 'VT', see if the elements can be replaced by a single large
5899 /// load which has the same value as a build_vector whose operands are 'elts'.
5900 ///
5901 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5902 ///
5903 /// FIXME: we'd also like to handle the case where the last elements are zero
5904 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5905 /// There's even a handy isZeroNode for that purpose.
5906 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5907                                         SDLoc &DL, SelectionDAG &DAG,
5908                                         bool isAfterLegalize) {
5909   EVT EltVT = VT.getVectorElementType();
5910   unsigned NumElems = Elts.size();
5911
5912   LoadSDNode *LDBase = nullptr;
5913   unsigned LastLoadedElt = -1U;
5914
5915   // For each element in the initializer, see if we've found a load or an undef.
5916   // If we don't find an initial load element, or later load elements are
5917   // non-consecutive, bail out.
5918   for (unsigned i = 0; i < NumElems; ++i) {
5919     SDValue Elt = Elts[i];
5920
5921     if (!Elt.getNode() ||
5922         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5923       return SDValue();
5924     if (!LDBase) {
5925       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5926         return SDValue();
5927       LDBase = cast<LoadSDNode>(Elt.getNode());
5928       LastLoadedElt = i;
5929       continue;
5930     }
5931     if (Elt.getOpcode() == ISD::UNDEF)
5932       continue;
5933
5934     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5935     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5936       return SDValue();
5937     LastLoadedElt = i;
5938   }
5939
5940   // If we have found an entire vector of loads and undefs, then return a large
5941   // load of the entire vector width starting at the base pointer.  If we found
5942   // consecutive loads for the low half, generate a vzext_load node.
5943   if (LastLoadedElt == NumElems - 1) {
5944
5945     if (isAfterLegalize &&
5946         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5947       return SDValue();
5948
5949     SDValue NewLd = SDValue();
5950
5951     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5952       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5953                           LDBase->getPointerInfo(),
5954                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5955                           LDBase->isInvariant(), 0);
5956     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5957                         LDBase->getPointerInfo(),
5958                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5959                         LDBase->isInvariant(), LDBase->getAlignment());
5960
5961     if (LDBase->hasAnyUseOfValue(1)) {
5962       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5963                                      SDValue(LDBase, 1),
5964                                      SDValue(NewLd.getNode(), 1));
5965       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5966       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5967                              SDValue(NewLd.getNode(), 1));
5968     }
5969
5970     return NewLd;
5971   }
5972   if (NumElems == 4 && LastLoadedElt == 1 &&
5973       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5974     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5975     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5976     SDValue ResNode =
5977         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5978                                 LDBase->getPointerInfo(),
5979                                 LDBase->getAlignment(),
5980                                 false/*isVolatile*/, true/*ReadMem*/,
5981                                 false/*WriteMem*/);
5982
5983     // Make sure the newly-created LOAD is in the same position as LDBase in
5984     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5985     // update uses of LDBase's output chain to use the TokenFactor.
5986     if (LDBase->hasAnyUseOfValue(1)) {
5987       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5988                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5989       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5990       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5991                              SDValue(ResNode.getNode(), 1));
5992     }
5993
5994     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5995   }
5996   return SDValue();
5997 }
5998
5999 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6000 /// to generate a splat value for the following cases:
6001 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6002 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6003 /// a scalar load, or a constant.
6004 /// The VBROADCAST node is returned when a pattern is found,
6005 /// or SDValue() otherwise.
6006 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6007                                     SelectionDAG &DAG) {
6008   if (!Subtarget->hasFp256())
6009     return SDValue();
6010
6011   MVT VT = Op.getSimpleValueType();
6012   SDLoc dl(Op);
6013
6014   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6015          "Unsupported vector type for broadcast.");
6016
6017   SDValue Ld;
6018   bool ConstSplatVal;
6019
6020   switch (Op.getOpcode()) {
6021     default:
6022       // Unknown pattern found.
6023       return SDValue();
6024
6025     case ISD::BUILD_VECTOR: {
6026       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6027       BitVector UndefElements;
6028       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6029
6030       // We need a splat of a single value to use broadcast, and it doesn't
6031       // make any sense if the value is only in one element of the vector.
6032       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6033         return SDValue();
6034
6035       Ld = Splat;
6036       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6037                        Ld.getOpcode() == ISD::ConstantFP);
6038
6039       // Make sure that all of the users of a non-constant load are from the
6040       // BUILD_VECTOR node.
6041       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6042         return SDValue();
6043       break;
6044     }
6045
6046     case ISD::VECTOR_SHUFFLE: {
6047       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6048
6049       // Shuffles must have a splat mask where the first element is
6050       // broadcasted.
6051       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6052         return SDValue();
6053
6054       SDValue Sc = Op.getOperand(0);
6055       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6056           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6057
6058         if (!Subtarget->hasInt256())
6059           return SDValue();
6060
6061         // Use the register form of the broadcast instruction available on AVX2.
6062         if (VT.getSizeInBits() >= 256)
6063           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6064         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6065       }
6066
6067       Ld = Sc.getOperand(0);
6068       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6069                        Ld.getOpcode() == ISD::ConstantFP);
6070
6071       // The scalar_to_vector node and the suspected
6072       // load node must have exactly one user.
6073       // Constants may have multiple users.
6074
6075       // AVX-512 has register version of the broadcast
6076       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6077         Ld.getValueType().getSizeInBits() >= 32;
6078       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6079           !hasRegVer))
6080         return SDValue();
6081       break;
6082     }
6083   }
6084
6085   bool IsGE256 = (VT.getSizeInBits() >= 256);
6086
6087   // Handle the broadcasting a single constant scalar from the constant pool
6088   // into a vector. On Sandybridge it is still better to load a constant vector
6089   // from the constant pool and not to broadcast it from a scalar.
6090   if (ConstSplatVal && Subtarget->hasInt256()) {
6091     EVT CVT = Ld.getValueType();
6092     assert(!CVT.isVector() && "Must not broadcast a vector type");
6093     unsigned ScalarSize = CVT.getSizeInBits();
6094
6095     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
6096       const Constant *C = nullptr;
6097       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6098         C = CI->getConstantIntValue();
6099       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6100         C = CF->getConstantFPValue();
6101
6102       assert(C && "Invalid constant type");
6103
6104       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6105       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6106       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6107       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6108                        MachinePointerInfo::getConstantPool(),
6109                        false, false, false, Alignment);
6110
6111       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6112     }
6113   }
6114
6115   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6116   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6117
6118   // Handle AVX2 in-register broadcasts.
6119   if (!IsLoad && Subtarget->hasInt256() &&
6120       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6121     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6122
6123   // The scalar source must be a normal load.
6124   if (!IsLoad)
6125     return SDValue();
6126
6127   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6128     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6129
6130   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6131   // double since there is no vbroadcastsd xmm
6132   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6133     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6134       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6135   }
6136
6137   // Unsupported broadcast.
6138   return SDValue();
6139 }
6140
6141 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6142 /// underlying vector and index.
6143 ///
6144 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6145 /// index.
6146 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6147                                          SDValue ExtIdx) {
6148   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6149   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6150     return Idx;
6151
6152   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6153   // lowered this:
6154   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6155   // to:
6156   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6157   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6158   //                           undef)
6159   //                       Constant<0>)
6160   // In this case the vector is the extract_subvector expression and the index
6161   // is 2, as specified by the shuffle.
6162   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6163   SDValue ShuffleVec = SVOp->getOperand(0);
6164   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6165   assert(ShuffleVecVT.getVectorElementType() ==
6166          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6167
6168   int ShuffleIdx = SVOp->getMaskElt(Idx);
6169   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6170     ExtractedFromVec = ShuffleVec;
6171     return ShuffleIdx;
6172   }
6173   return Idx;
6174 }
6175
6176 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6177   MVT VT = Op.getSimpleValueType();
6178
6179   // Skip if insert_vec_elt is not supported.
6180   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6181   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6182     return SDValue();
6183
6184   SDLoc DL(Op);
6185   unsigned NumElems = Op.getNumOperands();
6186
6187   SDValue VecIn1;
6188   SDValue VecIn2;
6189   SmallVector<unsigned, 4> InsertIndices;
6190   SmallVector<int, 8> Mask(NumElems, -1);
6191
6192   for (unsigned i = 0; i != NumElems; ++i) {
6193     unsigned Opc = Op.getOperand(i).getOpcode();
6194
6195     if (Opc == ISD::UNDEF)
6196       continue;
6197
6198     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6199       // Quit if more than 1 elements need inserting.
6200       if (InsertIndices.size() > 1)
6201         return SDValue();
6202
6203       InsertIndices.push_back(i);
6204       continue;
6205     }
6206
6207     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6208     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6209     // Quit if non-constant index.
6210     if (!isa<ConstantSDNode>(ExtIdx))
6211       return SDValue();
6212     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6213
6214     // Quit if extracted from vector of different type.
6215     if (ExtractedFromVec.getValueType() != VT)
6216       return SDValue();
6217
6218     if (!VecIn1.getNode())
6219       VecIn1 = ExtractedFromVec;
6220     else if (VecIn1 != ExtractedFromVec) {
6221       if (!VecIn2.getNode())
6222         VecIn2 = ExtractedFromVec;
6223       else if (VecIn2 != ExtractedFromVec)
6224         // Quit if more than 2 vectors to shuffle
6225         return SDValue();
6226     }
6227
6228     if (ExtractedFromVec == VecIn1)
6229       Mask[i] = Idx;
6230     else if (ExtractedFromVec == VecIn2)
6231       Mask[i] = Idx + NumElems;
6232   }
6233
6234   if (!VecIn1.getNode())
6235     return SDValue();
6236
6237   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6238   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6239   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6240     unsigned Idx = InsertIndices[i];
6241     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6242                      DAG.getIntPtrConstant(Idx));
6243   }
6244
6245   return NV;
6246 }
6247
6248 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6249 SDValue
6250 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6251
6252   MVT VT = Op.getSimpleValueType();
6253   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6254          "Unexpected type in LowerBUILD_VECTORvXi1!");
6255
6256   SDLoc dl(Op);
6257   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6258     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6259     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6260     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6261   }
6262
6263   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6264     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6265     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6266     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6267   }
6268
6269   bool AllContants = true;
6270   uint64_t Immediate = 0;
6271   int NonConstIdx = -1;
6272   bool IsSplat = true;
6273   unsigned NumNonConsts = 0;
6274   unsigned NumConsts = 0;
6275   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6276     SDValue In = Op.getOperand(idx);
6277     if (In.getOpcode() == ISD::UNDEF)
6278       continue;
6279     if (!isa<ConstantSDNode>(In)) {
6280       AllContants = false;
6281       NonConstIdx = idx;
6282       NumNonConsts++;
6283     }
6284     else {
6285       NumConsts++;
6286       if (cast<ConstantSDNode>(In)->getZExtValue())
6287       Immediate |= (1ULL << idx);
6288     }
6289     if (In != Op.getOperand(0))
6290       IsSplat = false;
6291   }
6292
6293   if (AllContants) {
6294     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6295       DAG.getConstant(Immediate, MVT::i16));
6296     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6297                        DAG.getIntPtrConstant(0));
6298   }
6299
6300   if (NumNonConsts == 1 && NonConstIdx != 0) {
6301     SDValue DstVec;
6302     if (NumConsts) {
6303       SDValue VecAsImm = DAG.getConstant(Immediate,
6304                                          MVT::getIntegerVT(VT.getSizeInBits()));
6305       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6306     }
6307     else 
6308       DstVec = DAG.getUNDEF(VT);
6309     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6310                        Op.getOperand(NonConstIdx),
6311                        DAG.getIntPtrConstant(NonConstIdx));
6312   }
6313   if (!IsSplat && (NonConstIdx != 0))
6314     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6315   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6316   SDValue Select;
6317   if (IsSplat)
6318     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6319                           DAG.getConstant(-1, SelectVT),
6320                           DAG.getConstant(0, SelectVT));
6321   else
6322     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6323                          DAG.getConstant((Immediate | 1), SelectVT),
6324                          DAG.getConstant(Immediate, SelectVT));
6325   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6326 }
6327
6328 /// \brief Return true if \p N implements a horizontal binop and return the
6329 /// operands for the horizontal binop into V0 and V1.
6330 /// 
6331 /// This is a helper function of PerformBUILD_VECTORCombine.
6332 /// This function checks that the build_vector \p N in input implements a
6333 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6334 /// operation to match.
6335 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6336 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6337 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6338 /// arithmetic sub.
6339 ///
6340 /// This function only analyzes elements of \p N whose indices are
6341 /// in range [BaseIdx, LastIdx).
6342 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6343                               SelectionDAG &DAG,
6344                               unsigned BaseIdx, unsigned LastIdx,
6345                               SDValue &V0, SDValue &V1) {
6346   EVT VT = N->getValueType(0);
6347
6348   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6349   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6350          "Invalid Vector in input!");
6351   
6352   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6353   bool CanFold = true;
6354   unsigned ExpectedVExtractIdx = BaseIdx;
6355   unsigned NumElts = LastIdx - BaseIdx;
6356   V0 = DAG.getUNDEF(VT);
6357   V1 = DAG.getUNDEF(VT);
6358
6359   // Check if N implements a horizontal binop.
6360   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6361     SDValue Op = N->getOperand(i + BaseIdx);
6362
6363     // Skip UNDEFs.
6364     if (Op->getOpcode() == ISD::UNDEF) {
6365       // Update the expected vector extract index.
6366       if (i * 2 == NumElts)
6367         ExpectedVExtractIdx = BaseIdx;
6368       ExpectedVExtractIdx += 2;
6369       continue;
6370     }
6371
6372     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6373
6374     if (!CanFold)
6375       break;
6376
6377     SDValue Op0 = Op.getOperand(0);
6378     SDValue Op1 = Op.getOperand(1);
6379
6380     // Try to match the following pattern:
6381     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6382     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6383         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6384         Op0.getOperand(0) == Op1.getOperand(0) &&
6385         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6386         isa<ConstantSDNode>(Op1.getOperand(1)));
6387     if (!CanFold)
6388       break;
6389
6390     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6391     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6392
6393     if (i * 2 < NumElts) {
6394       if (V0.getOpcode() == ISD::UNDEF)
6395         V0 = Op0.getOperand(0);
6396     } else {
6397       if (V1.getOpcode() == ISD::UNDEF)
6398         V1 = Op0.getOperand(0);
6399       if (i * 2 == NumElts)
6400         ExpectedVExtractIdx = BaseIdx;
6401     }
6402
6403     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6404     if (I0 == ExpectedVExtractIdx)
6405       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6406     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6407       // Try to match the following dag sequence:
6408       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6409       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6410     } else
6411       CanFold = false;
6412
6413     ExpectedVExtractIdx += 2;
6414   }
6415
6416   return CanFold;
6417 }
6418
6419 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6420 /// a concat_vector. 
6421 ///
6422 /// This is a helper function of PerformBUILD_VECTORCombine.
6423 /// This function expects two 256-bit vectors called V0 and V1.
6424 /// At first, each vector is split into two separate 128-bit vectors.
6425 /// Then, the resulting 128-bit vectors are used to implement two
6426 /// horizontal binary operations. 
6427 ///
6428 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6429 ///
6430 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6431 /// the two new horizontal binop.
6432 /// When Mode is set, the first horizontal binop dag node would take as input
6433 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6434 /// horizontal binop dag node would take as input the lower 128-bit of V1
6435 /// and the upper 128-bit of V1.
6436 ///   Example:
6437 ///     HADD V0_LO, V0_HI
6438 ///     HADD V1_LO, V1_HI
6439 ///
6440 /// Otherwise, the first horizontal binop dag node takes as input the lower
6441 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6442 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6443 ///   Example:
6444 ///     HADD V0_LO, V1_LO
6445 ///     HADD V0_HI, V1_HI
6446 ///
6447 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6448 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6449 /// the upper 128-bits of the result.
6450 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6451                                      SDLoc DL, SelectionDAG &DAG,
6452                                      unsigned X86Opcode, bool Mode,
6453                                      bool isUndefLO, bool isUndefHI) {
6454   EVT VT = V0.getValueType();
6455   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6456          "Invalid nodes in input!");
6457
6458   unsigned NumElts = VT.getVectorNumElements();
6459   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6460   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6461   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6462   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6463   EVT NewVT = V0_LO.getValueType();
6464
6465   SDValue LO = DAG.getUNDEF(NewVT);
6466   SDValue HI = DAG.getUNDEF(NewVT);
6467
6468   if (Mode) {
6469     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6470     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6471       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6472     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6473       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6474   } else {
6475     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6476     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6477                        V1_LO->getOpcode() != ISD::UNDEF))
6478       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6479
6480     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6481                        V1_HI->getOpcode() != ISD::UNDEF))
6482       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6483   }
6484
6485   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6486 }
6487
6488 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6489 /// sequence of 'vadd + vsub + blendi'.
6490 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6491                            const X86Subtarget *Subtarget) {
6492   SDLoc DL(BV);
6493   EVT VT = BV->getValueType(0);
6494   unsigned NumElts = VT.getVectorNumElements();
6495   SDValue InVec0 = DAG.getUNDEF(VT);
6496   SDValue InVec1 = DAG.getUNDEF(VT);
6497
6498   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6499           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6500
6501   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6503   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6504     return SDValue();
6505
6506   // Odd-numbered elements in the input build vector are obtained from
6507   // adding two integer/float elements.
6508   // Even-numbered elements in the input build vector are obtained from
6509   // subtracting two integer/float elements.
6510   unsigned ExpectedOpcode = ISD::FSUB;
6511   unsigned NextExpectedOpcode = ISD::FADD;
6512   bool AddFound = false;
6513   bool SubFound = false;
6514
6515   for (unsigned i = 0, e = NumElts; i != e; i++) {
6516     SDValue Op = BV->getOperand(i);
6517       
6518     // Skip 'undef' values.
6519     unsigned Opcode = Op.getOpcode();
6520     if (Opcode == ISD::UNDEF) {
6521       std::swap(ExpectedOpcode, NextExpectedOpcode);
6522       continue;
6523     }
6524       
6525     // Early exit if we found an unexpected opcode.
6526     if (Opcode != ExpectedOpcode)
6527       return SDValue();
6528
6529     SDValue Op0 = Op.getOperand(0);
6530     SDValue Op1 = Op.getOperand(1);
6531
6532     // Try to match the following pattern:
6533     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6534     // Early exit if we cannot match that sequence.
6535     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6536         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6537         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6538         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6539         Op0.getOperand(1) != Op1.getOperand(1))
6540       return SDValue();
6541
6542     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6543     if (I0 != i)
6544       return SDValue();
6545
6546     // We found a valid add/sub node. Update the information accordingly.
6547     if (i & 1)
6548       AddFound = true;
6549     else
6550       SubFound = true;
6551
6552     // Update InVec0 and InVec1.
6553     if (InVec0.getOpcode() == ISD::UNDEF)
6554       InVec0 = Op0.getOperand(0);
6555     if (InVec1.getOpcode() == ISD::UNDEF)
6556       InVec1 = Op1.getOperand(0);
6557
6558     // Make sure that operands in input to each add/sub node always
6559     // come from a same pair of vectors.
6560     if (InVec0 != Op0.getOperand(0)) {
6561       if (ExpectedOpcode == ISD::FSUB)
6562         return SDValue();
6563
6564       // FADD is commutable. Try to commute the operands
6565       // and then test again.
6566       std::swap(Op0, Op1);
6567       if (InVec0 != Op0.getOperand(0))
6568         return SDValue();
6569     }
6570
6571     if (InVec1 != Op1.getOperand(0))
6572       return SDValue();
6573
6574     // Update the pair of expected opcodes.
6575     std::swap(ExpectedOpcode, NextExpectedOpcode);
6576   }
6577
6578   // Don't try to fold this build_vector into a VSELECT if it has
6579   // too many UNDEF operands.
6580   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6581       InVec1.getOpcode() != ISD::UNDEF) {
6582     // Emit a sequence of vector add and sub followed by a VSELECT.
6583     // The new VSELECT will be lowered into a BLENDI.
6584     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6585     // and emit a single ADDSUB instruction.
6586     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6587     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6588
6589     // Construct the VSELECT mask.
6590     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6591     EVT SVT = MaskVT.getVectorElementType();
6592     unsigned SVTBits = SVT.getSizeInBits();
6593     SmallVector<SDValue, 8> Ops;
6594
6595     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6596       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6597                             APInt::getAllOnesValue(SVTBits);
6598       SDValue Constant = DAG.getConstant(Value, SVT);
6599       Ops.push_back(Constant);
6600     }
6601
6602     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6603     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6604   }
6605   
6606   return SDValue();
6607 }
6608
6609 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6610                                           const X86Subtarget *Subtarget) {
6611   SDLoc DL(N);
6612   EVT VT = N->getValueType(0);
6613   unsigned NumElts = VT.getVectorNumElements();
6614   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6615   SDValue InVec0, InVec1;
6616
6617   // Try to match an ADDSUB.
6618   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6619       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6620     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6621     if (Value.getNode())
6622       return Value;
6623   }
6624
6625   // Try to match horizontal ADD/SUB.
6626   unsigned NumUndefsLO = 0;
6627   unsigned NumUndefsHI = 0;
6628   unsigned Half = NumElts/2;
6629
6630   // Count the number of UNDEF operands in the build_vector in input.
6631   for (unsigned i = 0, e = Half; i != e; ++i)
6632     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6633       NumUndefsLO++;
6634
6635   for (unsigned i = Half, e = NumElts; i != e; ++i)
6636     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6637       NumUndefsHI++;
6638
6639   // Early exit if this is either a build_vector of all UNDEFs or all the
6640   // operands but one are UNDEF.
6641   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6642     return SDValue();
6643
6644   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6645     // Try to match an SSE3 float HADD/HSUB.
6646     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6647       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6648     
6649     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6650       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6651   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6652     // Try to match an SSSE3 integer HADD/HSUB.
6653     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6654       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6655     
6656     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6657       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6658   }
6659   
6660   if (!Subtarget->hasAVX())
6661     return SDValue();
6662
6663   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6664     // Try to match an AVX horizontal add/sub of packed single/double
6665     // precision floating point values from 256-bit vectors.
6666     SDValue InVec2, InVec3;
6667     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6668         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6669         ((InVec0.getOpcode() == ISD::UNDEF ||
6670           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6671         ((InVec1.getOpcode() == ISD::UNDEF ||
6672           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6673       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6674
6675     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6676         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6677         ((InVec0.getOpcode() == ISD::UNDEF ||
6678           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6679         ((InVec1.getOpcode() == ISD::UNDEF ||
6680           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6681       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6682   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6683     // Try to match an AVX2 horizontal add/sub of signed integers.
6684     SDValue InVec2, InVec3;
6685     unsigned X86Opcode;
6686     bool CanFold = true;
6687
6688     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6689         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6690         ((InVec0.getOpcode() == ISD::UNDEF ||
6691           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6692         ((InVec1.getOpcode() == ISD::UNDEF ||
6693           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6694       X86Opcode = X86ISD::HADD;
6695     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6696         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6697         ((InVec0.getOpcode() == ISD::UNDEF ||
6698           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6699         ((InVec1.getOpcode() == ISD::UNDEF ||
6700           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6701       X86Opcode = X86ISD::HSUB;
6702     else
6703       CanFold = false;
6704
6705     if (CanFold) {
6706       // Fold this build_vector into a single horizontal add/sub.
6707       // Do this only if the target has AVX2.
6708       if (Subtarget->hasAVX2())
6709         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6710  
6711       // Do not try to expand this build_vector into a pair of horizontal
6712       // add/sub if we can emit a pair of scalar add/sub.
6713       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6714         return SDValue();
6715
6716       // Convert this build_vector into a pair of horizontal binop followed by
6717       // a concat vector.
6718       bool isUndefLO = NumUndefsLO == Half;
6719       bool isUndefHI = NumUndefsHI == Half;
6720       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6721                                    isUndefLO, isUndefHI);
6722     }
6723   }
6724
6725   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6726        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6727     unsigned X86Opcode;
6728     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6729       X86Opcode = X86ISD::HADD;
6730     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6731       X86Opcode = X86ISD::HSUB;
6732     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6733       X86Opcode = X86ISD::FHADD;
6734     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6735       X86Opcode = X86ISD::FHSUB;
6736     else
6737       return SDValue();
6738
6739     // Don't try to expand this build_vector into a pair of horizontal add/sub
6740     // if we can simply emit a pair of scalar add/sub.
6741     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6742       return SDValue();
6743
6744     // Convert this build_vector into two horizontal add/sub followed by
6745     // a concat vector.
6746     bool isUndefLO = NumUndefsLO == Half;
6747     bool isUndefHI = NumUndefsHI == Half;
6748     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6749                                  isUndefLO, isUndefHI);
6750   }
6751
6752   return SDValue();
6753 }
6754
6755 SDValue
6756 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6757   SDLoc dl(Op);
6758
6759   MVT VT = Op.getSimpleValueType();
6760   MVT ExtVT = VT.getVectorElementType();
6761   unsigned NumElems = Op.getNumOperands();
6762
6763   // Generate vectors for predicate vectors.
6764   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6765     return LowerBUILD_VECTORvXi1(Op, DAG);
6766
6767   // Vectors containing all zeros can be matched by pxor and xorps later
6768   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6769     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6770     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6771     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6772       return Op;
6773
6774     return getZeroVector(VT, Subtarget, DAG, dl);
6775   }
6776
6777   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6778   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6779   // vpcmpeqd on 256-bit vectors.
6780   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6781     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6782       return Op;
6783
6784     if (!VT.is512BitVector())
6785       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6786   }
6787
6788   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6789   if (Broadcast.getNode())
6790     return Broadcast;
6791
6792   unsigned EVTBits = ExtVT.getSizeInBits();
6793
6794   unsigned NumZero  = 0;
6795   unsigned NumNonZero = 0;
6796   unsigned NonZeros = 0;
6797   bool IsAllConstants = true;
6798   SmallSet<SDValue, 8> Values;
6799   for (unsigned i = 0; i < NumElems; ++i) {
6800     SDValue Elt = Op.getOperand(i);
6801     if (Elt.getOpcode() == ISD::UNDEF)
6802       continue;
6803     Values.insert(Elt);
6804     if (Elt.getOpcode() != ISD::Constant &&
6805         Elt.getOpcode() != ISD::ConstantFP)
6806       IsAllConstants = false;
6807     if (X86::isZeroNode(Elt))
6808       NumZero++;
6809     else {
6810       NonZeros |= (1 << i);
6811       NumNonZero++;
6812     }
6813   }
6814
6815   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6816   if (NumNonZero == 0)
6817     return DAG.getUNDEF(VT);
6818
6819   // Special case for single non-zero, non-undef, element.
6820   if (NumNonZero == 1) {
6821     unsigned Idx = countTrailingZeros(NonZeros);
6822     SDValue Item = Op.getOperand(Idx);
6823
6824     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6825     // the value are obviously zero, truncate the value to i32 and do the
6826     // insertion that way.  Only do this if the value is non-constant or if the
6827     // value is a constant being inserted into element 0.  It is cheaper to do
6828     // a constant pool load than it is to do a movd + shuffle.
6829     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6830         (!IsAllConstants || Idx == 0)) {
6831       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6832         // Handle SSE only.
6833         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6834         EVT VecVT = MVT::v4i32;
6835         unsigned VecElts = 4;
6836
6837         // Truncate the value (which may itself be a constant) to i32, and
6838         // convert it to a vector with movd (S2V+shuffle to zero extend).
6839         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6840         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6841         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6842
6843         // Now we have our 32-bit value zero extended in the low element of
6844         // a vector.  If Idx != 0, swizzle it into place.
6845         if (Idx != 0) {
6846           SmallVector<int, 4> Mask;
6847           Mask.push_back(Idx);
6848           for (unsigned i = 1; i != VecElts; ++i)
6849             Mask.push_back(i);
6850           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6851                                       &Mask[0]);
6852         }
6853         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6854       }
6855     }
6856
6857     // If we have a constant or non-constant insertion into the low element of
6858     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6859     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6860     // depending on what the source datatype is.
6861     if (Idx == 0) {
6862       if (NumZero == 0)
6863         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6864
6865       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6866           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6867         if (VT.is256BitVector() || VT.is512BitVector()) {
6868           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6869           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6870                              Item, DAG.getIntPtrConstant(0));
6871         }
6872         assert(VT.is128BitVector() && "Expected an SSE value type!");
6873         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6874         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6875         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6876       }
6877
6878       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6879         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6880         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6881         if (VT.is256BitVector()) {
6882           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6883           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6884         } else {
6885           assert(VT.is128BitVector() && "Expected an SSE value type!");
6886           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6887         }
6888         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6889       }
6890     }
6891
6892     // Is it a vector logical left shift?
6893     if (NumElems == 2 && Idx == 1 &&
6894         X86::isZeroNode(Op.getOperand(0)) &&
6895         !X86::isZeroNode(Op.getOperand(1))) {
6896       unsigned NumBits = VT.getSizeInBits();
6897       return getVShift(true, VT,
6898                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6899                                    VT, Op.getOperand(1)),
6900                        NumBits/2, DAG, *this, dl);
6901     }
6902
6903     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6904       return SDValue();
6905
6906     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6907     // is a non-constant being inserted into an element other than the low one,
6908     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6909     // movd/movss) to move this into the low element, then shuffle it into
6910     // place.
6911     if (EVTBits == 32) {
6912       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6913
6914       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6915       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6916       SmallVector<int, 8> MaskVec;
6917       for (unsigned i = 0; i != NumElems; ++i)
6918         MaskVec.push_back(i == Idx ? 0 : 1);
6919       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6920     }
6921   }
6922
6923   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6924   if (Values.size() == 1) {
6925     if (EVTBits == 32) {
6926       // Instead of a shuffle like this:
6927       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6928       // Check if it's possible to issue this instead.
6929       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6930       unsigned Idx = countTrailingZeros(NonZeros);
6931       SDValue Item = Op.getOperand(Idx);
6932       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6933         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6934     }
6935     return SDValue();
6936   }
6937
6938   // A vector full of immediates; various special cases are already
6939   // handled, so this is best done with a single constant-pool load.
6940   if (IsAllConstants)
6941     return SDValue();
6942
6943   // For AVX-length vectors, build the individual 128-bit pieces and use
6944   // shuffles to put them in place.
6945   if (VT.is256BitVector() || VT.is512BitVector()) {
6946     SmallVector<SDValue, 64> V;
6947     for (unsigned i = 0; i != NumElems; ++i)
6948       V.push_back(Op.getOperand(i));
6949
6950     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6951
6952     // Build both the lower and upper subvector.
6953     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6954                                 makeArrayRef(&V[0], NumElems/2));
6955     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6956                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6957
6958     // Recreate the wider vector with the lower and upper part.
6959     if (VT.is256BitVector())
6960       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6961     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6962   }
6963
6964   // Let legalizer expand 2-wide build_vectors.
6965   if (EVTBits == 64) {
6966     if (NumNonZero == 1) {
6967       // One half is zero or undef.
6968       unsigned Idx = countTrailingZeros(NonZeros);
6969       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6970                                  Op.getOperand(Idx));
6971       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6972     }
6973     return SDValue();
6974   }
6975
6976   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6977   if (EVTBits == 8 && NumElems == 16) {
6978     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6979                                         Subtarget, *this);
6980     if (V.getNode()) return V;
6981   }
6982
6983   if (EVTBits == 16 && NumElems == 8) {
6984     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6985                                       Subtarget, *this);
6986     if (V.getNode()) return V;
6987   }
6988
6989   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6990   if (EVTBits == 32 && NumElems == 4) {
6991     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6992                                       NumZero, DAG, Subtarget, *this);
6993     if (V.getNode())
6994       return V;
6995   }
6996
6997   // If element VT is == 32 bits, turn it into a number of shuffles.
6998   SmallVector<SDValue, 8> V(NumElems);
6999   if (NumElems == 4 && NumZero > 0) {
7000     for (unsigned i = 0; i < 4; ++i) {
7001       bool isZero = !(NonZeros & (1 << i));
7002       if (isZero)
7003         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7004       else
7005         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7006     }
7007
7008     for (unsigned i = 0; i < 2; ++i) {
7009       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7010         default: break;
7011         case 0:
7012           V[i] = V[i*2];  // Must be a zero vector.
7013           break;
7014         case 1:
7015           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7016           break;
7017         case 2:
7018           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7019           break;
7020         case 3:
7021           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7022           break;
7023       }
7024     }
7025
7026     bool Reverse1 = (NonZeros & 0x3) == 2;
7027     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7028     int MaskVec[] = {
7029       Reverse1 ? 1 : 0,
7030       Reverse1 ? 0 : 1,
7031       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7032       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7033     };
7034     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7035   }
7036
7037   if (Values.size() > 1 && VT.is128BitVector()) {
7038     // Check for a build vector of consecutive loads.
7039     for (unsigned i = 0; i < NumElems; ++i)
7040       V[i] = Op.getOperand(i);
7041
7042     // Check for elements which are consecutive loads.
7043     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7044     if (LD.getNode())
7045       return LD;
7046
7047     // Check for a build vector from mostly shuffle plus few inserting.
7048     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7049     if (Sh.getNode())
7050       return Sh;
7051
7052     // For SSE 4.1, use insertps to put the high elements into the low element.
7053     if (getSubtarget()->hasSSE41()) {
7054       SDValue Result;
7055       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7056         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7057       else
7058         Result = DAG.getUNDEF(VT);
7059
7060       for (unsigned i = 1; i < NumElems; ++i) {
7061         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7062         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7063                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7064       }
7065       return Result;
7066     }
7067
7068     // Otherwise, expand into a number of unpckl*, start by extending each of
7069     // our (non-undef) elements to the full vector width with the element in the
7070     // bottom slot of the vector (which generates no code for SSE).
7071     for (unsigned i = 0; i < NumElems; ++i) {
7072       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7073         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7074       else
7075         V[i] = DAG.getUNDEF(VT);
7076     }
7077
7078     // Next, we iteratively mix elements, e.g. for v4f32:
7079     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7080     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7081     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7082     unsigned EltStride = NumElems >> 1;
7083     while (EltStride != 0) {
7084       for (unsigned i = 0; i < EltStride; ++i) {
7085         // If V[i+EltStride] is undef and this is the first round of mixing,
7086         // then it is safe to just drop this shuffle: V[i] is already in the
7087         // right place, the one element (since it's the first round) being
7088         // inserted as undef can be dropped.  This isn't safe for successive
7089         // rounds because they will permute elements within both vectors.
7090         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7091             EltStride == NumElems/2)
7092           continue;
7093
7094         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7095       }
7096       EltStride >>= 1;
7097     }
7098     return V[0];
7099   }
7100   return SDValue();
7101 }
7102
7103 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7104 // to create 256-bit vectors from two other 128-bit ones.
7105 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7106   SDLoc dl(Op);
7107   MVT ResVT = Op.getSimpleValueType();
7108
7109   assert((ResVT.is256BitVector() ||
7110           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7111
7112   SDValue V1 = Op.getOperand(0);
7113   SDValue V2 = Op.getOperand(1);
7114   unsigned NumElems = ResVT.getVectorNumElements();
7115   if(ResVT.is256BitVector())
7116     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7117
7118   if (Op.getNumOperands() == 4) {
7119     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7120                                 ResVT.getVectorNumElements()/2);
7121     SDValue V3 = Op.getOperand(2);
7122     SDValue V4 = Op.getOperand(3);
7123     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7124       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7125   }
7126   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7127 }
7128
7129 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7130   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7131   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7132          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7133           Op.getNumOperands() == 4)));
7134
7135   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7136   // from two other 128-bit ones.
7137
7138   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7139   return LowerAVXCONCAT_VECTORS(Op, DAG);
7140 }
7141
7142
7143 //===----------------------------------------------------------------------===//
7144 // Vector shuffle lowering
7145 //
7146 // This is an experimental code path for lowering vector shuffles on x86. It is
7147 // designed to handle arbitrary vector shuffles and blends, gracefully
7148 // degrading performance as necessary. It works hard to recognize idiomatic
7149 // shuffles and lower them to optimal instruction patterns without leaving
7150 // a framework that allows reasonably efficient handling of all vector shuffle
7151 // patterns.
7152 //===----------------------------------------------------------------------===//
7153
7154 /// \brief Tiny helper function to identify a no-op mask.
7155 ///
7156 /// This is a somewhat boring predicate function. It checks whether the mask
7157 /// array input, which is assumed to be a single-input shuffle mask of the kind
7158 /// used by the X86 shuffle instructions (not a fully general
7159 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7160 /// in-place shuffle are 'no-op's.
7161 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7162   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7163     if (Mask[i] != -1 && Mask[i] != i)
7164       return false;
7165   return true;
7166 }
7167
7168 /// \brief Helper function to classify a mask as a single-input mask.
7169 ///
7170 /// This isn't a generic single-input test because in the vector shuffle
7171 /// lowering we canonicalize single inputs to be the first input operand. This
7172 /// means we can more quickly test for a single input by only checking whether
7173 /// an input from the second operand exists. We also assume that the size of
7174 /// mask corresponds to the size of the input vectors which isn't true in the
7175 /// fully general case.
7176 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7177   for (int M : Mask)
7178     if (M >= (int)Mask.size())
7179       return false;
7180   return true;
7181 }
7182
7183 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7184 // 2013 will allow us to use it as a non-type template parameter.
7185 namespace {
7186
7187 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7188 ///
7189 /// See its documentation for details.
7190 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7191   if (Mask.size() != Args.size())
7192     return false;
7193   for (int i = 0, e = Mask.size(); i < e; ++i) {
7194     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7195     assert(*Args[i] < (int)Args.size() * 2 &&
7196            "Argument outside the range of possible shuffle inputs!");
7197     if (Mask[i] != -1 && Mask[i] != *Args[i])
7198       return false;
7199   }
7200   return true;
7201 }
7202
7203 } // namespace
7204
7205 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7206 /// arguments.
7207 ///
7208 /// This is a fast way to test a shuffle mask against a fixed pattern:
7209 ///
7210 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7211 ///
7212 /// It returns true if the mask is exactly as wide as the argument list, and
7213 /// each element of the mask is either -1 (signifying undef) or the value given
7214 /// in the argument.
7215 static const VariadicFunction1<
7216     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7217
7218 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7219 ///
7220 /// This helper function produces an 8-bit shuffle immediate corresponding to
7221 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7222 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7223 /// example.
7224 ///
7225 /// NB: We rely heavily on "undef" masks preserving the input lane.
7226 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7227                                           SelectionDAG &DAG) {
7228   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7229   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7230   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7231   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7232   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7233
7234   unsigned Imm = 0;
7235   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7236   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7237   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7238   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7239   return DAG.getConstant(Imm, MVT::i8);
7240 }
7241
7242 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7243 ///
7244 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7245 /// support for floating point shuffles but not integer shuffles. These
7246 /// instructions will incur a domain crossing penalty on some chips though so
7247 /// it is better to avoid lowering through this for integer vectors where
7248 /// possible.
7249 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7250                                        const X86Subtarget *Subtarget,
7251                                        SelectionDAG &DAG) {
7252   SDLoc DL(Op);
7253   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7254   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7255   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7256   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7257   ArrayRef<int> Mask = SVOp->getMask();
7258   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7259
7260   if (isSingleInputShuffleMask(Mask)) {
7261     // Straight shuffle of a single input vector. Simulate this by using the
7262     // single input as both of the "inputs" to this instruction..
7263     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7264     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7265                        DAG.getConstant(SHUFPDMask, MVT::i8));
7266   }
7267   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7268   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7269
7270   // Use dedicated unpack instructions for masks that match their pattern.
7271   if (isShuffleEquivalent(Mask, 0, 2))
7272     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7273   if (isShuffleEquivalent(Mask, 1, 3))
7274     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7275
7276   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7277   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7278                      DAG.getConstant(SHUFPDMask, MVT::i8));
7279 }
7280
7281 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7282 ///
7283 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7284 /// the integer unit to minimize domain crossing penalties. However, for blends
7285 /// it falls back to the floating point shuffle operation with appropriate bit
7286 /// casting.
7287 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7288                                        const X86Subtarget *Subtarget,
7289                                        SelectionDAG &DAG) {
7290   SDLoc DL(Op);
7291   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7292   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7293   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7295   ArrayRef<int> Mask = SVOp->getMask();
7296   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7297
7298   if (isSingleInputShuffleMask(Mask)) {
7299     // Straight shuffle of a single input vector. For everything from SSE2
7300     // onward this has a single fast instruction with no scary immediates.
7301     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7302     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7303     int WidenedMask[4] = {
7304         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7305         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7306     return DAG.getNode(
7307         ISD::BITCAST, DL, MVT::v2i64,
7308         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7309                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7310   }
7311
7312   // Use dedicated unpack instructions for masks that match their pattern.
7313   if (isShuffleEquivalent(Mask, 0, 2))
7314     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7315   if (isShuffleEquivalent(Mask, 1, 3))
7316     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7317
7318   // We implement this with SHUFPD which is pretty lame because it will likely
7319   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7320   // However, all the alternatives are still more cycles and newer chips don't
7321   // have this problem. It would be really nice if x86 had better shuffles here.
7322   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7323   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7324   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7325                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7326 }
7327
7328 /// \brief Lower 4-lane 32-bit floating point shuffles.
7329 ///
7330 /// Uses instructions exclusively from the floating point unit to minimize
7331 /// domain crossing penalties, as these are sufficient to implement all v4f32
7332 /// shuffles.
7333 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7334                                        const X86Subtarget *Subtarget,
7335                                        SelectionDAG &DAG) {
7336   SDLoc DL(Op);
7337   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7338   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7339   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7340   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7341   ArrayRef<int> Mask = SVOp->getMask();
7342   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7343
7344   SDValue LowV = V1, HighV = V2;
7345   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7346
7347   int NumV2Elements =
7348       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7349
7350   if (NumV2Elements == 0)
7351     // Straight shuffle of a single input vector. We pass the input vector to
7352     // both operands to simulate this with a SHUFPS.
7353     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7354                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7355
7356   // Use dedicated unpack instructions for masks that match their pattern.
7357   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7358     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7359   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7360     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7361
7362   if (NumV2Elements == 1) {
7363     int V2Index =
7364         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7365         Mask.begin();
7366     // Compute the index adjacent to V2Index and in the same half by toggling
7367     // the low bit.
7368     int V2AdjIndex = V2Index ^ 1;
7369
7370     if (Mask[V2AdjIndex] == -1) {
7371       // Handles all the cases where we have a single V2 element and an undef.
7372       // This will only ever happen in the high lanes because we commute the
7373       // vector otherwise.
7374       if (V2Index < 2)
7375         std::swap(LowV, HighV);
7376       NewMask[V2Index] -= 4;
7377     } else {
7378       // Handle the case where the V2 element ends up adjacent to a V1 element.
7379       // To make this work, blend them together as the first step.
7380       int V1Index = V2AdjIndex;
7381       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7382       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7383                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7384
7385       // Now proceed to reconstruct the final blend as we have the necessary
7386       // high or low half formed.
7387       if (V2Index < 2) {
7388         LowV = V2;
7389         HighV = V1;
7390       } else {
7391         HighV = V2;
7392       }
7393       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7394       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7395     }
7396   } else if (NumV2Elements == 2) {
7397     if (Mask[0] < 4 && Mask[1] < 4) {
7398       // Handle the easy case where we have V1 in the low lanes and V2 in the
7399       // high lanes. We never see this reversed because we sort the shuffle.
7400       NewMask[2] -= 4;
7401       NewMask[3] -= 4;
7402     } else {
7403       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7404       // trying to place elements directly, just blend them and set up the final
7405       // shuffle to place them.
7406
7407       // The first two blend mask elements are for V1, the second two are for
7408       // V2.
7409       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7410                           Mask[2] < 4 ? Mask[2] : Mask[3],
7411                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7412                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7413       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7414                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7415
7416       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7417       // a blend.
7418       LowV = HighV = V1;
7419       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7420       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7421       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7422       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7423     }
7424   }
7425   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7426                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7427 }
7428
7429 /// \brief Lower 4-lane i32 vector shuffles.
7430 ///
7431 /// We try to handle these with integer-domain shuffles where we can, but for
7432 /// blends we use the floating point domain blend instructions.
7433 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7434                                        const X86Subtarget *Subtarget,
7435                                        SelectionDAG &DAG) {
7436   SDLoc DL(Op);
7437   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7438   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7439   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7440   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7441   ArrayRef<int> Mask = SVOp->getMask();
7442   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7443
7444   if (isSingleInputShuffleMask(Mask))
7445     // Straight shuffle of a single input vector. For everything from SSE2
7446     // onward this has a single fast instruction with no scary immediates.
7447     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7448                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7449
7450   // Use dedicated unpack instructions for masks that match their pattern.
7451   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7452     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7453   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7454     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7455
7456   // We implement this with SHUFPS because it can blend from two vectors.
7457   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7458   // up the inputs, bypassing domain shift penalties that we would encur if we
7459   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7460   // relevant.
7461   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7462                      DAG.getVectorShuffle(
7463                          MVT::v4f32, DL,
7464                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7465                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7466 }
7467
7468 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7469 /// shuffle lowering, and the most complex part.
7470 ///
7471 /// The lowering strategy is to try to form pairs of input lanes which are
7472 /// targeted at the same half of the final vector, and then use a dword shuffle
7473 /// to place them onto the right half, and finally unpack the paired lanes into
7474 /// their final position.
7475 ///
7476 /// The exact breakdown of how to form these dword pairs and align them on the
7477 /// correct sides is really tricky. See the comments within the function for
7478 /// more of the details.
7479 static SDValue lowerV8I16SingleInputVectorShuffle(
7480     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7481     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7482   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7483   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7484   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7485
7486   SmallVector<int, 4> LoInputs;
7487   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7488                [](int M) { return M >= 0; });
7489   std::sort(LoInputs.begin(), LoInputs.end());
7490   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7491   SmallVector<int, 4> HiInputs;
7492   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7493                [](int M) { return M >= 0; });
7494   std::sort(HiInputs.begin(), HiInputs.end());
7495   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7496   int NumLToL =
7497       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7498   int NumHToL = LoInputs.size() - NumLToL;
7499   int NumLToH =
7500       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7501   int NumHToH = HiInputs.size() - NumLToH;
7502   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7503   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7504   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7505   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7506
7507   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7508   // such inputs we can swap two of the dwords across the half mark and end up
7509   // with <=2 inputs to each half in each half. Once there, we can fall through
7510   // to the generic code below. For example:
7511   //
7512   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7513   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7514   //
7515   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7516   // and an existing 2-into-2 on the other half. In this case we may have to
7517   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7518   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7519   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7520   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7521   // half than the one we target for fixing) will be fixed when we re-enter this
7522   // path. We will also combine away any sequence of PSHUFD instructions that
7523   // result into a single instruction. Here is an example of the tricky case:
7524   //
7525   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7526   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7527   //
7528   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7529   //
7530   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7531   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7532   //
7533   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7534   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7535   //
7536   // The result is fine to be handled by the generic logic.
7537   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7538                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7539                           int AOffset, int BOffset) {
7540     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7541            "Must call this with A having 3 or 1 inputs from the A half.");
7542     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7543            "Must call this with B having 1 or 3 inputs from the B half.");
7544     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7545            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7546
7547     // Compute the index of dword with only one word among the three inputs in
7548     // a half by taking the sum of the half with three inputs and subtracting
7549     // the sum of the actual three inputs. The difference is the remaining
7550     // slot.
7551     int ADWord, BDWord;
7552     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7553     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7554     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7555     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7556     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7557     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7558     int TripleNonInputIdx =
7559         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7560     TripleDWord = TripleNonInputIdx / 2;
7561
7562     // We use xor with one to compute the adjacent DWord to whichever one the
7563     // OneInput is in.
7564     OneInputDWord = (OneInput / 2) ^ 1;
7565
7566     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7567     // and BToA inputs. If there is also such a problem with the BToB and AToB
7568     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7569     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7570     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7571     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7572       // Compute how many inputs will be flipped by swapping these DWords. We
7573       // need
7574       // to balance this to ensure we don't form a 3-1 shuffle in the other
7575       // half.
7576       int NumFlippedAToBInputs =
7577           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7578           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7579       int NumFlippedBToBInputs =
7580           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7581           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7582       if ((NumFlippedAToBInputs == 1 &&
7583            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7584           (NumFlippedBToBInputs == 1 &&
7585            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7586         // We choose whether to fix the A half or B half based on whether that
7587         // half has zero flipped inputs. At zero, we may not be able to fix it
7588         // with that half. We also bias towards fixing the B half because that
7589         // will more commonly be the high half, and we have to bias one way.
7590         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7591                                                        ArrayRef<int> Inputs) {
7592           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7593           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7594                                          PinnedIdx ^ 1) != Inputs.end();
7595           // Determine whether the free index is in the flipped dword or the
7596           // unflipped dword based on where the pinned index is. We use this bit
7597           // in an xor to conditionally select the adjacent dword.
7598           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7599           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7600                                              FixFreeIdx) != Inputs.end();
7601           if (IsFixIdxInput == IsFixFreeIdxInput)
7602             FixFreeIdx += 1;
7603           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7604                                         FixFreeIdx) != Inputs.end();
7605           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7606                  "We need to be changing the number of flipped inputs!");
7607           int PSHUFHalfMask[] = {0, 1, 2, 3};
7608           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7609           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7610                           MVT::v8i16, V,
7611                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7612
7613           for (int &M : Mask)
7614             if (M != -1 && M == FixIdx)
7615               M = FixFreeIdx;
7616             else if (M != -1 && M == FixFreeIdx)
7617               M = FixIdx;
7618         };
7619         if (NumFlippedBToBInputs != 0) {
7620           int BPinnedIdx =
7621               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7622           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7623         } else {
7624           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7625           int APinnedIdx =
7626               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7627           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7628         }
7629       }
7630     }
7631
7632     int PSHUFDMask[] = {0, 1, 2, 3};
7633     PSHUFDMask[ADWord] = BDWord;
7634     PSHUFDMask[BDWord] = ADWord;
7635     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7636                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7637                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7638                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7639
7640     // Adjust the mask to match the new locations of A and B.
7641     for (int &M : Mask)
7642       if (M != -1 && M/2 == ADWord)
7643         M = 2 * BDWord + M % 2;
7644       else if (M != -1 && M/2 == BDWord)
7645         M = 2 * ADWord + M % 2;
7646
7647     // Recurse back into this routine to re-compute state now that this isn't
7648     // a 3 and 1 problem.
7649     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7650                                 Mask);
7651   };
7652   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7653     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7654   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7655     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7656
7657   // At this point there are at most two inputs to the low and high halves from
7658   // each half. That means the inputs can always be grouped into dwords and
7659   // those dwords can then be moved to the correct half with a dword shuffle.
7660   // We use at most one low and one high word shuffle to collect these paired
7661   // inputs into dwords, and finally a dword shuffle to place them.
7662   int PSHUFLMask[4] = {-1, -1, -1, -1};
7663   int PSHUFHMask[4] = {-1, -1, -1, -1};
7664   int PSHUFDMask[4] = {-1, -1, -1, -1};
7665
7666   // First fix the masks for all the inputs that are staying in their
7667   // original halves. This will then dictate the targets of the cross-half
7668   // shuffles.
7669   auto fixInPlaceInputs =
7670       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7671                     MutableArrayRef<int> SourceHalfMask,
7672                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7673     if (InPlaceInputs.empty())
7674       return;
7675     if (InPlaceInputs.size() == 1) {
7676       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7677           InPlaceInputs[0] - HalfOffset;
7678       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7679       return;
7680     }
7681     if (IncomingInputs.empty()) {
7682       // Just fix all of the in place inputs.
7683       for (int Input : InPlaceInputs) {
7684         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7685         PSHUFDMask[Input / 2] = Input / 2;
7686       }
7687       return;
7688     }
7689
7690     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7691     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7692         InPlaceInputs[0] - HalfOffset;
7693     // Put the second input next to the first so that they are packed into
7694     // a dword. We find the adjacent index by toggling the low bit.
7695     int AdjIndex = InPlaceInputs[0] ^ 1;
7696     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7697     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7698     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7699   };
7700   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7701   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7702
7703   // Now gather the cross-half inputs and place them into a free dword of
7704   // their target half.
7705   // FIXME: This operation could almost certainly be simplified dramatically to
7706   // look more like the 3-1 fixing operation.
7707   auto moveInputsToRightHalf = [&PSHUFDMask](
7708       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7709       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7710       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7711       int DestOffset) {
7712     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7713       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7714     };
7715     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7716                                                int Word) {
7717       int LowWord = Word & ~1;
7718       int HighWord = Word | 1;
7719       return isWordClobbered(SourceHalfMask, LowWord) ||
7720              isWordClobbered(SourceHalfMask, HighWord);
7721     };
7722
7723     if (IncomingInputs.empty())
7724       return;
7725
7726     if (ExistingInputs.empty()) {
7727       // Map any dwords with inputs from them into the right half.
7728       for (int Input : IncomingInputs) {
7729         // If the source half mask maps over the inputs, turn those into
7730         // swaps and use the swapped lane.
7731         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7732           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7733             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7734                 Input - SourceOffset;
7735             // We have to swap the uses in our half mask in one sweep.
7736             for (int &M : HalfMask)
7737               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7738                 M = Input;
7739               else if (M == Input)
7740                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7741           } else {
7742             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7743                        Input - SourceOffset &&
7744                    "Previous placement doesn't match!");
7745           }
7746           // Note that this correctly re-maps both when we do a swap and when
7747           // we observe the other side of the swap above. We rely on that to
7748           // avoid swapping the members of the input list directly.
7749           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7750         }
7751
7752         // Map the input's dword into the correct half.
7753         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7754           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7755         else
7756           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7757                      Input / 2 &&
7758                  "Previous placement doesn't match!");
7759       }
7760
7761       // And just directly shift any other-half mask elements to be same-half
7762       // as we will have mirrored the dword containing the element into the
7763       // same position within that half.
7764       for (int &M : HalfMask)
7765         if (M >= SourceOffset && M < SourceOffset + 4) {
7766           M = M - SourceOffset + DestOffset;
7767           assert(M >= 0 && "This should never wrap below zero!");
7768         }
7769       return;
7770     }
7771
7772     // Ensure we have the input in a viable dword of its current half. This
7773     // is particularly tricky because the original position may be clobbered
7774     // by inputs being moved and *staying* in that half.
7775     if (IncomingInputs.size() == 1) {
7776       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7777         int InputFixed = std::find(std::begin(SourceHalfMask),
7778                                    std::end(SourceHalfMask), -1) -
7779                          std::begin(SourceHalfMask) + SourceOffset;
7780         SourceHalfMask[InputFixed - SourceOffset] =
7781             IncomingInputs[0] - SourceOffset;
7782         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7783                      InputFixed);
7784         IncomingInputs[0] = InputFixed;
7785       }
7786     } else if (IncomingInputs.size() == 2) {
7787       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7788           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7789         // We have two non-adjacent or clobbered inputs we need to extract from
7790         // the source half. To do this, we need to map them into some adjacent
7791         // dword slot in the source mask.
7792         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7793                               IncomingInputs[1] - SourceOffset};
7794
7795         // If there is a free slot in the source half mask adjacent to one of
7796         // the inputs, place the other input in it. We use (Index XOR 1) to
7797         // compute an adjacent index.
7798         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7799             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7800           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7801           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7802           InputsFixed[1] = InputsFixed[0] ^ 1;
7803         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7804                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7805           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7806           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7807           InputsFixed[0] = InputsFixed[1] ^ 1;
7808         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7809                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7810           // The two inputs are in the same DWord but it is clobbered and the
7811           // adjacent DWord isn't used at all. Move both inputs to the free
7812           // slot.
7813           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7814           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7815           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7816           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7817         } else {
7818           // The only way we hit this point is if there is no clobbering
7819           // (because there are no off-half inputs to this half) and there is no
7820           // free slot adjacent to one of the inputs. In this case, we have to
7821           // swap an input with a non-input.
7822           for (int i = 0; i < 4; ++i)
7823             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7824                    "We can't handle any clobbers here!");
7825           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7826                  "Cannot have adjacent inputs here!");
7827
7828           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7829           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7830
7831           // We also have to update the final source mask in this case because
7832           // it may need to undo the above swap.
7833           for (int &M : FinalSourceHalfMask)
7834             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7835               M = InputsFixed[1] + SourceOffset;
7836             else if (M == InputsFixed[1] + SourceOffset)
7837               M = (InputsFixed[0] ^ 1) + SourceOffset;
7838
7839           InputsFixed[1] = InputsFixed[0] ^ 1;
7840         }
7841
7842         // Point everything at the fixed inputs.
7843         for (int &M : HalfMask)
7844           if (M == IncomingInputs[0])
7845             M = InputsFixed[0] + SourceOffset;
7846           else if (M == IncomingInputs[1])
7847             M = InputsFixed[1] + SourceOffset;
7848
7849         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7850         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7851       }
7852     } else {
7853       llvm_unreachable("Unhandled input size!");
7854     }
7855
7856     // Now hoist the DWord down to the right half.
7857     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7858     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7859     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7860     for (int &M : HalfMask)
7861       for (int Input : IncomingInputs)
7862         if (M == Input)
7863           M = FreeDWord * 2 + Input % 2;
7864   };
7865   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7866                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7867   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7868                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7869
7870   // Now enact all the shuffles we've computed to move the inputs into their
7871   // target half.
7872   if (!isNoopShuffleMask(PSHUFLMask))
7873     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7874                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7875   if (!isNoopShuffleMask(PSHUFHMask))
7876     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7877                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7878   if (!isNoopShuffleMask(PSHUFDMask))
7879     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7880                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7881                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7882                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7883
7884   // At this point, each half should contain all its inputs, and we can then
7885   // just shuffle them into their final position.
7886   assert(std::count_if(LoMask.begin(), LoMask.end(),
7887                        [](int M) { return M >= 4; }) == 0 &&
7888          "Failed to lift all the high half inputs to the low mask!");
7889   assert(std::count_if(HiMask.begin(), HiMask.end(),
7890                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7891          "Failed to lift all the low half inputs to the high mask!");
7892
7893   // Do a half shuffle for the low mask.
7894   if (!isNoopShuffleMask(LoMask))
7895     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7896                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7897
7898   // Do a half shuffle with the high mask after shifting its values down.
7899   for (int &M : HiMask)
7900     if (M >= 0)
7901       M -= 4;
7902   if (!isNoopShuffleMask(HiMask))
7903     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7904                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7905
7906   return V;
7907 }
7908
7909 /// \brief Detect whether the mask pattern should be lowered through
7910 /// interleaving.
7911 ///
7912 /// This essentially tests whether viewing the mask as an interleaving of two
7913 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7914 /// lowering it through interleaving is a significantly better strategy.
7915 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7916   int NumEvenInputs[2] = {0, 0};
7917   int NumOddInputs[2] = {0, 0};
7918   int NumLoInputs[2] = {0, 0};
7919   int NumHiInputs[2] = {0, 0};
7920   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7921     if (Mask[i] < 0)
7922       continue;
7923
7924     int InputIdx = Mask[i] >= Size;
7925
7926     if (i < Size / 2)
7927       ++NumLoInputs[InputIdx];
7928     else
7929       ++NumHiInputs[InputIdx];
7930
7931     if ((i % 2) == 0)
7932       ++NumEvenInputs[InputIdx];
7933     else
7934       ++NumOddInputs[InputIdx];
7935   }
7936
7937   // The minimum number of cross-input results for both the interleaved and
7938   // split cases. If interleaving results in fewer cross-input results, return
7939   // true.
7940   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7941                                     NumEvenInputs[0] + NumOddInputs[1]);
7942   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7943                               NumLoInputs[0] + NumHiInputs[1]);
7944   return InterleavedCrosses < SplitCrosses;
7945 }
7946
7947 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7948 ///
7949 /// This strategy only works when the inputs from each vector fit into a single
7950 /// half of that vector, and generally there are not so many inputs as to leave
7951 /// the in-place shuffles required highly constrained (and thus expensive). It
7952 /// shifts all the inputs into a single side of both input vectors and then
7953 /// uses an unpack to interleave these inputs in a single vector. At that
7954 /// point, we will fall back on the generic single input shuffle lowering.
7955 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7956                                                  SDValue V2,
7957                                                  MutableArrayRef<int> Mask,
7958                                                  const X86Subtarget *Subtarget,
7959                                                  SelectionDAG &DAG) {
7960   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7961   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7962   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7963   for (int i = 0; i < 8; ++i)
7964     if (Mask[i] >= 0 && Mask[i] < 4)
7965       LoV1Inputs.push_back(i);
7966     else if (Mask[i] >= 4 && Mask[i] < 8)
7967       HiV1Inputs.push_back(i);
7968     else if (Mask[i] >= 8 && Mask[i] < 12)
7969       LoV2Inputs.push_back(i);
7970     else if (Mask[i] >= 12)
7971       HiV2Inputs.push_back(i);
7972
7973   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7974   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7975   (void)NumV1Inputs;
7976   (void)NumV2Inputs;
7977   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7978   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7979   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7980
7981   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7982                      HiV1Inputs.size() + HiV2Inputs.size();
7983
7984   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7985                               ArrayRef<int> HiInputs, bool MoveToLo,
7986                               int MaskOffset) {
7987     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7988     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7989     if (BadInputs.empty())
7990       return V;
7991
7992     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7993     int MoveOffset = MoveToLo ? 0 : 4;
7994
7995     if (GoodInputs.empty()) {
7996       for (int BadInput : BadInputs) {
7997         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7998         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7999       }
8000     } else {
8001       if (GoodInputs.size() == 2) {
8002         // If the low inputs are spread across two dwords, pack them into
8003         // a single dword.
8004         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
8005         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
8006         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
8007         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
8008       } else {
8009         // Otherwise pin the good inputs.
8010         for (int GoodInput : GoodInputs)
8011           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
8012       }
8013
8014       if (BadInputs.size() == 2) {
8015         // If we have two bad inputs then there may be either one or two good
8016         // inputs fixed in place. Find a fixed input, and then find the *other*
8017         // two adjacent indices by using modular arithmetic.
8018         int GoodMaskIdx =
8019             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
8020                          [](int M) { return M >= 0; }) -
8021             std::begin(MoveMask);
8022         int MoveMaskIdx =
8023             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
8024         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
8025         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
8026         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8027         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
8028         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8029         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
8030       } else {
8031         assert(BadInputs.size() == 1 && "All sizes handled");
8032         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
8033                                     std::end(MoveMask), -1) -
8034                           std::begin(MoveMask);
8035         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8036         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8037       }
8038     }
8039
8040     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8041                                 MoveMask);
8042   };
8043   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
8044                         /*MaskOffset*/ 0);
8045   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
8046                         /*MaskOffset*/ 8);
8047
8048   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
8049   // cross-half traffic in the final shuffle.
8050
8051   // Munge the mask to be a single-input mask after the unpack merges the
8052   // results.
8053   for (int &M : Mask)
8054     if (M != -1)
8055       M = 2 * (M % 4) + (M / 8);
8056
8057   return DAG.getVectorShuffle(
8058       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
8059                                   DL, MVT::v8i16, V1, V2),
8060       DAG.getUNDEF(MVT::v8i16), Mask);
8061 }
8062
8063 /// \brief Generic lowering of 8-lane i16 shuffles.
8064 ///
8065 /// This handles both single-input shuffles and combined shuffle/blends with
8066 /// two inputs. The single input shuffles are immediately delegated to
8067 /// a dedicated lowering routine.
8068 ///
8069 /// The blends are lowered in one of three fundamental ways. If there are few
8070 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8071 /// of the input is significantly cheaper when lowered as an interleaving of
8072 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8073 /// halves of the inputs separately (making them have relatively few inputs)
8074 /// and then concatenate them.
8075 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8076                                        const X86Subtarget *Subtarget,
8077                                        SelectionDAG &DAG) {
8078   SDLoc DL(Op);
8079   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8080   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8081   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8082   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8083   ArrayRef<int> OrigMask = SVOp->getMask();
8084   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8085                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8086   MutableArrayRef<int> Mask(MaskStorage);
8087
8088   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8089
8090   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8091   auto isV2 = [](int M) { return M >= 8; };
8092
8093   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
8094   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8095
8096   if (NumV2Inputs == 0)
8097     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8098
8099   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
8100                             "to be V1-input shuffles.");
8101
8102   if (NumV1Inputs + NumV2Inputs <= 4)
8103     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
8104
8105   // Check whether an interleaving lowering is likely to be more efficient.
8106   // This isn't perfect but it is a strong heuristic that tends to work well on
8107   // the kinds of shuffles that show up in practice.
8108   //
8109   // FIXME: Handle 1x, 2x, and 4x interleaving.
8110   if (shouldLowerAsInterleaving(Mask)) {
8111     // FIXME: Figure out whether we should pack these into the low or high
8112     // halves.
8113
8114     int EMask[8], OMask[8];
8115     for (int i = 0; i < 4; ++i) {
8116       EMask[i] = Mask[2*i];
8117       OMask[i] = Mask[2*i + 1];
8118       EMask[i + 4] = -1;
8119       OMask[i + 4] = -1;
8120     }
8121
8122     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8123     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8124
8125     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8126   }
8127
8128   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8129   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8130
8131   for (int i = 0; i < 4; ++i) {
8132     LoBlendMask[i] = Mask[i];
8133     HiBlendMask[i] = Mask[i + 4];
8134   }
8135
8136   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8137   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8138   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8139   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8140
8141   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8142                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8143 }
8144
8145 /// \brief Check whether a compaction lowering can be done by dropping even
8146 /// elements and compute how many times even elements must be dropped.
8147 ///
8148 /// This handles shuffles which take every Nth element where N is a power of
8149 /// two. Example shuffle masks:
8150 ///
8151 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8152 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8153 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8154 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8155 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8156 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8157 ///
8158 /// Any of these lanes can of course be undef.
8159 ///
8160 /// This routine only supports N <= 3.
8161 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8162 /// for larger N.
8163 ///
8164 /// \returns N above, or the number of times even elements must be dropped if
8165 /// there is such a number. Otherwise returns zero.
8166 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8167   // Figure out whether we're looping over two inputs or just one.
8168   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8169
8170   // The modulus for the shuffle vector entries is based on whether this is
8171   // a single input or not.
8172   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8173   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8174          "We should only be called with masks with a power-of-2 size!");
8175
8176   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8177
8178   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8179   // and 2^3 simultaneously. This is because we may have ambiguity with
8180   // partially undef inputs.
8181   bool ViableForN[3] = {true, true, true};
8182
8183   for (int i = 0, e = Mask.size(); i < e; ++i) {
8184     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8185     // want.
8186     if (Mask[i] == -1)
8187       continue;
8188
8189     bool IsAnyViable = false;
8190     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8191       if (ViableForN[j]) {
8192         uint64_t N = j + 1;
8193
8194         // The shuffle mask must be equal to (i * 2^N) % M.
8195         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8196           IsAnyViable = true;
8197         else
8198           ViableForN[j] = false;
8199       }
8200     // Early exit if we exhaust the possible powers of two.
8201     if (!IsAnyViable)
8202       break;
8203   }
8204
8205   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8206     if (ViableForN[j])
8207       return j + 1;
8208
8209   // Return 0 as there is no viable power of two.
8210   return 0;
8211 }
8212
8213 /// \brief Generic lowering of v16i8 shuffles.
8214 ///
8215 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8216 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8217 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8218 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8219 /// back together.
8220 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8221                                        const X86Subtarget *Subtarget,
8222                                        SelectionDAG &DAG) {
8223   SDLoc DL(Op);
8224   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8225   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8226   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8227   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8228   ArrayRef<int> OrigMask = SVOp->getMask();
8229   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8230   int MaskStorage[16] = {
8231       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8232       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8233       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8234       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8235   MutableArrayRef<int> Mask(MaskStorage);
8236   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8237   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8238
8239   // For single-input shuffles, there are some nicer lowering tricks we can use.
8240   if (isSingleInputShuffleMask(Mask)) {
8241     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8242     // Notably, this handles splat and partial-splat shuffles more efficiently.
8243     // However, it only makes sense if the pre-duplication shuffle simplifies
8244     // things significantly. Currently, this means we need to be able to
8245     // express the pre-duplication shuffle as an i16 shuffle.
8246     //
8247     // FIXME: We should check for other patterns which can be widened into an
8248     // i16 shuffle as well.
8249     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8250       for (int i = 0; i < 16; i += 2) {
8251         if (Mask[i] != Mask[i + 1])
8252           return false;
8253       }
8254       return true;
8255     };
8256     auto tryToWidenViaDuplication = [&]() -> SDValue {
8257       if (!canWidenViaDuplication(Mask))
8258         return SDValue();
8259       SmallVector<int, 4> LoInputs;
8260       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8261                    [](int M) { return M >= 0 && M < 8; });
8262       std::sort(LoInputs.begin(), LoInputs.end());
8263       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8264                      LoInputs.end());
8265       SmallVector<int, 4> HiInputs;
8266       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8267                    [](int M) { return M >= 8; });
8268       std::sort(HiInputs.begin(), HiInputs.end());
8269       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8270                      HiInputs.end());
8271
8272       bool TargetLo = LoInputs.size() >= HiInputs.size();
8273       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8274       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8275
8276       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8277       SmallDenseMap<int, int, 8> LaneMap;
8278       for (int I : InPlaceInputs) {
8279         PreDupI16Shuffle[I/2] = I/2;
8280         LaneMap[I] = I;
8281       }
8282       int j = TargetLo ? 0 : 4, je = j + 4;
8283       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8284         // Check if j is already a shuffle of this input. This happens when
8285         // there are two adjacent bytes after we move the low one.
8286         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8287           // If we haven't yet mapped the input, search for a slot into which
8288           // we can map it.
8289           while (j < je && PreDupI16Shuffle[j] != -1)
8290             ++j;
8291
8292           if (j == je)
8293             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8294             return SDValue();
8295
8296           // Map this input with the i16 shuffle.
8297           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8298         }
8299
8300         // Update the lane map based on the mapping we ended up with.
8301         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8302       }
8303       V1 = DAG.getNode(
8304           ISD::BITCAST, DL, MVT::v16i8,
8305           DAG.getVectorShuffle(MVT::v8i16, DL,
8306                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8307                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8308
8309       // Unpack the bytes to form the i16s that will be shuffled into place.
8310       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8311                        MVT::v16i8, V1, V1);
8312
8313       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8314       for (int i = 0; i < 16; i += 2) {
8315         if (Mask[i] != -1)
8316           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8317         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8318       }
8319       return DAG.getNode(
8320           ISD::BITCAST, DL, MVT::v16i8,
8321           DAG.getVectorShuffle(MVT::v8i16, DL,
8322                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8323                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8324     };
8325     if (SDValue V = tryToWidenViaDuplication())
8326       return V;
8327   }
8328
8329   // Check whether an interleaving lowering is likely to be more efficient.
8330   // This isn't perfect but it is a strong heuristic that tends to work well on
8331   // the kinds of shuffles that show up in practice.
8332   //
8333   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8334   if (shouldLowerAsInterleaving(Mask)) {
8335     // FIXME: Figure out whether we should pack these into the low or high
8336     // halves.
8337
8338     int EMask[16], OMask[16];
8339     for (int i = 0; i < 8; ++i) {
8340       EMask[i] = Mask[2*i];
8341       OMask[i] = Mask[2*i + 1];
8342       EMask[i + 8] = -1;
8343       OMask[i + 8] = -1;
8344     }
8345
8346     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8347     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8348
8349     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8350   }
8351
8352   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8353   // with PSHUFB. It is important to do this before we attempt to generate any
8354   // blends but after all of the single-input lowerings. If the single input
8355   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8356   // want to preserve that and we can DAG combine any longer sequences into
8357   // a PSHUFB in the end. But once we start blending from multiple inputs,
8358   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8359   // and there are *very* few patterns that would actually be faster than the
8360   // PSHUFB approach because of its ability to zero lanes.
8361   //
8362   // FIXME: The only exceptions to the above are blends which are exact
8363   // interleavings with direct instructions supporting them. We currently don't
8364   // handle those well here.
8365   if (Subtarget->hasSSSE3()) {
8366     SDValue V1Mask[16];
8367     SDValue V2Mask[16];
8368     for (int i = 0; i < 16; ++i)
8369       if (Mask[i] == -1) {
8370         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8371       } else {
8372         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8373         V2Mask[i] =
8374             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8375       }
8376     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8377                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8378     if (isSingleInputShuffleMask(Mask))
8379       return V1; // Single inputs are easy.
8380
8381     // Otherwise, blend the two.
8382     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8383                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8384     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8385   }
8386
8387   // Check whether a compaction lowering can be done. This handles shuffles
8388   // which take every Nth element for some even N. See the helper function for
8389   // details.
8390   //
8391   // We special case these as they can be particularly efficiently handled with
8392   // the PACKUSB instruction on x86 and they show up in common patterns of
8393   // rearranging bytes to truncate wide elements.
8394   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8395     // NumEvenDrops is the power of two stride of the elements. Another way of
8396     // thinking about it is that we need to drop the even elements this many
8397     // times to get the original input.
8398     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8399
8400     // First we need to zero all the dropped bytes.
8401     assert(NumEvenDrops <= 3 &&
8402            "No support for dropping even elements more than 3 times.");
8403     // We use the mask type to pick which bytes are preserved based on how many
8404     // elements are dropped.
8405     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8406     SDValue ByteClearMask =
8407         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8408                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8409     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8410     if (!IsSingleInput)
8411       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8412
8413     // Now pack things back together.
8414     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8415     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8416     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8417     for (int i = 1; i < NumEvenDrops; ++i) {
8418       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8419       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8420     }
8421
8422     return Result;
8423   }
8424
8425   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8426   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8427   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8428   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8429
8430   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8431                             MutableArrayRef<int> V1HalfBlendMask,
8432                             MutableArrayRef<int> V2HalfBlendMask) {
8433     for (int i = 0; i < 8; ++i)
8434       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8435         V1HalfBlendMask[i] = HalfMask[i];
8436         HalfMask[i] = i;
8437       } else if (HalfMask[i] >= 16) {
8438         V2HalfBlendMask[i] = HalfMask[i] - 16;
8439         HalfMask[i] = i + 8;
8440       }
8441   };
8442   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8443   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8444
8445   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8446
8447   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8448                              MutableArrayRef<int> HiBlendMask) {
8449     SDValue V1, V2;
8450     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8451     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8452     // i16s.
8453     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8454                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8455         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8456                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8457       // Use a mask to drop the high bytes.
8458       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8459       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8460                        DAG.getConstant(0x00FF, MVT::v8i16));
8461
8462       // This will be a single vector shuffle instead of a blend so nuke V2.
8463       V2 = DAG.getUNDEF(MVT::v8i16);
8464
8465       // Squash the masks to point directly into V1.
8466       for (int &M : LoBlendMask)
8467         if (M >= 0)
8468           M /= 2;
8469       for (int &M : HiBlendMask)
8470         if (M >= 0)
8471           M /= 2;
8472     } else {
8473       // Otherwise just unpack the low half of V into V1 and the high half into
8474       // V2 so that we can blend them as i16s.
8475       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8476                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8477       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8478                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8479     }
8480
8481     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8482     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8483     return std::make_pair(BlendedLo, BlendedHi);
8484   };
8485   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8486   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8487   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8488
8489   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8490   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8491
8492   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8493 }
8494
8495 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8496 ///
8497 /// This routine breaks down the specific type of 128-bit shuffle and
8498 /// dispatches to the lowering routines accordingly.
8499 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8500                                         MVT VT, const X86Subtarget *Subtarget,
8501                                         SelectionDAG &DAG) {
8502   switch (VT.SimpleTy) {
8503   case MVT::v2i64:
8504     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8505   case MVT::v2f64:
8506     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8507   case MVT::v4i32:
8508     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8509   case MVT::v4f32:
8510     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8511   case MVT::v8i16:
8512     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8513   case MVT::v16i8:
8514     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8515
8516   default:
8517     llvm_unreachable("Unimplemented!");
8518   }
8519 }
8520
8521 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8522   int Size = Mask.size();
8523   for (int M : Mask.slice(0, Size / 2))
8524     if (M >= 0 && (M % Size) >= Size / 2)
8525       return true;
8526   for (int M : Mask.slice(Size / 2, Size / 2))
8527     if (M >= 0 && (M % Size) < Size / 2)
8528       return true;
8529   return false;
8530 }
8531
8532 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8533 /// shuffles.
8534 ///
8535 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8536 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8537 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8538 /// we encode the logic here for specific shuffle lowering routines to bail to
8539 /// when they exhaust the features avaible to more directly handle the shuffle.
8540 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8541                                                 SDValue V2,
8542                                                 const X86Subtarget *Subtarget,
8543                                                 SelectionDAG &DAG) {
8544   SDLoc DL(Op);
8545   MVT VT = Op.getSimpleValueType();
8546   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8547   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8548   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8549   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8550   ArrayRef<int> Mask = SVOp->getMask();
8551
8552   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8553   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8554
8555   int NumElements = VT.getVectorNumElements();
8556   int SplitNumElements = NumElements / 2;
8557   MVT ScalarVT = VT.getScalarType();
8558   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8559
8560   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8561                              DAG.getIntPtrConstant(0));
8562   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8563                              DAG.getIntPtrConstant(SplitNumElements));
8564   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8565                              DAG.getIntPtrConstant(0));
8566   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8567                              DAG.getIntPtrConstant(SplitNumElements));
8568
8569   // Now create two 4-way blends of these half-width vectors.
8570   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8571     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8572     for (int i = 0; i < SplitNumElements; ++i) {
8573       int M = HalfMask[i];
8574       if (M >= NumElements) {
8575         V2BlendMask.push_back(M - NumElements);
8576         V1BlendMask.push_back(-1);
8577         BlendMask.push_back(SplitNumElements + i);
8578       } else if (M >= 0) {
8579         V2BlendMask.push_back(-1);
8580         V1BlendMask.push_back(M);
8581         BlendMask.push_back(i);
8582       } else {
8583         V2BlendMask.push_back(-1);
8584         V1BlendMask.push_back(-1);
8585         BlendMask.push_back(-1);
8586       }
8587     }
8588     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8589     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8590     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8591   };
8592   SDValue Lo = HalfBlend(LoMask);
8593   SDValue Hi = HalfBlend(HiMask);
8594   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8595 }
8596
8597 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8598 ///
8599 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8600 /// isn't available.
8601 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8602                                        const X86Subtarget *Subtarget,
8603                                        SelectionDAG &DAG) {
8604   SDLoc DL(Op);
8605   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8606   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8607   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8608   ArrayRef<int> Mask = SVOp->getMask();
8609   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8610
8611   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8612   // shuffles aren't a problem and FP and int have the same patterns.
8613
8614   // FIXME: We can handle these more cleverly than splitting for v4f64.
8615   if (isHalfCrossingShuffleMask(Mask))
8616     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8617
8618   if (isSingleInputShuffleMask(Mask)) {
8619     // Non-half-crossing single input shuffles can be lowerid with an
8620     // interleaved permutation.
8621     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8622                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8623     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8624                        DAG.getConstant(VPERMILPMask, MVT::i8));
8625   }
8626
8627   // X86 has dedicated unpack instructions that can handle specific blend
8628   // operations: UNPCKH and UNPCKL.
8629   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8630     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8631   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8632     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8633   // FIXME: It would be nice to find a way to get canonicalization to commute
8634   // these patterns.
8635   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8636     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8637   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8638     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8639
8640   // Check if the blend happens to exactly fit that of SHUFPD.
8641   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8642       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8643     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8644                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8645     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8646                        DAG.getConstant(SHUFPDMask, MVT::i8));
8647   }
8648   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8649       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8650     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8651                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8652     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8653                        DAG.getConstant(SHUFPDMask, MVT::i8));
8654   }
8655
8656   // Shuffle the input elements into the desired positions in V1 and V2 and
8657   // blend them together.
8658   int V1Mask[] = {-1, -1, -1, -1};
8659   int V2Mask[] = {-1, -1, -1, -1};
8660   for (int i = 0; i < 4; ++i)
8661     if (Mask[i] >= 0 && Mask[i] < 4)
8662       V1Mask[i] = Mask[i];
8663     else if (Mask[i] >= 4)
8664       V2Mask[i] = Mask[i] - 4;
8665
8666   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8667   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8668
8669   unsigned BlendMask = 0;
8670   for (int i = 0; i < 4; ++i)
8671     if (Mask[i] >= 4)
8672       BlendMask |= 1 << i;
8673
8674   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8675                      DAG.getConstant(BlendMask, MVT::i8));
8676 }
8677
8678 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8679 ///
8680 /// Largely delegates to common code when we have AVX2 and to the floating-point
8681 /// code when we only have AVX.
8682 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8683                                        const X86Subtarget *Subtarget,
8684                                        SelectionDAG &DAG) {
8685   SDLoc DL(Op);
8686   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8687   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8688   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8689   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8690   ArrayRef<int> Mask = SVOp->getMask();
8691   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8692
8693   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8694   // shuffles aren't a problem and FP and int have the same patterns.
8695
8696   if (isHalfCrossingShuffleMask(Mask))
8697     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8698
8699   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8700   // delegate to floating point code.
8701   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8702   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8703   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8704                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8705 }
8706
8707 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8708 ///
8709 /// This routine either breaks down the specific type of a 256-bit x86 vector
8710 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8711 /// together based on the available instructions.
8712 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8713                                         MVT VT, const X86Subtarget *Subtarget,
8714                                         SelectionDAG &DAG) {
8715   switch (VT.SimpleTy) {
8716   case MVT::v4f64:
8717     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8718   case MVT::v4i64:
8719     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8720   case MVT::v8i32:
8721   case MVT::v8f32:
8722   case MVT::v16i16:
8723   case MVT::v32i8:
8724     // Fall back to the basic pattern of extracting the high half and forming
8725     // a 4-way blend.
8726     // FIXME: Add targeted lowering for each type that can document rationale
8727     // for delegating to this when necessary.
8728     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8729
8730   default:
8731     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8732   }
8733 }
8734
8735 /// \brief Tiny helper function to test whether a shuffle mask could be
8736 /// simplified by widening the elements being shuffled.
8737 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8738   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8739     if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8740       return false;
8741
8742   return true;
8743 }
8744
8745 /// \brief Top-level lowering for x86 vector shuffles.
8746 ///
8747 /// This handles decomposition, canonicalization, and lowering of all x86
8748 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8749 /// above in helper routines. The canonicalization attempts to widen shuffles
8750 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8751 /// s.t. only one of the two inputs needs to be tested, etc.
8752 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8753                                   SelectionDAG &DAG) {
8754   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8755   ArrayRef<int> Mask = SVOp->getMask();
8756   SDValue V1 = Op.getOperand(0);
8757   SDValue V2 = Op.getOperand(1);
8758   MVT VT = Op.getSimpleValueType();
8759   int NumElements = VT.getVectorNumElements();
8760   SDLoc dl(Op);
8761
8762   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8763
8764   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8765   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8766   if (V1IsUndef && V2IsUndef)
8767     return DAG.getUNDEF(VT);
8768
8769   // When we create a shuffle node we put the UNDEF node to second operand,
8770   // but in some cases the first operand may be transformed to UNDEF.
8771   // In this case we should just commute the node.
8772   if (V1IsUndef)
8773     return DAG.getCommutedVectorShuffle(*SVOp);
8774
8775   // Check for non-undef masks pointing at an undef vector and make the masks
8776   // undef as well. This makes it easier to match the shuffle based solely on
8777   // the mask.
8778   if (V2IsUndef)
8779     for (int M : Mask)
8780       if (M >= NumElements) {
8781         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8782         for (int &M : NewMask)
8783           if (M >= NumElements)
8784             M = -1;
8785         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8786       }
8787
8788   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8789   // lanes but wider integers. We cap this to not form integers larger than i64
8790   // but it might be interesting to form i128 integers to handle flipping the
8791   // low and high halves of AVX 256-bit vectors.
8792   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8793       canWidenShuffleElements(Mask)) {
8794     SmallVector<int, 8> NewMask;
8795     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8796       NewMask.push_back(Mask[i] / 2);
8797     MVT NewVT =
8798         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8799                          VT.getVectorNumElements() / 2);
8800     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8801     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8802     return DAG.getNode(ISD::BITCAST, dl, VT,
8803                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8804   }
8805
8806   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8807   for (int M : SVOp->getMask())
8808     if (M < 0)
8809       ++NumUndefElements;
8810     else if (M < NumElements)
8811       ++NumV1Elements;
8812     else
8813       ++NumV2Elements;
8814
8815   // Commute the shuffle as needed such that more elements come from V1 than
8816   // V2. This allows us to match the shuffle pattern strictly on how many
8817   // elements come from V1 without handling the symmetric cases.
8818   if (NumV2Elements > NumV1Elements)
8819     return DAG.getCommutedVectorShuffle(*SVOp);
8820
8821   // When the number of V1 and V2 elements are the same, try to minimize the
8822   // number of uses of V2 in the low half of the vector.
8823   if (NumV1Elements == NumV2Elements) {
8824     int LowV1Elements = 0, LowV2Elements = 0;
8825     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8826       if (M >= NumElements)
8827         ++LowV2Elements;
8828       else if (M >= 0)
8829         ++LowV1Elements;
8830     if (LowV2Elements > LowV1Elements)
8831       return DAG.getCommutedVectorShuffle(*SVOp);
8832   }
8833
8834   // For each vector width, delegate to a specialized lowering routine.
8835   if (VT.getSizeInBits() == 128)
8836     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8837
8838   if (VT.getSizeInBits() == 256)
8839     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8840
8841   llvm_unreachable("Unimplemented!");
8842 }
8843
8844
8845 //===----------------------------------------------------------------------===//
8846 // Legacy vector shuffle lowering
8847 //
8848 // This code is the legacy code handling vector shuffles until the above
8849 // replaces its functionality and performance.
8850 //===----------------------------------------------------------------------===//
8851
8852 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8853                         bool hasInt256, unsigned *MaskOut = nullptr) {
8854   MVT EltVT = VT.getVectorElementType();
8855
8856   // There is no blend with immediate in AVX-512.
8857   if (VT.is512BitVector())
8858     return false;
8859
8860   if (!hasSSE41 || EltVT == MVT::i8)
8861     return false;
8862   if (!hasInt256 && VT == MVT::v16i16)
8863     return false;
8864
8865   unsigned MaskValue = 0;
8866   unsigned NumElems = VT.getVectorNumElements();
8867   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8868   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8869   unsigned NumElemsInLane = NumElems / NumLanes;
8870
8871   // Blend for v16i16 should be symetric for the both lanes.
8872   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8873
8874     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8875     int EltIdx = MaskVals[i];
8876
8877     if ((EltIdx < 0 || EltIdx == (int)i) &&
8878         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8879       continue;
8880
8881     if (((unsigned)EltIdx == (i + NumElems)) &&
8882         (SndLaneEltIdx < 0 ||
8883          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8884       MaskValue |= (1 << i);
8885     else
8886       return false;
8887   }
8888
8889   if (MaskOut)
8890     *MaskOut = MaskValue;
8891   return true;
8892 }
8893
8894 // Try to lower a shuffle node into a simple blend instruction.
8895 // This function assumes isBlendMask returns true for this
8896 // SuffleVectorSDNode
8897 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8898                                           unsigned MaskValue,
8899                                           const X86Subtarget *Subtarget,
8900                                           SelectionDAG &DAG) {
8901   MVT VT = SVOp->getSimpleValueType(0);
8902   MVT EltVT = VT.getVectorElementType();
8903   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8904                      Subtarget->hasInt256() && "Trying to lower a "
8905                                                "VECTOR_SHUFFLE to a Blend but "
8906                                                "with the wrong mask"));
8907   SDValue V1 = SVOp->getOperand(0);
8908   SDValue V2 = SVOp->getOperand(1);
8909   SDLoc dl(SVOp);
8910   unsigned NumElems = VT.getVectorNumElements();
8911
8912   // Convert i32 vectors to floating point if it is not AVX2.
8913   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8914   MVT BlendVT = VT;
8915   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8916     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8917                                NumElems);
8918     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8919     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8920   }
8921
8922   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8923                             DAG.getConstant(MaskValue, MVT::i32));
8924   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8925 }
8926
8927 /// In vector type \p VT, return true if the element at index \p InputIdx
8928 /// falls on a different 128-bit lane than \p OutputIdx.
8929 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8930                                      unsigned OutputIdx) {
8931   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8932   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8933 }
8934
8935 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8936 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8937 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8938 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8939 /// zero.
8940 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8941                          SelectionDAG &DAG) {
8942   MVT VT = V1.getSimpleValueType();
8943   assert(VT.is128BitVector() || VT.is256BitVector());
8944
8945   MVT EltVT = VT.getVectorElementType();
8946   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8947   unsigned NumElts = VT.getVectorNumElements();
8948
8949   SmallVector<SDValue, 32> PshufbMask;
8950   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8951     int InputIdx = MaskVals[OutputIdx];
8952     unsigned InputByteIdx;
8953
8954     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8955       InputByteIdx = 0x80;
8956     else {
8957       // Cross lane is not allowed.
8958       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8959         return SDValue();
8960       InputByteIdx = InputIdx * EltSizeInBytes;
8961       // Index is an byte offset within the 128-bit lane.
8962       InputByteIdx &= 0xf;
8963     }
8964
8965     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8966       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8967       if (InputByteIdx != 0x80)
8968         ++InputByteIdx;
8969     }
8970   }
8971
8972   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8973   if (ShufVT != VT)
8974     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8975   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8976                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8977 }
8978
8979 // v8i16 shuffles - Prefer shuffles in the following order:
8980 // 1. [all]   pshuflw, pshufhw, optional move
8981 // 2. [ssse3] 1 x pshufb
8982 // 3. [ssse3] 2 x pshufb + 1 x por
8983 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8984 static SDValue
8985 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8986                          SelectionDAG &DAG) {
8987   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8988   SDValue V1 = SVOp->getOperand(0);
8989   SDValue V2 = SVOp->getOperand(1);
8990   SDLoc dl(SVOp);
8991   SmallVector<int, 8> MaskVals;
8992
8993   // Determine if more than 1 of the words in each of the low and high quadwords
8994   // of the result come from the same quadword of one of the two inputs.  Undef
8995   // mask values count as coming from any quadword, for better codegen.
8996   //
8997   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8998   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8999   unsigned LoQuad[] = { 0, 0, 0, 0 };
9000   unsigned HiQuad[] = { 0, 0, 0, 0 };
9001   // Indices of quads used.
9002   std::bitset<4> InputQuads;
9003   for (unsigned i = 0; i < 8; ++i) {
9004     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
9005     int EltIdx = SVOp->getMaskElt(i);
9006     MaskVals.push_back(EltIdx);
9007     if (EltIdx < 0) {
9008       ++Quad[0];
9009       ++Quad[1];
9010       ++Quad[2];
9011       ++Quad[3];
9012       continue;
9013     }
9014     ++Quad[EltIdx / 4];
9015     InputQuads.set(EltIdx / 4);
9016   }
9017
9018   int BestLoQuad = -1;
9019   unsigned MaxQuad = 1;
9020   for (unsigned i = 0; i < 4; ++i) {
9021     if (LoQuad[i] > MaxQuad) {
9022       BestLoQuad = i;
9023       MaxQuad = LoQuad[i];
9024     }
9025   }
9026
9027   int BestHiQuad = -1;
9028   MaxQuad = 1;
9029   for (unsigned i = 0; i < 4; ++i) {
9030     if (HiQuad[i] > MaxQuad) {
9031       BestHiQuad = i;
9032       MaxQuad = HiQuad[i];
9033     }
9034   }
9035
9036   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
9037   // of the two input vectors, shuffle them into one input vector so only a
9038   // single pshufb instruction is necessary. If there are more than 2 input
9039   // quads, disable the next transformation since it does not help SSSE3.
9040   bool V1Used = InputQuads[0] || InputQuads[1];
9041   bool V2Used = InputQuads[2] || InputQuads[3];
9042   if (Subtarget->hasSSSE3()) {
9043     if (InputQuads.count() == 2 && V1Used && V2Used) {
9044       BestLoQuad = InputQuads[0] ? 0 : 1;
9045       BestHiQuad = InputQuads[2] ? 2 : 3;
9046     }
9047     if (InputQuads.count() > 2) {
9048       BestLoQuad = -1;
9049       BestHiQuad = -1;
9050     }
9051   }
9052
9053   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
9054   // the shuffle mask.  If a quad is scored as -1, that means that it contains
9055   // words from all 4 input quadwords.
9056   SDValue NewV;
9057   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
9058     int MaskV[] = {
9059       BestLoQuad < 0 ? 0 : BestLoQuad,
9060       BestHiQuad < 0 ? 1 : BestHiQuad
9061     };
9062     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
9063                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
9064                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
9065     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
9066
9067     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
9068     // source words for the shuffle, to aid later transformations.
9069     bool AllWordsInNewV = true;
9070     bool InOrder[2] = { true, true };
9071     for (unsigned i = 0; i != 8; ++i) {
9072       int idx = MaskVals[i];
9073       if (idx != (int)i)
9074         InOrder[i/4] = false;
9075       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
9076         continue;
9077       AllWordsInNewV = false;
9078       break;
9079     }
9080
9081     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
9082     if (AllWordsInNewV) {
9083       for (int i = 0; i != 8; ++i) {
9084         int idx = MaskVals[i];
9085         if (idx < 0)
9086           continue;
9087         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
9088         if ((idx != i) && idx < 4)
9089           pshufhw = false;
9090         if ((idx != i) && idx > 3)
9091           pshuflw = false;
9092       }
9093       V1 = NewV;
9094       V2Used = false;
9095       BestLoQuad = 0;
9096       BestHiQuad = 1;
9097     }
9098
9099     // If we've eliminated the use of V2, and the new mask is a pshuflw or
9100     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
9101     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
9102       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
9103       unsigned TargetMask = 0;
9104       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
9105                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
9106       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9107       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
9108                              getShufflePSHUFLWImmediate(SVOp);
9109       V1 = NewV.getOperand(0);
9110       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
9111     }
9112   }
9113
9114   // Promote splats to a larger type which usually leads to more efficient code.
9115   // FIXME: Is this true if pshufb is available?
9116   if (SVOp->isSplat())
9117     return PromoteSplat(SVOp, DAG);
9118
9119   // If we have SSSE3, and all words of the result are from 1 input vector,
9120   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
9121   // is present, fall back to case 4.
9122   if (Subtarget->hasSSSE3()) {
9123     SmallVector<SDValue,16> pshufbMask;
9124
9125     // If we have elements from both input vectors, set the high bit of the
9126     // shuffle mask element to zero out elements that come from V2 in the V1
9127     // mask, and elements that come from V1 in the V2 mask, so that the two
9128     // results can be OR'd together.
9129     bool TwoInputs = V1Used && V2Used;
9130     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9131     if (!TwoInputs)
9132       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9133
9134     // Calculate the shuffle mask for the second input, shuffle it, and
9135     // OR it with the first shuffled input.
9136     CommuteVectorShuffleMask(MaskVals, 8);
9137     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9138     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9139     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9140   }
9141
9142   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9143   // and update MaskVals with new element order.
9144   std::bitset<8> InOrder;
9145   if (BestLoQuad >= 0) {
9146     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9147     for (int i = 0; i != 4; ++i) {
9148       int idx = MaskVals[i];
9149       if (idx < 0) {
9150         InOrder.set(i);
9151       } else if ((idx / 4) == BestLoQuad) {
9152         MaskV[i] = idx & 3;
9153         InOrder.set(i);
9154       }
9155     }
9156     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9157                                 &MaskV[0]);
9158
9159     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9160       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9161       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9162                                   NewV.getOperand(0),
9163                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9164     }
9165   }
9166
9167   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9168   // and update MaskVals with the new element order.
9169   if (BestHiQuad >= 0) {
9170     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9171     for (unsigned i = 4; i != 8; ++i) {
9172       int idx = MaskVals[i];
9173       if (idx < 0) {
9174         InOrder.set(i);
9175       } else if ((idx / 4) == BestHiQuad) {
9176         MaskV[i] = (idx & 3) + 4;
9177         InOrder.set(i);
9178       }
9179     }
9180     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9181                                 &MaskV[0]);
9182
9183     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9184       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9185       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9186                                   NewV.getOperand(0),
9187                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9188     }
9189   }
9190
9191   // In case BestHi & BestLo were both -1, which means each quadword has a word
9192   // from each of the four input quadwords, calculate the InOrder bitvector now
9193   // before falling through to the insert/extract cleanup.
9194   if (BestLoQuad == -1 && BestHiQuad == -1) {
9195     NewV = V1;
9196     for (int i = 0; i != 8; ++i)
9197       if (MaskVals[i] < 0 || MaskVals[i] == i)
9198         InOrder.set(i);
9199   }
9200
9201   // The other elements are put in the right place using pextrw and pinsrw.
9202   for (unsigned i = 0; i != 8; ++i) {
9203     if (InOrder[i])
9204       continue;
9205     int EltIdx = MaskVals[i];
9206     if (EltIdx < 0)
9207       continue;
9208     SDValue ExtOp = (EltIdx < 8) ?
9209       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9210                   DAG.getIntPtrConstant(EltIdx)) :
9211       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9212                   DAG.getIntPtrConstant(EltIdx - 8));
9213     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9214                        DAG.getIntPtrConstant(i));
9215   }
9216   return NewV;
9217 }
9218
9219 /// \brief v16i16 shuffles
9220 ///
9221 /// FIXME: We only support generation of a single pshufb currently.  We can
9222 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9223 /// well (e.g 2 x pshufb + 1 x por).
9224 static SDValue
9225 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9226   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9227   SDValue V1 = SVOp->getOperand(0);
9228   SDValue V2 = SVOp->getOperand(1);
9229   SDLoc dl(SVOp);
9230
9231   if (V2.getOpcode() != ISD::UNDEF)
9232     return SDValue();
9233
9234   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9235   return getPSHUFB(MaskVals, V1, dl, DAG);
9236 }
9237
9238 // v16i8 shuffles - Prefer shuffles in the following order:
9239 // 1. [ssse3] 1 x pshufb
9240 // 2. [ssse3] 2 x pshufb + 1 x por
9241 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9242 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9243                                         const X86Subtarget* Subtarget,
9244                                         SelectionDAG &DAG) {
9245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9246   SDValue V1 = SVOp->getOperand(0);
9247   SDValue V2 = SVOp->getOperand(1);
9248   SDLoc dl(SVOp);
9249   ArrayRef<int> MaskVals = SVOp->getMask();
9250
9251   // Promote splats to a larger type which usually leads to more efficient code.
9252   // FIXME: Is this true if pshufb is available?
9253   if (SVOp->isSplat())
9254     return PromoteSplat(SVOp, DAG);
9255
9256   // If we have SSSE3, case 1 is generated when all result bytes come from
9257   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9258   // present, fall back to case 3.
9259
9260   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9261   if (Subtarget->hasSSSE3()) {
9262     SmallVector<SDValue,16> pshufbMask;
9263
9264     // If all result elements are from one input vector, then only translate
9265     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9266     //
9267     // Otherwise, we have elements from both input vectors, and must zero out
9268     // elements that come from V2 in the first mask, and V1 in the second mask
9269     // so that we can OR them together.
9270     for (unsigned i = 0; i != 16; ++i) {
9271       int EltIdx = MaskVals[i];
9272       if (EltIdx < 0 || EltIdx >= 16)
9273         EltIdx = 0x80;
9274       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9275     }
9276     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9277                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9278                                  MVT::v16i8, pshufbMask));
9279
9280     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9281     // the 2nd operand if it's undefined or zero.
9282     if (V2.getOpcode() == ISD::UNDEF ||
9283         ISD::isBuildVectorAllZeros(V2.getNode()))
9284       return V1;
9285
9286     // Calculate the shuffle mask for the second input, shuffle it, and
9287     // OR it with the first shuffled input.
9288     pshufbMask.clear();
9289     for (unsigned i = 0; i != 16; ++i) {
9290       int EltIdx = MaskVals[i];
9291       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9292       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9293     }
9294     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9295                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9296                                  MVT::v16i8, pshufbMask));
9297     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9298   }
9299
9300   // No SSSE3 - Calculate in place words and then fix all out of place words
9301   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9302   // the 16 different words that comprise the two doublequadword input vectors.
9303   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9304   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9305   SDValue NewV = V1;
9306   for (int i = 0; i != 8; ++i) {
9307     int Elt0 = MaskVals[i*2];
9308     int Elt1 = MaskVals[i*2+1];
9309
9310     // This word of the result is all undef, skip it.
9311     if (Elt0 < 0 && Elt1 < 0)
9312       continue;
9313
9314     // This word of the result is already in the correct place, skip it.
9315     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9316       continue;
9317
9318     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9319     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9320     SDValue InsElt;
9321
9322     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9323     // using a single extract together, load it and store it.
9324     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9325       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9326                            DAG.getIntPtrConstant(Elt1 / 2));
9327       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9328                         DAG.getIntPtrConstant(i));
9329       continue;
9330     }
9331
9332     // If Elt1 is defined, extract it from the appropriate source.  If the
9333     // source byte is not also odd, shift the extracted word left 8 bits
9334     // otherwise clear the bottom 8 bits if we need to do an or.
9335     if (Elt1 >= 0) {
9336       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9337                            DAG.getIntPtrConstant(Elt1 / 2));
9338       if ((Elt1 & 1) == 0)
9339         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9340                              DAG.getConstant(8,
9341                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9342       else if (Elt0 >= 0)
9343         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9344                              DAG.getConstant(0xFF00, MVT::i16));
9345     }
9346     // If Elt0 is defined, extract it from the appropriate source.  If the
9347     // source byte is not also even, shift the extracted word right 8 bits. If
9348     // Elt1 was also defined, OR the extracted values together before
9349     // inserting them in the result.
9350     if (Elt0 >= 0) {
9351       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9352                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9353       if ((Elt0 & 1) != 0)
9354         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9355                               DAG.getConstant(8,
9356                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9357       else if (Elt1 >= 0)
9358         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9359                              DAG.getConstant(0x00FF, MVT::i16));
9360       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9361                          : InsElt0;
9362     }
9363     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9364                        DAG.getIntPtrConstant(i));
9365   }
9366   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9367 }
9368
9369 // v32i8 shuffles - Translate to VPSHUFB if possible.
9370 static
9371 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9372                                  const X86Subtarget *Subtarget,
9373                                  SelectionDAG &DAG) {
9374   MVT VT = SVOp->getSimpleValueType(0);
9375   SDValue V1 = SVOp->getOperand(0);
9376   SDValue V2 = SVOp->getOperand(1);
9377   SDLoc dl(SVOp);
9378   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9379
9380   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9381   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9382   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9383
9384   // VPSHUFB may be generated if
9385   // (1) one of input vector is undefined or zeroinitializer.
9386   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9387   // And (2) the mask indexes don't cross the 128-bit lane.
9388   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9389       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9390     return SDValue();
9391
9392   if (V1IsAllZero && !V2IsAllZero) {
9393     CommuteVectorShuffleMask(MaskVals, 32);
9394     V1 = V2;
9395   }
9396   return getPSHUFB(MaskVals, V1, dl, DAG);
9397 }
9398
9399 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9400 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9401 /// done when every pair / quad of shuffle mask elements point to elements in
9402 /// the right sequence. e.g.
9403 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9404 static
9405 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9406                                  SelectionDAG &DAG) {
9407   MVT VT = SVOp->getSimpleValueType(0);
9408   SDLoc dl(SVOp);
9409   unsigned NumElems = VT.getVectorNumElements();
9410   MVT NewVT;
9411   unsigned Scale;
9412   switch (VT.SimpleTy) {
9413   default: llvm_unreachable("Unexpected!");
9414   case MVT::v2i64:
9415   case MVT::v2f64:
9416            return SDValue(SVOp, 0);
9417   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9418   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9419   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9420   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9421   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9422   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9423   }
9424
9425   SmallVector<int, 8> MaskVec;
9426   for (unsigned i = 0; i != NumElems; i += Scale) {
9427     int StartIdx = -1;
9428     for (unsigned j = 0; j != Scale; ++j) {
9429       int EltIdx = SVOp->getMaskElt(i+j);
9430       if (EltIdx < 0)
9431         continue;
9432       if (StartIdx < 0)
9433         StartIdx = (EltIdx / Scale);
9434       if (EltIdx != (int)(StartIdx*Scale + j))
9435         return SDValue();
9436     }
9437     MaskVec.push_back(StartIdx);
9438   }
9439
9440   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9441   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9442   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9443 }
9444
9445 /// getVZextMovL - Return a zero-extending vector move low node.
9446 ///
9447 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9448                             SDValue SrcOp, SelectionDAG &DAG,
9449                             const X86Subtarget *Subtarget, SDLoc dl) {
9450   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9451     LoadSDNode *LD = nullptr;
9452     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9453       LD = dyn_cast<LoadSDNode>(SrcOp);
9454     if (!LD) {
9455       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9456       // instead.
9457       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9458       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9459           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9460           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9461           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9462         // PR2108
9463         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9464         return DAG.getNode(ISD::BITCAST, dl, VT,
9465                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9466                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9467                                                    OpVT,
9468                                                    SrcOp.getOperand(0)
9469                                                           .getOperand(0))));
9470       }
9471     }
9472   }
9473
9474   return DAG.getNode(ISD::BITCAST, dl, VT,
9475                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9476                                  DAG.getNode(ISD::BITCAST, dl,
9477                                              OpVT, SrcOp)));
9478 }
9479
9480 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9481 /// which could not be matched by any known target speficic shuffle
9482 static SDValue
9483 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9484
9485   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9486   if (NewOp.getNode())
9487     return NewOp;
9488
9489   MVT VT = SVOp->getSimpleValueType(0);
9490
9491   unsigned NumElems = VT.getVectorNumElements();
9492   unsigned NumLaneElems = NumElems / 2;
9493
9494   SDLoc dl(SVOp);
9495   MVT EltVT = VT.getVectorElementType();
9496   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9497   SDValue Output[2];
9498
9499   SmallVector<int, 16> Mask;
9500   for (unsigned l = 0; l < 2; ++l) {
9501     // Build a shuffle mask for the output, discovering on the fly which
9502     // input vectors to use as shuffle operands (recorded in InputUsed).
9503     // If building a suitable shuffle vector proves too hard, then bail
9504     // out with UseBuildVector set.
9505     bool UseBuildVector = false;
9506     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9507     unsigned LaneStart = l * NumLaneElems;
9508     for (unsigned i = 0; i != NumLaneElems; ++i) {
9509       // The mask element.  This indexes into the input.
9510       int Idx = SVOp->getMaskElt(i+LaneStart);
9511       if (Idx < 0) {
9512         // the mask element does not index into any input vector.
9513         Mask.push_back(-1);
9514         continue;
9515       }
9516
9517       // The input vector this mask element indexes into.
9518       int Input = Idx / NumLaneElems;
9519
9520       // Turn the index into an offset from the start of the input vector.
9521       Idx -= Input * NumLaneElems;
9522
9523       // Find or create a shuffle vector operand to hold this input.
9524       unsigned OpNo;
9525       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9526         if (InputUsed[OpNo] == Input)
9527           // This input vector is already an operand.
9528           break;
9529         if (InputUsed[OpNo] < 0) {
9530           // Create a new operand for this input vector.
9531           InputUsed[OpNo] = Input;
9532           break;
9533         }
9534       }
9535
9536       if (OpNo >= array_lengthof(InputUsed)) {
9537         // More than two input vectors used!  Give up on trying to create a
9538         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9539         UseBuildVector = true;
9540         break;
9541       }
9542
9543       // Add the mask index for the new shuffle vector.
9544       Mask.push_back(Idx + OpNo * NumLaneElems);
9545     }
9546
9547     if (UseBuildVector) {
9548       SmallVector<SDValue, 16> SVOps;
9549       for (unsigned i = 0; i != NumLaneElems; ++i) {
9550         // The mask element.  This indexes into the input.
9551         int Idx = SVOp->getMaskElt(i+LaneStart);
9552         if (Idx < 0) {
9553           SVOps.push_back(DAG.getUNDEF(EltVT));
9554           continue;
9555         }
9556
9557         // The input vector this mask element indexes into.
9558         int Input = Idx / NumElems;
9559
9560         // Turn the index into an offset from the start of the input vector.
9561         Idx -= Input * NumElems;
9562
9563         // Extract the vector element by hand.
9564         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9565                                     SVOp->getOperand(Input),
9566                                     DAG.getIntPtrConstant(Idx)));
9567       }
9568
9569       // Construct the output using a BUILD_VECTOR.
9570       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9571     } else if (InputUsed[0] < 0) {
9572       // No input vectors were used! The result is undefined.
9573       Output[l] = DAG.getUNDEF(NVT);
9574     } else {
9575       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9576                                         (InputUsed[0] % 2) * NumLaneElems,
9577                                         DAG, dl);
9578       // If only one input was used, use an undefined vector for the other.
9579       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9580         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9581                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9582       // At least one input vector was used. Create a new shuffle vector.
9583       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9584     }
9585
9586     Mask.clear();
9587   }
9588
9589   // Concatenate the result back
9590   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9591 }
9592
9593 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9594 /// 4 elements, and match them with several different shuffle types.
9595 static SDValue
9596 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9597   SDValue V1 = SVOp->getOperand(0);
9598   SDValue V2 = SVOp->getOperand(1);
9599   SDLoc dl(SVOp);
9600   MVT VT = SVOp->getSimpleValueType(0);
9601
9602   assert(VT.is128BitVector() && "Unsupported vector size");
9603
9604   std::pair<int, int> Locs[4];
9605   int Mask1[] = { -1, -1, -1, -1 };
9606   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9607
9608   unsigned NumHi = 0;
9609   unsigned NumLo = 0;
9610   for (unsigned i = 0; i != 4; ++i) {
9611     int Idx = PermMask[i];
9612     if (Idx < 0) {
9613       Locs[i] = std::make_pair(-1, -1);
9614     } else {
9615       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9616       if (Idx < 4) {
9617         Locs[i] = std::make_pair(0, NumLo);
9618         Mask1[NumLo] = Idx;
9619         NumLo++;
9620       } else {
9621         Locs[i] = std::make_pair(1, NumHi);
9622         if (2+NumHi < 4)
9623           Mask1[2+NumHi] = Idx;
9624         NumHi++;
9625       }
9626     }
9627   }
9628
9629   if (NumLo <= 2 && NumHi <= 2) {
9630     // If no more than two elements come from either vector. This can be
9631     // implemented with two shuffles. First shuffle gather the elements.
9632     // The second shuffle, which takes the first shuffle as both of its
9633     // vector operands, put the elements into the right order.
9634     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9635
9636     int Mask2[] = { -1, -1, -1, -1 };
9637
9638     for (unsigned i = 0; i != 4; ++i)
9639       if (Locs[i].first != -1) {
9640         unsigned Idx = (i < 2) ? 0 : 4;
9641         Idx += Locs[i].first * 2 + Locs[i].second;
9642         Mask2[i] = Idx;
9643       }
9644
9645     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9646   }
9647
9648   if (NumLo == 3 || NumHi == 3) {
9649     // Otherwise, we must have three elements from one vector, call it X, and
9650     // one element from the other, call it Y.  First, use a shufps to build an
9651     // intermediate vector with the one element from Y and the element from X
9652     // that will be in the same half in the final destination (the indexes don't
9653     // matter). Then, use a shufps to build the final vector, taking the half
9654     // containing the element from Y from the intermediate, and the other half
9655     // from X.
9656     if (NumHi == 3) {
9657       // Normalize it so the 3 elements come from V1.
9658       CommuteVectorShuffleMask(PermMask, 4);
9659       std::swap(V1, V2);
9660     }
9661
9662     // Find the element from V2.
9663     unsigned HiIndex;
9664     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9665       int Val = PermMask[HiIndex];
9666       if (Val < 0)
9667         continue;
9668       if (Val >= 4)
9669         break;
9670     }
9671
9672     Mask1[0] = PermMask[HiIndex];
9673     Mask1[1] = -1;
9674     Mask1[2] = PermMask[HiIndex^1];
9675     Mask1[3] = -1;
9676     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9677
9678     if (HiIndex >= 2) {
9679       Mask1[0] = PermMask[0];
9680       Mask1[1] = PermMask[1];
9681       Mask1[2] = HiIndex & 1 ? 6 : 4;
9682       Mask1[3] = HiIndex & 1 ? 4 : 6;
9683       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9684     }
9685
9686     Mask1[0] = HiIndex & 1 ? 2 : 0;
9687     Mask1[1] = HiIndex & 1 ? 0 : 2;
9688     Mask1[2] = PermMask[2];
9689     Mask1[3] = PermMask[3];
9690     if (Mask1[2] >= 0)
9691       Mask1[2] += 4;
9692     if (Mask1[3] >= 0)
9693       Mask1[3] += 4;
9694     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9695   }
9696
9697   // Break it into (shuffle shuffle_hi, shuffle_lo).
9698   int LoMask[] = { -1, -1, -1, -1 };
9699   int HiMask[] = { -1, -1, -1, -1 };
9700
9701   int *MaskPtr = LoMask;
9702   unsigned MaskIdx = 0;
9703   unsigned LoIdx = 0;
9704   unsigned HiIdx = 2;
9705   for (unsigned i = 0; i != 4; ++i) {
9706     if (i == 2) {
9707       MaskPtr = HiMask;
9708       MaskIdx = 1;
9709       LoIdx = 0;
9710       HiIdx = 2;
9711     }
9712     int Idx = PermMask[i];
9713     if (Idx < 0) {
9714       Locs[i] = std::make_pair(-1, -1);
9715     } else if (Idx < 4) {
9716       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9717       MaskPtr[LoIdx] = Idx;
9718       LoIdx++;
9719     } else {
9720       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9721       MaskPtr[HiIdx] = Idx;
9722       HiIdx++;
9723     }
9724   }
9725
9726   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9727   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9728   int MaskOps[] = { -1, -1, -1, -1 };
9729   for (unsigned i = 0; i != 4; ++i)
9730     if (Locs[i].first != -1)
9731       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9732   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9733 }
9734
9735 static bool MayFoldVectorLoad(SDValue V) {
9736   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9737     V = V.getOperand(0);
9738
9739   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9740     V = V.getOperand(0);
9741   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9742       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9743     // BUILD_VECTOR (load), undef
9744     V = V.getOperand(0);
9745
9746   return MayFoldLoad(V);
9747 }
9748
9749 static
9750 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9751   MVT VT = Op.getSimpleValueType();
9752
9753   // Canonizalize to v2f64.
9754   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9755   return DAG.getNode(ISD::BITCAST, dl, VT,
9756                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9757                                           V1, DAG));
9758 }
9759
9760 static
9761 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9762                         bool HasSSE2) {
9763   SDValue V1 = Op.getOperand(0);
9764   SDValue V2 = Op.getOperand(1);
9765   MVT VT = Op.getSimpleValueType();
9766
9767   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9768
9769   if (HasSSE2 && VT == MVT::v2f64)
9770     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9771
9772   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9773   return DAG.getNode(ISD::BITCAST, dl, VT,
9774                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9775                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9776                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9777 }
9778
9779 static
9780 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9781   SDValue V1 = Op.getOperand(0);
9782   SDValue V2 = Op.getOperand(1);
9783   MVT VT = Op.getSimpleValueType();
9784
9785   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9786          "unsupported shuffle type");
9787
9788   if (V2.getOpcode() == ISD::UNDEF)
9789     V2 = V1;
9790
9791   // v4i32 or v4f32
9792   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9793 }
9794
9795 static
9796 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9797   SDValue V1 = Op.getOperand(0);
9798   SDValue V2 = Op.getOperand(1);
9799   MVT VT = Op.getSimpleValueType();
9800   unsigned NumElems = VT.getVectorNumElements();
9801
9802   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9803   // operand of these instructions is only memory, so check if there's a
9804   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9805   // same masks.
9806   bool CanFoldLoad = false;
9807
9808   // Trivial case, when V2 comes from a load.
9809   if (MayFoldVectorLoad(V2))
9810     CanFoldLoad = true;
9811
9812   // When V1 is a load, it can be folded later into a store in isel, example:
9813   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9814   //    turns into:
9815   //  (MOVLPSmr addr:$src1, VR128:$src2)
9816   // So, recognize this potential and also use MOVLPS or MOVLPD
9817   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9818     CanFoldLoad = true;
9819
9820   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9821   if (CanFoldLoad) {
9822     if (HasSSE2 && NumElems == 2)
9823       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9824
9825     if (NumElems == 4)
9826       // If we don't care about the second element, proceed to use movss.
9827       if (SVOp->getMaskElt(1) != -1)
9828         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9829   }
9830
9831   // movl and movlp will both match v2i64, but v2i64 is never matched by
9832   // movl earlier because we make it strict to avoid messing with the movlp load
9833   // folding logic (see the code above getMOVLP call). Match it here then,
9834   // this is horrible, but will stay like this until we move all shuffle
9835   // matching to x86 specific nodes. Note that for the 1st condition all
9836   // types are matched with movsd.
9837   if (HasSSE2) {
9838     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9839     // as to remove this logic from here, as much as possible
9840     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9841       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9842     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9843   }
9844
9845   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9846
9847   // Invert the operand order and use SHUFPS to match it.
9848   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9849                               getShuffleSHUFImmediate(SVOp), DAG);
9850 }
9851
9852 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9853                                          SelectionDAG &DAG) {
9854   SDLoc dl(Load);
9855   MVT VT = Load->getSimpleValueType(0);
9856   MVT EVT = VT.getVectorElementType();
9857   SDValue Addr = Load->getOperand(1);
9858   SDValue NewAddr = DAG.getNode(
9859       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9860       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9861
9862   SDValue NewLoad =
9863       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9864                   DAG.getMachineFunction().getMachineMemOperand(
9865                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9866   return NewLoad;
9867 }
9868
9869 // It is only safe to call this function if isINSERTPSMask is true for
9870 // this shufflevector mask.
9871 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9872                            SelectionDAG &DAG) {
9873   // Generate an insertps instruction when inserting an f32 from memory onto a
9874   // v4f32 or when copying a member from one v4f32 to another.
9875   // We also use it for transferring i32 from one register to another,
9876   // since it simply copies the same bits.
9877   // If we're transferring an i32 from memory to a specific element in a
9878   // register, we output a generic DAG that will match the PINSRD
9879   // instruction.
9880   MVT VT = SVOp->getSimpleValueType(0);
9881   MVT EVT = VT.getVectorElementType();
9882   SDValue V1 = SVOp->getOperand(0);
9883   SDValue V2 = SVOp->getOperand(1);
9884   auto Mask = SVOp->getMask();
9885   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9886          "unsupported vector type for insertps/pinsrd");
9887
9888   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9889   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9890   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9891
9892   SDValue From;
9893   SDValue To;
9894   unsigned DestIndex;
9895   if (FromV1 == 1) {
9896     From = V1;
9897     To = V2;
9898     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9899                 Mask.begin();
9900
9901     // If we have 1 element from each vector, we have to check if we're
9902     // changing V1's element's place. If so, we're done. Otherwise, we
9903     // should assume we're changing V2's element's place and behave
9904     // accordingly.
9905     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9906     assert(DestIndex <= INT32_MAX && "truncated destination index");
9907     if (FromV1 == FromV2 &&
9908         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9909       From = V2;
9910       To = V1;
9911       DestIndex =
9912           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9913     }
9914   } else {
9915     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9916            "More than one element from V1 and from V2, or no elements from one "
9917            "of the vectors. This case should not have returned true from "
9918            "isINSERTPSMask");
9919     From = V2;
9920     To = V1;
9921     DestIndex =
9922         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9923   }
9924
9925   // Get an index into the source vector in the range [0,4) (the mask is
9926   // in the range [0,8) because it can address V1 and V2)
9927   unsigned SrcIndex = Mask[DestIndex] % 4;
9928   if (MayFoldLoad(From)) {
9929     // Trivial case, when From comes from a load and is only used by the
9930     // shuffle. Make it use insertps from the vector that we need from that
9931     // load.
9932     SDValue NewLoad =
9933         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9934     if (!NewLoad.getNode())
9935       return SDValue();
9936
9937     if (EVT == MVT::f32) {
9938       // Create this as a scalar to vector to match the instruction pattern.
9939       SDValue LoadScalarToVector =
9940           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9941       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9942       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9943                          InsertpsMask);
9944     } else { // EVT == MVT::i32
9945       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9946       // instruction, to match the PINSRD instruction, which loads an i32 to a
9947       // certain vector element.
9948       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9949                          DAG.getConstant(DestIndex, MVT::i32));
9950     }
9951   }
9952
9953   // Vector-element-to-vector
9954   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9955   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9956 }
9957
9958 // Reduce a vector shuffle to zext.
9959 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9960                                     SelectionDAG &DAG) {
9961   // PMOVZX is only available from SSE41.
9962   if (!Subtarget->hasSSE41())
9963     return SDValue();
9964
9965   MVT VT = Op.getSimpleValueType();
9966
9967   // Only AVX2 support 256-bit vector integer extending.
9968   if (!Subtarget->hasInt256() && VT.is256BitVector())
9969     return SDValue();
9970
9971   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9972   SDLoc DL(Op);
9973   SDValue V1 = Op.getOperand(0);
9974   SDValue V2 = Op.getOperand(1);
9975   unsigned NumElems = VT.getVectorNumElements();
9976
9977   // Extending is an unary operation and the element type of the source vector
9978   // won't be equal to or larger than i64.
9979   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9980       VT.getVectorElementType() == MVT::i64)
9981     return SDValue();
9982
9983   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9984   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9985   while ((1U << Shift) < NumElems) {
9986     if (SVOp->getMaskElt(1U << Shift) == 1)
9987       break;
9988     Shift += 1;
9989     // The maximal ratio is 8, i.e. from i8 to i64.
9990     if (Shift > 3)
9991       return SDValue();
9992   }
9993
9994   // Check the shuffle mask.
9995   unsigned Mask = (1U << Shift) - 1;
9996   for (unsigned i = 0; i != NumElems; ++i) {
9997     int EltIdx = SVOp->getMaskElt(i);
9998     if ((i & Mask) != 0 && EltIdx != -1)
9999       return SDValue();
10000     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
10001       return SDValue();
10002   }
10003
10004   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
10005   MVT NeVT = MVT::getIntegerVT(NBits);
10006   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
10007
10008   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
10009     return SDValue();
10010
10011   // Simplify the operand as it's prepared to be fed into shuffle.
10012   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
10013   if (V1.getOpcode() == ISD::BITCAST &&
10014       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
10015       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10016       V1.getOperand(0).getOperand(0)
10017         .getSimpleValueType().getSizeInBits() == SignificantBits) {
10018     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
10019     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
10020     ConstantSDNode *CIdx =
10021       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
10022     // If it's foldable, i.e. normal load with single use, we will let code
10023     // selection to fold it. Otherwise, we will short the conversion sequence.
10024     if (CIdx && CIdx->getZExtValue() == 0 &&
10025         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
10026       MVT FullVT = V.getSimpleValueType();
10027       MVT V1VT = V1.getSimpleValueType();
10028       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
10029         // The "ext_vec_elt" node is wider than the result node.
10030         // In this case we should extract subvector from V.
10031         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
10032         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
10033         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
10034                                         FullVT.getVectorNumElements()/Ratio);
10035         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
10036                         DAG.getIntPtrConstant(0));
10037       }
10038       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
10039     }
10040   }
10041
10042   return DAG.getNode(ISD::BITCAST, DL, VT,
10043                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
10044 }
10045
10046 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10047                                       SelectionDAG &DAG) {
10048   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10049   MVT VT = Op.getSimpleValueType();
10050   SDLoc dl(Op);
10051   SDValue V1 = Op.getOperand(0);
10052   SDValue V2 = Op.getOperand(1);
10053
10054   if (isZeroShuffle(SVOp))
10055     return getZeroVector(VT, Subtarget, DAG, dl);
10056
10057   // Handle splat operations
10058   if (SVOp->isSplat()) {
10059     // Use vbroadcast whenever the splat comes from a foldable load
10060     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
10061     if (Broadcast.getNode())
10062       return Broadcast;
10063   }
10064
10065   // Check integer expanding shuffles.
10066   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
10067   if (NewOp.getNode())
10068     return NewOp;
10069
10070   // If the shuffle can be profitably rewritten as a narrower shuffle, then
10071   // do it!
10072   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
10073       VT == MVT::v32i8) {
10074     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10075     if (NewOp.getNode())
10076       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
10077   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
10078     // FIXME: Figure out a cleaner way to do this.
10079     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
10080       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10081       if (NewOp.getNode()) {
10082         MVT NewVT = NewOp.getSimpleValueType();
10083         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
10084                                NewVT, true, false))
10085           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
10086                               dl);
10087       }
10088     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
10089       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10090       if (NewOp.getNode()) {
10091         MVT NewVT = NewOp.getSimpleValueType();
10092         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
10093           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
10094                               dl);
10095       }
10096     }
10097   }
10098   return SDValue();
10099 }
10100
10101 SDValue
10102 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
10103   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10104   SDValue V1 = Op.getOperand(0);
10105   SDValue V2 = Op.getOperand(1);
10106   MVT VT = Op.getSimpleValueType();
10107   SDLoc dl(Op);
10108   unsigned NumElems = VT.getVectorNumElements();
10109   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10110   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10111   bool V1IsSplat = false;
10112   bool V2IsSplat = false;
10113   bool HasSSE2 = Subtarget->hasSSE2();
10114   bool HasFp256    = Subtarget->hasFp256();
10115   bool HasInt256   = Subtarget->hasInt256();
10116   MachineFunction &MF = DAG.getMachineFunction();
10117   bool OptForSize = MF.getFunction()->getAttributes().
10118     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10119
10120   // Check if we should use the experimental vector shuffle lowering. If so,
10121   // delegate completely to that code path.
10122   if (ExperimentalVectorShuffleLowering)
10123     return lowerVectorShuffle(Op, Subtarget, DAG);
10124
10125   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10126
10127   if (V1IsUndef && V2IsUndef)
10128     return DAG.getUNDEF(VT);
10129
10130   // When we create a shuffle node we put the UNDEF node to second operand,
10131   // but in some cases the first operand may be transformed to UNDEF.
10132   // In this case we should just commute the node.
10133   if (V1IsUndef)
10134     return DAG.getCommutedVectorShuffle(*SVOp);
10135
10136   // Vector shuffle lowering takes 3 steps:
10137   //
10138   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10139   //    narrowing and commutation of operands should be handled.
10140   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10141   //    shuffle nodes.
10142   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10143   //    so the shuffle can be broken into other shuffles and the legalizer can
10144   //    try the lowering again.
10145   //
10146   // The general idea is that no vector_shuffle operation should be left to
10147   // be matched during isel, all of them must be converted to a target specific
10148   // node here.
10149
10150   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10151   // narrowing and commutation of operands should be handled. The actual code
10152   // doesn't include all of those, work in progress...
10153   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10154   if (NewOp.getNode())
10155     return NewOp;
10156
10157   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10158
10159   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10160   // unpckh_undef). Only use pshufd if speed is more important than size.
10161   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10162     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10163   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10164     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10165
10166   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10167       V2IsUndef && MayFoldVectorLoad(V1))
10168     return getMOVDDup(Op, dl, V1, DAG);
10169
10170   if (isMOVHLPS_v_undef_Mask(M, VT))
10171     return getMOVHighToLow(Op, dl, DAG);
10172
10173   // Use to match splats
10174   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10175       (VT == MVT::v2f64 || VT == MVT::v2i64))
10176     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10177
10178   if (isPSHUFDMask(M, VT)) {
10179     // The actual implementation will match the mask in the if above and then
10180     // during isel it can match several different instructions, not only pshufd
10181     // as its name says, sad but true, emulate the behavior for now...
10182     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10183       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10184
10185     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10186
10187     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10188       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10189
10190     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10191       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10192                                   DAG);
10193
10194     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10195                                 TargetMask, DAG);
10196   }
10197
10198   if (isPALIGNRMask(M, VT, Subtarget))
10199     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10200                                 getShufflePALIGNRImmediate(SVOp),
10201                                 DAG);
10202
10203   if (isVALIGNMask(M, VT, Subtarget))
10204     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10205                                 getShuffleVALIGNImmediate(SVOp),
10206                                 DAG);
10207
10208   // Check if this can be converted into a logical shift.
10209   bool isLeft = false;
10210   unsigned ShAmt = 0;
10211   SDValue ShVal;
10212   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10213   if (isShift && ShVal.hasOneUse()) {
10214     // If the shifted value has multiple uses, it may be cheaper to use
10215     // v_set0 + movlhps or movhlps, etc.
10216     MVT EltVT = VT.getVectorElementType();
10217     ShAmt *= EltVT.getSizeInBits();
10218     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10219   }
10220
10221   if (isMOVLMask(M, VT)) {
10222     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10223       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10224     if (!isMOVLPMask(M, VT)) {
10225       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10226         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10227
10228       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10229         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10230     }
10231   }
10232
10233   // FIXME: fold these into legal mask.
10234   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10235     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10236
10237   if (isMOVHLPSMask(M, VT))
10238     return getMOVHighToLow(Op, dl, DAG);
10239
10240   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10241     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10242
10243   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10244     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10245
10246   if (isMOVLPMask(M, VT))
10247     return getMOVLP(Op, dl, DAG, HasSSE2);
10248
10249   if (ShouldXformToMOVHLPS(M, VT) ||
10250       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10251     return DAG.getCommutedVectorShuffle(*SVOp);
10252
10253   if (isShift) {
10254     // No better options. Use a vshldq / vsrldq.
10255     MVT EltVT = VT.getVectorElementType();
10256     ShAmt *= EltVT.getSizeInBits();
10257     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10258   }
10259
10260   bool Commuted = false;
10261   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10262   // 1,1,1,1 -> v8i16 though.
10263   BitVector UndefElements;
10264   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10265     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10266       V1IsSplat = true;
10267   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10268     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10269       V2IsSplat = true;
10270
10271   // Canonicalize the splat or undef, if present, to be on the RHS.
10272   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10273     CommuteVectorShuffleMask(M, NumElems);
10274     std::swap(V1, V2);
10275     std::swap(V1IsSplat, V2IsSplat);
10276     Commuted = true;
10277   }
10278
10279   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10280     // Shuffling low element of v1 into undef, just return v1.
10281     if (V2IsUndef)
10282       return V1;
10283     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10284     // the instruction selector will not match, so get a canonical MOVL with
10285     // swapped operands to undo the commute.
10286     return getMOVL(DAG, dl, VT, V2, V1);
10287   }
10288
10289   if (isUNPCKLMask(M, VT, HasInt256))
10290     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10291
10292   if (isUNPCKHMask(M, VT, HasInt256))
10293     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10294
10295   if (V2IsSplat) {
10296     // Normalize mask so all entries that point to V2 points to its first
10297     // element then try to match unpck{h|l} again. If match, return a
10298     // new vector_shuffle with the corrected mask.p
10299     SmallVector<int, 8> NewMask(M.begin(), M.end());
10300     NormalizeMask(NewMask, NumElems);
10301     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10302       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10303     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10304       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10305   }
10306
10307   if (Commuted) {
10308     // Commute is back and try unpck* again.
10309     // FIXME: this seems wrong.
10310     CommuteVectorShuffleMask(M, NumElems);
10311     std::swap(V1, V2);
10312     std::swap(V1IsSplat, V2IsSplat);
10313
10314     if (isUNPCKLMask(M, VT, HasInt256))
10315       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10316
10317     if (isUNPCKHMask(M, VT, HasInt256))
10318       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10319   }
10320
10321   // Normalize the node to match x86 shuffle ops if needed
10322   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10323     return DAG.getCommutedVectorShuffle(*SVOp);
10324
10325   // The checks below are all present in isShuffleMaskLegal, but they are
10326   // inlined here right now to enable us to directly emit target specific
10327   // nodes, and remove one by one until they don't return Op anymore.
10328
10329   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10330       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10331     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10332       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10333   }
10334
10335   if (isPSHUFHWMask(M, VT, HasInt256))
10336     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10337                                 getShufflePSHUFHWImmediate(SVOp),
10338                                 DAG);
10339
10340   if (isPSHUFLWMask(M, VT, HasInt256))
10341     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10342                                 getShufflePSHUFLWImmediate(SVOp),
10343                                 DAG);
10344
10345   unsigned MaskValue;
10346   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10347                   &MaskValue))
10348     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10349
10350   if (isSHUFPMask(M, VT))
10351     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10352                                 getShuffleSHUFImmediate(SVOp), DAG);
10353
10354   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10355     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10356   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10357     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10358
10359   //===--------------------------------------------------------------------===//
10360   // Generate target specific nodes for 128 or 256-bit shuffles only
10361   // supported in the AVX instruction set.
10362   //
10363
10364   // Handle VMOVDDUPY permutations
10365   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10366     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10367
10368   // Handle VPERMILPS/D* permutations
10369   if (isVPERMILPMask(M, VT)) {
10370     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10371       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10372                                   getShuffleSHUFImmediate(SVOp), DAG);
10373     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10374                                 getShuffleSHUFImmediate(SVOp), DAG);
10375   }
10376
10377   unsigned Idx;
10378   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10379     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10380                               Idx*(NumElems/2), DAG, dl);
10381
10382   // Handle VPERM2F128/VPERM2I128 permutations
10383   if (isVPERM2X128Mask(M, VT, HasFp256))
10384     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10385                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10386
10387   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10388     return getINSERTPS(SVOp, dl, DAG);
10389
10390   unsigned Imm8;
10391   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10392     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10393
10394   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10395       VT.is512BitVector()) {
10396     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10397     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10398     SmallVector<SDValue, 16> permclMask;
10399     for (unsigned i = 0; i != NumElems; ++i) {
10400       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10401     }
10402
10403     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10404     if (V2IsUndef)
10405       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10406       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10407                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10408     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10409                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10410   }
10411
10412   //===--------------------------------------------------------------------===//
10413   // Since no target specific shuffle was selected for this generic one,
10414   // lower it into other known shuffles. FIXME: this isn't true yet, but
10415   // this is the plan.
10416   //
10417
10418   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10419   if (VT == MVT::v8i16) {
10420     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10421     if (NewOp.getNode())
10422       return NewOp;
10423   }
10424
10425   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10426     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10427     if (NewOp.getNode())
10428       return NewOp;
10429   }
10430
10431   if (VT == MVT::v16i8) {
10432     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10433     if (NewOp.getNode())
10434       return NewOp;
10435   }
10436
10437   if (VT == MVT::v32i8) {
10438     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10439     if (NewOp.getNode())
10440       return NewOp;
10441   }
10442
10443   // Handle all 128-bit wide vectors with 4 elements, and match them with
10444   // several different shuffle types.
10445   if (NumElems == 4 && VT.is128BitVector())
10446     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10447
10448   // Handle general 256-bit shuffles
10449   if (VT.is256BitVector())
10450     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10451
10452   return SDValue();
10453 }
10454
10455 // This function assumes its argument is a BUILD_VECTOR of constants or
10456 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10457 // true.
10458 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10459                                     unsigned &MaskValue) {
10460   MaskValue = 0;
10461   unsigned NumElems = BuildVector->getNumOperands();
10462   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10463   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10464   unsigned NumElemsInLane = NumElems / NumLanes;
10465
10466   // Blend for v16i16 should be symetric for the both lanes.
10467   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10468     SDValue EltCond = BuildVector->getOperand(i);
10469     SDValue SndLaneEltCond =
10470         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10471
10472     int Lane1Cond = -1, Lane2Cond = -1;
10473     if (isa<ConstantSDNode>(EltCond))
10474       Lane1Cond = !isZero(EltCond);
10475     if (isa<ConstantSDNode>(SndLaneEltCond))
10476       Lane2Cond = !isZero(SndLaneEltCond);
10477
10478     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10479       // Lane1Cond != 0, means we want the first argument.
10480       // Lane1Cond == 0, means we want the second argument.
10481       // The encoding of this argument is 0 for the first argument, 1
10482       // for the second. Therefore, invert the condition.
10483       MaskValue |= !Lane1Cond << i;
10484     else if (Lane1Cond < 0)
10485       MaskValue |= !Lane2Cond << i;
10486     else
10487       return false;
10488   }
10489   return true;
10490 }
10491
10492 // Try to lower a vselect node into a simple blend instruction.
10493 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10494                                    SelectionDAG &DAG) {
10495   SDValue Cond = Op.getOperand(0);
10496   SDValue LHS = Op.getOperand(1);
10497   SDValue RHS = Op.getOperand(2);
10498   SDLoc dl(Op);
10499   MVT VT = Op.getSimpleValueType();
10500   MVT EltVT = VT.getVectorElementType();
10501   unsigned NumElems = VT.getVectorNumElements();
10502
10503   // There is no blend with immediate in AVX-512.
10504   if (VT.is512BitVector())
10505     return SDValue();
10506
10507   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10508     return SDValue();
10509   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10510     return SDValue();
10511
10512   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10513     return SDValue();
10514
10515   // Check the mask for BLEND and build the value.
10516   unsigned MaskValue = 0;
10517   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10518     return SDValue();
10519
10520   // Convert i32 vectors to floating point if it is not AVX2.
10521   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10522   MVT BlendVT = VT;
10523   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10524     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10525                                NumElems);
10526     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10527     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10528   }
10529
10530   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10531                             DAG.getConstant(MaskValue, MVT::i32));
10532   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10533 }
10534
10535 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10536   // A vselect where all conditions and data are constants can be optimized into
10537   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10538   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10539       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10540       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10541     return SDValue();
10542   
10543   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10544   if (BlendOp.getNode())
10545     return BlendOp;
10546
10547   // Some types for vselect were previously set to Expand, not Legal or
10548   // Custom. Return an empty SDValue so we fall-through to Expand, after
10549   // the Custom lowering phase.
10550   MVT VT = Op.getSimpleValueType();
10551   switch (VT.SimpleTy) {
10552   default:
10553     break;
10554   case MVT::v8i16:
10555   case MVT::v16i16:
10556     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10557       break;
10558     return SDValue();
10559   }
10560
10561   // We couldn't create a "Blend with immediate" node.
10562   // This node should still be legal, but we'll have to emit a blendv*
10563   // instruction.
10564   return Op;
10565 }
10566
10567 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10568   MVT VT = Op.getSimpleValueType();
10569   SDLoc dl(Op);
10570
10571   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10572     return SDValue();
10573
10574   if (VT.getSizeInBits() == 8) {
10575     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10576                                   Op.getOperand(0), Op.getOperand(1));
10577     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10578                                   DAG.getValueType(VT));
10579     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10580   }
10581
10582   if (VT.getSizeInBits() == 16) {
10583     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10584     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10585     if (Idx == 0)
10586       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10587                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10588                                      DAG.getNode(ISD::BITCAST, dl,
10589                                                  MVT::v4i32,
10590                                                  Op.getOperand(0)),
10591                                      Op.getOperand(1)));
10592     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10593                                   Op.getOperand(0), Op.getOperand(1));
10594     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10595                                   DAG.getValueType(VT));
10596     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10597   }
10598
10599   if (VT == MVT::f32) {
10600     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10601     // the result back to FR32 register. It's only worth matching if the
10602     // result has a single use which is a store or a bitcast to i32.  And in
10603     // the case of a store, it's not worth it if the index is a constant 0,
10604     // because a MOVSSmr can be used instead, which is smaller and faster.
10605     if (!Op.hasOneUse())
10606       return SDValue();
10607     SDNode *User = *Op.getNode()->use_begin();
10608     if ((User->getOpcode() != ISD::STORE ||
10609          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10610           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10611         (User->getOpcode() != ISD::BITCAST ||
10612          User->getValueType(0) != MVT::i32))
10613       return SDValue();
10614     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10615                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10616                                               Op.getOperand(0)),
10617                                               Op.getOperand(1));
10618     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10619   }
10620
10621   if (VT == MVT::i32 || VT == MVT::i64) {
10622     // ExtractPS/pextrq works with constant index.
10623     if (isa<ConstantSDNode>(Op.getOperand(1)))
10624       return Op;
10625   }
10626   return SDValue();
10627 }
10628
10629 /// Extract one bit from mask vector, like v16i1 or v8i1.
10630 /// AVX-512 feature.
10631 SDValue
10632 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10633   SDValue Vec = Op.getOperand(0);
10634   SDLoc dl(Vec);
10635   MVT VecVT = Vec.getSimpleValueType();
10636   SDValue Idx = Op.getOperand(1);
10637   MVT EltVT = Op.getSimpleValueType();
10638
10639   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10640
10641   // variable index can't be handled in mask registers,
10642   // extend vector to VR512
10643   if (!isa<ConstantSDNode>(Idx)) {
10644     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10645     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10646     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10647                               ExtVT.getVectorElementType(), Ext, Idx);
10648     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10649   }
10650
10651   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10652   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10653   unsigned MaxSift = rc->getSize()*8 - 1;
10654   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10655                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10656   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10657                     DAG.getConstant(MaxSift, MVT::i8));
10658   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10659                        DAG.getIntPtrConstant(0));
10660 }
10661
10662 SDValue
10663 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10664                                            SelectionDAG &DAG) const {
10665   SDLoc dl(Op);
10666   SDValue Vec = Op.getOperand(0);
10667   MVT VecVT = Vec.getSimpleValueType();
10668   SDValue Idx = Op.getOperand(1);
10669
10670   if (Op.getSimpleValueType() == MVT::i1)
10671     return ExtractBitFromMaskVector(Op, DAG);
10672
10673   if (!isa<ConstantSDNode>(Idx)) {
10674     if (VecVT.is512BitVector() ||
10675         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10676          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10677
10678       MVT MaskEltVT =
10679         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10680       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10681                                     MaskEltVT.getSizeInBits());
10682
10683       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10684       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10685                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10686                                 Idx, DAG.getConstant(0, getPointerTy()));
10687       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10688       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10689                         Perm, DAG.getConstant(0, getPointerTy()));
10690     }
10691     return SDValue();
10692   }
10693
10694   // If this is a 256-bit vector result, first extract the 128-bit vector and
10695   // then extract the element from the 128-bit vector.
10696   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10697
10698     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10699     // Get the 128-bit vector.
10700     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10701     MVT EltVT = VecVT.getVectorElementType();
10702
10703     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10704
10705     //if (IdxVal >= NumElems/2)
10706     //  IdxVal -= NumElems/2;
10707     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10708     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10709                        DAG.getConstant(IdxVal, MVT::i32));
10710   }
10711
10712   assert(VecVT.is128BitVector() && "Unexpected vector length");
10713
10714   if (Subtarget->hasSSE41()) {
10715     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10716     if (Res.getNode())
10717       return Res;
10718   }
10719
10720   MVT VT = Op.getSimpleValueType();
10721   // TODO: handle v16i8.
10722   if (VT.getSizeInBits() == 16) {
10723     SDValue Vec = Op.getOperand(0);
10724     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10725     if (Idx == 0)
10726       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10727                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10728                                      DAG.getNode(ISD::BITCAST, dl,
10729                                                  MVT::v4i32, Vec),
10730                                      Op.getOperand(1)));
10731     // Transform it so it match pextrw which produces a 32-bit result.
10732     MVT EltVT = MVT::i32;
10733     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10734                                   Op.getOperand(0), Op.getOperand(1));
10735     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10736                                   DAG.getValueType(VT));
10737     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10738   }
10739
10740   if (VT.getSizeInBits() == 32) {
10741     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10742     if (Idx == 0)
10743       return Op;
10744
10745     // SHUFPS the element to the lowest double word, then movss.
10746     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10747     MVT VVT = Op.getOperand(0).getSimpleValueType();
10748     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10749                                        DAG.getUNDEF(VVT), Mask);
10750     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10751                        DAG.getIntPtrConstant(0));
10752   }
10753
10754   if (VT.getSizeInBits() == 64) {
10755     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10756     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10757     //        to match extract_elt for f64.
10758     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10759     if (Idx == 0)
10760       return Op;
10761
10762     // UNPCKHPD the element to the lowest double word, then movsd.
10763     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10764     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10765     int Mask[2] = { 1, -1 };
10766     MVT VVT = Op.getOperand(0).getSimpleValueType();
10767     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10768                                        DAG.getUNDEF(VVT), Mask);
10769     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10770                        DAG.getIntPtrConstant(0));
10771   }
10772
10773   return SDValue();
10774 }
10775
10776 /// Insert one bit to mask vector, like v16i1 or v8i1.
10777 /// AVX-512 feature.
10778 SDValue 
10779 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10780   SDLoc dl(Op);
10781   SDValue Vec = Op.getOperand(0);
10782   SDValue Elt = Op.getOperand(1);
10783   SDValue Idx = Op.getOperand(2);
10784   MVT VecVT = Vec.getSimpleValueType();
10785
10786   if (!isa<ConstantSDNode>(Idx)) {
10787     // Non constant index. Extend source and destination,
10788     // insert element and then truncate the result.
10789     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10790     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10791     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10792       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10793       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10794     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10795   }
10796
10797   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10798   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10799   if (Vec.getOpcode() == ISD::UNDEF)
10800     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10801                        DAG.getConstant(IdxVal, MVT::i8));
10802   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10803   unsigned MaxSift = rc->getSize()*8 - 1;
10804   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10805                     DAG.getConstant(MaxSift, MVT::i8));
10806   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10807                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10808   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10809 }
10810
10811 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10812                                                   SelectionDAG &DAG) const {
10813   MVT VT = Op.getSimpleValueType();
10814   MVT EltVT = VT.getVectorElementType();
10815
10816   if (EltVT == MVT::i1)
10817     return InsertBitToMaskVector(Op, DAG);
10818
10819   SDLoc dl(Op);
10820   SDValue N0 = Op.getOperand(0);
10821   SDValue N1 = Op.getOperand(1);
10822   SDValue N2 = Op.getOperand(2);
10823   if (!isa<ConstantSDNode>(N2))
10824     return SDValue();
10825   auto *N2C = cast<ConstantSDNode>(N2);
10826   unsigned IdxVal = N2C->getZExtValue();
10827
10828   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10829   // into that, and then insert the subvector back into the result.
10830   if (VT.is256BitVector() || VT.is512BitVector()) {
10831     // Get the desired 128-bit vector half.
10832     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10833
10834     // Insert the element into the desired half.
10835     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10836     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10837
10838     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10839                     DAG.getConstant(IdxIn128, MVT::i32));
10840
10841     // Insert the changed part back to the 256-bit vector
10842     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10843   }
10844   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10845
10846   if (Subtarget->hasSSE41()) {
10847     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10848       unsigned Opc;
10849       if (VT == MVT::v8i16) {
10850         Opc = X86ISD::PINSRW;
10851       } else {
10852         assert(VT == MVT::v16i8);
10853         Opc = X86ISD::PINSRB;
10854       }
10855
10856       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10857       // argument.
10858       if (N1.getValueType() != MVT::i32)
10859         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10860       if (N2.getValueType() != MVT::i32)
10861         N2 = DAG.getIntPtrConstant(IdxVal);
10862       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10863     }
10864
10865     if (EltVT == MVT::f32) {
10866       // Bits [7:6] of the constant are the source select.  This will always be
10867       //  zero here.  The DAG Combiner may combine an extract_elt index into
10868       //  these
10869       //  bits.  For example (insert (extract, 3), 2) could be matched by
10870       //  putting
10871       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10872       // Bits [5:4] of the constant are the destination select.  This is the
10873       //  value of the incoming immediate.
10874       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10875       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10876       N2 = DAG.getIntPtrConstant(IdxVal << 4);
10877       // Create this as a scalar to vector..
10878       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10879       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10880     }
10881
10882     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10883       // PINSR* works with constant index.
10884       return Op;
10885     }
10886   }
10887
10888   if (EltVT == MVT::i8)
10889     return SDValue();
10890
10891   if (EltVT.getSizeInBits() == 16) {
10892     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10893     // as its second argument.
10894     if (N1.getValueType() != MVT::i32)
10895       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10896     if (N2.getValueType() != MVT::i32)
10897       N2 = DAG.getIntPtrConstant(IdxVal);
10898     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10899   }
10900   return SDValue();
10901 }
10902
10903 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10904   SDLoc dl(Op);
10905   MVT OpVT = Op.getSimpleValueType();
10906
10907   // If this is a 256-bit vector result, first insert into a 128-bit
10908   // vector and then insert into the 256-bit vector.
10909   if (!OpVT.is128BitVector()) {
10910     // Insert into a 128-bit vector.
10911     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10912     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10913                                  OpVT.getVectorNumElements() / SizeFactor);
10914
10915     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10916
10917     // Insert the 128-bit vector.
10918     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10919   }
10920
10921   if (OpVT == MVT::v1i64 &&
10922       Op.getOperand(0).getValueType() == MVT::i64)
10923     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10924
10925   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10926   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10927   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10928                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10929 }
10930
10931 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10932 // a simple subregister reference or explicit instructions to grab
10933 // upper bits of a vector.
10934 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10935                                       SelectionDAG &DAG) {
10936   SDLoc dl(Op);
10937   SDValue In =  Op.getOperand(0);
10938   SDValue Idx = Op.getOperand(1);
10939   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10940   MVT ResVT   = Op.getSimpleValueType();
10941   MVT InVT    = In.getSimpleValueType();
10942
10943   if (Subtarget->hasFp256()) {
10944     if (ResVT.is128BitVector() &&
10945         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10946         isa<ConstantSDNode>(Idx)) {
10947       return Extract128BitVector(In, IdxVal, DAG, dl);
10948     }
10949     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10950         isa<ConstantSDNode>(Idx)) {
10951       return Extract256BitVector(In, IdxVal, DAG, dl);
10952     }
10953   }
10954   return SDValue();
10955 }
10956
10957 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10958 // simple superregister reference or explicit instructions to insert
10959 // the upper bits of a vector.
10960 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10961                                      SelectionDAG &DAG) {
10962   if (Subtarget->hasFp256()) {
10963     SDLoc dl(Op.getNode());
10964     SDValue Vec = Op.getNode()->getOperand(0);
10965     SDValue SubVec = Op.getNode()->getOperand(1);
10966     SDValue Idx = Op.getNode()->getOperand(2);
10967
10968     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10969          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10970         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10971         isa<ConstantSDNode>(Idx)) {
10972       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10973       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10974     }
10975
10976     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10977         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10978         isa<ConstantSDNode>(Idx)) {
10979       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10980       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10981     }
10982   }
10983   return SDValue();
10984 }
10985
10986 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10987 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10988 // one of the above mentioned nodes. It has to be wrapped because otherwise
10989 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10990 // be used to form addressing mode. These wrapped nodes will be selected
10991 // into MOV32ri.
10992 SDValue
10993 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10994   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10995
10996   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10997   // global base reg.
10998   unsigned char OpFlag = 0;
10999   unsigned WrapperKind = X86ISD::Wrapper;
11000   CodeModel::Model M = DAG.getTarget().getCodeModel();
11001
11002   if (Subtarget->isPICStyleRIPRel() &&
11003       (M == CodeModel::Small || M == CodeModel::Kernel))
11004     WrapperKind = X86ISD::WrapperRIP;
11005   else if (Subtarget->isPICStyleGOT())
11006     OpFlag = X86II::MO_GOTOFF;
11007   else if (Subtarget->isPICStyleStubPIC())
11008     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11009
11010   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11011                                              CP->getAlignment(),
11012                                              CP->getOffset(), OpFlag);
11013   SDLoc DL(CP);
11014   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11015   // With PIC, the address is actually $g + Offset.
11016   if (OpFlag) {
11017     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11018                          DAG.getNode(X86ISD::GlobalBaseReg,
11019                                      SDLoc(), getPointerTy()),
11020                          Result);
11021   }
11022
11023   return Result;
11024 }
11025
11026 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11027   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11028
11029   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11030   // global base reg.
11031   unsigned char OpFlag = 0;
11032   unsigned WrapperKind = X86ISD::Wrapper;
11033   CodeModel::Model M = DAG.getTarget().getCodeModel();
11034
11035   if (Subtarget->isPICStyleRIPRel() &&
11036       (M == CodeModel::Small || M == CodeModel::Kernel))
11037     WrapperKind = X86ISD::WrapperRIP;
11038   else if (Subtarget->isPICStyleGOT())
11039     OpFlag = X86II::MO_GOTOFF;
11040   else if (Subtarget->isPICStyleStubPIC())
11041     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11042
11043   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11044                                           OpFlag);
11045   SDLoc DL(JT);
11046   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11047
11048   // With PIC, the address is actually $g + Offset.
11049   if (OpFlag)
11050     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11051                          DAG.getNode(X86ISD::GlobalBaseReg,
11052                                      SDLoc(), getPointerTy()),
11053                          Result);
11054
11055   return Result;
11056 }
11057
11058 SDValue
11059 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11060   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11061
11062   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11063   // global base reg.
11064   unsigned char OpFlag = 0;
11065   unsigned WrapperKind = X86ISD::Wrapper;
11066   CodeModel::Model M = DAG.getTarget().getCodeModel();
11067
11068   if (Subtarget->isPICStyleRIPRel() &&
11069       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11070     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11071       OpFlag = X86II::MO_GOTPCREL;
11072     WrapperKind = X86ISD::WrapperRIP;
11073   } else if (Subtarget->isPICStyleGOT()) {
11074     OpFlag = X86II::MO_GOT;
11075   } else if (Subtarget->isPICStyleStubPIC()) {
11076     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11077   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11078     OpFlag = X86II::MO_DARWIN_NONLAZY;
11079   }
11080
11081   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11082
11083   SDLoc DL(Op);
11084   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11085
11086   // With PIC, the address is actually $g + Offset.
11087   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11088       !Subtarget->is64Bit()) {
11089     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11090                          DAG.getNode(X86ISD::GlobalBaseReg,
11091                                      SDLoc(), getPointerTy()),
11092                          Result);
11093   }
11094
11095   // For symbols that require a load from a stub to get the address, emit the
11096   // load.
11097   if (isGlobalStubReference(OpFlag))
11098     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11099                          MachinePointerInfo::getGOT(), false, false, false, 0);
11100
11101   return Result;
11102 }
11103
11104 SDValue
11105 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11106   // Create the TargetBlockAddressAddress node.
11107   unsigned char OpFlags =
11108     Subtarget->ClassifyBlockAddressReference();
11109   CodeModel::Model M = DAG.getTarget().getCodeModel();
11110   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11111   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11112   SDLoc dl(Op);
11113   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11114                                              OpFlags);
11115
11116   if (Subtarget->isPICStyleRIPRel() &&
11117       (M == CodeModel::Small || M == CodeModel::Kernel))
11118     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11119   else
11120     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11121
11122   // With PIC, the address is actually $g + Offset.
11123   if (isGlobalRelativeToPICBase(OpFlags)) {
11124     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11125                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11126                          Result);
11127   }
11128
11129   return Result;
11130 }
11131
11132 SDValue
11133 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11134                                       int64_t Offset, SelectionDAG &DAG) const {
11135   // Create the TargetGlobalAddress node, folding in the constant
11136   // offset if it is legal.
11137   unsigned char OpFlags =
11138       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11139   CodeModel::Model M = DAG.getTarget().getCodeModel();
11140   SDValue Result;
11141   if (OpFlags == X86II::MO_NO_FLAG &&
11142       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11143     // A direct static reference to a global.
11144     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11145     Offset = 0;
11146   } else {
11147     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11148   }
11149
11150   if (Subtarget->isPICStyleRIPRel() &&
11151       (M == CodeModel::Small || M == CodeModel::Kernel))
11152     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11153   else
11154     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11155
11156   // With PIC, the address is actually $g + Offset.
11157   if (isGlobalRelativeToPICBase(OpFlags)) {
11158     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11159                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11160                          Result);
11161   }
11162
11163   // For globals that require a load from a stub to get the address, emit the
11164   // load.
11165   if (isGlobalStubReference(OpFlags))
11166     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11167                          MachinePointerInfo::getGOT(), false, false, false, 0);
11168
11169   // If there was a non-zero offset that we didn't fold, create an explicit
11170   // addition for it.
11171   if (Offset != 0)
11172     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11173                          DAG.getConstant(Offset, getPointerTy()));
11174
11175   return Result;
11176 }
11177
11178 SDValue
11179 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11180   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11181   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11182   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11183 }
11184
11185 static SDValue
11186 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11187            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11188            unsigned char OperandFlags, bool LocalDynamic = false) {
11189   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11190   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11191   SDLoc dl(GA);
11192   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11193                                            GA->getValueType(0),
11194                                            GA->getOffset(),
11195                                            OperandFlags);
11196
11197   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11198                                            : X86ISD::TLSADDR;
11199
11200   if (InFlag) {
11201     SDValue Ops[] = { Chain,  TGA, *InFlag };
11202     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11203   } else {
11204     SDValue Ops[]  = { Chain, TGA };
11205     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11206   }
11207
11208   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11209   MFI->setAdjustsStack(true);
11210
11211   SDValue Flag = Chain.getValue(1);
11212   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11213 }
11214
11215 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11216 static SDValue
11217 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11218                                 const EVT PtrVT) {
11219   SDValue InFlag;
11220   SDLoc dl(GA);  // ? function entry point might be better
11221   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11222                                    DAG.getNode(X86ISD::GlobalBaseReg,
11223                                                SDLoc(), PtrVT), InFlag);
11224   InFlag = Chain.getValue(1);
11225
11226   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11227 }
11228
11229 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11230 static SDValue
11231 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11232                                 const EVT PtrVT) {
11233   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11234                     X86::RAX, X86II::MO_TLSGD);
11235 }
11236
11237 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11238                                            SelectionDAG &DAG,
11239                                            const EVT PtrVT,
11240                                            bool is64Bit) {
11241   SDLoc dl(GA);
11242
11243   // Get the start address of the TLS block for this module.
11244   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11245       .getInfo<X86MachineFunctionInfo>();
11246   MFI->incNumLocalDynamicTLSAccesses();
11247
11248   SDValue Base;
11249   if (is64Bit) {
11250     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11251                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11252   } else {
11253     SDValue InFlag;
11254     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11255         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11256     InFlag = Chain.getValue(1);
11257     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11258                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11259   }
11260
11261   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11262   // of Base.
11263
11264   // Build x@dtpoff.
11265   unsigned char OperandFlags = X86II::MO_DTPOFF;
11266   unsigned WrapperKind = X86ISD::Wrapper;
11267   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11268                                            GA->getValueType(0),
11269                                            GA->getOffset(), OperandFlags);
11270   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11271
11272   // Add x@dtpoff with the base.
11273   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11274 }
11275
11276 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11277 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11278                                    const EVT PtrVT, TLSModel::Model model,
11279                                    bool is64Bit, bool isPIC) {
11280   SDLoc dl(GA);
11281
11282   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11283   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11284                                                          is64Bit ? 257 : 256));
11285
11286   SDValue ThreadPointer =
11287       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11288                   MachinePointerInfo(Ptr), false, false, false, 0);
11289
11290   unsigned char OperandFlags = 0;
11291   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11292   // initialexec.
11293   unsigned WrapperKind = X86ISD::Wrapper;
11294   if (model == TLSModel::LocalExec) {
11295     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11296   } else if (model == TLSModel::InitialExec) {
11297     if (is64Bit) {
11298       OperandFlags = X86II::MO_GOTTPOFF;
11299       WrapperKind = X86ISD::WrapperRIP;
11300     } else {
11301       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11302     }
11303   } else {
11304     llvm_unreachable("Unexpected model");
11305   }
11306
11307   // emit "addl x@ntpoff,%eax" (local exec)
11308   // or "addl x@indntpoff,%eax" (initial exec)
11309   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11310   SDValue TGA =
11311       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11312                                  GA->getOffset(), OperandFlags);
11313   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11314
11315   if (model == TLSModel::InitialExec) {
11316     if (isPIC && !is64Bit) {
11317       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11318                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11319                            Offset);
11320     }
11321
11322     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11323                          MachinePointerInfo::getGOT(), false, false, false, 0);
11324   }
11325
11326   // The address of the thread local variable is the add of the thread
11327   // pointer with the offset of the variable.
11328   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11329 }
11330
11331 SDValue
11332 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11333
11334   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11335   const GlobalValue *GV = GA->getGlobal();
11336
11337   if (Subtarget->isTargetELF()) {
11338     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11339
11340     switch (model) {
11341       case TLSModel::GeneralDynamic:
11342         if (Subtarget->is64Bit())
11343           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11344         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11345       case TLSModel::LocalDynamic:
11346         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11347                                            Subtarget->is64Bit());
11348       case TLSModel::InitialExec:
11349       case TLSModel::LocalExec:
11350         return LowerToTLSExecModel(
11351             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11352             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11353     }
11354     llvm_unreachable("Unknown TLS model.");
11355   }
11356
11357   if (Subtarget->isTargetDarwin()) {
11358     // Darwin only has one model of TLS.  Lower to that.
11359     unsigned char OpFlag = 0;
11360     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11361                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11362
11363     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11364     // global base reg.
11365     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11366                  !Subtarget->is64Bit();
11367     if (PIC32)
11368       OpFlag = X86II::MO_TLVP_PIC_BASE;
11369     else
11370       OpFlag = X86II::MO_TLVP;
11371     SDLoc DL(Op);
11372     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11373                                                 GA->getValueType(0),
11374                                                 GA->getOffset(), OpFlag);
11375     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11376
11377     // With PIC32, the address is actually $g + Offset.
11378     if (PIC32)
11379       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11380                            DAG.getNode(X86ISD::GlobalBaseReg,
11381                                        SDLoc(), getPointerTy()),
11382                            Offset);
11383
11384     // Lowering the machine isd will make sure everything is in the right
11385     // location.
11386     SDValue Chain = DAG.getEntryNode();
11387     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11388     SDValue Args[] = { Chain, Offset };
11389     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11390
11391     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11392     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11393     MFI->setAdjustsStack(true);
11394
11395     // And our return value (tls address) is in the standard call return value
11396     // location.
11397     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11398     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11399                               Chain.getValue(1));
11400   }
11401
11402   if (Subtarget->isTargetKnownWindowsMSVC() ||
11403       Subtarget->isTargetWindowsGNU()) {
11404     // Just use the implicit TLS architecture
11405     // Need to generate someting similar to:
11406     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11407     //                                  ; from TEB
11408     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11409     //   mov     rcx, qword [rdx+rcx*8]
11410     //   mov     eax, .tls$:tlsvar
11411     //   [rax+rcx] contains the address
11412     // Windows 64bit: gs:0x58
11413     // Windows 32bit: fs:__tls_array
11414
11415     SDLoc dl(GA);
11416     SDValue Chain = DAG.getEntryNode();
11417
11418     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11419     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11420     // use its literal value of 0x2C.
11421     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11422                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11423                                                              256)
11424                                         : Type::getInt32PtrTy(*DAG.getContext(),
11425                                                               257));
11426
11427     SDValue TlsArray =
11428         Subtarget->is64Bit()
11429             ? DAG.getIntPtrConstant(0x58)
11430             : (Subtarget->isTargetWindowsGNU()
11431                    ? DAG.getIntPtrConstant(0x2C)
11432                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11433
11434     SDValue ThreadPointer =
11435         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11436                     MachinePointerInfo(Ptr), false, false, false, 0);
11437
11438     // Load the _tls_index variable
11439     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11440     if (Subtarget->is64Bit())
11441       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11442                            IDX, MachinePointerInfo(), MVT::i32,
11443                            false, false, false, 0);
11444     else
11445       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11446                         false, false, false, 0);
11447
11448     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11449                                     getPointerTy());
11450     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11451
11452     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11453     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11454                       false, false, false, 0);
11455
11456     // Get the offset of start of .tls section
11457     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11458                                              GA->getValueType(0),
11459                                              GA->getOffset(), X86II::MO_SECREL);
11460     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11461
11462     // The address of the thread local variable is the add of the thread
11463     // pointer with the offset of the variable.
11464     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11465   }
11466
11467   llvm_unreachable("TLS not implemented for this target.");
11468 }
11469
11470 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11471 /// and take a 2 x i32 value to shift plus a shift amount.
11472 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11473   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11474   MVT VT = Op.getSimpleValueType();
11475   unsigned VTBits = VT.getSizeInBits();
11476   SDLoc dl(Op);
11477   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11478   SDValue ShOpLo = Op.getOperand(0);
11479   SDValue ShOpHi = Op.getOperand(1);
11480   SDValue ShAmt  = Op.getOperand(2);
11481   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11482   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11483   // during isel.
11484   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11485                                   DAG.getConstant(VTBits - 1, MVT::i8));
11486   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11487                                      DAG.getConstant(VTBits - 1, MVT::i8))
11488                        : DAG.getConstant(0, VT);
11489
11490   SDValue Tmp2, Tmp3;
11491   if (Op.getOpcode() == ISD::SHL_PARTS) {
11492     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11493     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11494   } else {
11495     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11496     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11497   }
11498
11499   // If the shift amount is larger or equal than the width of a part we can't
11500   // rely on the results of shld/shrd. Insert a test and select the appropriate
11501   // values for large shift amounts.
11502   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11503                                 DAG.getConstant(VTBits, MVT::i8));
11504   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11505                              AndNode, DAG.getConstant(0, MVT::i8));
11506
11507   SDValue Hi, Lo;
11508   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11509   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11510   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11511
11512   if (Op.getOpcode() == ISD::SHL_PARTS) {
11513     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11514     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11515   } else {
11516     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11517     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11518   }
11519
11520   SDValue Ops[2] = { Lo, Hi };
11521   return DAG.getMergeValues(Ops, dl);
11522 }
11523
11524 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11525                                            SelectionDAG &DAG) const {
11526   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11527
11528   if (SrcVT.isVector())
11529     return SDValue();
11530
11531   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11532          "Unknown SINT_TO_FP to lower!");
11533
11534   // These are really Legal; return the operand so the caller accepts it as
11535   // Legal.
11536   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11537     return Op;
11538   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11539       Subtarget->is64Bit()) {
11540     return Op;
11541   }
11542
11543   SDLoc dl(Op);
11544   unsigned Size = SrcVT.getSizeInBits()/8;
11545   MachineFunction &MF = DAG.getMachineFunction();
11546   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11547   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11548   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11549                                StackSlot,
11550                                MachinePointerInfo::getFixedStack(SSFI),
11551                                false, false, 0);
11552   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11553 }
11554
11555 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11556                                      SDValue StackSlot,
11557                                      SelectionDAG &DAG) const {
11558   // Build the FILD
11559   SDLoc DL(Op);
11560   SDVTList Tys;
11561   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11562   if (useSSE)
11563     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11564   else
11565     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11566
11567   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11568
11569   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11570   MachineMemOperand *MMO;
11571   if (FI) {
11572     int SSFI = FI->getIndex();
11573     MMO =
11574       DAG.getMachineFunction()
11575       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11576                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11577   } else {
11578     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11579     StackSlot = StackSlot.getOperand(1);
11580   }
11581   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11582   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11583                                            X86ISD::FILD, DL,
11584                                            Tys, Ops, SrcVT, MMO);
11585
11586   if (useSSE) {
11587     Chain = Result.getValue(1);
11588     SDValue InFlag = Result.getValue(2);
11589
11590     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11591     // shouldn't be necessary except that RFP cannot be live across
11592     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11593     MachineFunction &MF = DAG.getMachineFunction();
11594     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11595     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11596     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11597     Tys = DAG.getVTList(MVT::Other);
11598     SDValue Ops[] = {
11599       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11600     };
11601     MachineMemOperand *MMO =
11602       DAG.getMachineFunction()
11603       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11604                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11605
11606     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11607                                     Ops, Op.getValueType(), MMO);
11608     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11609                          MachinePointerInfo::getFixedStack(SSFI),
11610                          false, false, false, 0);
11611   }
11612
11613   return Result;
11614 }
11615
11616 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11617 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11618                                                SelectionDAG &DAG) const {
11619   // This algorithm is not obvious. Here it is what we're trying to output:
11620   /*
11621      movq       %rax,  %xmm0
11622      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11623      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11624      #ifdef __SSE3__
11625        haddpd   %xmm0, %xmm0
11626      #else
11627        pshufd   $0x4e, %xmm0, %xmm1
11628        addpd    %xmm1, %xmm0
11629      #endif
11630   */
11631
11632   SDLoc dl(Op);
11633   LLVMContext *Context = DAG.getContext();
11634
11635   // Build some magic constants.
11636   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11637   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11638   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11639
11640   SmallVector<Constant*,2> CV1;
11641   CV1.push_back(
11642     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11643                                       APInt(64, 0x4330000000000000ULL))));
11644   CV1.push_back(
11645     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11646                                       APInt(64, 0x4530000000000000ULL))));
11647   Constant *C1 = ConstantVector::get(CV1);
11648   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11649
11650   // Load the 64-bit value into an XMM register.
11651   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11652                             Op.getOperand(0));
11653   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11654                               MachinePointerInfo::getConstantPool(),
11655                               false, false, false, 16);
11656   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11657                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11658                               CLod0);
11659
11660   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11661                               MachinePointerInfo::getConstantPool(),
11662                               false, false, false, 16);
11663   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11664   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11665   SDValue Result;
11666
11667   if (Subtarget->hasSSE3()) {
11668     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11669     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11670   } else {
11671     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11672     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11673                                            S2F, 0x4E, DAG);
11674     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11675                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11676                          Sub);
11677   }
11678
11679   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11680                      DAG.getIntPtrConstant(0));
11681 }
11682
11683 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11684 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11685                                                SelectionDAG &DAG) const {
11686   SDLoc dl(Op);
11687   // FP constant to bias correct the final result.
11688   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11689                                    MVT::f64);
11690
11691   // Load the 32-bit value into an XMM register.
11692   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11693                              Op.getOperand(0));
11694
11695   // Zero out the upper parts of the register.
11696   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11697
11698   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11699                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11700                      DAG.getIntPtrConstant(0));
11701
11702   // Or the load with the bias.
11703   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11704                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11705                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11706                                                    MVT::v2f64, Load)),
11707                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11708                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11709                                                    MVT::v2f64, Bias)));
11710   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11711                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11712                    DAG.getIntPtrConstant(0));
11713
11714   // Subtract the bias.
11715   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11716
11717   // Handle final rounding.
11718   EVT DestVT = Op.getValueType();
11719
11720   if (DestVT.bitsLT(MVT::f64))
11721     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11722                        DAG.getIntPtrConstant(0));
11723   if (DestVT.bitsGT(MVT::f64))
11724     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11725
11726   // Handle final rounding.
11727   return Sub;
11728 }
11729
11730 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11731                                                SelectionDAG &DAG) const {
11732   SDValue N0 = Op.getOperand(0);
11733   MVT SVT = N0.getSimpleValueType();
11734   SDLoc dl(Op);
11735
11736   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11737           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11738          "Custom UINT_TO_FP is not supported!");
11739
11740   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11741   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11742                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11743 }
11744
11745 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11746                                            SelectionDAG &DAG) const {
11747   SDValue N0 = Op.getOperand(0);
11748   SDLoc dl(Op);
11749
11750   if (Op.getValueType().isVector())
11751     return lowerUINT_TO_FP_vec(Op, DAG);
11752
11753   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11754   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11755   // the optimization here.
11756   if (DAG.SignBitIsZero(N0))
11757     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11758
11759   MVT SrcVT = N0.getSimpleValueType();
11760   MVT DstVT = Op.getSimpleValueType();
11761   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11762     return LowerUINT_TO_FP_i64(Op, DAG);
11763   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11764     return LowerUINT_TO_FP_i32(Op, DAG);
11765   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11766     return SDValue();
11767
11768   // Make a 64-bit buffer, and use it to build an FILD.
11769   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11770   if (SrcVT == MVT::i32) {
11771     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11772     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11773                                      getPointerTy(), StackSlot, WordOff);
11774     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11775                                   StackSlot, MachinePointerInfo(),
11776                                   false, false, 0);
11777     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11778                                   OffsetSlot, MachinePointerInfo(),
11779                                   false, false, 0);
11780     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11781     return Fild;
11782   }
11783
11784   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11785   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11786                                StackSlot, MachinePointerInfo(),
11787                                false, false, 0);
11788   // For i64 source, we need to add the appropriate power of 2 if the input
11789   // was negative.  This is the same as the optimization in
11790   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11791   // we must be careful to do the computation in x87 extended precision, not
11792   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11793   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11794   MachineMemOperand *MMO =
11795     DAG.getMachineFunction()
11796     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11797                           MachineMemOperand::MOLoad, 8, 8);
11798
11799   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11800   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11801   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11802                                          MVT::i64, MMO);
11803
11804   APInt FF(32, 0x5F800000ULL);
11805
11806   // Check whether the sign bit is set.
11807   SDValue SignSet = DAG.getSetCC(dl,
11808                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11809                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11810                                  ISD::SETLT);
11811
11812   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11813   SDValue FudgePtr = DAG.getConstantPool(
11814                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11815                                          getPointerTy());
11816
11817   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11818   SDValue Zero = DAG.getIntPtrConstant(0);
11819   SDValue Four = DAG.getIntPtrConstant(4);
11820   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11821                                Zero, Four);
11822   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11823
11824   // Load the value out, extending it from f32 to f80.
11825   // FIXME: Avoid the extend by constructing the right constant pool?
11826   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11827                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11828                                  MVT::f32, false, false, false, 4);
11829   // Extend everything to 80 bits to force it to be done on x87.
11830   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11831   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11832 }
11833
11834 std::pair<SDValue,SDValue>
11835 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11836                                     bool IsSigned, bool IsReplace) const {
11837   SDLoc DL(Op);
11838
11839   EVT DstTy = Op.getValueType();
11840
11841   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11842     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11843     DstTy = MVT::i64;
11844   }
11845
11846   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11847          DstTy.getSimpleVT() >= MVT::i16 &&
11848          "Unknown FP_TO_INT to lower!");
11849
11850   // These are really Legal.
11851   if (DstTy == MVT::i32 &&
11852       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11853     return std::make_pair(SDValue(), SDValue());
11854   if (Subtarget->is64Bit() &&
11855       DstTy == MVT::i64 &&
11856       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11857     return std::make_pair(SDValue(), SDValue());
11858
11859   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11860   // stack slot, or into the FTOL runtime function.
11861   MachineFunction &MF = DAG.getMachineFunction();
11862   unsigned MemSize = DstTy.getSizeInBits()/8;
11863   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11864   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11865
11866   unsigned Opc;
11867   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11868     Opc = X86ISD::WIN_FTOL;
11869   else
11870     switch (DstTy.getSimpleVT().SimpleTy) {
11871     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11872     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11873     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11874     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11875     }
11876
11877   SDValue Chain = DAG.getEntryNode();
11878   SDValue Value = Op.getOperand(0);
11879   EVT TheVT = Op.getOperand(0).getValueType();
11880   // FIXME This causes a redundant load/store if the SSE-class value is already
11881   // in memory, such as if it is on the callstack.
11882   if (isScalarFPTypeInSSEReg(TheVT)) {
11883     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11884     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11885                          MachinePointerInfo::getFixedStack(SSFI),
11886                          false, false, 0);
11887     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11888     SDValue Ops[] = {
11889       Chain, StackSlot, DAG.getValueType(TheVT)
11890     };
11891
11892     MachineMemOperand *MMO =
11893       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11894                               MachineMemOperand::MOLoad, MemSize, MemSize);
11895     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11896     Chain = Value.getValue(1);
11897     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11898     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11899   }
11900
11901   MachineMemOperand *MMO =
11902     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11903                             MachineMemOperand::MOStore, MemSize, MemSize);
11904
11905   if (Opc != X86ISD::WIN_FTOL) {
11906     // Build the FP_TO_INT*_IN_MEM
11907     SDValue Ops[] = { Chain, Value, StackSlot };
11908     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11909                                            Ops, DstTy, MMO);
11910     return std::make_pair(FIST, StackSlot);
11911   } else {
11912     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11913       DAG.getVTList(MVT::Other, MVT::Glue),
11914       Chain, Value);
11915     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11916       MVT::i32, ftol.getValue(1));
11917     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11918       MVT::i32, eax.getValue(2));
11919     SDValue Ops[] = { eax, edx };
11920     SDValue pair = IsReplace
11921       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11922       : DAG.getMergeValues(Ops, DL);
11923     return std::make_pair(pair, SDValue());
11924   }
11925 }
11926
11927 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11928                               const X86Subtarget *Subtarget) {
11929   MVT VT = Op->getSimpleValueType(0);
11930   SDValue In = Op->getOperand(0);
11931   MVT InVT = In.getSimpleValueType();
11932   SDLoc dl(Op);
11933
11934   // Optimize vectors in AVX mode:
11935   //
11936   //   v8i16 -> v8i32
11937   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11938   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11939   //   Concat upper and lower parts.
11940   //
11941   //   v4i32 -> v4i64
11942   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11943   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11944   //   Concat upper and lower parts.
11945   //
11946
11947   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11948       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11949       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11950     return SDValue();
11951
11952   if (Subtarget->hasInt256())
11953     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11954
11955   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11956   SDValue Undef = DAG.getUNDEF(InVT);
11957   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11958   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11959   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11960
11961   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11962                              VT.getVectorNumElements()/2);
11963
11964   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11965   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11966
11967   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11968 }
11969
11970 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11971                                         SelectionDAG &DAG) {
11972   MVT VT = Op->getSimpleValueType(0);
11973   SDValue In = Op->getOperand(0);
11974   MVT InVT = In.getSimpleValueType();
11975   SDLoc DL(Op);
11976   unsigned int NumElts = VT.getVectorNumElements();
11977   if (NumElts != 8 && NumElts != 16)
11978     return SDValue();
11979
11980   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11981     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11982
11983   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11985   // Now we have only mask extension
11986   assert(InVT.getVectorElementType() == MVT::i1);
11987   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11988   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11989   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11990   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11991   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11992                            MachinePointerInfo::getConstantPool(),
11993                            false, false, false, Alignment);
11994
11995   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11996   if (VT.is512BitVector())
11997     return Brcst;
11998   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11999 }
12000
12001 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12002                                SelectionDAG &DAG) {
12003   if (Subtarget->hasFp256()) {
12004     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12005     if (Res.getNode())
12006       return Res;
12007   }
12008
12009   return SDValue();
12010 }
12011
12012 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12013                                 SelectionDAG &DAG) {
12014   SDLoc DL(Op);
12015   MVT VT = Op.getSimpleValueType();
12016   SDValue In = Op.getOperand(0);
12017   MVT SVT = In.getSimpleValueType();
12018
12019   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12020     return LowerZERO_EXTEND_AVX512(Op, DAG);
12021
12022   if (Subtarget->hasFp256()) {
12023     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12024     if (Res.getNode())
12025       return Res;
12026   }
12027
12028   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12029          VT.getVectorNumElements() != SVT.getVectorNumElements());
12030   return SDValue();
12031 }
12032
12033 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12034   SDLoc DL(Op);
12035   MVT VT = Op.getSimpleValueType();
12036   SDValue In = Op.getOperand(0);
12037   MVT InVT = In.getSimpleValueType();
12038
12039   if (VT == MVT::i1) {
12040     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12041            "Invalid scalar TRUNCATE operation");
12042     if (InVT.getSizeInBits() >= 32)
12043       return SDValue();
12044     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12045     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12046   }
12047   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12048          "Invalid TRUNCATE operation");
12049
12050   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12051     if (VT.getVectorElementType().getSizeInBits() >=8)
12052       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12053
12054     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12055     unsigned NumElts = InVT.getVectorNumElements();
12056     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12057     if (InVT.getSizeInBits() < 512) {
12058       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12059       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12060       InVT = ExtVT;
12061     }
12062     
12063     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12064     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12065     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12066     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12067     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12068                            MachinePointerInfo::getConstantPool(),
12069                            false, false, false, Alignment);
12070     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12071     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12072     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12073   }
12074
12075   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12076     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12077     if (Subtarget->hasInt256()) {
12078       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12079       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12080       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12081                                 ShufMask);
12082       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12083                          DAG.getIntPtrConstant(0));
12084     }
12085
12086     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12087                                DAG.getIntPtrConstant(0));
12088     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12089                                DAG.getIntPtrConstant(2));
12090     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12091     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12092     static const int ShufMask[] = {0, 2, 4, 6};
12093     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12094   }
12095
12096   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12097     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12098     if (Subtarget->hasInt256()) {
12099       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12100
12101       SmallVector<SDValue,32> pshufbMask;
12102       for (unsigned i = 0; i < 2; ++i) {
12103         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12104         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12105         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12106         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12107         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12108         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12109         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12110         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12111         for (unsigned j = 0; j < 8; ++j)
12112           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12113       }
12114       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12115       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12116       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12117
12118       static const int ShufMask[] = {0,  2,  -1,  -1};
12119       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12120                                 &ShufMask[0]);
12121       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12122                        DAG.getIntPtrConstant(0));
12123       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12124     }
12125
12126     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12127                                DAG.getIntPtrConstant(0));
12128
12129     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12130                                DAG.getIntPtrConstant(4));
12131
12132     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12133     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12134
12135     // The PSHUFB mask:
12136     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12137                                    -1, -1, -1, -1, -1, -1, -1, -1};
12138
12139     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12140     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12141     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12142
12143     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12144     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12145
12146     // The MOVLHPS Mask:
12147     static const int ShufMask2[] = {0, 1, 4, 5};
12148     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12149     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12150   }
12151
12152   // Handle truncation of V256 to V128 using shuffles.
12153   if (!VT.is128BitVector() || !InVT.is256BitVector())
12154     return SDValue();
12155
12156   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12157
12158   unsigned NumElems = VT.getVectorNumElements();
12159   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12160
12161   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12162   // Prepare truncation shuffle mask
12163   for (unsigned i = 0; i != NumElems; ++i)
12164     MaskVec[i] = i * 2;
12165   SDValue V = DAG.getVectorShuffle(NVT, DL,
12166                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12167                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12168   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12169                      DAG.getIntPtrConstant(0));
12170 }
12171
12172 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12173                                            SelectionDAG &DAG) const {
12174   assert(!Op.getSimpleValueType().isVector());
12175
12176   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12177     /*IsSigned=*/ true, /*IsReplace=*/ false);
12178   SDValue FIST = Vals.first, StackSlot = Vals.second;
12179   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12180   if (!FIST.getNode()) return Op;
12181
12182   if (StackSlot.getNode())
12183     // Load the result.
12184     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12185                        FIST, StackSlot, MachinePointerInfo(),
12186                        false, false, false, 0);
12187
12188   // The node is the result.
12189   return FIST;
12190 }
12191
12192 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12193                                            SelectionDAG &DAG) const {
12194   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12195     /*IsSigned=*/ false, /*IsReplace=*/ false);
12196   SDValue FIST = Vals.first, StackSlot = Vals.second;
12197   assert(FIST.getNode() && "Unexpected failure");
12198
12199   if (StackSlot.getNode())
12200     // Load the result.
12201     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12202                        FIST, StackSlot, MachinePointerInfo(),
12203                        false, false, false, 0);
12204
12205   // The node is the result.
12206   return FIST;
12207 }
12208
12209 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12210   SDLoc DL(Op);
12211   MVT VT = Op.getSimpleValueType();
12212   SDValue In = Op.getOperand(0);
12213   MVT SVT = In.getSimpleValueType();
12214
12215   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12216
12217   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12218                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12219                                  In, DAG.getUNDEF(SVT)));
12220 }
12221
12222 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12223   LLVMContext *Context = DAG.getContext();
12224   SDLoc dl(Op);
12225   MVT VT = Op.getSimpleValueType();
12226   MVT EltVT = VT;
12227   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12228   if (VT.isVector()) {
12229     EltVT = VT.getVectorElementType();
12230     NumElts = VT.getVectorNumElements();
12231   }
12232   Constant *C;
12233   if (EltVT == MVT::f64)
12234     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12235                                           APInt(64, ~(1ULL << 63))));
12236   else
12237     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12238                                           APInt(32, ~(1U << 31))));
12239   C = ConstantVector::getSplat(NumElts, C);
12240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12241   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12242   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12243   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12244                              MachinePointerInfo::getConstantPool(),
12245                              false, false, false, Alignment);
12246   if (VT.isVector()) {
12247     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12248     return DAG.getNode(ISD::BITCAST, dl, VT,
12249                        DAG.getNode(ISD::AND, dl, ANDVT,
12250                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
12251                                                Op.getOperand(0)),
12252                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12253   }
12254   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12255 }
12256
12257 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12258   LLVMContext *Context = DAG.getContext();
12259   SDLoc dl(Op);
12260   MVT VT = Op.getSimpleValueType();
12261   MVT EltVT = VT;
12262   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12263   if (VT.isVector()) {
12264     EltVT = VT.getVectorElementType();
12265     NumElts = VT.getVectorNumElements();
12266   }
12267   Constant *C;
12268   if (EltVT == MVT::f64)
12269     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12270                                           APInt(64, 1ULL << 63)));
12271   else
12272     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12273                                           APInt(32, 1U << 31)));
12274   C = ConstantVector::getSplat(NumElts, C);
12275   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12276   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12277   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12278   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12279                              MachinePointerInfo::getConstantPool(),
12280                              false, false, false, Alignment);
12281   if (VT.isVector()) {
12282     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12283     return DAG.getNode(ISD::BITCAST, dl, VT,
12284                        DAG.getNode(ISD::XOR, dl, XORVT,
12285                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
12286                                                Op.getOperand(0)),
12287                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12288   }
12289
12290   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12291 }
12292
12293 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12295   LLVMContext *Context = DAG.getContext();
12296   SDValue Op0 = Op.getOperand(0);
12297   SDValue Op1 = Op.getOperand(1);
12298   SDLoc dl(Op);
12299   MVT VT = Op.getSimpleValueType();
12300   MVT SrcVT = Op1.getSimpleValueType();
12301
12302   // If second operand is smaller, extend it first.
12303   if (SrcVT.bitsLT(VT)) {
12304     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12305     SrcVT = VT;
12306   }
12307   // And if it is bigger, shrink it first.
12308   if (SrcVT.bitsGT(VT)) {
12309     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12310     SrcVT = VT;
12311   }
12312
12313   // At this point the operands and the result should have the same
12314   // type, and that won't be f80 since that is not custom lowered.
12315
12316   // First get the sign bit of second operand.
12317   SmallVector<Constant*,4> CV;
12318   if (SrcVT == MVT::f64) {
12319     const fltSemantics &Sem = APFloat::IEEEdouble;
12320     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12321     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12322   } else {
12323     const fltSemantics &Sem = APFloat::IEEEsingle;
12324     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12325     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12326     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12327     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12328   }
12329   Constant *C = ConstantVector::get(CV);
12330   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12331   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12332                               MachinePointerInfo::getConstantPool(),
12333                               false, false, false, 16);
12334   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12335
12336   // Shift sign bit right or left if the two operands have different types.
12337   if (SrcVT.bitsGT(VT)) {
12338     // Op0 is MVT::f32, Op1 is MVT::f64.
12339     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12340     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12341                           DAG.getConstant(32, MVT::i32));
12342     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12343     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12344                           DAG.getIntPtrConstant(0));
12345   }
12346
12347   // Clear first operand sign bit.
12348   CV.clear();
12349   if (VT == MVT::f64) {
12350     const fltSemantics &Sem = APFloat::IEEEdouble;
12351     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12352                                                    APInt(64, ~(1ULL << 63)))));
12353     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12354   } else {
12355     const fltSemantics &Sem = APFloat::IEEEsingle;
12356     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12357                                                    APInt(32, ~(1U << 31)))));
12358     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12359     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12360     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12361   }
12362   C = ConstantVector::get(CV);
12363   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12364   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12365                               MachinePointerInfo::getConstantPool(),
12366                               false, false, false, 16);
12367   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12368
12369   // Or the value with the sign bit.
12370   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12371 }
12372
12373 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12374   SDValue N0 = Op.getOperand(0);
12375   SDLoc dl(Op);
12376   MVT VT = Op.getSimpleValueType();
12377
12378   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12379   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12380                                   DAG.getConstant(1, VT));
12381   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12382 }
12383
12384 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12385 //
12386 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12387                                       SelectionDAG &DAG) {
12388   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12389
12390   if (!Subtarget->hasSSE41())
12391     return SDValue();
12392
12393   if (!Op->hasOneUse())
12394     return SDValue();
12395
12396   SDNode *N = Op.getNode();
12397   SDLoc DL(N);
12398
12399   SmallVector<SDValue, 8> Opnds;
12400   DenseMap<SDValue, unsigned> VecInMap;
12401   SmallVector<SDValue, 8> VecIns;
12402   EVT VT = MVT::Other;
12403
12404   // Recognize a special case where a vector is casted into wide integer to
12405   // test all 0s.
12406   Opnds.push_back(N->getOperand(0));
12407   Opnds.push_back(N->getOperand(1));
12408
12409   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12410     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12411     // BFS traverse all OR'd operands.
12412     if (I->getOpcode() == ISD::OR) {
12413       Opnds.push_back(I->getOperand(0));
12414       Opnds.push_back(I->getOperand(1));
12415       // Re-evaluate the number of nodes to be traversed.
12416       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12417       continue;
12418     }
12419
12420     // Quit if a non-EXTRACT_VECTOR_ELT
12421     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12422       return SDValue();
12423
12424     // Quit if without a constant index.
12425     SDValue Idx = I->getOperand(1);
12426     if (!isa<ConstantSDNode>(Idx))
12427       return SDValue();
12428
12429     SDValue ExtractedFromVec = I->getOperand(0);
12430     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12431     if (M == VecInMap.end()) {
12432       VT = ExtractedFromVec.getValueType();
12433       // Quit if not 128/256-bit vector.
12434       if (!VT.is128BitVector() && !VT.is256BitVector())
12435         return SDValue();
12436       // Quit if not the same type.
12437       if (VecInMap.begin() != VecInMap.end() &&
12438           VT != VecInMap.begin()->first.getValueType())
12439         return SDValue();
12440       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12441       VecIns.push_back(ExtractedFromVec);
12442     }
12443     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12444   }
12445
12446   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12447          "Not extracted from 128-/256-bit vector.");
12448
12449   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12450
12451   for (DenseMap<SDValue, unsigned>::const_iterator
12452         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12453     // Quit if not all elements are used.
12454     if (I->second != FullMask)
12455       return SDValue();
12456   }
12457
12458   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12459
12460   // Cast all vectors into TestVT for PTEST.
12461   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12462     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12463
12464   // If more than one full vectors are evaluated, OR them first before PTEST.
12465   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12466     // Each iteration will OR 2 nodes and append the result until there is only
12467     // 1 node left, i.e. the final OR'd value of all vectors.
12468     SDValue LHS = VecIns[Slot];
12469     SDValue RHS = VecIns[Slot + 1];
12470     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12471   }
12472
12473   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12474                      VecIns.back(), VecIns.back());
12475 }
12476
12477 /// \brief return true if \c Op has a use that doesn't just read flags.
12478 static bool hasNonFlagsUse(SDValue Op) {
12479   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12480        ++UI) {
12481     SDNode *User = *UI;
12482     unsigned UOpNo = UI.getOperandNo();
12483     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12484       // Look pass truncate.
12485       UOpNo = User->use_begin().getOperandNo();
12486       User = *User->use_begin();
12487     }
12488
12489     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12490         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12491       return true;
12492   }
12493   return false;
12494 }
12495
12496 /// Emit nodes that will be selected as "test Op0,Op0", or something
12497 /// equivalent.
12498 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12499                                     SelectionDAG &DAG) const {
12500   if (Op.getValueType() == MVT::i1)
12501     // KORTEST instruction should be selected
12502     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12503                        DAG.getConstant(0, Op.getValueType()));
12504
12505   // CF and OF aren't always set the way we want. Determine which
12506   // of these we need.
12507   bool NeedCF = false;
12508   bool NeedOF = false;
12509   switch (X86CC) {
12510   default: break;
12511   case X86::COND_A: case X86::COND_AE:
12512   case X86::COND_B: case X86::COND_BE:
12513     NeedCF = true;
12514     break;
12515   case X86::COND_G: case X86::COND_GE:
12516   case X86::COND_L: case X86::COND_LE:
12517   case X86::COND_O: case X86::COND_NO: {
12518     // Check if we really need to set the
12519     // Overflow flag. If NoSignedWrap is present
12520     // that is not actually needed.
12521     switch (Op->getOpcode()) {
12522     case ISD::ADD:
12523     case ISD::SUB:
12524     case ISD::MUL:
12525     case ISD::SHL: {
12526       const BinaryWithFlagsSDNode *BinNode =
12527           cast<BinaryWithFlagsSDNode>(Op.getNode());
12528       if (BinNode->hasNoSignedWrap())
12529         break;
12530     }
12531     default:
12532       NeedOF = true;
12533       break;
12534     }
12535     break;
12536   }
12537   }
12538   // See if we can use the EFLAGS value from the operand instead of
12539   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12540   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12541   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12542     // Emit a CMP with 0, which is the TEST pattern.
12543     //if (Op.getValueType() == MVT::i1)
12544     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12545     //                     DAG.getConstant(0, MVT::i1));
12546     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12547                        DAG.getConstant(0, Op.getValueType()));
12548   }
12549   unsigned Opcode = 0;
12550   unsigned NumOperands = 0;
12551
12552   // Truncate operations may prevent the merge of the SETCC instruction
12553   // and the arithmetic instruction before it. Attempt to truncate the operands
12554   // of the arithmetic instruction and use a reduced bit-width instruction.
12555   bool NeedTruncation = false;
12556   SDValue ArithOp = Op;
12557   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12558     SDValue Arith = Op->getOperand(0);
12559     // Both the trunc and the arithmetic op need to have one user each.
12560     if (Arith->hasOneUse())
12561       switch (Arith.getOpcode()) {
12562         default: break;
12563         case ISD::ADD:
12564         case ISD::SUB:
12565         case ISD::AND:
12566         case ISD::OR:
12567         case ISD::XOR: {
12568           NeedTruncation = true;
12569           ArithOp = Arith;
12570         }
12571       }
12572   }
12573
12574   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12575   // which may be the result of a CAST.  We use the variable 'Op', which is the
12576   // non-casted variable when we check for possible users.
12577   switch (ArithOp.getOpcode()) {
12578   case ISD::ADD:
12579     // Due to an isel shortcoming, be conservative if this add is likely to be
12580     // selected as part of a load-modify-store instruction. When the root node
12581     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12582     // uses of other nodes in the match, such as the ADD in this case. This
12583     // leads to the ADD being left around and reselected, with the result being
12584     // two adds in the output.  Alas, even if none our users are stores, that
12585     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12586     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12587     // climbing the DAG back to the root, and it doesn't seem to be worth the
12588     // effort.
12589     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12590          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12591       if (UI->getOpcode() != ISD::CopyToReg &&
12592           UI->getOpcode() != ISD::SETCC &&
12593           UI->getOpcode() != ISD::STORE)
12594         goto default_case;
12595
12596     if (ConstantSDNode *C =
12597         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12598       // An add of one will be selected as an INC.
12599       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12600         Opcode = X86ISD::INC;
12601         NumOperands = 1;
12602         break;
12603       }
12604
12605       // An add of negative one (subtract of one) will be selected as a DEC.
12606       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12607         Opcode = X86ISD::DEC;
12608         NumOperands = 1;
12609         break;
12610       }
12611     }
12612
12613     // Otherwise use a regular EFLAGS-setting add.
12614     Opcode = X86ISD::ADD;
12615     NumOperands = 2;
12616     break;
12617   case ISD::SHL:
12618   case ISD::SRL:
12619     // If we have a constant logical shift that's only used in a comparison
12620     // against zero turn it into an equivalent AND. This allows turning it into
12621     // a TEST instruction later.
12622     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12623         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12624       EVT VT = Op.getValueType();
12625       unsigned BitWidth = VT.getSizeInBits();
12626       unsigned ShAmt = Op->getConstantOperandVal(1);
12627       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12628         break;
12629       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12630                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12631                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12632       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12633         break;
12634       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12635                                 DAG.getConstant(Mask, VT));
12636       DAG.ReplaceAllUsesWith(Op, New);
12637       Op = New;
12638     }
12639     break;
12640
12641   case ISD::AND:
12642     // If the primary and result isn't used, don't bother using X86ISD::AND,
12643     // because a TEST instruction will be better.
12644     if (!hasNonFlagsUse(Op))
12645       break;
12646     // FALL THROUGH
12647   case ISD::SUB:
12648   case ISD::OR:
12649   case ISD::XOR:
12650     // Due to the ISEL shortcoming noted above, be conservative if this op is
12651     // likely to be selected as part of a load-modify-store instruction.
12652     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12653            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12654       if (UI->getOpcode() == ISD::STORE)
12655         goto default_case;
12656
12657     // Otherwise use a regular EFLAGS-setting instruction.
12658     switch (ArithOp.getOpcode()) {
12659     default: llvm_unreachable("unexpected operator!");
12660     case ISD::SUB: Opcode = X86ISD::SUB; break;
12661     case ISD::XOR: Opcode = X86ISD::XOR; break;
12662     case ISD::AND: Opcode = X86ISD::AND; break;
12663     case ISD::OR: {
12664       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12665         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12666         if (EFLAGS.getNode())
12667           return EFLAGS;
12668       }
12669       Opcode = X86ISD::OR;
12670       break;
12671     }
12672     }
12673
12674     NumOperands = 2;
12675     break;
12676   case X86ISD::ADD:
12677   case X86ISD::SUB:
12678   case X86ISD::INC:
12679   case X86ISD::DEC:
12680   case X86ISD::OR:
12681   case X86ISD::XOR:
12682   case X86ISD::AND:
12683     return SDValue(Op.getNode(), 1);
12684   default:
12685   default_case:
12686     break;
12687   }
12688
12689   // If we found that truncation is beneficial, perform the truncation and
12690   // update 'Op'.
12691   if (NeedTruncation) {
12692     EVT VT = Op.getValueType();
12693     SDValue WideVal = Op->getOperand(0);
12694     EVT WideVT = WideVal.getValueType();
12695     unsigned ConvertedOp = 0;
12696     // Use a target machine opcode to prevent further DAGCombine
12697     // optimizations that may separate the arithmetic operations
12698     // from the setcc node.
12699     switch (WideVal.getOpcode()) {
12700       default: break;
12701       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12702       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12703       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12704       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12705       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12706     }
12707
12708     if (ConvertedOp) {
12709       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12710       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12711         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12712         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12713         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12714       }
12715     }
12716   }
12717
12718   if (Opcode == 0)
12719     // Emit a CMP with 0, which is the TEST pattern.
12720     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12721                        DAG.getConstant(0, Op.getValueType()));
12722
12723   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12724   SmallVector<SDValue, 4> Ops;
12725   for (unsigned i = 0; i != NumOperands; ++i)
12726     Ops.push_back(Op.getOperand(i));
12727
12728   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12729   DAG.ReplaceAllUsesWith(Op, New);
12730   return SDValue(New.getNode(), 1);
12731 }
12732
12733 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12734 /// equivalent.
12735 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12736                                    SDLoc dl, SelectionDAG &DAG) const {
12737   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12738     if (C->getAPIntValue() == 0)
12739       return EmitTest(Op0, X86CC, dl, DAG);
12740
12741      if (Op0.getValueType() == MVT::i1)
12742        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12743   }
12744  
12745   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12746        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12747     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12748     // This avoids subregister aliasing issues. Keep the smaller reference 
12749     // if we're optimizing for size, however, as that'll allow better folding 
12750     // of memory operations.
12751     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12752         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12753              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12754         !Subtarget->isAtom()) {
12755       unsigned ExtendOp =
12756           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12757       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12758       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12759     }
12760     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12761     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12762     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12763                               Op0, Op1);
12764     return SDValue(Sub.getNode(), 1);
12765   }
12766   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12767 }
12768
12769 /// Convert a comparison if required by the subtarget.
12770 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12771                                                  SelectionDAG &DAG) const {
12772   // If the subtarget does not support the FUCOMI instruction, floating-point
12773   // comparisons have to be converted.
12774   if (Subtarget->hasCMov() ||
12775       Cmp.getOpcode() != X86ISD::CMP ||
12776       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12777       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12778     return Cmp;
12779
12780   // The instruction selector will select an FUCOM instruction instead of
12781   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12782   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12783   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12784   SDLoc dl(Cmp);
12785   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12786   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12787   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12788                             DAG.getConstant(8, MVT::i8));
12789   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12790   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12791 }
12792
12793 static bool isAllOnes(SDValue V) {
12794   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12795   return C && C->isAllOnesValue();
12796 }
12797
12798 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12799 /// if it's possible.
12800 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12801                                      SDLoc dl, SelectionDAG &DAG) const {
12802   SDValue Op0 = And.getOperand(0);
12803   SDValue Op1 = And.getOperand(1);
12804   if (Op0.getOpcode() == ISD::TRUNCATE)
12805     Op0 = Op0.getOperand(0);
12806   if (Op1.getOpcode() == ISD::TRUNCATE)
12807     Op1 = Op1.getOperand(0);
12808
12809   SDValue LHS, RHS;
12810   if (Op1.getOpcode() == ISD::SHL)
12811     std::swap(Op0, Op1);
12812   if (Op0.getOpcode() == ISD::SHL) {
12813     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12814       if (And00C->getZExtValue() == 1) {
12815         // If we looked past a truncate, check that it's only truncating away
12816         // known zeros.
12817         unsigned BitWidth = Op0.getValueSizeInBits();
12818         unsigned AndBitWidth = And.getValueSizeInBits();
12819         if (BitWidth > AndBitWidth) {
12820           APInt Zeros, Ones;
12821           DAG.computeKnownBits(Op0, Zeros, Ones);
12822           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12823             return SDValue();
12824         }
12825         LHS = Op1;
12826         RHS = Op0.getOperand(1);
12827       }
12828   } else if (Op1.getOpcode() == ISD::Constant) {
12829     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12830     uint64_t AndRHSVal = AndRHS->getZExtValue();
12831     SDValue AndLHS = Op0;
12832
12833     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12834       LHS = AndLHS.getOperand(0);
12835       RHS = AndLHS.getOperand(1);
12836     }
12837
12838     // Use BT if the immediate can't be encoded in a TEST instruction.
12839     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12840       LHS = AndLHS;
12841       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12842     }
12843   }
12844
12845   if (LHS.getNode()) {
12846     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12847     // instruction.  Since the shift amount is in-range-or-undefined, we know
12848     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12849     // the encoding for the i16 version is larger than the i32 version.
12850     // Also promote i16 to i32 for performance / code size reason.
12851     if (LHS.getValueType() == MVT::i8 ||
12852         LHS.getValueType() == MVT::i16)
12853       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12854
12855     // If the operand types disagree, extend the shift amount to match.  Since
12856     // BT ignores high bits (like shifts) we can use anyextend.
12857     if (LHS.getValueType() != RHS.getValueType())
12858       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12859
12860     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12861     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12862     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12863                        DAG.getConstant(Cond, MVT::i8), BT);
12864   }
12865
12866   return SDValue();
12867 }
12868
12869 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12870 /// mask CMPs.
12871 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12872                               SDValue &Op1) {
12873   unsigned SSECC;
12874   bool Swap = false;
12875
12876   // SSE Condition code mapping:
12877   //  0 - EQ
12878   //  1 - LT
12879   //  2 - LE
12880   //  3 - UNORD
12881   //  4 - NEQ
12882   //  5 - NLT
12883   //  6 - NLE
12884   //  7 - ORD
12885   switch (SetCCOpcode) {
12886   default: llvm_unreachable("Unexpected SETCC condition");
12887   case ISD::SETOEQ:
12888   case ISD::SETEQ:  SSECC = 0; break;
12889   case ISD::SETOGT:
12890   case ISD::SETGT:  Swap = true; // Fallthrough
12891   case ISD::SETLT:
12892   case ISD::SETOLT: SSECC = 1; break;
12893   case ISD::SETOGE:
12894   case ISD::SETGE:  Swap = true; // Fallthrough
12895   case ISD::SETLE:
12896   case ISD::SETOLE: SSECC = 2; break;
12897   case ISD::SETUO:  SSECC = 3; break;
12898   case ISD::SETUNE:
12899   case ISD::SETNE:  SSECC = 4; break;
12900   case ISD::SETULE: Swap = true; // Fallthrough
12901   case ISD::SETUGE: SSECC = 5; break;
12902   case ISD::SETULT: Swap = true; // Fallthrough
12903   case ISD::SETUGT: SSECC = 6; break;
12904   case ISD::SETO:   SSECC = 7; break;
12905   case ISD::SETUEQ:
12906   case ISD::SETONE: SSECC = 8; break;
12907   }
12908   if (Swap)
12909     std::swap(Op0, Op1);
12910
12911   return SSECC;
12912 }
12913
12914 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12915 // ones, and then concatenate the result back.
12916 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12917   MVT VT = Op.getSimpleValueType();
12918
12919   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12920          "Unsupported value type for operation");
12921
12922   unsigned NumElems = VT.getVectorNumElements();
12923   SDLoc dl(Op);
12924   SDValue CC = Op.getOperand(2);
12925
12926   // Extract the LHS vectors
12927   SDValue LHS = Op.getOperand(0);
12928   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12929   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12930
12931   // Extract the RHS vectors
12932   SDValue RHS = Op.getOperand(1);
12933   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12934   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12935
12936   // Issue the operation on the smaller types and concatenate the result back
12937   MVT EltVT = VT.getVectorElementType();
12938   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12939   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12940                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12941                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12942 }
12943
12944 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12945                                      const X86Subtarget *Subtarget) {
12946   SDValue Op0 = Op.getOperand(0);
12947   SDValue Op1 = Op.getOperand(1);
12948   SDValue CC = Op.getOperand(2);
12949   MVT VT = Op.getSimpleValueType();
12950   SDLoc dl(Op);
12951
12952   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12953          Op.getValueType().getScalarType() == MVT::i1 &&
12954          "Cannot set masked compare for this operation");
12955
12956   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12957   unsigned  Opc = 0;
12958   bool Unsigned = false;
12959   bool Swap = false;
12960   unsigned SSECC;
12961   switch (SetCCOpcode) {
12962   default: llvm_unreachable("Unexpected SETCC condition");
12963   case ISD::SETNE:  SSECC = 4; break;
12964   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12965   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12966   case ISD::SETLT:  Swap = true; //fall-through
12967   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12968   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12969   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12970   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12971   case ISD::SETULE: Unsigned = true; //fall-through
12972   case ISD::SETLE:  SSECC = 2; break;
12973   }
12974
12975   if (Swap)
12976     std::swap(Op0, Op1);
12977   if (Opc)
12978     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12979   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12980   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12981                      DAG.getConstant(SSECC, MVT::i8));
12982 }
12983
12984 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12985 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12986 /// return an empty value.
12987 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12988 {
12989   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12990   if (!BV)
12991     return SDValue();
12992
12993   MVT VT = Op1.getSimpleValueType();
12994   MVT EVT = VT.getVectorElementType();
12995   unsigned n = VT.getVectorNumElements();
12996   SmallVector<SDValue, 8> ULTOp1;
12997
12998   for (unsigned i = 0; i < n; ++i) {
12999     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13000     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13001       return SDValue();
13002
13003     // Avoid underflow.
13004     APInt Val = Elt->getAPIntValue();
13005     if (Val == 0)
13006       return SDValue();
13007
13008     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13009   }
13010
13011   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13012 }
13013
13014 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13015                            SelectionDAG &DAG) {
13016   SDValue Op0 = Op.getOperand(0);
13017   SDValue Op1 = Op.getOperand(1);
13018   SDValue CC = Op.getOperand(2);
13019   MVT VT = Op.getSimpleValueType();
13020   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13021   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13022   SDLoc dl(Op);
13023
13024   if (isFP) {
13025 #ifndef NDEBUG
13026     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13027     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13028 #endif
13029
13030     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13031     unsigned Opc = X86ISD::CMPP;
13032     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13033       assert(VT.getVectorNumElements() <= 16);
13034       Opc = X86ISD::CMPM;
13035     }
13036     // In the two special cases we can't handle, emit two comparisons.
13037     if (SSECC == 8) {
13038       unsigned CC0, CC1;
13039       unsigned CombineOpc;
13040       if (SetCCOpcode == ISD::SETUEQ) {
13041         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13042       } else {
13043         assert(SetCCOpcode == ISD::SETONE);
13044         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13045       }
13046
13047       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13048                                  DAG.getConstant(CC0, MVT::i8));
13049       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13050                                  DAG.getConstant(CC1, MVT::i8));
13051       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13052     }
13053     // Handle all other FP comparisons here.
13054     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13055                        DAG.getConstant(SSECC, MVT::i8));
13056   }
13057
13058   // Break 256-bit integer vector compare into smaller ones.
13059   if (VT.is256BitVector() && !Subtarget->hasInt256())
13060     return Lower256IntVSETCC(Op, DAG);
13061
13062   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13063   EVT OpVT = Op1.getValueType();
13064   if (Subtarget->hasAVX512()) {
13065     if (Op1.getValueType().is512BitVector() ||
13066         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13067         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13068       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13069
13070     // In AVX-512 architecture setcc returns mask with i1 elements,
13071     // But there is no compare instruction for i8 and i16 elements in KNL.
13072     // We are not talking about 512-bit operands in this case, these
13073     // types are illegal.
13074     if (MaskResult &&
13075         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13076          OpVT.getVectorElementType().getSizeInBits() >= 8))
13077       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13078                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13079   }
13080
13081   // We are handling one of the integer comparisons here.  Since SSE only has
13082   // GT and EQ comparisons for integer, swapping operands and multiple
13083   // operations may be required for some comparisons.
13084   unsigned Opc;
13085   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13086   bool Subus = false;
13087
13088   switch (SetCCOpcode) {
13089   default: llvm_unreachable("Unexpected SETCC condition");
13090   case ISD::SETNE:  Invert = true;
13091   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13092   case ISD::SETLT:  Swap = true;
13093   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13094   case ISD::SETGE:  Swap = true;
13095   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13096                     Invert = true; break;
13097   case ISD::SETULT: Swap = true;
13098   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13099                     FlipSigns = true; break;
13100   case ISD::SETUGE: Swap = true;
13101   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13102                     FlipSigns = true; Invert = true; break;
13103   }
13104
13105   // Special case: Use min/max operations for SETULE/SETUGE
13106   MVT VET = VT.getVectorElementType();
13107   bool hasMinMax =
13108        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13109     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13110
13111   if (hasMinMax) {
13112     switch (SetCCOpcode) {
13113     default: break;
13114     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13115     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13116     }
13117
13118     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13119   }
13120
13121   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13122   if (!MinMax && hasSubus) {
13123     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13124     // Op0 u<= Op1:
13125     //   t = psubus Op0, Op1
13126     //   pcmpeq t, <0..0>
13127     switch (SetCCOpcode) {
13128     default: break;
13129     case ISD::SETULT: {
13130       // If the comparison is against a constant we can turn this into a
13131       // setule.  With psubus, setule does not require a swap.  This is
13132       // beneficial because the constant in the register is no longer
13133       // destructed as the destination so it can be hoisted out of a loop.
13134       // Only do this pre-AVX since vpcmp* is no longer destructive.
13135       if (Subtarget->hasAVX())
13136         break;
13137       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13138       if (ULEOp1.getNode()) {
13139         Op1 = ULEOp1;
13140         Subus = true; Invert = false; Swap = false;
13141       }
13142       break;
13143     }
13144     // Psubus is better than flip-sign because it requires no inversion.
13145     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13146     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13147     }
13148
13149     if (Subus) {
13150       Opc = X86ISD::SUBUS;
13151       FlipSigns = false;
13152     }
13153   }
13154
13155   if (Swap)
13156     std::swap(Op0, Op1);
13157
13158   // Check that the operation in question is available (most are plain SSE2,
13159   // but PCMPGTQ and PCMPEQQ have different requirements).
13160   if (VT == MVT::v2i64) {
13161     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13162       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13163
13164       // First cast everything to the right type.
13165       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13166       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13167
13168       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13169       // bits of the inputs before performing those operations. The lower
13170       // compare is always unsigned.
13171       SDValue SB;
13172       if (FlipSigns) {
13173         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13174       } else {
13175         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13176         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13177         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13178                          Sign, Zero, Sign, Zero);
13179       }
13180       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13181       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13182
13183       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13184       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13185       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13186
13187       // Create masks for only the low parts/high parts of the 64 bit integers.
13188       static const int MaskHi[] = { 1, 1, 3, 3 };
13189       static const int MaskLo[] = { 0, 0, 2, 2 };
13190       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13191       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13192       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13193
13194       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13195       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13196
13197       if (Invert)
13198         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13199
13200       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13201     }
13202
13203     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13204       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13205       // pcmpeqd + pshufd + pand.
13206       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13207
13208       // First cast everything to the right type.
13209       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13210       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13211
13212       // Do the compare.
13213       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13214
13215       // Make sure the lower and upper halves are both all-ones.
13216       static const int Mask[] = { 1, 0, 3, 2 };
13217       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13218       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13219
13220       if (Invert)
13221         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13222
13223       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13224     }
13225   }
13226
13227   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13228   // bits of the inputs before performing those operations.
13229   if (FlipSigns) {
13230     EVT EltVT = VT.getVectorElementType();
13231     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13232     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13233     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13234   }
13235
13236   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13237
13238   // If the logical-not of the result is required, perform that now.
13239   if (Invert)
13240     Result = DAG.getNOT(dl, Result, VT);
13241
13242   if (MinMax)
13243     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13244
13245   if (Subus)
13246     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13247                          getZeroVector(VT, Subtarget, DAG, dl));
13248
13249   return Result;
13250 }
13251
13252 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13253
13254   MVT VT = Op.getSimpleValueType();
13255
13256   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13257
13258   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13259          && "SetCC type must be 8-bit or 1-bit integer");
13260   SDValue Op0 = Op.getOperand(0);
13261   SDValue Op1 = Op.getOperand(1);
13262   SDLoc dl(Op);
13263   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13264
13265   // Optimize to BT if possible.
13266   // Lower (X & (1 << N)) == 0 to BT(X, N).
13267   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13268   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13269   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13270       Op1.getOpcode() == ISD::Constant &&
13271       cast<ConstantSDNode>(Op1)->isNullValue() &&
13272       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13273     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13274     if (NewSetCC.getNode())
13275       return NewSetCC;
13276   }
13277
13278   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13279   // these.
13280   if (Op1.getOpcode() == ISD::Constant &&
13281       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13282        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13283       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13284
13285     // If the input is a setcc, then reuse the input setcc or use a new one with
13286     // the inverted condition.
13287     if (Op0.getOpcode() == X86ISD::SETCC) {
13288       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13289       bool Invert = (CC == ISD::SETNE) ^
13290         cast<ConstantSDNode>(Op1)->isNullValue();
13291       if (!Invert)
13292         return Op0;
13293
13294       CCode = X86::GetOppositeBranchCondition(CCode);
13295       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13296                                   DAG.getConstant(CCode, MVT::i8),
13297                                   Op0.getOperand(1));
13298       if (VT == MVT::i1)
13299         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13300       return SetCC;
13301     }
13302   }
13303   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13304       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13305       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13306
13307     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13308     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13309   }
13310
13311   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13312   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13313   if (X86CC == X86::COND_INVALID)
13314     return SDValue();
13315
13316   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13317   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13318   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13319                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13320   if (VT == MVT::i1)
13321     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13322   return SetCC;
13323 }
13324
13325 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13326 static bool isX86LogicalCmp(SDValue Op) {
13327   unsigned Opc = Op.getNode()->getOpcode();
13328   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13329       Opc == X86ISD::SAHF)
13330     return true;
13331   if (Op.getResNo() == 1 &&
13332       (Opc == X86ISD::ADD ||
13333        Opc == X86ISD::SUB ||
13334        Opc == X86ISD::ADC ||
13335        Opc == X86ISD::SBB ||
13336        Opc == X86ISD::SMUL ||
13337        Opc == X86ISD::UMUL ||
13338        Opc == X86ISD::INC ||
13339        Opc == X86ISD::DEC ||
13340        Opc == X86ISD::OR ||
13341        Opc == X86ISD::XOR ||
13342        Opc == X86ISD::AND))
13343     return true;
13344
13345   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13346     return true;
13347
13348   return false;
13349 }
13350
13351 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13352   if (V.getOpcode() != ISD::TRUNCATE)
13353     return false;
13354
13355   SDValue VOp0 = V.getOperand(0);
13356   unsigned InBits = VOp0.getValueSizeInBits();
13357   unsigned Bits = V.getValueSizeInBits();
13358   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13359 }
13360
13361 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13362   bool addTest = true;
13363   SDValue Cond  = Op.getOperand(0);
13364   SDValue Op1 = Op.getOperand(1);
13365   SDValue Op2 = Op.getOperand(2);
13366   SDLoc DL(Op);
13367   EVT VT = Op1.getValueType();
13368   SDValue CC;
13369
13370   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13371   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13372   // sequence later on.
13373   if (Cond.getOpcode() == ISD::SETCC &&
13374       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13375        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13376       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13377     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13378     int SSECC = translateX86FSETCC(
13379         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13380
13381     if (SSECC != 8) {
13382       if (Subtarget->hasAVX512()) {
13383         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13384                                   DAG.getConstant(SSECC, MVT::i8));
13385         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13386       }
13387       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13388                                 DAG.getConstant(SSECC, MVT::i8));
13389       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13390       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13391       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13392     }
13393   }
13394
13395   if (Cond.getOpcode() == ISD::SETCC) {
13396     SDValue NewCond = LowerSETCC(Cond, DAG);
13397     if (NewCond.getNode())
13398       Cond = NewCond;
13399   }
13400
13401   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13402   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13403   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13404   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13405   if (Cond.getOpcode() == X86ISD::SETCC &&
13406       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13407       isZero(Cond.getOperand(1).getOperand(1))) {
13408     SDValue Cmp = Cond.getOperand(1);
13409
13410     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13411
13412     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13413         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13414       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13415
13416       SDValue CmpOp0 = Cmp.getOperand(0);
13417       // Apply further optimizations for special cases
13418       // (select (x != 0), -1, 0) -> neg & sbb
13419       // (select (x == 0), 0, -1) -> neg & sbb
13420       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13421         if (YC->isNullValue() &&
13422             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13423           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13424           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13425                                     DAG.getConstant(0, CmpOp0.getValueType()),
13426                                     CmpOp0);
13427           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13428                                     DAG.getConstant(X86::COND_B, MVT::i8),
13429                                     SDValue(Neg.getNode(), 1));
13430           return Res;
13431         }
13432
13433       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13434                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13435       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13436
13437       SDValue Res =   // Res = 0 or -1.
13438         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13439                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13440
13441       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13442         Res = DAG.getNOT(DL, Res, Res.getValueType());
13443
13444       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13445       if (!N2C || !N2C->isNullValue())
13446         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13447       return Res;
13448     }
13449   }
13450
13451   // Look past (and (setcc_carry (cmp ...)), 1).
13452   if (Cond.getOpcode() == ISD::AND &&
13453       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13454     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13455     if (C && C->getAPIntValue() == 1)
13456       Cond = Cond.getOperand(0);
13457   }
13458
13459   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13460   // setting operand in place of the X86ISD::SETCC.
13461   unsigned CondOpcode = Cond.getOpcode();
13462   if (CondOpcode == X86ISD::SETCC ||
13463       CondOpcode == X86ISD::SETCC_CARRY) {
13464     CC = Cond.getOperand(0);
13465
13466     SDValue Cmp = Cond.getOperand(1);
13467     unsigned Opc = Cmp.getOpcode();
13468     MVT VT = Op.getSimpleValueType();
13469
13470     bool IllegalFPCMov = false;
13471     if (VT.isFloatingPoint() && !VT.isVector() &&
13472         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13473       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13474
13475     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13476         Opc == X86ISD::BT) { // FIXME
13477       Cond = Cmp;
13478       addTest = false;
13479     }
13480   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13481              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13482              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13483               Cond.getOperand(0).getValueType() != MVT::i8)) {
13484     SDValue LHS = Cond.getOperand(0);
13485     SDValue RHS = Cond.getOperand(1);
13486     unsigned X86Opcode;
13487     unsigned X86Cond;
13488     SDVTList VTs;
13489     switch (CondOpcode) {
13490     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13491     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13492     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13493     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13494     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13495     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13496     default: llvm_unreachable("unexpected overflowing operator");
13497     }
13498     if (CondOpcode == ISD::UMULO)
13499       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13500                           MVT::i32);
13501     else
13502       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13503
13504     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13505
13506     if (CondOpcode == ISD::UMULO)
13507       Cond = X86Op.getValue(2);
13508     else
13509       Cond = X86Op.getValue(1);
13510
13511     CC = DAG.getConstant(X86Cond, MVT::i8);
13512     addTest = false;
13513   }
13514
13515   if (addTest) {
13516     // Look pass the truncate if the high bits are known zero.
13517     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13518         Cond = Cond.getOperand(0);
13519
13520     // We know the result of AND is compared against zero. Try to match
13521     // it to BT.
13522     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13523       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13524       if (NewSetCC.getNode()) {
13525         CC = NewSetCC.getOperand(0);
13526         Cond = NewSetCC.getOperand(1);
13527         addTest = false;
13528       }
13529     }
13530   }
13531
13532   if (addTest) {
13533     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13534     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13535   }
13536
13537   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13538   // a <  b ?  0 : -1 -> RES = setcc_carry
13539   // a >= b ? -1 :  0 -> RES = setcc_carry
13540   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13541   if (Cond.getOpcode() == X86ISD::SUB) {
13542     Cond = ConvertCmpIfNecessary(Cond, DAG);
13543     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13544
13545     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13546         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13547       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13548                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13549       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13550         return DAG.getNOT(DL, Res, Res.getValueType());
13551       return Res;
13552     }
13553   }
13554
13555   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13556   // widen the cmov and push the truncate through. This avoids introducing a new
13557   // branch during isel and doesn't add any extensions.
13558   if (Op.getValueType() == MVT::i8 &&
13559       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13560     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13561     if (T1.getValueType() == T2.getValueType() &&
13562         // Blacklist CopyFromReg to avoid partial register stalls.
13563         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13564       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13565       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13566       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13567     }
13568   }
13569
13570   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13571   // condition is true.
13572   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13573   SDValue Ops[] = { Op2, Op1, CC, Cond };
13574   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13575 }
13576
13577 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13578   MVT VT = Op->getSimpleValueType(0);
13579   SDValue In = Op->getOperand(0);
13580   MVT InVT = In.getSimpleValueType();
13581   SDLoc dl(Op);
13582
13583   unsigned int NumElts = VT.getVectorNumElements();
13584   if (NumElts != 8 && NumElts != 16)
13585     return SDValue();
13586
13587   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13588     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13589
13590   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13591   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13592
13593   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13594   Constant *C = ConstantInt::get(*DAG.getContext(),
13595     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13596
13597   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13598   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13599   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13600                           MachinePointerInfo::getConstantPool(),
13601                           false, false, false, Alignment);
13602   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13603   if (VT.is512BitVector())
13604     return Brcst;
13605   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13606 }
13607
13608 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13609                                 SelectionDAG &DAG) {
13610   MVT VT = Op->getSimpleValueType(0);
13611   SDValue In = Op->getOperand(0);
13612   MVT InVT = In.getSimpleValueType();
13613   SDLoc dl(Op);
13614
13615   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13616     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13617
13618   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13619       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13620       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13621     return SDValue();
13622
13623   if (Subtarget->hasInt256())
13624     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13625
13626   // Optimize vectors in AVX mode
13627   // Sign extend  v8i16 to v8i32 and
13628   //              v4i32 to v4i64
13629   //
13630   // Divide input vector into two parts
13631   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13632   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13633   // concat the vectors to original VT
13634
13635   unsigned NumElems = InVT.getVectorNumElements();
13636   SDValue Undef = DAG.getUNDEF(InVT);
13637
13638   SmallVector<int,8> ShufMask1(NumElems, -1);
13639   for (unsigned i = 0; i != NumElems/2; ++i)
13640     ShufMask1[i] = i;
13641
13642   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13643
13644   SmallVector<int,8> ShufMask2(NumElems, -1);
13645   for (unsigned i = 0; i != NumElems/2; ++i)
13646     ShufMask2[i] = i + NumElems/2;
13647
13648   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13649
13650   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13651                                 VT.getVectorNumElements()/2);
13652
13653   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13654   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13655
13656   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13657 }
13658
13659 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13660 // may emit an illegal shuffle but the expansion is still better than scalar
13661 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13662 // we'll emit a shuffle and a arithmetic shift.
13663 // TODO: It is possible to support ZExt by zeroing the undef values during
13664 // the shuffle phase or after the shuffle.
13665 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13666                                  SelectionDAG &DAG) {
13667   MVT RegVT = Op.getSimpleValueType();
13668   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13669   assert(RegVT.isInteger() &&
13670          "We only custom lower integer vector sext loads.");
13671
13672   // Nothing useful we can do without SSE2 shuffles.
13673   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13674
13675   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13676   SDLoc dl(Ld);
13677   EVT MemVT = Ld->getMemoryVT();
13678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13679   unsigned RegSz = RegVT.getSizeInBits();
13680
13681   ISD::LoadExtType Ext = Ld->getExtensionType();
13682
13683   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13684          && "Only anyext and sext are currently implemented.");
13685   assert(MemVT != RegVT && "Cannot extend to the same type");
13686   assert(MemVT.isVector() && "Must load a vector from memory");
13687
13688   unsigned NumElems = RegVT.getVectorNumElements();
13689   unsigned MemSz = MemVT.getSizeInBits();
13690   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13691
13692   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13693     // The only way in which we have a legal 256-bit vector result but not the
13694     // integer 256-bit operations needed to directly lower a sextload is if we
13695     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13696     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13697     // correctly legalized. We do this late to allow the canonical form of
13698     // sextload to persist throughout the rest of the DAG combiner -- it wants
13699     // to fold together any extensions it can, and so will fuse a sign_extend
13700     // of an sextload into a sextload targeting a wider value.
13701     SDValue Load;
13702     if (MemSz == 128) {
13703       // Just switch this to a normal load.
13704       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13705                                        "it must be a legal 128-bit vector "
13706                                        "type!");
13707       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13708                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13709                   Ld->isInvariant(), Ld->getAlignment());
13710     } else {
13711       assert(MemSz < 128 &&
13712              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13713       // Do an sext load to a 128-bit vector type. We want to use the same
13714       // number of elements, but elements half as wide. This will end up being
13715       // recursively lowered by this routine, but will succeed as we definitely
13716       // have all the necessary features if we're using AVX1.
13717       EVT HalfEltVT =
13718           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13719       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13720       Load =
13721           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13722                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13723                          Ld->isNonTemporal(), Ld->isInvariant(),
13724                          Ld->getAlignment());
13725     }
13726
13727     // Replace chain users with the new chain.
13728     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13729     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13730
13731     // Finally, do a normal sign-extend to the desired register.
13732     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13733   }
13734
13735   // All sizes must be a power of two.
13736   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13737          "Non-power-of-two elements are not custom lowered!");
13738
13739   // Attempt to load the original value using scalar loads.
13740   // Find the largest scalar type that divides the total loaded size.
13741   MVT SclrLoadTy = MVT::i8;
13742   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13743        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13744     MVT Tp = (MVT::SimpleValueType)tp;
13745     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13746       SclrLoadTy = Tp;
13747     }
13748   }
13749
13750   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13751   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13752       (64 <= MemSz))
13753     SclrLoadTy = MVT::f64;
13754
13755   // Calculate the number of scalar loads that we need to perform
13756   // in order to load our vector from memory.
13757   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13758
13759   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13760          "Can only lower sext loads with a single scalar load!");
13761
13762   unsigned loadRegZize = RegSz;
13763   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13764     loadRegZize /= 2;
13765
13766   // Represent our vector as a sequence of elements which are the
13767   // largest scalar that we can load.
13768   EVT LoadUnitVecVT = EVT::getVectorVT(
13769       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13770
13771   // Represent the data using the same element type that is stored in
13772   // memory. In practice, we ''widen'' MemVT.
13773   EVT WideVecVT =
13774       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13775                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13776
13777   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13778          "Invalid vector type");
13779
13780   // We can't shuffle using an illegal type.
13781   assert(TLI.isTypeLegal(WideVecVT) &&
13782          "We only lower types that form legal widened vector types");
13783
13784   SmallVector<SDValue, 8> Chains;
13785   SDValue Ptr = Ld->getBasePtr();
13786   SDValue Increment =
13787       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13788   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13789
13790   for (unsigned i = 0; i < NumLoads; ++i) {
13791     // Perform a single load.
13792     SDValue ScalarLoad =
13793         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13794                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13795                     Ld->getAlignment());
13796     Chains.push_back(ScalarLoad.getValue(1));
13797     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13798     // another round of DAGCombining.
13799     if (i == 0)
13800       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13801     else
13802       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13803                         ScalarLoad, DAG.getIntPtrConstant(i));
13804
13805     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13806   }
13807
13808   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13809
13810   // Bitcast the loaded value to a vector of the original element type, in
13811   // the size of the target vector type.
13812   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13813   unsigned SizeRatio = RegSz / MemSz;
13814
13815   if (Ext == ISD::SEXTLOAD) {
13816     // If we have SSE4.1, we can directly emit a VSEXT node.
13817     if (Subtarget->hasSSE41()) {
13818       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13819       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13820       return Sext;
13821     }
13822
13823     // Otherwise we'll shuffle the small elements in the high bits of the
13824     // larger type and perform an arithmetic shift. If the shift is not legal
13825     // it's better to scalarize.
13826     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13827            "We can't implement a sext load without an arithmetic right shift!");
13828
13829     // Redistribute the loaded elements into the different locations.
13830     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13831     for (unsigned i = 0; i != NumElems; ++i)
13832       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13833
13834     SDValue Shuff = DAG.getVectorShuffle(
13835         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13836
13837     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13838
13839     // Build the arithmetic shift.
13840     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13841                    MemVT.getVectorElementType().getSizeInBits();
13842     Shuff =
13843         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13844
13845     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13846     return Shuff;
13847   }
13848
13849   // Redistribute the loaded elements into the different locations.
13850   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13851   for (unsigned i = 0; i != NumElems; ++i)
13852     ShuffleVec[i * SizeRatio] = i;
13853
13854   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13855                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13856
13857   // Bitcast to the requested type.
13858   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13859   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13860   return Shuff;
13861 }
13862
13863 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13864 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13865 // from the AND / OR.
13866 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13867   Opc = Op.getOpcode();
13868   if (Opc != ISD::OR && Opc != ISD::AND)
13869     return false;
13870   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13871           Op.getOperand(0).hasOneUse() &&
13872           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13873           Op.getOperand(1).hasOneUse());
13874 }
13875
13876 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13877 // 1 and that the SETCC node has a single use.
13878 static bool isXor1OfSetCC(SDValue Op) {
13879   if (Op.getOpcode() != ISD::XOR)
13880     return false;
13881   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13882   if (N1C && N1C->getAPIntValue() == 1) {
13883     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13884       Op.getOperand(0).hasOneUse();
13885   }
13886   return false;
13887 }
13888
13889 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13890   bool addTest = true;
13891   SDValue Chain = Op.getOperand(0);
13892   SDValue Cond  = Op.getOperand(1);
13893   SDValue Dest  = Op.getOperand(2);
13894   SDLoc dl(Op);
13895   SDValue CC;
13896   bool Inverted = false;
13897
13898   if (Cond.getOpcode() == ISD::SETCC) {
13899     // Check for setcc([su]{add,sub,mul}o == 0).
13900     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13901         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13902         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13903         Cond.getOperand(0).getResNo() == 1 &&
13904         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13905          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13906          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13907          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13908          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13909          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13910       Inverted = true;
13911       Cond = Cond.getOperand(0);
13912     } else {
13913       SDValue NewCond = LowerSETCC(Cond, DAG);
13914       if (NewCond.getNode())
13915         Cond = NewCond;
13916     }
13917   }
13918 #if 0
13919   // FIXME: LowerXALUO doesn't handle these!!
13920   else if (Cond.getOpcode() == X86ISD::ADD  ||
13921            Cond.getOpcode() == X86ISD::SUB  ||
13922            Cond.getOpcode() == X86ISD::SMUL ||
13923            Cond.getOpcode() == X86ISD::UMUL)
13924     Cond = LowerXALUO(Cond, DAG);
13925 #endif
13926
13927   // Look pass (and (setcc_carry (cmp ...)), 1).
13928   if (Cond.getOpcode() == ISD::AND &&
13929       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13930     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13931     if (C && C->getAPIntValue() == 1)
13932       Cond = Cond.getOperand(0);
13933   }
13934
13935   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13936   // setting operand in place of the X86ISD::SETCC.
13937   unsigned CondOpcode = Cond.getOpcode();
13938   if (CondOpcode == X86ISD::SETCC ||
13939       CondOpcode == X86ISD::SETCC_CARRY) {
13940     CC = Cond.getOperand(0);
13941
13942     SDValue Cmp = Cond.getOperand(1);
13943     unsigned Opc = Cmp.getOpcode();
13944     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13945     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13946       Cond = Cmp;
13947       addTest = false;
13948     } else {
13949       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13950       default: break;
13951       case X86::COND_O:
13952       case X86::COND_B:
13953         // These can only come from an arithmetic instruction with overflow,
13954         // e.g. SADDO, UADDO.
13955         Cond = Cond.getNode()->getOperand(1);
13956         addTest = false;
13957         break;
13958       }
13959     }
13960   }
13961   CondOpcode = Cond.getOpcode();
13962   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13963       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13964       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13965        Cond.getOperand(0).getValueType() != MVT::i8)) {
13966     SDValue LHS = Cond.getOperand(0);
13967     SDValue RHS = Cond.getOperand(1);
13968     unsigned X86Opcode;
13969     unsigned X86Cond;
13970     SDVTList VTs;
13971     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13972     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13973     // X86ISD::INC).
13974     switch (CondOpcode) {
13975     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13976     case ISD::SADDO:
13977       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13978         if (C->isOne()) {
13979           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13980           break;
13981         }
13982       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13983     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13984     case ISD::SSUBO:
13985       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13986         if (C->isOne()) {
13987           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13988           break;
13989         }
13990       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13991     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13992     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13993     default: llvm_unreachable("unexpected overflowing operator");
13994     }
13995     if (Inverted)
13996       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13997     if (CondOpcode == ISD::UMULO)
13998       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13999                           MVT::i32);
14000     else
14001       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14002
14003     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14004
14005     if (CondOpcode == ISD::UMULO)
14006       Cond = X86Op.getValue(2);
14007     else
14008       Cond = X86Op.getValue(1);
14009
14010     CC = DAG.getConstant(X86Cond, MVT::i8);
14011     addTest = false;
14012   } else {
14013     unsigned CondOpc;
14014     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14015       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14016       if (CondOpc == ISD::OR) {
14017         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14018         // two branches instead of an explicit OR instruction with a
14019         // separate test.
14020         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14021             isX86LogicalCmp(Cmp)) {
14022           CC = Cond.getOperand(0).getOperand(0);
14023           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14024                               Chain, Dest, CC, Cmp);
14025           CC = Cond.getOperand(1).getOperand(0);
14026           Cond = Cmp;
14027           addTest = false;
14028         }
14029       } else { // ISD::AND
14030         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14031         // two branches instead of an explicit AND instruction with a
14032         // separate test. However, we only do this if this block doesn't
14033         // have a fall-through edge, because this requires an explicit
14034         // jmp when the condition is false.
14035         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14036             isX86LogicalCmp(Cmp) &&
14037             Op.getNode()->hasOneUse()) {
14038           X86::CondCode CCode =
14039             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14040           CCode = X86::GetOppositeBranchCondition(CCode);
14041           CC = DAG.getConstant(CCode, MVT::i8);
14042           SDNode *User = *Op.getNode()->use_begin();
14043           // Look for an unconditional branch following this conditional branch.
14044           // We need this because we need to reverse the successors in order
14045           // to implement FCMP_OEQ.
14046           if (User->getOpcode() == ISD::BR) {
14047             SDValue FalseBB = User->getOperand(1);
14048             SDNode *NewBR =
14049               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14050             assert(NewBR == User);
14051             (void)NewBR;
14052             Dest = FalseBB;
14053
14054             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14055                                 Chain, Dest, CC, Cmp);
14056             X86::CondCode CCode =
14057               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14058             CCode = X86::GetOppositeBranchCondition(CCode);
14059             CC = DAG.getConstant(CCode, MVT::i8);
14060             Cond = Cmp;
14061             addTest = false;
14062           }
14063         }
14064       }
14065     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14066       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14067       // It should be transformed during dag combiner except when the condition
14068       // is set by a arithmetics with overflow node.
14069       X86::CondCode CCode =
14070         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14071       CCode = X86::GetOppositeBranchCondition(CCode);
14072       CC = DAG.getConstant(CCode, MVT::i8);
14073       Cond = Cond.getOperand(0).getOperand(1);
14074       addTest = false;
14075     } else if (Cond.getOpcode() == ISD::SETCC &&
14076                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14077       // For FCMP_OEQ, we can emit
14078       // two branches instead of an explicit AND instruction with a
14079       // separate test. However, we only do this if this block doesn't
14080       // have a fall-through edge, because this requires an explicit
14081       // jmp when the condition is false.
14082       if (Op.getNode()->hasOneUse()) {
14083         SDNode *User = *Op.getNode()->use_begin();
14084         // Look for an unconditional branch following this conditional branch.
14085         // We need this because we need to reverse the successors in order
14086         // to implement FCMP_OEQ.
14087         if (User->getOpcode() == ISD::BR) {
14088           SDValue FalseBB = User->getOperand(1);
14089           SDNode *NewBR =
14090             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14091           assert(NewBR == User);
14092           (void)NewBR;
14093           Dest = FalseBB;
14094
14095           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14096                                     Cond.getOperand(0), Cond.getOperand(1));
14097           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14098           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14099           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14100                               Chain, Dest, CC, Cmp);
14101           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14102           Cond = Cmp;
14103           addTest = false;
14104         }
14105       }
14106     } else if (Cond.getOpcode() == ISD::SETCC &&
14107                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14108       // For FCMP_UNE, we can emit
14109       // two branches instead of an explicit AND instruction with a
14110       // separate test. However, we only do this if this block doesn't
14111       // have a fall-through edge, because this requires an explicit
14112       // jmp when the condition is false.
14113       if (Op.getNode()->hasOneUse()) {
14114         SDNode *User = *Op.getNode()->use_begin();
14115         // Look for an unconditional branch following this conditional branch.
14116         // We need this because we need to reverse the successors in order
14117         // to implement FCMP_UNE.
14118         if (User->getOpcode() == ISD::BR) {
14119           SDValue FalseBB = User->getOperand(1);
14120           SDNode *NewBR =
14121             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14122           assert(NewBR == User);
14123           (void)NewBR;
14124
14125           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14126                                     Cond.getOperand(0), Cond.getOperand(1));
14127           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14128           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14129           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14130                               Chain, Dest, CC, Cmp);
14131           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14132           Cond = Cmp;
14133           addTest = false;
14134           Dest = FalseBB;
14135         }
14136       }
14137     }
14138   }
14139
14140   if (addTest) {
14141     // Look pass the truncate if the high bits are known zero.
14142     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14143         Cond = Cond.getOperand(0);
14144
14145     // We know the result of AND is compared against zero. Try to match
14146     // it to BT.
14147     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14148       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14149       if (NewSetCC.getNode()) {
14150         CC = NewSetCC.getOperand(0);
14151         Cond = NewSetCC.getOperand(1);
14152         addTest = false;
14153       }
14154     }
14155   }
14156
14157   if (addTest) {
14158     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14159     CC = DAG.getConstant(X86Cond, MVT::i8);
14160     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14161   }
14162   Cond = ConvertCmpIfNecessary(Cond, DAG);
14163   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14164                      Chain, Dest, CC, Cond);
14165 }
14166
14167 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14168 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14169 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14170 // that the guard pages used by the OS virtual memory manager are allocated in
14171 // correct sequence.
14172 SDValue
14173 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14174                                            SelectionDAG &DAG) const {
14175   MachineFunction &MF = DAG.getMachineFunction();
14176   bool SplitStack = MF.shouldSplitStack();
14177   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14178                SplitStack;
14179   SDLoc dl(Op);
14180
14181   if (!Lower) {
14182     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14183     SDNode* Node = Op.getNode();
14184
14185     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14186     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14187         " not tell us which reg is the stack pointer!");
14188     EVT VT = Node->getValueType(0);
14189     SDValue Tmp1 = SDValue(Node, 0);
14190     SDValue Tmp2 = SDValue(Node, 1);
14191     SDValue Tmp3 = Node->getOperand(2);
14192     SDValue Chain = Tmp1.getOperand(0);
14193
14194     // Chain the dynamic stack allocation so that it doesn't modify the stack
14195     // pointer when other instructions are using the stack.
14196     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14197         SDLoc(Node));
14198
14199     SDValue Size = Tmp2.getOperand(1);
14200     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14201     Chain = SP.getValue(1);
14202     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14203     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14204     unsigned StackAlign = TFI.getStackAlignment();
14205     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14206     if (Align > StackAlign)
14207       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14208           DAG.getConstant(-(uint64_t)Align, VT));
14209     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14210
14211     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14212         DAG.getIntPtrConstant(0, true), SDValue(),
14213         SDLoc(Node));
14214
14215     SDValue Ops[2] = { Tmp1, Tmp2 };
14216     return DAG.getMergeValues(Ops, dl);
14217   }
14218
14219   // Get the inputs.
14220   SDValue Chain = Op.getOperand(0);
14221   SDValue Size  = Op.getOperand(1);
14222   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14223   EVT VT = Op.getNode()->getValueType(0);
14224
14225   bool Is64Bit = Subtarget->is64Bit();
14226   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14227
14228   if (SplitStack) {
14229     MachineRegisterInfo &MRI = MF.getRegInfo();
14230
14231     if (Is64Bit) {
14232       // The 64 bit implementation of segmented stacks needs to clobber both r10
14233       // r11. This makes it impossible to use it along with nested parameters.
14234       const Function *F = MF.getFunction();
14235
14236       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14237            I != E; ++I)
14238         if (I->hasNestAttr())
14239           report_fatal_error("Cannot use segmented stacks with functions that "
14240                              "have nested arguments.");
14241     }
14242
14243     const TargetRegisterClass *AddrRegClass =
14244       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14245     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14246     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14247     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14248                                 DAG.getRegister(Vreg, SPTy));
14249     SDValue Ops1[2] = { Value, Chain };
14250     return DAG.getMergeValues(Ops1, dl);
14251   } else {
14252     SDValue Flag;
14253     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14254
14255     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14256     Flag = Chain.getValue(1);
14257     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14258
14259     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14260
14261     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14262         DAG.getSubtarget().getRegisterInfo());
14263     unsigned SPReg = RegInfo->getStackRegister();
14264     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14265     Chain = SP.getValue(1);
14266
14267     if (Align) {
14268       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14269                        DAG.getConstant(-(uint64_t)Align, VT));
14270       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14271     }
14272
14273     SDValue Ops1[2] = { SP, Chain };
14274     return DAG.getMergeValues(Ops1, dl);
14275   }
14276 }
14277
14278 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14279   MachineFunction &MF = DAG.getMachineFunction();
14280   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14281
14282   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14283   SDLoc DL(Op);
14284
14285   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14286     // vastart just stores the address of the VarArgsFrameIndex slot into the
14287     // memory location argument.
14288     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14289                                    getPointerTy());
14290     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14291                         MachinePointerInfo(SV), false, false, 0);
14292   }
14293
14294   // __va_list_tag:
14295   //   gp_offset         (0 - 6 * 8)
14296   //   fp_offset         (48 - 48 + 8 * 16)
14297   //   overflow_arg_area (point to parameters coming in memory).
14298   //   reg_save_area
14299   SmallVector<SDValue, 8> MemOps;
14300   SDValue FIN = Op.getOperand(1);
14301   // Store gp_offset
14302   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14303                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14304                                                MVT::i32),
14305                                FIN, MachinePointerInfo(SV), false, false, 0);
14306   MemOps.push_back(Store);
14307
14308   // Store fp_offset
14309   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14310                     FIN, DAG.getIntPtrConstant(4));
14311   Store = DAG.getStore(Op.getOperand(0), DL,
14312                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14313                                        MVT::i32),
14314                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14315   MemOps.push_back(Store);
14316
14317   // Store ptr to overflow_arg_area
14318   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14319                     FIN, DAG.getIntPtrConstant(4));
14320   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14321                                     getPointerTy());
14322   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14323                        MachinePointerInfo(SV, 8),
14324                        false, false, 0);
14325   MemOps.push_back(Store);
14326
14327   // Store ptr to reg_save_area.
14328   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14329                     FIN, DAG.getIntPtrConstant(8));
14330   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14331                                     getPointerTy());
14332   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14333                        MachinePointerInfo(SV, 16), false, false, 0);
14334   MemOps.push_back(Store);
14335   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14336 }
14337
14338 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14339   assert(Subtarget->is64Bit() &&
14340          "LowerVAARG only handles 64-bit va_arg!");
14341   assert((Subtarget->isTargetLinux() ||
14342           Subtarget->isTargetDarwin()) &&
14343           "Unhandled target in LowerVAARG");
14344   assert(Op.getNode()->getNumOperands() == 4);
14345   SDValue Chain = Op.getOperand(0);
14346   SDValue SrcPtr = Op.getOperand(1);
14347   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14348   unsigned Align = Op.getConstantOperandVal(3);
14349   SDLoc dl(Op);
14350
14351   EVT ArgVT = Op.getNode()->getValueType(0);
14352   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14353   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14354   uint8_t ArgMode;
14355
14356   // Decide which area this value should be read from.
14357   // TODO: Implement the AMD64 ABI in its entirety. This simple
14358   // selection mechanism works only for the basic types.
14359   if (ArgVT == MVT::f80) {
14360     llvm_unreachable("va_arg for f80 not yet implemented");
14361   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14362     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14363   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14364     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14365   } else {
14366     llvm_unreachable("Unhandled argument type in LowerVAARG");
14367   }
14368
14369   if (ArgMode == 2) {
14370     // Sanity Check: Make sure using fp_offset makes sense.
14371     assert(!DAG.getTarget().Options.UseSoftFloat &&
14372            !(DAG.getMachineFunction()
14373                 .getFunction()->getAttributes()
14374                 .hasAttribute(AttributeSet::FunctionIndex,
14375                               Attribute::NoImplicitFloat)) &&
14376            Subtarget->hasSSE1());
14377   }
14378
14379   // Insert VAARG_64 node into the DAG
14380   // VAARG_64 returns two values: Variable Argument Address, Chain
14381   SmallVector<SDValue, 11> InstOps;
14382   InstOps.push_back(Chain);
14383   InstOps.push_back(SrcPtr);
14384   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14385   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14386   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14387   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14388   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14389                                           VTs, InstOps, MVT::i64,
14390                                           MachinePointerInfo(SV),
14391                                           /*Align=*/0,
14392                                           /*Volatile=*/false,
14393                                           /*ReadMem=*/true,
14394                                           /*WriteMem=*/true);
14395   Chain = VAARG.getValue(1);
14396
14397   // Load the next argument and return it
14398   return DAG.getLoad(ArgVT, dl,
14399                      Chain,
14400                      VAARG,
14401                      MachinePointerInfo(),
14402                      false, false, false, 0);
14403 }
14404
14405 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14406                            SelectionDAG &DAG) {
14407   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14408   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14409   SDValue Chain = Op.getOperand(0);
14410   SDValue DstPtr = Op.getOperand(1);
14411   SDValue SrcPtr = Op.getOperand(2);
14412   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14413   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14414   SDLoc DL(Op);
14415
14416   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14417                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14418                        false,
14419                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14420 }
14421
14422 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14423 // amount is a constant. Takes immediate version of shift as input.
14424 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14425                                           SDValue SrcOp, uint64_t ShiftAmt,
14426                                           SelectionDAG &DAG) {
14427   MVT ElementType = VT.getVectorElementType();
14428
14429   // Fold this packed shift into its first operand if ShiftAmt is 0.
14430   if (ShiftAmt == 0)
14431     return SrcOp;
14432
14433   // Check for ShiftAmt >= element width
14434   if (ShiftAmt >= ElementType.getSizeInBits()) {
14435     if (Opc == X86ISD::VSRAI)
14436       ShiftAmt = ElementType.getSizeInBits() - 1;
14437     else
14438       return DAG.getConstant(0, VT);
14439   }
14440
14441   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14442          && "Unknown target vector shift-by-constant node");
14443
14444   // Fold this packed vector shift into a build vector if SrcOp is a
14445   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14446   if (VT == SrcOp.getSimpleValueType() &&
14447       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14448     SmallVector<SDValue, 8> Elts;
14449     unsigned NumElts = SrcOp->getNumOperands();
14450     ConstantSDNode *ND;
14451
14452     switch(Opc) {
14453     default: llvm_unreachable(nullptr);
14454     case X86ISD::VSHLI:
14455       for (unsigned i=0; i!=NumElts; ++i) {
14456         SDValue CurrentOp = SrcOp->getOperand(i);
14457         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14458           Elts.push_back(CurrentOp);
14459           continue;
14460         }
14461         ND = cast<ConstantSDNode>(CurrentOp);
14462         const APInt &C = ND->getAPIntValue();
14463         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14464       }
14465       break;
14466     case X86ISD::VSRLI:
14467       for (unsigned i=0; i!=NumElts; ++i) {
14468         SDValue CurrentOp = SrcOp->getOperand(i);
14469         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14470           Elts.push_back(CurrentOp);
14471           continue;
14472         }
14473         ND = cast<ConstantSDNode>(CurrentOp);
14474         const APInt &C = ND->getAPIntValue();
14475         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14476       }
14477       break;
14478     case X86ISD::VSRAI:
14479       for (unsigned i=0; i!=NumElts; ++i) {
14480         SDValue CurrentOp = SrcOp->getOperand(i);
14481         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14482           Elts.push_back(CurrentOp);
14483           continue;
14484         }
14485         ND = cast<ConstantSDNode>(CurrentOp);
14486         const APInt &C = ND->getAPIntValue();
14487         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14488       }
14489       break;
14490     }
14491
14492     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14493   }
14494
14495   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14496 }
14497
14498 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14499 // may or may not be a constant. Takes immediate version of shift as input.
14500 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14501                                    SDValue SrcOp, SDValue ShAmt,
14502                                    SelectionDAG &DAG) {
14503   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14504
14505   // Catch shift-by-constant.
14506   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14507     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14508                                       CShAmt->getZExtValue(), DAG);
14509
14510   // Change opcode to non-immediate version
14511   switch (Opc) {
14512     default: llvm_unreachable("Unknown target vector shift node");
14513     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14514     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14515     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14516   }
14517
14518   // Need to build a vector containing shift amount
14519   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14520   SDValue ShOps[4];
14521   ShOps[0] = ShAmt;
14522   ShOps[1] = DAG.getConstant(0, MVT::i32);
14523   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14524   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14525
14526   // The return type has to be a 128-bit type with the same element
14527   // type as the input type.
14528   MVT EltVT = VT.getVectorElementType();
14529   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14530
14531   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14532   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14533 }
14534
14535 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14536 /// necessary casting for \p Mask when lowering masking intrinsics.
14537 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14538                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14539     EVT VT = Op.getValueType();
14540     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14541                                   MVT::i1, VT.getVectorNumElements());
14542     SDLoc dl(Op);
14543
14544     assert(MaskVT.isSimple() && "invalid mask type");
14545     return DAG.getNode(ISD::VSELECT, dl, VT,
14546                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14547                        Op, PreservedSrc);
14548 }
14549
14550 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14551     switch (IntNo) {
14552     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14553     case Intrinsic::x86_fma_vfmadd_ps:
14554     case Intrinsic::x86_fma_vfmadd_pd:
14555     case Intrinsic::x86_fma_vfmadd_ps_256:
14556     case Intrinsic::x86_fma_vfmadd_pd_256:
14557     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14558     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14559       return X86ISD::FMADD;
14560     case Intrinsic::x86_fma_vfmsub_ps:
14561     case Intrinsic::x86_fma_vfmsub_pd:
14562     case Intrinsic::x86_fma_vfmsub_ps_256:
14563     case Intrinsic::x86_fma_vfmsub_pd_256:
14564     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14565     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14566       return X86ISD::FMSUB;
14567     case Intrinsic::x86_fma_vfnmadd_ps:
14568     case Intrinsic::x86_fma_vfnmadd_pd:
14569     case Intrinsic::x86_fma_vfnmadd_ps_256:
14570     case Intrinsic::x86_fma_vfnmadd_pd_256:
14571     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14572     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14573       return X86ISD::FNMADD;
14574     case Intrinsic::x86_fma_vfnmsub_ps:
14575     case Intrinsic::x86_fma_vfnmsub_pd:
14576     case Intrinsic::x86_fma_vfnmsub_ps_256:
14577     case Intrinsic::x86_fma_vfnmsub_pd_256:
14578     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14579     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14580       return X86ISD::FNMSUB;
14581     case Intrinsic::x86_fma_vfmaddsub_ps:
14582     case Intrinsic::x86_fma_vfmaddsub_pd:
14583     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14584     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14585     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14586     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14587       return X86ISD::FMADDSUB;
14588     case Intrinsic::x86_fma_vfmsubadd_ps:
14589     case Intrinsic::x86_fma_vfmsubadd_pd:
14590     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14591     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14592     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14593     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14594       return X86ISD::FMSUBADD;
14595     }
14596 }
14597
14598 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14599   SDLoc dl(Op);
14600   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14601
14602   const IntrinsicData* IntrData = GetIntrinsicWithoutChain(IntNo);
14603   if (IntrData) {
14604     switch(IntrData->Type) {
14605     case INTR_TYPE_1OP:
14606       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14607     case INTR_TYPE_2OP:
14608       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14609         Op.getOperand(2));
14610     case INTR_TYPE_3OP:
14611       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14612         Op.getOperand(2), Op.getOperand(3));
14613     case COMI: { // Comparison intrinsics
14614       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14615       SDValue LHS = Op.getOperand(1);
14616       SDValue RHS = Op.getOperand(2);
14617       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14618       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14619       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14620       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14621                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14622       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14623     }
14624     case VSHIFT:
14625       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14626                                  Op.getOperand(1), Op.getOperand(2), DAG);
14627     default:
14628       break;
14629     }
14630   }
14631
14632   switch (IntNo) {
14633   default: return SDValue();    // Don't custom lower most intrinsics.
14634
14635   // Arithmetic intrinsics.
14636   case Intrinsic::x86_sse2_pmulu_dq:
14637   case Intrinsic::x86_avx2_pmulu_dq:
14638     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14639                        Op.getOperand(1), Op.getOperand(2));
14640
14641   case Intrinsic::x86_sse41_pmuldq:
14642   case Intrinsic::x86_avx2_pmul_dq:
14643     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14644                        Op.getOperand(1), Op.getOperand(2));
14645
14646   case Intrinsic::x86_sse2_pmulhu_w:
14647   case Intrinsic::x86_avx2_pmulhu_w:
14648     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14649                        Op.getOperand(1), Op.getOperand(2));
14650
14651   case Intrinsic::x86_sse2_pmulh_w:
14652   case Intrinsic::x86_avx2_pmulh_w:
14653     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14654                        Op.getOperand(1), Op.getOperand(2));
14655
14656   // SSE/SSE2/AVX floating point max/min intrinsics.
14657   case Intrinsic::x86_sse_max_ps:
14658   case Intrinsic::x86_sse2_max_pd:
14659   case Intrinsic::x86_avx_max_ps_256:
14660   case Intrinsic::x86_avx_max_pd_256:
14661   case Intrinsic::x86_sse_min_ps:
14662   case Intrinsic::x86_sse2_min_pd:
14663   case Intrinsic::x86_avx_min_ps_256:
14664   case Intrinsic::x86_avx_min_pd_256: {
14665     unsigned Opcode;
14666     switch (IntNo) {
14667     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14668     case Intrinsic::x86_sse_max_ps:
14669     case Intrinsic::x86_sse2_max_pd:
14670     case Intrinsic::x86_avx_max_ps_256:
14671     case Intrinsic::x86_avx_max_pd_256:
14672       Opcode = X86ISD::FMAX;
14673       break;
14674     case Intrinsic::x86_sse_min_ps:
14675     case Intrinsic::x86_sse2_min_pd:
14676     case Intrinsic::x86_avx_min_ps_256:
14677     case Intrinsic::x86_avx_min_pd_256:
14678       Opcode = X86ISD::FMIN;
14679       break;
14680     }
14681     return DAG.getNode(Opcode, dl, Op.getValueType(),
14682                        Op.getOperand(1), Op.getOperand(2));
14683   }
14684
14685   // AVX2 variable shift intrinsics
14686   case Intrinsic::x86_avx2_psllv_d:
14687   case Intrinsic::x86_avx2_psllv_q:
14688   case Intrinsic::x86_avx2_psllv_d_256:
14689   case Intrinsic::x86_avx2_psllv_q_256:
14690   case Intrinsic::x86_avx2_psrlv_d:
14691   case Intrinsic::x86_avx2_psrlv_q:
14692   case Intrinsic::x86_avx2_psrlv_d_256:
14693   case Intrinsic::x86_avx2_psrlv_q_256:
14694   case Intrinsic::x86_avx2_psrav_d:
14695   case Intrinsic::x86_avx2_psrav_d_256: {
14696     unsigned Opcode;
14697     switch (IntNo) {
14698     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14699     case Intrinsic::x86_avx2_psllv_d:
14700     case Intrinsic::x86_avx2_psllv_q:
14701     case Intrinsic::x86_avx2_psllv_d_256:
14702     case Intrinsic::x86_avx2_psllv_q_256:
14703       Opcode = ISD::SHL;
14704       break;
14705     case Intrinsic::x86_avx2_psrlv_d:
14706     case Intrinsic::x86_avx2_psrlv_q:
14707     case Intrinsic::x86_avx2_psrlv_d_256:
14708     case Intrinsic::x86_avx2_psrlv_q_256:
14709       Opcode = ISD::SRL;
14710       break;
14711     case Intrinsic::x86_avx2_psrav_d:
14712     case Intrinsic::x86_avx2_psrav_d_256:
14713       Opcode = ISD::SRA;
14714       break;
14715     }
14716     return DAG.getNode(Opcode, dl, Op.getValueType(),
14717                        Op.getOperand(1), Op.getOperand(2));
14718   }
14719
14720   case Intrinsic::x86_sse2_packssdw_128:
14721   case Intrinsic::x86_sse2_packsswb_128:
14722   case Intrinsic::x86_avx2_packssdw:
14723   case Intrinsic::x86_avx2_packsswb:
14724     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14725                        Op.getOperand(1), Op.getOperand(2));
14726
14727   case Intrinsic::x86_sse2_packuswb_128:
14728   case Intrinsic::x86_sse41_packusdw:
14729   case Intrinsic::x86_avx2_packuswb:
14730   case Intrinsic::x86_avx2_packusdw:
14731     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14732                        Op.getOperand(1), Op.getOperand(2));
14733
14734   case Intrinsic::x86_ssse3_pshuf_b_128:
14735   case Intrinsic::x86_avx2_pshuf_b:
14736     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14737                        Op.getOperand(1), Op.getOperand(2));
14738
14739   case Intrinsic::x86_sse2_pshuf_d:
14740     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14741                        Op.getOperand(1), Op.getOperand(2));
14742
14743   case Intrinsic::x86_sse2_pshufl_w:
14744     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14745                        Op.getOperand(1), Op.getOperand(2));
14746
14747   case Intrinsic::x86_sse2_pshufh_w:
14748     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14749                        Op.getOperand(1), Op.getOperand(2));
14750
14751   case Intrinsic::x86_ssse3_psign_b_128:
14752   case Intrinsic::x86_ssse3_psign_w_128:
14753   case Intrinsic::x86_ssse3_psign_d_128:
14754   case Intrinsic::x86_avx2_psign_b:
14755   case Intrinsic::x86_avx2_psign_w:
14756   case Intrinsic::x86_avx2_psign_d:
14757     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14758                        Op.getOperand(1), Op.getOperand(2));
14759
14760   case Intrinsic::x86_avx2_permd:
14761   case Intrinsic::x86_avx2_permps:
14762     // Operands intentionally swapped. Mask is last operand to intrinsic,
14763     // but second operand for node/instruction.
14764     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14765                        Op.getOperand(2), Op.getOperand(1));
14766
14767   case Intrinsic::x86_avx512_mask_valign_q_512:
14768   case Intrinsic::x86_avx512_mask_valign_d_512:
14769     // Vector source operands are swapped.
14770     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14771                                             Op.getValueType(), Op.getOperand(2),
14772                                             Op.getOperand(1),
14773                                             Op.getOperand(3)),
14774                                 Op.getOperand(5), Op.getOperand(4), DAG);
14775
14776   // ptest and testp intrinsics. The intrinsic these come from are designed to
14777   // return an integer value, not just an instruction so lower it to the ptest
14778   // or testp pattern and a setcc for the result.
14779   case Intrinsic::x86_sse41_ptestz:
14780   case Intrinsic::x86_sse41_ptestc:
14781   case Intrinsic::x86_sse41_ptestnzc:
14782   case Intrinsic::x86_avx_ptestz_256:
14783   case Intrinsic::x86_avx_ptestc_256:
14784   case Intrinsic::x86_avx_ptestnzc_256:
14785   case Intrinsic::x86_avx_vtestz_ps:
14786   case Intrinsic::x86_avx_vtestc_ps:
14787   case Intrinsic::x86_avx_vtestnzc_ps:
14788   case Intrinsic::x86_avx_vtestz_pd:
14789   case Intrinsic::x86_avx_vtestc_pd:
14790   case Intrinsic::x86_avx_vtestnzc_pd:
14791   case Intrinsic::x86_avx_vtestz_ps_256:
14792   case Intrinsic::x86_avx_vtestc_ps_256:
14793   case Intrinsic::x86_avx_vtestnzc_ps_256:
14794   case Intrinsic::x86_avx_vtestz_pd_256:
14795   case Intrinsic::x86_avx_vtestc_pd_256:
14796   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14797     bool IsTestPacked = false;
14798     unsigned X86CC;
14799     switch (IntNo) {
14800     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14801     case Intrinsic::x86_avx_vtestz_ps:
14802     case Intrinsic::x86_avx_vtestz_pd:
14803     case Intrinsic::x86_avx_vtestz_ps_256:
14804     case Intrinsic::x86_avx_vtestz_pd_256:
14805       IsTestPacked = true; // Fallthrough
14806     case Intrinsic::x86_sse41_ptestz:
14807     case Intrinsic::x86_avx_ptestz_256:
14808       // ZF = 1
14809       X86CC = X86::COND_E;
14810       break;
14811     case Intrinsic::x86_avx_vtestc_ps:
14812     case Intrinsic::x86_avx_vtestc_pd:
14813     case Intrinsic::x86_avx_vtestc_ps_256:
14814     case Intrinsic::x86_avx_vtestc_pd_256:
14815       IsTestPacked = true; // Fallthrough
14816     case Intrinsic::x86_sse41_ptestc:
14817     case Intrinsic::x86_avx_ptestc_256:
14818       // CF = 1
14819       X86CC = X86::COND_B;
14820       break;
14821     case Intrinsic::x86_avx_vtestnzc_ps:
14822     case Intrinsic::x86_avx_vtestnzc_pd:
14823     case Intrinsic::x86_avx_vtestnzc_ps_256:
14824     case Intrinsic::x86_avx_vtestnzc_pd_256:
14825       IsTestPacked = true; // Fallthrough
14826     case Intrinsic::x86_sse41_ptestnzc:
14827     case Intrinsic::x86_avx_ptestnzc_256:
14828       // ZF and CF = 0
14829       X86CC = X86::COND_A;
14830       break;
14831     }
14832
14833     SDValue LHS = Op.getOperand(1);
14834     SDValue RHS = Op.getOperand(2);
14835     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14836     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14837     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14838     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14839     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14840   }
14841   case Intrinsic::x86_avx512_kortestz_w:
14842   case Intrinsic::x86_avx512_kortestc_w: {
14843     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14844     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14845     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14846     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14847     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14848     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14849     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14850   }
14851
14852   case Intrinsic::x86_sse42_pcmpistria128:
14853   case Intrinsic::x86_sse42_pcmpestria128:
14854   case Intrinsic::x86_sse42_pcmpistric128:
14855   case Intrinsic::x86_sse42_pcmpestric128:
14856   case Intrinsic::x86_sse42_pcmpistrio128:
14857   case Intrinsic::x86_sse42_pcmpestrio128:
14858   case Intrinsic::x86_sse42_pcmpistris128:
14859   case Intrinsic::x86_sse42_pcmpestris128:
14860   case Intrinsic::x86_sse42_pcmpistriz128:
14861   case Intrinsic::x86_sse42_pcmpestriz128: {
14862     unsigned Opcode;
14863     unsigned X86CC;
14864     switch (IntNo) {
14865     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14866     case Intrinsic::x86_sse42_pcmpistria128:
14867       Opcode = X86ISD::PCMPISTRI;
14868       X86CC = X86::COND_A;
14869       break;
14870     case Intrinsic::x86_sse42_pcmpestria128:
14871       Opcode = X86ISD::PCMPESTRI;
14872       X86CC = X86::COND_A;
14873       break;
14874     case Intrinsic::x86_sse42_pcmpistric128:
14875       Opcode = X86ISD::PCMPISTRI;
14876       X86CC = X86::COND_B;
14877       break;
14878     case Intrinsic::x86_sse42_pcmpestric128:
14879       Opcode = X86ISD::PCMPESTRI;
14880       X86CC = X86::COND_B;
14881       break;
14882     case Intrinsic::x86_sse42_pcmpistrio128:
14883       Opcode = X86ISD::PCMPISTRI;
14884       X86CC = X86::COND_O;
14885       break;
14886     case Intrinsic::x86_sse42_pcmpestrio128:
14887       Opcode = X86ISD::PCMPESTRI;
14888       X86CC = X86::COND_O;
14889       break;
14890     case Intrinsic::x86_sse42_pcmpistris128:
14891       Opcode = X86ISD::PCMPISTRI;
14892       X86CC = X86::COND_S;
14893       break;
14894     case Intrinsic::x86_sse42_pcmpestris128:
14895       Opcode = X86ISD::PCMPESTRI;
14896       X86CC = X86::COND_S;
14897       break;
14898     case Intrinsic::x86_sse42_pcmpistriz128:
14899       Opcode = X86ISD::PCMPISTRI;
14900       X86CC = X86::COND_E;
14901       break;
14902     case Intrinsic::x86_sse42_pcmpestriz128:
14903       Opcode = X86ISD::PCMPESTRI;
14904       X86CC = X86::COND_E;
14905       break;
14906     }
14907     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14908     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14909     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14910     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14911                                 DAG.getConstant(X86CC, MVT::i8),
14912                                 SDValue(PCMP.getNode(), 1));
14913     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14914   }
14915
14916   case Intrinsic::x86_sse42_pcmpistri128:
14917   case Intrinsic::x86_sse42_pcmpestri128: {
14918     unsigned Opcode;
14919     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14920       Opcode = X86ISD::PCMPISTRI;
14921     else
14922       Opcode = X86ISD::PCMPESTRI;
14923
14924     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14925     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14926     return DAG.getNode(Opcode, dl, VTs, NewOps);
14927   }
14928
14929   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14930   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14931   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14932   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14933   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14934   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14935   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14936   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14937   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14938   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14939   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14940   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
14941     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
14942     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
14943       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
14944                                               dl, Op.getValueType(),
14945                                               Op.getOperand(1),
14946                                               Op.getOperand(2),
14947                                               Op.getOperand(3)),
14948                                   Op.getOperand(4), Op.getOperand(1), DAG);
14949     else
14950       return SDValue();
14951   }
14952
14953   case Intrinsic::x86_fma_vfmadd_ps:
14954   case Intrinsic::x86_fma_vfmadd_pd:
14955   case Intrinsic::x86_fma_vfmsub_ps:
14956   case Intrinsic::x86_fma_vfmsub_pd:
14957   case Intrinsic::x86_fma_vfnmadd_ps:
14958   case Intrinsic::x86_fma_vfnmadd_pd:
14959   case Intrinsic::x86_fma_vfnmsub_ps:
14960   case Intrinsic::x86_fma_vfnmsub_pd:
14961   case Intrinsic::x86_fma_vfmaddsub_ps:
14962   case Intrinsic::x86_fma_vfmaddsub_pd:
14963   case Intrinsic::x86_fma_vfmsubadd_ps:
14964   case Intrinsic::x86_fma_vfmsubadd_pd:
14965   case Intrinsic::x86_fma_vfmadd_ps_256:
14966   case Intrinsic::x86_fma_vfmadd_pd_256:
14967   case Intrinsic::x86_fma_vfmsub_ps_256:
14968   case Intrinsic::x86_fma_vfmsub_pd_256:
14969   case Intrinsic::x86_fma_vfnmadd_ps_256:
14970   case Intrinsic::x86_fma_vfnmadd_pd_256:
14971   case Intrinsic::x86_fma_vfnmsub_ps_256:
14972   case Intrinsic::x86_fma_vfnmsub_pd_256:
14973   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14974   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14975   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14976   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14977     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
14978                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14979   }
14980 }
14981
14982 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14983                               SDValue Src, SDValue Mask, SDValue Base,
14984                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14985                               const X86Subtarget * Subtarget) {
14986   SDLoc dl(Op);
14987   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14988   assert(C && "Invalid scale type");
14989   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14990   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14991                              Index.getSimpleValueType().getVectorNumElements());
14992   SDValue MaskInReg;
14993   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14994   if (MaskC)
14995     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14996   else
14997     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14998   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14999   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15000   SDValue Segment = DAG.getRegister(0, MVT::i32);
15001   if (Src.getOpcode() == ISD::UNDEF)
15002     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15003   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15004   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15005   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15006   return DAG.getMergeValues(RetOps, dl);
15007 }
15008
15009 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15010                                SDValue Src, SDValue Mask, SDValue Base,
15011                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15012   SDLoc dl(Op);
15013   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15014   assert(C && "Invalid scale type");
15015   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15016   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15017   SDValue Segment = DAG.getRegister(0, MVT::i32);
15018   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15019                              Index.getSimpleValueType().getVectorNumElements());
15020   SDValue MaskInReg;
15021   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15022   if (MaskC)
15023     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15024   else
15025     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15026   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15027   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15028   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15029   return SDValue(Res, 1);
15030 }
15031
15032 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15033                                SDValue Mask, SDValue Base, SDValue Index,
15034                                SDValue ScaleOp, SDValue Chain) {
15035   SDLoc dl(Op);
15036   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15037   assert(C && "Invalid scale type");
15038   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15039   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15040   SDValue Segment = DAG.getRegister(0, MVT::i32);
15041   EVT MaskVT =
15042     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15043   SDValue MaskInReg;
15044   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15045   if (MaskC)
15046     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15047   else
15048     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15049   //SDVTList VTs = DAG.getVTList(MVT::Other);
15050   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15051   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15052   return SDValue(Res, 0);
15053 }
15054
15055 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15056 // read performance monitor counters (x86_rdpmc).
15057 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15058                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15059                               SmallVectorImpl<SDValue> &Results) {
15060   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15061   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15062   SDValue LO, HI;
15063
15064   // The ECX register is used to select the index of the performance counter
15065   // to read.
15066   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15067                                    N->getOperand(2));
15068   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15069
15070   // Reads the content of a 64-bit performance counter and returns it in the
15071   // registers EDX:EAX.
15072   if (Subtarget->is64Bit()) {
15073     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15074     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15075                             LO.getValue(2));
15076   } else {
15077     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15078     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15079                             LO.getValue(2));
15080   }
15081   Chain = HI.getValue(1);
15082
15083   if (Subtarget->is64Bit()) {
15084     // The EAX register is loaded with the low-order 32 bits. The EDX register
15085     // is loaded with the supported high-order bits of the counter.
15086     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15087                               DAG.getConstant(32, MVT::i8));
15088     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15089     Results.push_back(Chain);
15090     return;
15091   }
15092
15093   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15094   SDValue Ops[] = { LO, HI };
15095   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15096   Results.push_back(Pair);
15097   Results.push_back(Chain);
15098 }
15099
15100 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15101 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15102 // also used to custom lower READCYCLECOUNTER nodes.
15103 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15104                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15105                               SmallVectorImpl<SDValue> &Results) {
15106   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15107   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15108   SDValue LO, HI;
15109
15110   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15111   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15112   // and the EAX register is loaded with the low-order 32 bits.
15113   if (Subtarget->is64Bit()) {
15114     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15115     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15116                             LO.getValue(2));
15117   } else {
15118     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15119     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15120                             LO.getValue(2));
15121   }
15122   SDValue Chain = HI.getValue(1);
15123
15124   if (Opcode == X86ISD::RDTSCP_DAG) {
15125     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15126
15127     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15128     // the ECX register. Add 'ecx' explicitly to the chain.
15129     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15130                                      HI.getValue(2));
15131     // Explicitly store the content of ECX at the location passed in input
15132     // to the 'rdtscp' intrinsic.
15133     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15134                          MachinePointerInfo(), false, false, 0);
15135   }
15136
15137   if (Subtarget->is64Bit()) {
15138     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15139     // the EAX register is loaded with the low-order 32 bits.
15140     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15141                               DAG.getConstant(32, MVT::i8));
15142     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15143     Results.push_back(Chain);
15144     return;
15145   }
15146
15147   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15148   SDValue Ops[] = { LO, HI };
15149   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15150   Results.push_back(Pair);
15151   Results.push_back(Chain);
15152 }
15153
15154 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15155                                      SelectionDAG &DAG) {
15156   SmallVector<SDValue, 2> Results;
15157   SDLoc DL(Op);
15158   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15159                           Results);
15160   return DAG.getMergeValues(Results, DL);
15161 }
15162
15163
15164 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15165                                       SelectionDAG &DAG) {
15166   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15167
15168   const IntrinsicData* IntrData = GetIntrinsicWithChain(IntNo);
15169   if (!IntrData)
15170     return SDValue();
15171
15172   SDLoc dl(Op);
15173   switch(IntrData->Type) {
15174   default:
15175     llvm_unreachable("Unknown Intrinsic Type");
15176     break;    
15177   case RDSEED:
15178   case RDRAND: {
15179     // Emit the node with the right value type.
15180     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15181     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15182
15183     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15184     // Otherwise return the value from Rand, which is always 0, casted to i32.
15185     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15186                       DAG.getConstant(1, Op->getValueType(1)),
15187                       DAG.getConstant(X86::COND_B, MVT::i32),
15188                       SDValue(Result.getNode(), 1) };
15189     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15190                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15191                                   Ops);
15192
15193     // Return { result, isValid, chain }.
15194     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15195                        SDValue(Result.getNode(), 2));
15196   }
15197   case GATHER: {
15198   //gather(v1, mask, index, base, scale);
15199     SDValue Chain = Op.getOperand(0);
15200     SDValue Src   = Op.getOperand(2);
15201     SDValue Base  = Op.getOperand(3);
15202     SDValue Index = Op.getOperand(4);
15203     SDValue Mask  = Op.getOperand(5);
15204     SDValue Scale = Op.getOperand(6);
15205     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15206                           Subtarget);
15207   }
15208   case SCATTER: {
15209   //scatter(base, mask, index, v1, scale);
15210     SDValue Chain = Op.getOperand(0);
15211     SDValue Base  = Op.getOperand(2);
15212     SDValue Mask  = Op.getOperand(3);
15213     SDValue Index = Op.getOperand(4);
15214     SDValue Src   = Op.getOperand(5);
15215     SDValue Scale = Op.getOperand(6);
15216     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15217   }
15218   case PREFETCH: {
15219     SDValue Hint = Op.getOperand(6);
15220     unsigned HintVal;
15221     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15222         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15223       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15224     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15225     SDValue Chain = Op.getOperand(0);
15226     SDValue Mask  = Op.getOperand(2);
15227     SDValue Index = Op.getOperand(3);
15228     SDValue Base  = Op.getOperand(4);
15229     SDValue Scale = Op.getOperand(5);
15230     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15231   }
15232   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15233   case RDTSC: {
15234     SmallVector<SDValue, 2> Results;
15235     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15236     return DAG.getMergeValues(Results, dl);
15237   }
15238   // Read Performance Monitoring Counters.
15239   case RDPMC: {
15240     SmallVector<SDValue, 2> Results;
15241     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15242     return DAG.getMergeValues(Results, dl);
15243   }
15244   // XTEST intrinsics.
15245   case XTEST: {
15246     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15247     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15248     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15249                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15250                                 InTrans);
15251     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15252     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15253                        Ret, SDValue(InTrans.getNode(), 1));
15254   }
15255   // ADC/ADCX/SBB
15256   case ADX: {
15257     SmallVector<SDValue, 2> Results;
15258     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15259     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15260     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15261                                 DAG.getConstant(-1, MVT::i8));
15262     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15263                               Op.getOperand(4), GenCF.getValue(1));
15264     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15265                                  Op.getOperand(5), MachinePointerInfo(),
15266                                  false, false, 0);
15267     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15268                                 DAG.getConstant(X86::COND_B, MVT::i8),
15269                                 Res.getValue(1));
15270     Results.push_back(SetCC);
15271     Results.push_back(Store);
15272     return DAG.getMergeValues(Results, dl);
15273   }
15274   }
15275 }
15276
15277 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15278                                            SelectionDAG &DAG) const {
15279   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15280   MFI->setReturnAddressIsTaken(true);
15281
15282   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15283     return SDValue();
15284
15285   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15286   SDLoc dl(Op);
15287   EVT PtrVT = getPointerTy();
15288
15289   if (Depth > 0) {
15290     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15291     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15292         DAG.getSubtarget().getRegisterInfo());
15293     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15294     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15295                        DAG.getNode(ISD::ADD, dl, PtrVT,
15296                                    FrameAddr, Offset),
15297                        MachinePointerInfo(), false, false, false, 0);
15298   }
15299
15300   // Just load the return address.
15301   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15302   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15303                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15304 }
15305
15306 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15307   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15308   MFI->setFrameAddressIsTaken(true);
15309
15310   EVT VT = Op.getValueType();
15311   SDLoc dl(Op);  // FIXME probably not meaningful
15312   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15313   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15314       DAG.getSubtarget().getRegisterInfo());
15315   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15316   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15317           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15318          "Invalid Frame Register!");
15319   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15320   while (Depth--)
15321     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15322                             MachinePointerInfo(),
15323                             false, false, false, 0);
15324   return FrameAddr;
15325 }
15326
15327 // FIXME? Maybe this could be a TableGen attribute on some registers and
15328 // this table could be generated automatically from RegInfo.
15329 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15330                                               EVT VT) const {
15331   unsigned Reg = StringSwitch<unsigned>(RegName)
15332                        .Case("esp", X86::ESP)
15333                        .Case("rsp", X86::RSP)
15334                        .Default(0);
15335   if (Reg)
15336     return Reg;
15337   report_fatal_error("Invalid register name global variable");
15338 }
15339
15340 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15341                                                      SelectionDAG &DAG) const {
15342   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15343       DAG.getSubtarget().getRegisterInfo());
15344   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15345 }
15346
15347 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15348   SDValue Chain     = Op.getOperand(0);
15349   SDValue Offset    = Op.getOperand(1);
15350   SDValue Handler   = Op.getOperand(2);
15351   SDLoc dl      (Op);
15352
15353   EVT PtrVT = getPointerTy();
15354   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15355       DAG.getSubtarget().getRegisterInfo());
15356   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15357   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15358           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15359          "Invalid Frame Register!");
15360   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15361   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15362
15363   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15364                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15365   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15366   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15367                        false, false, 0);
15368   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15369
15370   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15371                      DAG.getRegister(StoreAddrReg, PtrVT));
15372 }
15373
15374 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15375                                                SelectionDAG &DAG) const {
15376   SDLoc DL(Op);
15377   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15378                      DAG.getVTList(MVT::i32, MVT::Other),
15379                      Op.getOperand(0), Op.getOperand(1));
15380 }
15381
15382 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15383                                                 SelectionDAG &DAG) const {
15384   SDLoc DL(Op);
15385   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15386                      Op.getOperand(0), Op.getOperand(1));
15387 }
15388
15389 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15390   return Op.getOperand(0);
15391 }
15392
15393 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15394                                                 SelectionDAG &DAG) const {
15395   SDValue Root = Op.getOperand(0);
15396   SDValue Trmp = Op.getOperand(1); // trampoline
15397   SDValue FPtr = Op.getOperand(2); // nested function
15398   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15399   SDLoc dl (Op);
15400
15401   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15402   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15403
15404   if (Subtarget->is64Bit()) {
15405     SDValue OutChains[6];
15406
15407     // Large code-model.
15408     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15409     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15410
15411     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15412     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15413
15414     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15415
15416     // Load the pointer to the nested function into R11.
15417     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15418     SDValue Addr = Trmp;
15419     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15420                                 Addr, MachinePointerInfo(TrmpAddr),
15421                                 false, false, 0);
15422
15423     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15424                        DAG.getConstant(2, MVT::i64));
15425     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15426                                 MachinePointerInfo(TrmpAddr, 2),
15427                                 false, false, 2);
15428
15429     // Load the 'nest' parameter value into R10.
15430     // R10 is specified in X86CallingConv.td
15431     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15432     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15433                        DAG.getConstant(10, MVT::i64));
15434     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15435                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15436                                 false, false, 0);
15437
15438     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15439                        DAG.getConstant(12, MVT::i64));
15440     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15441                                 MachinePointerInfo(TrmpAddr, 12),
15442                                 false, false, 2);
15443
15444     // Jump to the nested function.
15445     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15446     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15447                        DAG.getConstant(20, MVT::i64));
15448     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15449                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15450                                 false, false, 0);
15451
15452     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15453     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15454                        DAG.getConstant(22, MVT::i64));
15455     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15456                                 MachinePointerInfo(TrmpAddr, 22),
15457                                 false, false, 0);
15458
15459     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15460   } else {
15461     const Function *Func =
15462       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15463     CallingConv::ID CC = Func->getCallingConv();
15464     unsigned NestReg;
15465
15466     switch (CC) {
15467     default:
15468       llvm_unreachable("Unsupported calling convention");
15469     case CallingConv::C:
15470     case CallingConv::X86_StdCall: {
15471       // Pass 'nest' parameter in ECX.
15472       // Must be kept in sync with X86CallingConv.td
15473       NestReg = X86::ECX;
15474
15475       // Check that ECX wasn't needed by an 'inreg' parameter.
15476       FunctionType *FTy = Func->getFunctionType();
15477       const AttributeSet &Attrs = Func->getAttributes();
15478
15479       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15480         unsigned InRegCount = 0;
15481         unsigned Idx = 1;
15482
15483         for (FunctionType::param_iterator I = FTy->param_begin(),
15484              E = FTy->param_end(); I != E; ++I, ++Idx)
15485           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15486             // FIXME: should only count parameters that are lowered to integers.
15487             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15488
15489         if (InRegCount > 2) {
15490           report_fatal_error("Nest register in use - reduce number of inreg"
15491                              " parameters!");
15492         }
15493       }
15494       break;
15495     }
15496     case CallingConv::X86_FastCall:
15497     case CallingConv::X86_ThisCall:
15498     case CallingConv::Fast:
15499       // Pass 'nest' parameter in EAX.
15500       // Must be kept in sync with X86CallingConv.td
15501       NestReg = X86::EAX;
15502       break;
15503     }
15504
15505     SDValue OutChains[4];
15506     SDValue Addr, Disp;
15507
15508     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15509                        DAG.getConstant(10, MVT::i32));
15510     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15511
15512     // This is storing the opcode for MOV32ri.
15513     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15514     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15515     OutChains[0] = DAG.getStore(Root, dl,
15516                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15517                                 Trmp, MachinePointerInfo(TrmpAddr),
15518                                 false, false, 0);
15519
15520     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15521                        DAG.getConstant(1, MVT::i32));
15522     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15523                                 MachinePointerInfo(TrmpAddr, 1),
15524                                 false, false, 1);
15525
15526     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15527     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15528                        DAG.getConstant(5, MVT::i32));
15529     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15530                                 MachinePointerInfo(TrmpAddr, 5),
15531                                 false, false, 1);
15532
15533     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15534                        DAG.getConstant(6, MVT::i32));
15535     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15536                                 MachinePointerInfo(TrmpAddr, 6),
15537                                 false, false, 1);
15538
15539     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15540   }
15541 }
15542
15543 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15544                                             SelectionDAG &DAG) const {
15545   /*
15546    The rounding mode is in bits 11:10 of FPSR, and has the following
15547    settings:
15548      00 Round to nearest
15549      01 Round to -inf
15550      10 Round to +inf
15551      11 Round to 0
15552
15553   FLT_ROUNDS, on the other hand, expects the following:
15554     -1 Undefined
15555      0 Round to 0
15556      1 Round to nearest
15557      2 Round to +inf
15558      3 Round to -inf
15559
15560   To perform the conversion, we do:
15561     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15562   */
15563
15564   MachineFunction &MF = DAG.getMachineFunction();
15565   const TargetMachine &TM = MF.getTarget();
15566   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15567   unsigned StackAlignment = TFI.getStackAlignment();
15568   MVT VT = Op.getSimpleValueType();
15569   SDLoc DL(Op);
15570
15571   // Save FP Control Word to stack slot
15572   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15573   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15574
15575   MachineMemOperand *MMO =
15576    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15577                            MachineMemOperand::MOStore, 2, 2);
15578
15579   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15580   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15581                                           DAG.getVTList(MVT::Other),
15582                                           Ops, MVT::i16, MMO);
15583
15584   // Load FP Control Word from stack slot
15585   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15586                             MachinePointerInfo(), false, false, false, 0);
15587
15588   // Transform as necessary
15589   SDValue CWD1 =
15590     DAG.getNode(ISD::SRL, DL, MVT::i16,
15591                 DAG.getNode(ISD::AND, DL, MVT::i16,
15592                             CWD, DAG.getConstant(0x800, MVT::i16)),
15593                 DAG.getConstant(11, MVT::i8));
15594   SDValue CWD2 =
15595     DAG.getNode(ISD::SRL, DL, MVT::i16,
15596                 DAG.getNode(ISD::AND, DL, MVT::i16,
15597                             CWD, DAG.getConstant(0x400, MVT::i16)),
15598                 DAG.getConstant(9, MVT::i8));
15599
15600   SDValue RetVal =
15601     DAG.getNode(ISD::AND, DL, MVT::i16,
15602                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15603                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15604                             DAG.getConstant(1, MVT::i16)),
15605                 DAG.getConstant(3, MVT::i16));
15606
15607   return DAG.getNode((VT.getSizeInBits() < 16 ?
15608                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15609 }
15610
15611 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15612   MVT VT = Op.getSimpleValueType();
15613   EVT OpVT = VT;
15614   unsigned NumBits = VT.getSizeInBits();
15615   SDLoc dl(Op);
15616
15617   Op = Op.getOperand(0);
15618   if (VT == MVT::i8) {
15619     // Zero extend to i32 since there is not an i8 bsr.
15620     OpVT = MVT::i32;
15621     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15622   }
15623
15624   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15625   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15626   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15627
15628   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15629   SDValue Ops[] = {
15630     Op,
15631     DAG.getConstant(NumBits+NumBits-1, OpVT),
15632     DAG.getConstant(X86::COND_E, MVT::i8),
15633     Op.getValue(1)
15634   };
15635   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15636
15637   // Finally xor with NumBits-1.
15638   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15639
15640   if (VT == MVT::i8)
15641     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15642   return Op;
15643 }
15644
15645 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15646   MVT VT = Op.getSimpleValueType();
15647   EVT OpVT = VT;
15648   unsigned NumBits = VT.getSizeInBits();
15649   SDLoc dl(Op);
15650
15651   Op = Op.getOperand(0);
15652   if (VT == MVT::i8) {
15653     // Zero extend to i32 since there is not an i8 bsr.
15654     OpVT = MVT::i32;
15655     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15656   }
15657
15658   // Issue a bsr (scan bits in reverse).
15659   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15660   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15661
15662   // And xor with NumBits-1.
15663   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15664
15665   if (VT == MVT::i8)
15666     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15667   return Op;
15668 }
15669
15670 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15671   MVT VT = Op.getSimpleValueType();
15672   unsigned NumBits = VT.getSizeInBits();
15673   SDLoc dl(Op);
15674   Op = Op.getOperand(0);
15675
15676   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15677   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15678   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15679
15680   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15681   SDValue Ops[] = {
15682     Op,
15683     DAG.getConstant(NumBits, VT),
15684     DAG.getConstant(X86::COND_E, MVT::i8),
15685     Op.getValue(1)
15686   };
15687   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15688 }
15689
15690 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15691 // ones, and then concatenate the result back.
15692 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15693   MVT VT = Op.getSimpleValueType();
15694
15695   assert(VT.is256BitVector() && VT.isInteger() &&
15696          "Unsupported value type for operation");
15697
15698   unsigned NumElems = VT.getVectorNumElements();
15699   SDLoc dl(Op);
15700
15701   // Extract the LHS vectors
15702   SDValue LHS = Op.getOperand(0);
15703   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15704   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15705
15706   // Extract the RHS vectors
15707   SDValue RHS = Op.getOperand(1);
15708   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15709   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15710
15711   MVT EltVT = VT.getVectorElementType();
15712   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15713
15714   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15715                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15716                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15717 }
15718
15719 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15720   assert(Op.getSimpleValueType().is256BitVector() &&
15721          Op.getSimpleValueType().isInteger() &&
15722          "Only handle AVX 256-bit vector integer operation");
15723   return Lower256IntArith(Op, DAG);
15724 }
15725
15726 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15727   assert(Op.getSimpleValueType().is256BitVector() &&
15728          Op.getSimpleValueType().isInteger() &&
15729          "Only handle AVX 256-bit vector integer operation");
15730   return Lower256IntArith(Op, DAG);
15731 }
15732
15733 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15734                         SelectionDAG &DAG) {
15735   SDLoc dl(Op);
15736   MVT VT = Op.getSimpleValueType();
15737
15738   // Decompose 256-bit ops into smaller 128-bit ops.
15739   if (VT.is256BitVector() && !Subtarget->hasInt256())
15740     return Lower256IntArith(Op, DAG);
15741
15742   SDValue A = Op.getOperand(0);
15743   SDValue B = Op.getOperand(1);
15744
15745   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15746   if (VT == MVT::v4i32) {
15747     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15748            "Should not custom lower when pmuldq is available!");
15749
15750     // Extract the odd parts.
15751     static const int UnpackMask[] = { 1, -1, 3, -1 };
15752     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15753     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15754
15755     // Multiply the even parts.
15756     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15757     // Now multiply odd parts.
15758     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15759
15760     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15761     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15762
15763     // Merge the two vectors back together with a shuffle. This expands into 2
15764     // shuffles.
15765     static const int ShufMask[] = { 0, 4, 2, 6 };
15766     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15767   }
15768
15769   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15770          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15771
15772   //  Ahi = psrlqi(a, 32);
15773   //  Bhi = psrlqi(b, 32);
15774   //
15775   //  AloBlo = pmuludq(a, b);
15776   //  AloBhi = pmuludq(a, Bhi);
15777   //  AhiBlo = pmuludq(Ahi, b);
15778
15779   //  AloBhi = psllqi(AloBhi, 32);
15780   //  AhiBlo = psllqi(AhiBlo, 32);
15781   //  return AloBlo + AloBhi + AhiBlo;
15782
15783   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15784   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15785
15786   // Bit cast to 32-bit vectors for MULUDQ
15787   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15788                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15789   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15790   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15791   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15792   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15793
15794   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15795   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15796   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15797
15798   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15799   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15800
15801   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15802   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15803 }
15804
15805 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15806   assert(Subtarget->isTargetWin64() && "Unexpected target");
15807   EVT VT = Op.getValueType();
15808   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15809          "Unexpected return type for lowering");
15810
15811   RTLIB::Libcall LC;
15812   bool isSigned;
15813   switch (Op->getOpcode()) {
15814   default: llvm_unreachable("Unexpected request for libcall!");
15815   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15816   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15817   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15818   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15819   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15820   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15821   }
15822
15823   SDLoc dl(Op);
15824   SDValue InChain = DAG.getEntryNode();
15825
15826   TargetLowering::ArgListTy Args;
15827   TargetLowering::ArgListEntry Entry;
15828   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15829     EVT ArgVT = Op->getOperand(i).getValueType();
15830     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15831            "Unexpected argument type for lowering");
15832     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15833     Entry.Node = StackPtr;
15834     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15835                            false, false, 16);
15836     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15837     Entry.Ty = PointerType::get(ArgTy,0);
15838     Entry.isSExt = false;
15839     Entry.isZExt = false;
15840     Args.push_back(Entry);
15841   }
15842
15843   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15844                                          getPointerTy());
15845
15846   TargetLowering::CallLoweringInfo CLI(DAG);
15847   CLI.setDebugLoc(dl).setChain(InChain)
15848     .setCallee(getLibcallCallingConv(LC),
15849                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15850                Callee, std::move(Args), 0)
15851     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15852
15853   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15854   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15855 }
15856
15857 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15858                              SelectionDAG &DAG) {
15859   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15860   EVT VT = Op0.getValueType();
15861   SDLoc dl(Op);
15862
15863   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15864          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15865
15866   // PMULxD operations multiply each even value (starting at 0) of LHS with
15867   // the related value of RHS and produce a widen result.
15868   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15869   // => <2 x i64> <ae|cg>
15870   //
15871   // In other word, to have all the results, we need to perform two PMULxD:
15872   // 1. one with the even values.
15873   // 2. one with the odd values.
15874   // To achieve #2, with need to place the odd values at an even position.
15875   //
15876   // Place the odd value at an even position (basically, shift all values 1
15877   // step to the left):
15878   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15879   // <a|b|c|d> => <b|undef|d|undef>
15880   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15881   // <e|f|g|h> => <f|undef|h|undef>
15882   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15883
15884   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15885   // ints.
15886   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15887   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15888   unsigned Opcode =
15889       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15890   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15891   // => <2 x i64> <ae|cg>
15892   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15893                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15894   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15895   // => <2 x i64> <bf|dh>
15896   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15897                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15898
15899   // Shuffle it back into the right order.
15900   SDValue Highs, Lows;
15901   if (VT == MVT::v8i32) {
15902     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15903     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15904     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15905     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15906   } else {
15907     const int HighMask[] = {1, 5, 3, 7};
15908     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15909     const int LowMask[] = {0, 4, 2, 6};
15910     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15911   }
15912
15913   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15914   // unsigned multiply.
15915   if (IsSigned && !Subtarget->hasSSE41()) {
15916     SDValue ShAmt =
15917         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15918     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15919                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15920     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15921                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15922
15923     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15924     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15925   }
15926
15927   // The first result of MUL_LOHI is actually the low value, followed by the
15928   // high value.
15929   SDValue Ops[] = {Lows, Highs};
15930   return DAG.getMergeValues(Ops, dl);
15931 }
15932
15933 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15934                                          const X86Subtarget *Subtarget) {
15935   MVT VT = Op.getSimpleValueType();
15936   SDLoc dl(Op);
15937   SDValue R = Op.getOperand(0);
15938   SDValue Amt = Op.getOperand(1);
15939
15940   // Optimize shl/srl/sra with constant shift amount.
15941   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15942     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15943       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15944
15945       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15946           (Subtarget->hasInt256() &&
15947            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15948           (Subtarget->hasAVX512() &&
15949            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15950         if (Op.getOpcode() == ISD::SHL)
15951           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15952                                             DAG);
15953         if (Op.getOpcode() == ISD::SRL)
15954           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15955                                             DAG);
15956         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15957           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15958                                             DAG);
15959       }
15960
15961       if (VT == MVT::v16i8) {
15962         if (Op.getOpcode() == ISD::SHL) {
15963           // Make a large shift.
15964           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15965                                                    MVT::v8i16, R, ShiftAmt,
15966                                                    DAG);
15967           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15968           // Zero out the rightmost bits.
15969           SmallVector<SDValue, 16> V(16,
15970                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15971                                                      MVT::i8));
15972           return DAG.getNode(ISD::AND, dl, VT, SHL,
15973                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15974         }
15975         if (Op.getOpcode() == ISD::SRL) {
15976           // Make a large shift.
15977           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15978                                                    MVT::v8i16, R, ShiftAmt,
15979                                                    DAG);
15980           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15981           // Zero out the leftmost bits.
15982           SmallVector<SDValue, 16> V(16,
15983                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15984                                                      MVT::i8));
15985           return DAG.getNode(ISD::AND, dl, VT, SRL,
15986                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15987         }
15988         if (Op.getOpcode() == ISD::SRA) {
15989           if (ShiftAmt == 7) {
15990             // R s>> 7  ===  R s< 0
15991             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15992             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15993           }
15994
15995           // R s>> a === ((R u>> a) ^ m) - m
15996           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15997           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15998                                                          MVT::i8));
15999           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16000           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16001           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16002           return Res;
16003         }
16004         llvm_unreachable("Unknown shift opcode.");
16005       }
16006
16007       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16008         if (Op.getOpcode() == ISD::SHL) {
16009           // Make a large shift.
16010           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16011                                                    MVT::v16i16, R, ShiftAmt,
16012                                                    DAG);
16013           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16014           // Zero out the rightmost bits.
16015           SmallVector<SDValue, 32> V(32,
16016                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16017                                                      MVT::i8));
16018           return DAG.getNode(ISD::AND, dl, VT, SHL,
16019                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16020         }
16021         if (Op.getOpcode() == ISD::SRL) {
16022           // Make a large shift.
16023           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16024                                                    MVT::v16i16, R, ShiftAmt,
16025                                                    DAG);
16026           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16027           // Zero out the leftmost bits.
16028           SmallVector<SDValue, 32> V(32,
16029                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16030                                                      MVT::i8));
16031           return DAG.getNode(ISD::AND, dl, VT, SRL,
16032                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16033         }
16034         if (Op.getOpcode() == ISD::SRA) {
16035           if (ShiftAmt == 7) {
16036             // R s>> 7  ===  R s< 0
16037             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16038             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16039           }
16040
16041           // R s>> a === ((R u>> a) ^ m) - m
16042           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16043           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16044                                                          MVT::i8));
16045           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16046           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16047           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16048           return Res;
16049         }
16050         llvm_unreachable("Unknown shift opcode.");
16051       }
16052     }
16053   }
16054
16055   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16056   if (!Subtarget->is64Bit() &&
16057       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16058       Amt.getOpcode() == ISD::BITCAST &&
16059       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16060     Amt = Amt.getOperand(0);
16061     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16062                      VT.getVectorNumElements();
16063     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16064     uint64_t ShiftAmt = 0;
16065     for (unsigned i = 0; i != Ratio; ++i) {
16066       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16067       if (!C)
16068         return SDValue();
16069       // 6 == Log2(64)
16070       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16071     }
16072     // Check remaining shift amounts.
16073     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16074       uint64_t ShAmt = 0;
16075       for (unsigned j = 0; j != Ratio; ++j) {
16076         ConstantSDNode *C =
16077           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16078         if (!C)
16079           return SDValue();
16080         // 6 == Log2(64)
16081         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16082       }
16083       if (ShAmt != ShiftAmt)
16084         return SDValue();
16085     }
16086     switch (Op.getOpcode()) {
16087     default:
16088       llvm_unreachable("Unknown shift opcode!");
16089     case ISD::SHL:
16090       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16091                                         DAG);
16092     case ISD::SRL:
16093       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16094                                         DAG);
16095     case ISD::SRA:
16096       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16097                                         DAG);
16098     }
16099   }
16100
16101   return SDValue();
16102 }
16103
16104 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16105                                         const X86Subtarget* Subtarget) {
16106   MVT VT = Op.getSimpleValueType();
16107   SDLoc dl(Op);
16108   SDValue R = Op.getOperand(0);
16109   SDValue Amt = Op.getOperand(1);
16110
16111   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16112       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16113       (Subtarget->hasInt256() &&
16114        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16115         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16116        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16117     SDValue BaseShAmt;
16118     EVT EltVT = VT.getVectorElementType();
16119
16120     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16121       unsigned NumElts = VT.getVectorNumElements();
16122       unsigned i, j;
16123       for (i = 0; i != NumElts; ++i) {
16124         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16125           continue;
16126         break;
16127       }
16128       for (j = i; j != NumElts; ++j) {
16129         SDValue Arg = Amt.getOperand(j);
16130         if (Arg.getOpcode() == ISD::UNDEF) continue;
16131         if (Arg != Amt.getOperand(i))
16132           break;
16133       }
16134       if (i != NumElts && j == NumElts)
16135         BaseShAmt = Amt.getOperand(i);
16136     } else {
16137       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16138         Amt = Amt.getOperand(0);
16139       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16140                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16141         SDValue InVec = Amt.getOperand(0);
16142         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16143           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16144           unsigned i = 0;
16145           for (; i != NumElts; ++i) {
16146             SDValue Arg = InVec.getOperand(i);
16147             if (Arg.getOpcode() == ISD::UNDEF) continue;
16148             BaseShAmt = Arg;
16149             break;
16150           }
16151         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16152            if (ConstantSDNode *C =
16153                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16154              unsigned SplatIdx =
16155                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16156              if (C->getZExtValue() == SplatIdx)
16157                BaseShAmt = InVec.getOperand(1);
16158            }
16159         }
16160         if (!BaseShAmt.getNode())
16161           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16162                                   DAG.getIntPtrConstant(0));
16163       }
16164     }
16165
16166     if (BaseShAmt.getNode()) {
16167       if (EltVT.bitsGT(MVT::i32))
16168         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16169       else if (EltVT.bitsLT(MVT::i32))
16170         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16171
16172       switch (Op.getOpcode()) {
16173       default:
16174         llvm_unreachable("Unknown shift opcode!");
16175       case ISD::SHL:
16176         switch (VT.SimpleTy) {
16177         default: return SDValue();
16178         case MVT::v2i64:
16179         case MVT::v4i32:
16180         case MVT::v8i16:
16181         case MVT::v4i64:
16182         case MVT::v8i32:
16183         case MVT::v16i16:
16184         case MVT::v16i32:
16185         case MVT::v8i64:
16186           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16187         }
16188       case ISD::SRA:
16189         switch (VT.SimpleTy) {
16190         default: return SDValue();
16191         case MVT::v4i32:
16192         case MVT::v8i16:
16193         case MVT::v8i32:
16194         case MVT::v16i16:
16195         case MVT::v16i32:
16196         case MVT::v8i64:
16197           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16198         }
16199       case ISD::SRL:
16200         switch (VT.SimpleTy) {
16201         default: return SDValue();
16202         case MVT::v2i64:
16203         case MVT::v4i32:
16204         case MVT::v8i16:
16205         case MVT::v4i64:
16206         case MVT::v8i32:
16207         case MVT::v16i16:
16208         case MVT::v16i32:
16209         case MVT::v8i64:
16210           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16211         }
16212       }
16213     }
16214   }
16215
16216   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16217   if (!Subtarget->is64Bit() &&
16218       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16219       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16220       Amt.getOpcode() == ISD::BITCAST &&
16221       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16222     Amt = Amt.getOperand(0);
16223     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16224                      VT.getVectorNumElements();
16225     std::vector<SDValue> Vals(Ratio);
16226     for (unsigned i = 0; i != Ratio; ++i)
16227       Vals[i] = Amt.getOperand(i);
16228     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16229       for (unsigned j = 0; j != Ratio; ++j)
16230         if (Vals[j] != Amt.getOperand(i + j))
16231           return SDValue();
16232     }
16233     switch (Op.getOpcode()) {
16234     default:
16235       llvm_unreachable("Unknown shift opcode!");
16236     case ISD::SHL:
16237       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16238     case ISD::SRL:
16239       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16240     case ISD::SRA:
16241       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16242     }
16243   }
16244
16245   return SDValue();
16246 }
16247
16248 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16249                           SelectionDAG &DAG) {
16250   MVT VT = Op.getSimpleValueType();
16251   SDLoc dl(Op);
16252   SDValue R = Op.getOperand(0);
16253   SDValue Amt = Op.getOperand(1);
16254   SDValue V;
16255
16256   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16257   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16258
16259   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16260   if (V.getNode())
16261     return V;
16262
16263   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16264   if (V.getNode())
16265       return V;
16266
16267   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16268     return Op;
16269   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16270   if (Subtarget->hasInt256()) {
16271     if (Op.getOpcode() == ISD::SRL &&
16272         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16273          VT == MVT::v4i64 || VT == MVT::v8i32))
16274       return Op;
16275     if (Op.getOpcode() == ISD::SHL &&
16276         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16277          VT == MVT::v4i64 || VT == MVT::v8i32))
16278       return Op;
16279     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16280       return Op;
16281   }
16282
16283   // If possible, lower this packed shift into a vector multiply instead of
16284   // expanding it into a sequence of scalar shifts.
16285   // Do this only if the vector shift count is a constant build_vector.
16286   if (Op.getOpcode() == ISD::SHL && 
16287       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16288        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16289       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16290     SmallVector<SDValue, 8> Elts;
16291     EVT SVT = VT.getScalarType();
16292     unsigned SVTBits = SVT.getSizeInBits();
16293     const APInt &One = APInt(SVTBits, 1);
16294     unsigned NumElems = VT.getVectorNumElements();
16295
16296     for (unsigned i=0; i !=NumElems; ++i) {
16297       SDValue Op = Amt->getOperand(i);
16298       if (Op->getOpcode() == ISD::UNDEF) {
16299         Elts.push_back(Op);
16300         continue;
16301       }
16302
16303       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16304       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16305       uint64_t ShAmt = C.getZExtValue();
16306       if (ShAmt >= SVTBits) {
16307         Elts.push_back(DAG.getUNDEF(SVT));
16308         continue;
16309       }
16310       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16311     }
16312     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16313     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16314   }
16315
16316   // Lower SHL with variable shift amount.
16317   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16318     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16319
16320     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16321     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16322     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16323     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16324   }
16325
16326   // If possible, lower this shift as a sequence of two shifts by
16327   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16328   // Example:
16329   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16330   //
16331   // Could be rewritten as:
16332   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16333   //
16334   // The advantage is that the two shifts from the example would be
16335   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16336   // the vector shift into four scalar shifts plus four pairs of vector
16337   // insert/extract.
16338   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16339       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16340     unsigned TargetOpcode = X86ISD::MOVSS;
16341     bool CanBeSimplified;
16342     // The splat value for the first packed shift (the 'X' from the example).
16343     SDValue Amt1 = Amt->getOperand(0);
16344     // The splat value for the second packed shift (the 'Y' from the example).
16345     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16346                                         Amt->getOperand(2);
16347
16348     // See if it is possible to replace this node with a sequence of
16349     // two shifts followed by a MOVSS/MOVSD
16350     if (VT == MVT::v4i32) {
16351       // Check if it is legal to use a MOVSS.
16352       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16353                         Amt2 == Amt->getOperand(3);
16354       if (!CanBeSimplified) {
16355         // Otherwise, check if we can still simplify this node using a MOVSD.
16356         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16357                           Amt->getOperand(2) == Amt->getOperand(3);
16358         TargetOpcode = X86ISD::MOVSD;
16359         Amt2 = Amt->getOperand(2);
16360       }
16361     } else {
16362       // Do similar checks for the case where the machine value type
16363       // is MVT::v8i16.
16364       CanBeSimplified = Amt1 == Amt->getOperand(1);
16365       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16366         CanBeSimplified = Amt2 == Amt->getOperand(i);
16367
16368       if (!CanBeSimplified) {
16369         TargetOpcode = X86ISD::MOVSD;
16370         CanBeSimplified = true;
16371         Amt2 = Amt->getOperand(4);
16372         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16373           CanBeSimplified = Amt1 == Amt->getOperand(i);
16374         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16375           CanBeSimplified = Amt2 == Amt->getOperand(j);
16376       }
16377     }
16378     
16379     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16380         isa<ConstantSDNode>(Amt2)) {
16381       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16382       EVT CastVT = MVT::v4i32;
16383       SDValue Splat1 = 
16384         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16385       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16386       SDValue Splat2 = 
16387         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16388       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16389       if (TargetOpcode == X86ISD::MOVSD)
16390         CastVT = MVT::v2i64;
16391       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16392       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16393       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16394                                             BitCast1, DAG);
16395       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16396     }
16397   }
16398
16399   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16400     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16401
16402     // a = a << 5;
16403     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16404     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16405
16406     // Turn 'a' into a mask suitable for VSELECT
16407     SDValue VSelM = DAG.getConstant(0x80, VT);
16408     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16409     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16410
16411     SDValue CM1 = DAG.getConstant(0x0f, VT);
16412     SDValue CM2 = DAG.getConstant(0x3f, VT);
16413
16414     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16415     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16416     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16417     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16418     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16419
16420     // a += a
16421     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16422     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16423     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16424
16425     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16426     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16427     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16428     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16429     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16430
16431     // a += a
16432     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16433     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16434     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16435
16436     // return VSELECT(r, r+r, a);
16437     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16438                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16439     return R;
16440   }
16441
16442   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16443   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16444   // solution better.
16445   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16446     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16447     unsigned ExtOpc =
16448         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16449     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16450     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16451     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16452                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16453     }
16454
16455   // Decompose 256-bit shifts into smaller 128-bit shifts.
16456   if (VT.is256BitVector()) {
16457     unsigned NumElems = VT.getVectorNumElements();
16458     MVT EltVT = VT.getVectorElementType();
16459     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16460
16461     // Extract the two vectors
16462     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16463     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16464
16465     // Recreate the shift amount vectors
16466     SDValue Amt1, Amt2;
16467     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16468       // Constant shift amount
16469       SmallVector<SDValue, 4> Amt1Csts;
16470       SmallVector<SDValue, 4> Amt2Csts;
16471       for (unsigned i = 0; i != NumElems/2; ++i)
16472         Amt1Csts.push_back(Amt->getOperand(i));
16473       for (unsigned i = NumElems/2; i != NumElems; ++i)
16474         Amt2Csts.push_back(Amt->getOperand(i));
16475
16476       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16477       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16478     } else {
16479       // Variable shift amount
16480       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16481       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16482     }
16483
16484     // Issue new vector shifts for the smaller types
16485     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16486     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16487
16488     // Concatenate the result back
16489     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16490   }
16491
16492   return SDValue();
16493 }
16494
16495 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16496   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16497   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16498   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16499   // has only one use.
16500   SDNode *N = Op.getNode();
16501   SDValue LHS = N->getOperand(0);
16502   SDValue RHS = N->getOperand(1);
16503   unsigned BaseOp = 0;
16504   unsigned Cond = 0;
16505   SDLoc DL(Op);
16506   switch (Op.getOpcode()) {
16507   default: llvm_unreachable("Unknown ovf instruction!");
16508   case ISD::SADDO:
16509     // A subtract of one will be selected as a INC. Note that INC doesn't
16510     // set CF, so we can't do this for UADDO.
16511     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16512       if (C->isOne()) {
16513         BaseOp = X86ISD::INC;
16514         Cond = X86::COND_O;
16515         break;
16516       }
16517     BaseOp = X86ISD::ADD;
16518     Cond = X86::COND_O;
16519     break;
16520   case ISD::UADDO:
16521     BaseOp = X86ISD::ADD;
16522     Cond = X86::COND_B;
16523     break;
16524   case ISD::SSUBO:
16525     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16526     // set CF, so we can't do this for USUBO.
16527     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16528       if (C->isOne()) {
16529         BaseOp = X86ISD::DEC;
16530         Cond = X86::COND_O;
16531         break;
16532       }
16533     BaseOp = X86ISD::SUB;
16534     Cond = X86::COND_O;
16535     break;
16536   case ISD::USUBO:
16537     BaseOp = X86ISD::SUB;
16538     Cond = X86::COND_B;
16539     break;
16540   case ISD::SMULO:
16541     BaseOp = X86ISD::SMUL;
16542     Cond = X86::COND_O;
16543     break;
16544   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16545     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16546                                  MVT::i32);
16547     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16548
16549     SDValue SetCC =
16550       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16551                   DAG.getConstant(X86::COND_O, MVT::i32),
16552                   SDValue(Sum.getNode(), 2));
16553
16554     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16555   }
16556   }
16557
16558   // Also sets EFLAGS.
16559   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16560   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16561
16562   SDValue SetCC =
16563     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16564                 DAG.getConstant(Cond, MVT::i32),
16565                 SDValue(Sum.getNode(), 1));
16566
16567   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16568 }
16569
16570 // Sign extension of the low part of vector elements. This may be used either
16571 // when sign extend instructions are not available or if the vector element
16572 // sizes already match the sign-extended size. If the vector elements are in
16573 // their pre-extended size and sign extend instructions are available, that will
16574 // be handled by LowerSIGN_EXTEND.
16575 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16576                                                   SelectionDAG &DAG) const {
16577   SDLoc dl(Op);
16578   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16579   MVT VT = Op.getSimpleValueType();
16580
16581   if (!Subtarget->hasSSE2() || !VT.isVector())
16582     return SDValue();
16583
16584   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16585                       ExtraVT.getScalarType().getSizeInBits();
16586
16587   switch (VT.SimpleTy) {
16588     default: return SDValue();
16589     case MVT::v8i32:
16590     case MVT::v16i16:
16591       if (!Subtarget->hasFp256())
16592         return SDValue();
16593       if (!Subtarget->hasInt256()) {
16594         // needs to be split
16595         unsigned NumElems = VT.getVectorNumElements();
16596
16597         // Extract the LHS vectors
16598         SDValue LHS = Op.getOperand(0);
16599         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16600         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16601
16602         MVT EltVT = VT.getVectorElementType();
16603         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16604
16605         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16606         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16607         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16608                                    ExtraNumElems/2);
16609         SDValue Extra = DAG.getValueType(ExtraVT);
16610
16611         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16612         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16613
16614         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16615       }
16616       // fall through
16617     case MVT::v4i32:
16618     case MVT::v8i16: {
16619       SDValue Op0 = Op.getOperand(0);
16620
16621       // This is a sign extension of some low part of vector elements without
16622       // changing the size of the vector elements themselves:
16623       // Shift-Left + Shift-Right-Algebraic.
16624       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16625                                                BitsDiff, DAG);
16626       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16627                                         DAG);
16628     }
16629   }
16630 }
16631
16632 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16633                                  SelectionDAG &DAG) {
16634   SDLoc dl(Op);
16635   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16636     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16637   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16638     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16639
16640   // The only fence that needs an instruction is a sequentially-consistent
16641   // cross-thread fence.
16642   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16643     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16644     // no-sse2). There isn't any reason to disable it if the target processor
16645     // supports it.
16646     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16647       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16648
16649     SDValue Chain = Op.getOperand(0);
16650     SDValue Zero = DAG.getConstant(0, MVT::i32);
16651     SDValue Ops[] = {
16652       DAG.getRegister(X86::ESP, MVT::i32), // Base
16653       DAG.getTargetConstant(1, MVT::i8),   // Scale
16654       DAG.getRegister(0, MVT::i32),        // Index
16655       DAG.getTargetConstant(0, MVT::i32),  // Disp
16656       DAG.getRegister(0, MVT::i32),        // Segment.
16657       Zero,
16658       Chain
16659     };
16660     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16661     return SDValue(Res, 0);
16662   }
16663
16664   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16665   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16666 }
16667
16668 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16669                              SelectionDAG &DAG) {
16670   MVT T = Op.getSimpleValueType();
16671   SDLoc DL(Op);
16672   unsigned Reg = 0;
16673   unsigned size = 0;
16674   switch(T.SimpleTy) {
16675   default: llvm_unreachable("Invalid value type!");
16676   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16677   case MVT::i16: Reg = X86::AX;  size = 2; break;
16678   case MVT::i32: Reg = X86::EAX; size = 4; break;
16679   case MVT::i64:
16680     assert(Subtarget->is64Bit() && "Node not type legal!");
16681     Reg = X86::RAX; size = 8;
16682     break;
16683   }
16684   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16685                                   Op.getOperand(2), SDValue());
16686   SDValue Ops[] = { cpIn.getValue(0),
16687                     Op.getOperand(1),
16688                     Op.getOperand(3),
16689                     DAG.getTargetConstant(size, MVT::i8),
16690                     cpIn.getValue(1) };
16691   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16692   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16693   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16694                                            Ops, T, MMO);
16695
16696   SDValue cpOut =
16697     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16698   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16699                                       MVT::i32, cpOut.getValue(2));
16700   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16701                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16702
16703   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16704   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16705   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16706   return SDValue();
16707 }
16708
16709 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16710                             SelectionDAG &DAG) {
16711   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16712   MVT DstVT = Op.getSimpleValueType();
16713
16714   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16715     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16716     if (DstVT != MVT::f64)
16717       // This conversion needs to be expanded.
16718       return SDValue();
16719
16720     SDValue InVec = Op->getOperand(0);
16721     SDLoc dl(Op);
16722     unsigned NumElts = SrcVT.getVectorNumElements();
16723     EVT SVT = SrcVT.getVectorElementType();
16724
16725     // Widen the vector in input in the case of MVT::v2i32.
16726     // Example: from MVT::v2i32 to MVT::v4i32.
16727     SmallVector<SDValue, 16> Elts;
16728     for (unsigned i = 0, e = NumElts; i != e; ++i)
16729       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16730                                  DAG.getIntPtrConstant(i)));
16731
16732     // Explicitly mark the extra elements as Undef.
16733     SDValue Undef = DAG.getUNDEF(SVT);
16734     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16735       Elts.push_back(Undef);
16736
16737     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16738     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16739     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16740     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16741                        DAG.getIntPtrConstant(0));
16742   }
16743
16744   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16745          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16746   assert((DstVT == MVT::i64 ||
16747           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16748          "Unexpected custom BITCAST");
16749   // i64 <=> MMX conversions are Legal.
16750   if (SrcVT==MVT::i64 && DstVT.isVector())
16751     return Op;
16752   if (DstVT==MVT::i64 && SrcVT.isVector())
16753     return Op;
16754   // MMX <=> MMX conversions are Legal.
16755   if (SrcVT.isVector() && DstVT.isVector())
16756     return Op;
16757   // All other conversions need to be expanded.
16758   return SDValue();
16759 }
16760
16761 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16762   SDNode *Node = Op.getNode();
16763   SDLoc dl(Node);
16764   EVT T = Node->getValueType(0);
16765   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16766                               DAG.getConstant(0, T), Node->getOperand(2));
16767   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16768                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16769                        Node->getOperand(0),
16770                        Node->getOperand(1), negOp,
16771                        cast<AtomicSDNode>(Node)->getMemOperand(),
16772                        cast<AtomicSDNode>(Node)->getOrdering(),
16773                        cast<AtomicSDNode>(Node)->getSynchScope());
16774 }
16775
16776 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16777   SDNode *Node = Op.getNode();
16778   SDLoc dl(Node);
16779   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16780
16781   // Convert seq_cst store -> xchg
16782   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16783   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16784   //        (The only way to get a 16-byte store is cmpxchg16b)
16785   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16786   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16787       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16788     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16789                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16790                                  Node->getOperand(0),
16791                                  Node->getOperand(1), Node->getOperand(2),
16792                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16793                                  cast<AtomicSDNode>(Node)->getOrdering(),
16794                                  cast<AtomicSDNode>(Node)->getSynchScope());
16795     return Swap.getValue(1);
16796   }
16797   // Other atomic stores have a simple pattern.
16798   return Op;
16799 }
16800
16801 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16802   EVT VT = Op.getNode()->getSimpleValueType(0);
16803
16804   // Let legalize expand this if it isn't a legal type yet.
16805   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16806     return SDValue();
16807
16808   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16809
16810   unsigned Opc;
16811   bool ExtraOp = false;
16812   switch (Op.getOpcode()) {
16813   default: llvm_unreachable("Invalid code");
16814   case ISD::ADDC: Opc = X86ISD::ADD; break;
16815   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16816   case ISD::SUBC: Opc = X86ISD::SUB; break;
16817   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16818   }
16819
16820   if (!ExtraOp)
16821     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16822                        Op.getOperand(1));
16823   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16824                      Op.getOperand(1), Op.getOperand(2));
16825 }
16826
16827 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16828                             SelectionDAG &DAG) {
16829   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16830
16831   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16832   // which returns the values as { float, float } (in XMM0) or
16833   // { double, double } (which is returned in XMM0, XMM1).
16834   SDLoc dl(Op);
16835   SDValue Arg = Op.getOperand(0);
16836   EVT ArgVT = Arg.getValueType();
16837   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16838
16839   TargetLowering::ArgListTy Args;
16840   TargetLowering::ArgListEntry Entry;
16841
16842   Entry.Node = Arg;
16843   Entry.Ty = ArgTy;
16844   Entry.isSExt = false;
16845   Entry.isZExt = false;
16846   Args.push_back(Entry);
16847
16848   bool isF64 = ArgVT == MVT::f64;
16849   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16850   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16851   // the results are returned via SRet in memory.
16852   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16854   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16855
16856   Type *RetTy = isF64
16857     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16858     : (Type*)VectorType::get(ArgTy, 4);
16859
16860   TargetLowering::CallLoweringInfo CLI(DAG);
16861   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16862     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16863
16864   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16865
16866   if (isF64)
16867     // Returned in xmm0 and xmm1.
16868     return CallResult.first;
16869
16870   // Returned in bits 0:31 and 32:64 xmm0.
16871   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16872                                CallResult.first, DAG.getIntPtrConstant(0));
16873   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16874                                CallResult.first, DAG.getIntPtrConstant(1));
16875   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16876   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16877 }
16878
16879 /// LowerOperation - Provide custom lowering hooks for some operations.
16880 ///
16881 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16882   switch (Op.getOpcode()) {
16883   default: llvm_unreachable("Should not custom lower this!");
16884   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16885   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16886   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16887     return LowerCMP_SWAP(Op, Subtarget, DAG);
16888   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16889   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16890   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16891   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16892   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16893   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16894   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16895   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16896   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16897   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16898   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16899   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16900   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16901   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16902   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16903   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16904   case ISD::SHL_PARTS:
16905   case ISD::SRA_PARTS:
16906   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16907   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16908   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16909   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16910   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16911   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16912   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16913   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16914   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16915   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16916   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16917   case ISD::FABS:               return LowerFABS(Op, DAG);
16918   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16919   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16920   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16921   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16922   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16923   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16924   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16925   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16926   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16927   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16928   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16929   case ISD::INTRINSIC_VOID:
16930   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16931   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16932   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16933   case ISD::FRAME_TO_ARGS_OFFSET:
16934                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16935   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16936   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16937   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16938   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16939   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16940   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16941   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16942   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16943   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16944   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16945   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16946   case ISD::UMUL_LOHI:
16947   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16948   case ISD::SRA:
16949   case ISD::SRL:
16950   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16951   case ISD::SADDO:
16952   case ISD::UADDO:
16953   case ISD::SSUBO:
16954   case ISD::USUBO:
16955   case ISD::SMULO:
16956   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16957   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16958   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16959   case ISD::ADDC:
16960   case ISD::ADDE:
16961   case ISD::SUBC:
16962   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16963   case ISD::ADD:                return LowerADD(Op, DAG);
16964   case ISD::SUB:                return LowerSUB(Op, DAG);
16965   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16966   }
16967 }
16968
16969 static void ReplaceATOMIC_LOAD(SDNode *Node,
16970                                SmallVectorImpl<SDValue> &Results,
16971                                SelectionDAG &DAG) {
16972   SDLoc dl(Node);
16973   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16974
16975   // Convert wide load -> cmpxchg8b/cmpxchg16b
16976   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16977   //        (The only way to get a 16-byte load is cmpxchg16b)
16978   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16979   SDValue Zero = DAG.getConstant(0, VT);
16980   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16981   SDValue Swap =
16982       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16983                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16984                            cast<AtomicSDNode>(Node)->getMemOperand(),
16985                            cast<AtomicSDNode>(Node)->getOrdering(),
16986                            cast<AtomicSDNode>(Node)->getOrdering(),
16987                            cast<AtomicSDNode>(Node)->getSynchScope());
16988   Results.push_back(Swap.getValue(0));
16989   Results.push_back(Swap.getValue(2));
16990 }
16991
16992 /// ReplaceNodeResults - Replace a node with an illegal result type
16993 /// with a new node built out of custom code.
16994 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16995                                            SmallVectorImpl<SDValue>&Results,
16996                                            SelectionDAG &DAG) const {
16997   SDLoc dl(N);
16998   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16999   switch (N->getOpcode()) {
17000   default:
17001     llvm_unreachable("Do not know how to custom type legalize this operation!");
17002   case ISD::SIGN_EXTEND_INREG:
17003   case ISD::ADDC:
17004   case ISD::ADDE:
17005   case ISD::SUBC:
17006   case ISD::SUBE:
17007     // We don't want to expand or promote these.
17008     return;
17009   case ISD::SDIV:
17010   case ISD::UDIV:
17011   case ISD::SREM:
17012   case ISD::UREM:
17013   case ISD::SDIVREM:
17014   case ISD::UDIVREM: {
17015     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17016     Results.push_back(V);
17017     return;
17018   }
17019   case ISD::FP_TO_SINT:
17020   case ISD::FP_TO_UINT: {
17021     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17022
17023     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17024       return;
17025
17026     std::pair<SDValue,SDValue> Vals =
17027         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17028     SDValue FIST = Vals.first, StackSlot = Vals.second;
17029     if (FIST.getNode()) {
17030       EVT VT = N->getValueType(0);
17031       // Return a load from the stack slot.
17032       if (StackSlot.getNode())
17033         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17034                                       MachinePointerInfo(),
17035                                       false, false, false, 0));
17036       else
17037         Results.push_back(FIST);
17038     }
17039     return;
17040   }
17041   case ISD::UINT_TO_FP: {
17042     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17043     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17044         N->getValueType(0) != MVT::v2f32)
17045       return;
17046     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17047                                  N->getOperand(0));
17048     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17049                                      MVT::f64);
17050     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17051     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17052                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17053     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17054     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17055     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17056     return;
17057   }
17058   case ISD::FP_ROUND: {
17059     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17060         return;
17061     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17062     Results.push_back(V);
17063     return;
17064   }
17065   case ISD::INTRINSIC_W_CHAIN: {
17066     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17067     switch (IntNo) {
17068     default : llvm_unreachable("Do not know how to custom type "
17069                                "legalize this intrinsic operation!");
17070     case Intrinsic::x86_rdtsc:
17071       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17072                                      Results);
17073     case Intrinsic::x86_rdtscp:
17074       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17075                                      Results);
17076     case Intrinsic::x86_rdpmc:
17077       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17078     }
17079   }
17080   case ISD::READCYCLECOUNTER: {
17081     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17082                                    Results);
17083   }
17084   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17085     EVT T = N->getValueType(0);
17086     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17087     bool Regs64bit = T == MVT::i128;
17088     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17089     SDValue cpInL, cpInH;
17090     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17091                         DAG.getConstant(0, HalfT));
17092     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17093                         DAG.getConstant(1, HalfT));
17094     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17095                              Regs64bit ? X86::RAX : X86::EAX,
17096                              cpInL, SDValue());
17097     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17098                              Regs64bit ? X86::RDX : X86::EDX,
17099                              cpInH, cpInL.getValue(1));
17100     SDValue swapInL, swapInH;
17101     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17102                           DAG.getConstant(0, HalfT));
17103     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17104                           DAG.getConstant(1, HalfT));
17105     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17106                                Regs64bit ? X86::RBX : X86::EBX,
17107                                swapInL, cpInH.getValue(1));
17108     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17109                                Regs64bit ? X86::RCX : X86::ECX,
17110                                swapInH, swapInL.getValue(1));
17111     SDValue Ops[] = { swapInH.getValue(0),
17112                       N->getOperand(1),
17113                       swapInH.getValue(1) };
17114     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17115     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17116     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17117                                   X86ISD::LCMPXCHG8_DAG;
17118     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17119     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17120                                         Regs64bit ? X86::RAX : X86::EAX,
17121                                         HalfT, Result.getValue(1));
17122     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17123                                         Regs64bit ? X86::RDX : X86::EDX,
17124                                         HalfT, cpOutL.getValue(2));
17125     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17126
17127     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17128                                         MVT::i32, cpOutH.getValue(2));
17129     SDValue Success =
17130         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17131                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17132     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17133
17134     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17135     Results.push_back(Success);
17136     Results.push_back(EFLAGS.getValue(1));
17137     return;
17138   }
17139   case ISD::ATOMIC_SWAP:
17140   case ISD::ATOMIC_LOAD_ADD:
17141   case ISD::ATOMIC_LOAD_SUB:
17142   case ISD::ATOMIC_LOAD_AND:
17143   case ISD::ATOMIC_LOAD_OR:
17144   case ISD::ATOMIC_LOAD_XOR:
17145   case ISD::ATOMIC_LOAD_NAND:
17146   case ISD::ATOMIC_LOAD_MIN:
17147   case ISD::ATOMIC_LOAD_MAX:
17148   case ISD::ATOMIC_LOAD_UMIN:
17149   case ISD::ATOMIC_LOAD_UMAX:
17150     // Delegate to generic TypeLegalization. Situations we can really handle
17151     // should have already been dealt with by X86AtomicExpandPass.cpp.
17152     break;
17153   case ISD::ATOMIC_LOAD: {
17154     ReplaceATOMIC_LOAD(N, Results, DAG);
17155     return;
17156   }
17157   case ISD::BITCAST: {
17158     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17159     EVT DstVT = N->getValueType(0);
17160     EVT SrcVT = N->getOperand(0)->getValueType(0);
17161
17162     if (SrcVT != MVT::f64 ||
17163         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17164       return;
17165
17166     unsigned NumElts = DstVT.getVectorNumElements();
17167     EVT SVT = DstVT.getVectorElementType();
17168     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17169     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17170                                    MVT::v2f64, N->getOperand(0));
17171     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17172
17173     if (ExperimentalVectorWideningLegalization) {
17174       // If we are legalizing vectors by widening, we already have the desired
17175       // legal vector type, just return it.
17176       Results.push_back(ToVecInt);
17177       return;
17178     }
17179
17180     SmallVector<SDValue, 8> Elts;
17181     for (unsigned i = 0, e = NumElts; i != e; ++i)
17182       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17183                                    ToVecInt, DAG.getIntPtrConstant(i)));
17184
17185     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17186   }
17187   }
17188 }
17189
17190 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17191   switch (Opcode) {
17192   default: return nullptr;
17193   case X86ISD::BSF:                return "X86ISD::BSF";
17194   case X86ISD::BSR:                return "X86ISD::BSR";
17195   case X86ISD::SHLD:               return "X86ISD::SHLD";
17196   case X86ISD::SHRD:               return "X86ISD::SHRD";
17197   case X86ISD::FAND:               return "X86ISD::FAND";
17198   case X86ISD::FANDN:              return "X86ISD::FANDN";
17199   case X86ISD::FOR:                return "X86ISD::FOR";
17200   case X86ISD::FXOR:               return "X86ISD::FXOR";
17201   case X86ISD::FSRL:               return "X86ISD::FSRL";
17202   case X86ISD::FILD:               return "X86ISD::FILD";
17203   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17204   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17205   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17206   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17207   case X86ISD::FLD:                return "X86ISD::FLD";
17208   case X86ISD::FST:                return "X86ISD::FST";
17209   case X86ISD::CALL:               return "X86ISD::CALL";
17210   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17211   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17212   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17213   case X86ISD::BT:                 return "X86ISD::BT";
17214   case X86ISD::CMP:                return "X86ISD::CMP";
17215   case X86ISD::COMI:               return "X86ISD::COMI";
17216   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17217   case X86ISD::CMPM:               return "X86ISD::CMPM";
17218   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17219   case X86ISD::SETCC:              return "X86ISD::SETCC";
17220   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17221   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17222   case X86ISD::CMOV:               return "X86ISD::CMOV";
17223   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17224   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17225   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17226   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17227   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17228   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17229   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17230   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17231   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17232   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17233   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17234   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17235   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17236   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17237   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17238   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17239   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17240   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17241   case X86ISD::HADD:               return "X86ISD::HADD";
17242   case X86ISD::HSUB:               return "X86ISD::HSUB";
17243   case X86ISD::FHADD:              return "X86ISD::FHADD";
17244   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17245   case X86ISD::UMAX:               return "X86ISD::UMAX";
17246   case X86ISD::UMIN:               return "X86ISD::UMIN";
17247   case X86ISD::SMAX:               return "X86ISD::SMAX";
17248   case X86ISD::SMIN:               return "X86ISD::SMIN";
17249   case X86ISD::FMAX:               return "X86ISD::FMAX";
17250   case X86ISD::FMIN:               return "X86ISD::FMIN";
17251   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17252   case X86ISD::FMINC:              return "X86ISD::FMINC";
17253   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17254   case X86ISD::FRCP:               return "X86ISD::FRCP";
17255   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17256   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17257   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17258   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17259   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17260   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17261   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17262   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17263   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17264   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17265   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17266   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17267   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17268   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17269   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17270   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17271   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17272   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17273   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17274   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17275   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17276   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17277   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17278   case X86ISD::VSHL:               return "X86ISD::VSHL";
17279   case X86ISD::VSRL:               return "X86ISD::VSRL";
17280   case X86ISD::VSRA:               return "X86ISD::VSRA";
17281   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17282   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17283   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17284   case X86ISD::CMPP:               return "X86ISD::CMPP";
17285   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17286   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17287   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17288   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17289   case X86ISD::ADD:                return "X86ISD::ADD";
17290   case X86ISD::SUB:                return "X86ISD::SUB";
17291   case X86ISD::ADC:                return "X86ISD::ADC";
17292   case X86ISD::SBB:                return "X86ISD::SBB";
17293   case X86ISD::SMUL:               return "X86ISD::SMUL";
17294   case X86ISD::UMUL:               return "X86ISD::UMUL";
17295   case X86ISD::INC:                return "X86ISD::INC";
17296   case X86ISD::DEC:                return "X86ISD::DEC";
17297   case X86ISD::OR:                 return "X86ISD::OR";
17298   case X86ISD::XOR:                return "X86ISD::XOR";
17299   case X86ISD::AND:                return "X86ISD::AND";
17300   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17301   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17302   case X86ISD::PTEST:              return "X86ISD::PTEST";
17303   case X86ISD::TESTP:              return "X86ISD::TESTP";
17304   case X86ISD::TESTM:              return "X86ISD::TESTM";
17305   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17306   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17307   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17308   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17309   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17310   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17311   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17312   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17313   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17314   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17315   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17316   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17317   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17318   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17319   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17320   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17321   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17322   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17323   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17324   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17325   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17326   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17327   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17328   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17329   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17330   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17331   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17332   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17333   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17334   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17335   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17336   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17337   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17338   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17339   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17340   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17341   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17342   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17343   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17344   case X86ISD::SAHF:               return "X86ISD::SAHF";
17345   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17346   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17347   case X86ISD::FMADD:              return "X86ISD::FMADD";
17348   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17349   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17350   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17351   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17352   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17353   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17354   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17355   case X86ISD::XTEST:              return "X86ISD::XTEST";
17356   }
17357 }
17358
17359 // isLegalAddressingMode - Return true if the addressing mode represented
17360 // by AM is legal for this target, for a load/store of the specified type.
17361 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17362                                               Type *Ty) const {
17363   // X86 supports extremely general addressing modes.
17364   CodeModel::Model M = getTargetMachine().getCodeModel();
17365   Reloc::Model R = getTargetMachine().getRelocationModel();
17366
17367   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17368   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17369     return false;
17370
17371   if (AM.BaseGV) {
17372     unsigned GVFlags =
17373       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17374
17375     // If a reference to this global requires an extra load, we can't fold it.
17376     if (isGlobalStubReference(GVFlags))
17377       return false;
17378
17379     // If BaseGV requires a register for the PIC base, we cannot also have a
17380     // BaseReg specified.
17381     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17382       return false;
17383
17384     // If lower 4G is not available, then we must use rip-relative addressing.
17385     if ((M != CodeModel::Small || R != Reloc::Static) &&
17386         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17387       return false;
17388   }
17389
17390   switch (AM.Scale) {
17391   case 0:
17392   case 1:
17393   case 2:
17394   case 4:
17395   case 8:
17396     // These scales always work.
17397     break;
17398   case 3:
17399   case 5:
17400   case 9:
17401     // These scales are formed with basereg+scalereg.  Only accept if there is
17402     // no basereg yet.
17403     if (AM.HasBaseReg)
17404       return false;
17405     break;
17406   default:  // Other stuff never works.
17407     return false;
17408   }
17409
17410   return true;
17411 }
17412
17413 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17414   unsigned Bits = Ty->getScalarSizeInBits();
17415
17416   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17417   // particularly cheaper than those without.
17418   if (Bits == 8)
17419     return false;
17420
17421   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17422   // variable shifts just as cheap as scalar ones.
17423   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17424     return false;
17425
17426   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17427   // fully general vector.
17428   return true;
17429 }
17430
17431 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17432   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17433     return false;
17434   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17435   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17436   return NumBits1 > NumBits2;
17437 }
17438
17439 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17440   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17441     return false;
17442
17443   if (!isTypeLegal(EVT::getEVT(Ty1)))
17444     return false;
17445
17446   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17447
17448   // Assuming the caller doesn't have a zeroext or signext return parameter,
17449   // truncation all the way down to i1 is valid.
17450   return true;
17451 }
17452
17453 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17454   return isInt<32>(Imm);
17455 }
17456
17457 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17458   // Can also use sub to handle negated immediates.
17459   return isInt<32>(Imm);
17460 }
17461
17462 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17463   if (!VT1.isInteger() || !VT2.isInteger())
17464     return false;
17465   unsigned NumBits1 = VT1.getSizeInBits();
17466   unsigned NumBits2 = VT2.getSizeInBits();
17467   return NumBits1 > NumBits2;
17468 }
17469
17470 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17471   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17472   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17473 }
17474
17475 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17476   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17477   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17478 }
17479
17480 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17481   EVT VT1 = Val.getValueType();
17482   if (isZExtFree(VT1, VT2))
17483     return true;
17484
17485   if (Val.getOpcode() != ISD::LOAD)
17486     return false;
17487
17488   if (!VT1.isSimple() || !VT1.isInteger() ||
17489       !VT2.isSimple() || !VT2.isInteger())
17490     return false;
17491
17492   switch (VT1.getSimpleVT().SimpleTy) {
17493   default: break;
17494   case MVT::i8:
17495   case MVT::i16:
17496   case MVT::i32:
17497     // X86 has 8, 16, and 32-bit zero-extending loads.
17498     return true;
17499   }
17500
17501   return false;
17502 }
17503
17504 bool
17505 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17506   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17507     return false;
17508
17509   VT = VT.getScalarType();
17510
17511   if (!VT.isSimple())
17512     return false;
17513
17514   switch (VT.getSimpleVT().SimpleTy) {
17515   case MVT::f32:
17516   case MVT::f64:
17517     return true;
17518   default:
17519     break;
17520   }
17521
17522   return false;
17523 }
17524
17525 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17526   // i16 instructions are longer (0x66 prefix) and potentially slower.
17527   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17528 }
17529
17530 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17531 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17532 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17533 /// are assumed to be legal.
17534 bool
17535 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17536                                       EVT VT) const {
17537   if (!VT.isSimple())
17538     return false;
17539
17540   MVT SVT = VT.getSimpleVT();
17541
17542   // Very little shuffling can be done for 64-bit vectors right now.
17543   if (VT.getSizeInBits() == 64)
17544     return false;
17545
17546   // If this is a single-input shuffle with no 128 bit lane crossings we can
17547   // lower it into pshufb.
17548   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17549       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17550     bool isLegal = true;
17551     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17552       if (M[I] >= (int)SVT.getVectorNumElements() ||
17553           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17554         isLegal = false;
17555         break;
17556       }
17557     }
17558     if (isLegal)
17559       return true;
17560   }
17561
17562   // FIXME: blends, shifts.
17563   return (SVT.getVectorNumElements() == 2 ||
17564           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17565           isMOVLMask(M, SVT) ||
17566           isMOVHLPSMask(M, SVT) ||
17567           isSHUFPMask(M, SVT) ||
17568           isPSHUFDMask(M, SVT) ||
17569           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17570           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17571           isPALIGNRMask(M, SVT, Subtarget) ||
17572           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17573           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17574           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17575           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17576           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17577 }
17578
17579 bool
17580 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17581                                           EVT VT) const {
17582   if (!VT.isSimple())
17583     return false;
17584
17585   MVT SVT = VT.getSimpleVT();
17586   unsigned NumElts = SVT.getVectorNumElements();
17587   // FIXME: This collection of masks seems suspect.
17588   if (NumElts == 2)
17589     return true;
17590   if (NumElts == 4 && SVT.is128BitVector()) {
17591     return (isMOVLMask(Mask, SVT)  ||
17592             isCommutedMOVLMask(Mask, SVT, true) ||
17593             isSHUFPMask(Mask, SVT) ||
17594             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17595   }
17596   return false;
17597 }
17598
17599 //===----------------------------------------------------------------------===//
17600 //                           X86 Scheduler Hooks
17601 //===----------------------------------------------------------------------===//
17602
17603 /// Utility function to emit xbegin specifying the start of an RTM region.
17604 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17605                                      const TargetInstrInfo *TII) {
17606   DebugLoc DL = MI->getDebugLoc();
17607
17608   const BasicBlock *BB = MBB->getBasicBlock();
17609   MachineFunction::iterator I = MBB;
17610   ++I;
17611
17612   // For the v = xbegin(), we generate
17613   //
17614   // thisMBB:
17615   //  xbegin sinkMBB
17616   //
17617   // mainMBB:
17618   //  eax = -1
17619   //
17620   // sinkMBB:
17621   //  v = eax
17622
17623   MachineBasicBlock *thisMBB = MBB;
17624   MachineFunction *MF = MBB->getParent();
17625   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17626   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17627   MF->insert(I, mainMBB);
17628   MF->insert(I, sinkMBB);
17629
17630   // Transfer the remainder of BB and its successor edges to sinkMBB.
17631   sinkMBB->splice(sinkMBB->begin(), MBB,
17632                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17633   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17634
17635   // thisMBB:
17636   //  xbegin sinkMBB
17637   //  # fallthrough to mainMBB
17638   //  # abortion to sinkMBB
17639   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17640   thisMBB->addSuccessor(mainMBB);
17641   thisMBB->addSuccessor(sinkMBB);
17642
17643   // mainMBB:
17644   //  EAX = -1
17645   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17646   mainMBB->addSuccessor(sinkMBB);
17647
17648   // sinkMBB:
17649   // EAX is live into the sinkMBB
17650   sinkMBB->addLiveIn(X86::EAX);
17651   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17652           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17653     .addReg(X86::EAX);
17654
17655   MI->eraseFromParent();
17656   return sinkMBB;
17657 }
17658
17659 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17660 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17661 // in the .td file.
17662 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17663                                        const TargetInstrInfo *TII) {
17664   unsigned Opc;
17665   switch (MI->getOpcode()) {
17666   default: llvm_unreachable("illegal opcode!");
17667   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17668   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17669   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17670   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17671   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17672   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17673   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17674   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17675   }
17676
17677   DebugLoc dl = MI->getDebugLoc();
17678   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17679
17680   unsigned NumArgs = MI->getNumOperands();
17681   for (unsigned i = 1; i < NumArgs; ++i) {
17682     MachineOperand &Op = MI->getOperand(i);
17683     if (!(Op.isReg() && Op.isImplicit()))
17684       MIB.addOperand(Op);
17685   }
17686   if (MI->hasOneMemOperand())
17687     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17688
17689   BuildMI(*BB, MI, dl,
17690     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17691     .addReg(X86::XMM0);
17692
17693   MI->eraseFromParent();
17694   return BB;
17695 }
17696
17697 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17698 // defs in an instruction pattern
17699 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17700                                        const TargetInstrInfo *TII) {
17701   unsigned Opc;
17702   switch (MI->getOpcode()) {
17703   default: llvm_unreachable("illegal opcode!");
17704   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17705   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17706   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17707   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17708   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17709   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17710   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17711   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17712   }
17713
17714   DebugLoc dl = MI->getDebugLoc();
17715   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17716
17717   unsigned NumArgs = MI->getNumOperands(); // remove the results
17718   for (unsigned i = 1; i < NumArgs; ++i) {
17719     MachineOperand &Op = MI->getOperand(i);
17720     if (!(Op.isReg() && Op.isImplicit()))
17721       MIB.addOperand(Op);
17722   }
17723   if (MI->hasOneMemOperand())
17724     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17725
17726   BuildMI(*BB, MI, dl,
17727     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17728     .addReg(X86::ECX);
17729
17730   MI->eraseFromParent();
17731   return BB;
17732 }
17733
17734 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17735                                        const TargetInstrInfo *TII,
17736                                        const X86Subtarget* Subtarget) {
17737   DebugLoc dl = MI->getDebugLoc();
17738
17739   // Address into RAX/EAX, other two args into ECX, EDX.
17740   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17741   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17742   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17743   for (int i = 0; i < X86::AddrNumOperands; ++i)
17744     MIB.addOperand(MI->getOperand(i));
17745
17746   unsigned ValOps = X86::AddrNumOperands;
17747   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17748     .addReg(MI->getOperand(ValOps).getReg());
17749   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17750     .addReg(MI->getOperand(ValOps+1).getReg());
17751
17752   // The instruction doesn't actually take any operands though.
17753   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17754
17755   MI->eraseFromParent(); // The pseudo is gone now.
17756   return BB;
17757 }
17758
17759 MachineBasicBlock *
17760 X86TargetLowering::EmitVAARG64WithCustomInserter(
17761                    MachineInstr *MI,
17762                    MachineBasicBlock *MBB) const {
17763   // Emit va_arg instruction on X86-64.
17764
17765   // Operands to this pseudo-instruction:
17766   // 0  ) Output        : destination address (reg)
17767   // 1-5) Input         : va_list address (addr, i64mem)
17768   // 6  ) ArgSize       : Size (in bytes) of vararg type
17769   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17770   // 8  ) Align         : Alignment of type
17771   // 9  ) EFLAGS (implicit-def)
17772
17773   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17774   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17775
17776   unsigned DestReg = MI->getOperand(0).getReg();
17777   MachineOperand &Base = MI->getOperand(1);
17778   MachineOperand &Scale = MI->getOperand(2);
17779   MachineOperand &Index = MI->getOperand(3);
17780   MachineOperand &Disp = MI->getOperand(4);
17781   MachineOperand &Segment = MI->getOperand(5);
17782   unsigned ArgSize = MI->getOperand(6).getImm();
17783   unsigned ArgMode = MI->getOperand(7).getImm();
17784   unsigned Align = MI->getOperand(8).getImm();
17785
17786   // Memory Reference
17787   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17788   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17789   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17790
17791   // Machine Information
17792   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17793   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17794   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17795   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17796   DebugLoc DL = MI->getDebugLoc();
17797
17798   // struct va_list {
17799   //   i32   gp_offset
17800   //   i32   fp_offset
17801   //   i64   overflow_area (address)
17802   //   i64   reg_save_area (address)
17803   // }
17804   // sizeof(va_list) = 24
17805   // alignment(va_list) = 8
17806
17807   unsigned TotalNumIntRegs = 6;
17808   unsigned TotalNumXMMRegs = 8;
17809   bool UseGPOffset = (ArgMode == 1);
17810   bool UseFPOffset = (ArgMode == 2);
17811   unsigned MaxOffset = TotalNumIntRegs * 8 +
17812                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17813
17814   /* Align ArgSize to a multiple of 8 */
17815   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17816   bool NeedsAlign = (Align > 8);
17817
17818   MachineBasicBlock *thisMBB = MBB;
17819   MachineBasicBlock *overflowMBB;
17820   MachineBasicBlock *offsetMBB;
17821   MachineBasicBlock *endMBB;
17822
17823   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17824   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17825   unsigned OffsetReg = 0;
17826
17827   if (!UseGPOffset && !UseFPOffset) {
17828     // If we only pull from the overflow region, we don't create a branch.
17829     // We don't need to alter control flow.
17830     OffsetDestReg = 0; // unused
17831     OverflowDestReg = DestReg;
17832
17833     offsetMBB = nullptr;
17834     overflowMBB = thisMBB;
17835     endMBB = thisMBB;
17836   } else {
17837     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17838     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17839     // If not, pull from overflow_area. (branch to overflowMBB)
17840     //
17841     //       thisMBB
17842     //         |     .
17843     //         |        .
17844     //     offsetMBB   overflowMBB
17845     //         |        .
17846     //         |     .
17847     //        endMBB
17848
17849     // Registers for the PHI in endMBB
17850     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17851     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17852
17853     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17854     MachineFunction *MF = MBB->getParent();
17855     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17856     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17857     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17858
17859     MachineFunction::iterator MBBIter = MBB;
17860     ++MBBIter;
17861
17862     // Insert the new basic blocks
17863     MF->insert(MBBIter, offsetMBB);
17864     MF->insert(MBBIter, overflowMBB);
17865     MF->insert(MBBIter, endMBB);
17866
17867     // Transfer the remainder of MBB and its successor edges to endMBB.
17868     endMBB->splice(endMBB->begin(), thisMBB,
17869                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17870     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17871
17872     // Make offsetMBB and overflowMBB successors of thisMBB
17873     thisMBB->addSuccessor(offsetMBB);
17874     thisMBB->addSuccessor(overflowMBB);
17875
17876     // endMBB is a successor of both offsetMBB and overflowMBB
17877     offsetMBB->addSuccessor(endMBB);
17878     overflowMBB->addSuccessor(endMBB);
17879
17880     // Load the offset value into a register
17881     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17882     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17883       .addOperand(Base)
17884       .addOperand(Scale)
17885       .addOperand(Index)
17886       .addDisp(Disp, UseFPOffset ? 4 : 0)
17887       .addOperand(Segment)
17888       .setMemRefs(MMOBegin, MMOEnd);
17889
17890     // Check if there is enough room left to pull this argument.
17891     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17892       .addReg(OffsetReg)
17893       .addImm(MaxOffset + 8 - ArgSizeA8);
17894
17895     // Branch to "overflowMBB" if offset >= max
17896     // Fall through to "offsetMBB" otherwise
17897     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17898       .addMBB(overflowMBB);
17899   }
17900
17901   // In offsetMBB, emit code to use the reg_save_area.
17902   if (offsetMBB) {
17903     assert(OffsetReg != 0);
17904
17905     // Read the reg_save_area address.
17906     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17907     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17908       .addOperand(Base)
17909       .addOperand(Scale)
17910       .addOperand(Index)
17911       .addDisp(Disp, 16)
17912       .addOperand(Segment)
17913       .setMemRefs(MMOBegin, MMOEnd);
17914
17915     // Zero-extend the offset
17916     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17917       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17918         .addImm(0)
17919         .addReg(OffsetReg)
17920         .addImm(X86::sub_32bit);
17921
17922     // Add the offset to the reg_save_area to get the final address.
17923     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17924       .addReg(OffsetReg64)
17925       .addReg(RegSaveReg);
17926
17927     // Compute the offset for the next argument
17928     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17929     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17930       .addReg(OffsetReg)
17931       .addImm(UseFPOffset ? 16 : 8);
17932
17933     // Store it back into the va_list.
17934     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17935       .addOperand(Base)
17936       .addOperand(Scale)
17937       .addOperand(Index)
17938       .addDisp(Disp, UseFPOffset ? 4 : 0)
17939       .addOperand(Segment)
17940       .addReg(NextOffsetReg)
17941       .setMemRefs(MMOBegin, MMOEnd);
17942
17943     // Jump to endMBB
17944     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17945       .addMBB(endMBB);
17946   }
17947
17948   //
17949   // Emit code to use overflow area
17950   //
17951
17952   // Load the overflow_area address into a register.
17953   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17954   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17955     .addOperand(Base)
17956     .addOperand(Scale)
17957     .addOperand(Index)
17958     .addDisp(Disp, 8)
17959     .addOperand(Segment)
17960     .setMemRefs(MMOBegin, MMOEnd);
17961
17962   // If we need to align it, do so. Otherwise, just copy the address
17963   // to OverflowDestReg.
17964   if (NeedsAlign) {
17965     // Align the overflow address
17966     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17967     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17968
17969     // aligned_addr = (addr + (align-1)) & ~(align-1)
17970     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17971       .addReg(OverflowAddrReg)
17972       .addImm(Align-1);
17973
17974     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17975       .addReg(TmpReg)
17976       .addImm(~(uint64_t)(Align-1));
17977   } else {
17978     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17979       .addReg(OverflowAddrReg);
17980   }
17981
17982   // Compute the next overflow address after this argument.
17983   // (the overflow address should be kept 8-byte aligned)
17984   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17985   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17986     .addReg(OverflowDestReg)
17987     .addImm(ArgSizeA8);
17988
17989   // Store the new overflow address.
17990   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17991     .addOperand(Base)
17992     .addOperand(Scale)
17993     .addOperand(Index)
17994     .addDisp(Disp, 8)
17995     .addOperand(Segment)
17996     .addReg(NextAddrReg)
17997     .setMemRefs(MMOBegin, MMOEnd);
17998
17999   // If we branched, emit the PHI to the front of endMBB.
18000   if (offsetMBB) {
18001     BuildMI(*endMBB, endMBB->begin(), DL,
18002             TII->get(X86::PHI), DestReg)
18003       .addReg(OffsetDestReg).addMBB(offsetMBB)
18004       .addReg(OverflowDestReg).addMBB(overflowMBB);
18005   }
18006
18007   // Erase the pseudo instruction
18008   MI->eraseFromParent();
18009
18010   return endMBB;
18011 }
18012
18013 MachineBasicBlock *
18014 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18015                                                  MachineInstr *MI,
18016                                                  MachineBasicBlock *MBB) const {
18017   // Emit code to save XMM registers to the stack. The ABI says that the
18018   // number of registers to save is given in %al, so it's theoretically
18019   // possible to do an indirect jump trick to avoid saving all of them,
18020   // however this code takes a simpler approach and just executes all
18021   // of the stores if %al is non-zero. It's less code, and it's probably
18022   // easier on the hardware branch predictor, and stores aren't all that
18023   // expensive anyway.
18024
18025   // Create the new basic blocks. One block contains all the XMM stores,
18026   // and one block is the final destination regardless of whether any
18027   // stores were performed.
18028   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18029   MachineFunction *F = MBB->getParent();
18030   MachineFunction::iterator MBBIter = MBB;
18031   ++MBBIter;
18032   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18033   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18034   F->insert(MBBIter, XMMSaveMBB);
18035   F->insert(MBBIter, EndMBB);
18036
18037   // Transfer the remainder of MBB and its successor edges to EndMBB.
18038   EndMBB->splice(EndMBB->begin(), MBB,
18039                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18040   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18041
18042   // The original block will now fall through to the XMM save block.
18043   MBB->addSuccessor(XMMSaveMBB);
18044   // The XMMSaveMBB will fall through to the end block.
18045   XMMSaveMBB->addSuccessor(EndMBB);
18046
18047   // Now add the instructions.
18048   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18049   DebugLoc DL = MI->getDebugLoc();
18050
18051   unsigned CountReg = MI->getOperand(0).getReg();
18052   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18053   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18054
18055   if (!Subtarget->isTargetWin64()) {
18056     // If %al is 0, branch around the XMM save block.
18057     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18058     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18059     MBB->addSuccessor(EndMBB);
18060   }
18061
18062   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18063   // that was just emitted, but clearly shouldn't be "saved".
18064   assert((MI->getNumOperands() <= 3 ||
18065           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18066           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18067          && "Expected last argument to be EFLAGS");
18068   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18069   // In the XMM save block, save all the XMM argument registers.
18070   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18071     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18072     MachineMemOperand *MMO =
18073       F->getMachineMemOperand(
18074           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18075         MachineMemOperand::MOStore,
18076         /*Size=*/16, /*Align=*/16);
18077     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18078       .addFrameIndex(RegSaveFrameIndex)
18079       .addImm(/*Scale=*/1)
18080       .addReg(/*IndexReg=*/0)
18081       .addImm(/*Disp=*/Offset)
18082       .addReg(/*Segment=*/0)
18083       .addReg(MI->getOperand(i).getReg())
18084       .addMemOperand(MMO);
18085   }
18086
18087   MI->eraseFromParent();   // The pseudo instruction is gone now.
18088
18089   return EndMBB;
18090 }
18091
18092 // The EFLAGS operand of SelectItr might be missing a kill marker
18093 // because there were multiple uses of EFLAGS, and ISel didn't know
18094 // which to mark. Figure out whether SelectItr should have had a
18095 // kill marker, and set it if it should. Returns the correct kill
18096 // marker value.
18097 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18098                                      MachineBasicBlock* BB,
18099                                      const TargetRegisterInfo* TRI) {
18100   // Scan forward through BB for a use/def of EFLAGS.
18101   MachineBasicBlock::iterator miI(std::next(SelectItr));
18102   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18103     const MachineInstr& mi = *miI;
18104     if (mi.readsRegister(X86::EFLAGS))
18105       return false;
18106     if (mi.definesRegister(X86::EFLAGS))
18107       break; // Should have kill-flag - update below.
18108   }
18109
18110   // If we hit the end of the block, check whether EFLAGS is live into a
18111   // successor.
18112   if (miI == BB->end()) {
18113     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18114                                           sEnd = BB->succ_end();
18115          sItr != sEnd; ++sItr) {
18116       MachineBasicBlock* succ = *sItr;
18117       if (succ->isLiveIn(X86::EFLAGS))
18118         return false;
18119     }
18120   }
18121
18122   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18123   // out. SelectMI should have a kill flag on EFLAGS.
18124   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18125   return true;
18126 }
18127
18128 MachineBasicBlock *
18129 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18130                                      MachineBasicBlock *BB) const {
18131   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18132   DebugLoc DL = MI->getDebugLoc();
18133
18134   // To "insert" a SELECT_CC instruction, we actually have to insert the
18135   // diamond control-flow pattern.  The incoming instruction knows the
18136   // destination vreg to set, the condition code register to branch on, the
18137   // true/false values to select between, and a branch opcode to use.
18138   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18139   MachineFunction::iterator It = BB;
18140   ++It;
18141
18142   //  thisMBB:
18143   //  ...
18144   //   TrueVal = ...
18145   //   cmpTY ccX, r1, r2
18146   //   bCC copy1MBB
18147   //   fallthrough --> copy0MBB
18148   MachineBasicBlock *thisMBB = BB;
18149   MachineFunction *F = BB->getParent();
18150   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18151   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18152   F->insert(It, copy0MBB);
18153   F->insert(It, sinkMBB);
18154
18155   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18156   // live into the sink and copy blocks.
18157   const TargetRegisterInfo *TRI =
18158       BB->getParent()->getSubtarget().getRegisterInfo();
18159   if (!MI->killsRegister(X86::EFLAGS) &&
18160       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18161     copy0MBB->addLiveIn(X86::EFLAGS);
18162     sinkMBB->addLiveIn(X86::EFLAGS);
18163   }
18164
18165   // Transfer the remainder of BB and its successor edges to sinkMBB.
18166   sinkMBB->splice(sinkMBB->begin(), BB,
18167                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18168   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18169
18170   // Add the true and fallthrough blocks as its successors.
18171   BB->addSuccessor(copy0MBB);
18172   BB->addSuccessor(sinkMBB);
18173
18174   // Create the conditional branch instruction.
18175   unsigned Opc =
18176     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18177   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18178
18179   //  copy0MBB:
18180   //   %FalseValue = ...
18181   //   # fallthrough to sinkMBB
18182   copy0MBB->addSuccessor(sinkMBB);
18183
18184   //  sinkMBB:
18185   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18186   //  ...
18187   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18188           TII->get(X86::PHI), MI->getOperand(0).getReg())
18189     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18190     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18191
18192   MI->eraseFromParent();   // The pseudo instruction is gone now.
18193   return sinkMBB;
18194 }
18195
18196 MachineBasicBlock *
18197 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18198                                         bool Is64Bit) const {
18199   MachineFunction *MF = BB->getParent();
18200   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18201   DebugLoc DL = MI->getDebugLoc();
18202   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18203
18204   assert(MF->shouldSplitStack());
18205
18206   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18207   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18208
18209   // BB:
18210   //  ... [Till the alloca]
18211   // If stacklet is not large enough, jump to mallocMBB
18212   //
18213   // bumpMBB:
18214   //  Allocate by subtracting from RSP
18215   //  Jump to continueMBB
18216   //
18217   // mallocMBB:
18218   //  Allocate by call to runtime
18219   //
18220   // continueMBB:
18221   //  ...
18222   //  [rest of original BB]
18223   //
18224
18225   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18226   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18227   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18228
18229   MachineRegisterInfo &MRI = MF->getRegInfo();
18230   const TargetRegisterClass *AddrRegClass =
18231     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18232
18233   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18234     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18235     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18236     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18237     sizeVReg = MI->getOperand(1).getReg(),
18238     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18239
18240   MachineFunction::iterator MBBIter = BB;
18241   ++MBBIter;
18242
18243   MF->insert(MBBIter, bumpMBB);
18244   MF->insert(MBBIter, mallocMBB);
18245   MF->insert(MBBIter, continueMBB);
18246
18247   continueMBB->splice(continueMBB->begin(), BB,
18248                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18249   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18250
18251   // Add code to the main basic block to check if the stack limit has been hit,
18252   // and if so, jump to mallocMBB otherwise to bumpMBB.
18253   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18254   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18255     .addReg(tmpSPVReg).addReg(sizeVReg);
18256   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18257     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18258     .addReg(SPLimitVReg);
18259   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18260
18261   // bumpMBB simply decreases the stack pointer, since we know the current
18262   // stacklet has enough space.
18263   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18264     .addReg(SPLimitVReg);
18265   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18266     .addReg(SPLimitVReg);
18267   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18268
18269   // Calls into a routine in libgcc to allocate more space from the heap.
18270   const uint32_t *RegMask = MF->getTarget()
18271                                 .getSubtargetImpl()
18272                                 ->getRegisterInfo()
18273                                 ->getCallPreservedMask(CallingConv::C);
18274   if (Is64Bit) {
18275     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18276       .addReg(sizeVReg);
18277     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18278       .addExternalSymbol("__morestack_allocate_stack_space")
18279       .addRegMask(RegMask)
18280       .addReg(X86::RDI, RegState::Implicit)
18281       .addReg(X86::RAX, RegState::ImplicitDefine);
18282   } else {
18283     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18284       .addImm(12);
18285     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18286     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18287       .addExternalSymbol("__morestack_allocate_stack_space")
18288       .addRegMask(RegMask)
18289       .addReg(X86::EAX, RegState::ImplicitDefine);
18290   }
18291
18292   if (!Is64Bit)
18293     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18294       .addImm(16);
18295
18296   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18297     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18298   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18299
18300   // Set up the CFG correctly.
18301   BB->addSuccessor(bumpMBB);
18302   BB->addSuccessor(mallocMBB);
18303   mallocMBB->addSuccessor(continueMBB);
18304   bumpMBB->addSuccessor(continueMBB);
18305
18306   // Take care of the PHI nodes.
18307   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18308           MI->getOperand(0).getReg())
18309     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18310     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18311
18312   // Delete the original pseudo instruction.
18313   MI->eraseFromParent();
18314
18315   // And we're done.
18316   return continueMBB;
18317 }
18318
18319 MachineBasicBlock *
18320 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18321                                         MachineBasicBlock *BB) const {
18322   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18323   DebugLoc DL = MI->getDebugLoc();
18324
18325   assert(!Subtarget->isTargetMacho());
18326
18327   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18328   // non-trivial part is impdef of ESP.
18329
18330   if (Subtarget->isTargetWin64()) {
18331     if (Subtarget->isTargetCygMing()) {
18332       // ___chkstk(Mingw64):
18333       // Clobbers R10, R11, RAX and EFLAGS.
18334       // Updates RSP.
18335       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18336         .addExternalSymbol("___chkstk")
18337         .addReg(X86::RAX, RegState::Implicit)
18338         .addReg(X86::RSP, RegState::Implicit)
18339         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18340         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18341         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18342     } else {
18343       // __chkstk(MSVCRT): does not update stack pointer.
18344       // Clobbers R10, R11 and EFLAGS.
18345       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18346         .addExternalSymbol("__chkstk")
18347         .addReg(X86::RAX, RegState::Implicit)
18348         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18349       // RAX has the offset to be subtracted from RSP.
18350       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18351         .addReg(X86::RSP)
18352         .addReg(X86::RAX);
18353     }
18354   } else {
18355     const char *StackProbeSymbol =
18356       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18357
18358     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18359       .addExternalSymbol(StackProbeSymbol)
18360       .addReg(X86::EAX, RegState::Implicit)
18361       .addReg(X86::ESP, RegState::Implicit)
18362       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18363       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18364       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18365   }
18366
18367   MI->eraseFromParent();   // The pseudo instruction is gone now.
18368   return BB;
18369 }
18370
18371 MachineBasicBlock *
18372 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18373                                       MachineBasicBlock *BB) const {
18374   // This is pretty easy.  We're taking the value that we received from
18375   // our load from the relocation, sticking it in either RDI (x86-64)
18376   // or EAX and doing an indirect call.  The return value will then
18377   // be in the normal return register.
18378   MachineFunction *F = BB->getParent();
18379   const X86InstrInfo *TII =
18380       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18381   DebugLoc DL = MI->getDebugLoc();
18382
18383   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18384   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18385
18386   // Get a register mask for the lowered call.
18387   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18388   // proper register mask.
18389   const uint32_t *RegMask = F->getTarget()
18390                                 .getSubtargetImpl()
18391                                 ->getRegisterInfo()
18392                                 ->getCallPreservedMask(CallingConv::C);
18393   if (Subtarget->is64Bit()) {
18394     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18395                                       TII->get(X86::MOV64rm), X86::RDI)
18396     .addReg(X86::RIP)
18397     .addImm(0).addReg(0)
18398     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18399                       MI->getOperand(3).getTargetFlags())
18400     .addReg(0);
18401     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18402     addDirectMem(MIB, X86::RDI);
18403     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18404   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18405     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18406                                       TII->get(X86::MOV32rm), X86::EAX)
18407     .addReg(0)
18408     .addImm(0).addReg(0)
18409     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18410                       MI->getOperand(3).getTargetFlags())
18411     .addReg(0);
18412     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18413     addDirectMem(MIB, X86::EAX);
18414     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18415   } else {
18416     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18417                                       TII->get(X86::MOV32rm), X86::EAX)
18418     .addReg(TII->getGlobalBaseReg(F))
18419     .addImm(0).addReg(0)
18420     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18421                       MI->getOperand(3).getTargetFlags())
18422     .addReg(0);
18423     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18424     addDirectMem(MIB, X86::EAX);
18425     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18426   }
18427
18428   MI->eraseFromParent(); // The pseudo instruction is gone now.
18429   return BB;
18430 }
18431
18432 MachineBasicBlock *
18433 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18434                                     MachineBasicBlock *MBB) const {
18435   DebugLoc DL = MI->getDebugLoc();
18436   MachineFunction *MF = MBB->getParent();
18437   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18438   MachineRegisterInfo &MRI = MF->getRegInfo();
18439
18440   const BasicBlock *BB = MBB->getBasicBlock();
18441   MachineFunction::iterator I = MBB;
18442   ++I;
18443
18444   // Memory Reference
18445   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18446   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18447
18448   unsigned DstReg;
18449   unsigned MemOpndSlot = 0;
18450
18451   unsigned CurOp = 0;
18452
18453   DstReg = MI->getOperand(CurOp++).getReg();
18454   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18455   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18456   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18457   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18458
18459   MemOpndSlot = CurOp;
18460
18461   MVT PVT = getPointerTy();
18462   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18463          "Invalid Pointer Size!");
18464
18465   // For v = setjmp(buf), we generate
18466   //
18467   // thisMBB:
18468   //  buf[LabelOffset] = restoreMBB
18469   //  SjLjSetup restoreMBB
18470   //
18471   // mainMBB:
18472   //  v_main = 0
18473   //
18474   // sinkMBB:
18475   //  v = phi(main, restore)
18476   //
18477   // restoreMBB:
18478   //  v_restore = 1
18479
18480   MachineBasicBlock *thisMBB = MBB;
18481   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18482   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18483   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18484   MF->insert(I, mainMBB);
18485   MF->insert(I, sinkMBB);
18486   MF->push_back(restoreMBB);
18487
18488   MachineInstrBuilder MIB;
18489
18490   // Transfer the remainder of BB and its successor edges to sinkMBB.
18491   sinkMBB->splice(sinkMBB->begin(), MBB,
18492                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18493   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18494
18495   // thisMBB:
18496   unsigned PtrStoreOpc = 0;
18497   unsigned LabelReg = 0;
18498   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18499   Reloc::Model RM = MF->getTarget().getRelocationModel();
18500   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18501                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18502
18503   // Prepare IP either in reg or imm.
18504   if (!UseImmLabel) {
18505     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18506     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18507     LabelReg = MRI.createVirtualRegister(PtrRC);
18508     if (Subtarget->is64Bit()) {
18509       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18510               .addReg(X86::RIP)
18511               .addImm(0)
18512               .addReg(0)
18513               .addMBB(restoreMBB)
18514               .addReg(0);
18515     } else {
18516       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18517       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18518               .addReg(XII->getGlobalBaseReg(MF))
18519               .addImm(0)
18520               .addReg(0)
18521               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18522               .addReg(0);
18523     }
18524   } else
18525     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18526   // Store IP
18527   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18528   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18529     if (i == X86::AddrDisp)
18530       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18531     else
18532       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18533   }
18534   if (!UseImmLabel)
18535     MIB.addReg(LabelReg);
18536   else
18537     MIB.addMBB(restoreMBB);
18538   MIB.setMemRefs(MMOBegin, MMOEnd);
18539   // Setup
18540   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18541           .addMBB(restoreMBB);
18542
18543   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18544       MF->getSubtarget().getRegisterInfo());
18545   MIB.addRegMask(RegInfo->getNoPreservedMask());
18546   thisMBB->addSuccessor(mainMBB);
18547   thisMBB->addSuccessor(restoreMBB);
18548
18549   // mainMBB:
18550   //  EAX = 0
18551   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18552   mainMBB->addSuccessor(sinkMBB);
18553
18554   // sinkMBB:
18555   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18556           TII->get(X86::PHI), DstReg)
18557     .addReg(mainDstReg).addMBB(mainMBB)
18558     .addReg(restoreDstReg).addMBB(restoreMBB);
18559
18560   // restoreMBB:
18561   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18562   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18563   restoreMBB->addSuccessor(sinkMBB);
18564
18565   MI->eraseFromParent();
18566   return sinkMBB;
18567 }
18568
18569 MachineBasicBlock *
18570 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18571                                      MachineBasicBlock *MBB) const {
18572   DebugLoc DL = MI->getDebugLoc();
18573   MachineFunction *MF = MBB->getParent();
18574   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18575   MachineRegisterInfo &MRI = MF->getRegInfo();
18576
18577   // Memory Reference
18578   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18579   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18580
18581   MVT PVT = getPointerTy();
18582   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18583          "Invalid Pointer Size!");
18584
18585   const TargetRegisterClass *RC =
18586     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18587   unsigned Tmp = MRI.createVirtualRegister(RC);
18588   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18589   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18590       MF->getSubtarget().getRegisterInfo());
18591   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18592   unsigned SP = RegInfo->getStackRegister();
18593
18594   MachineInstrBuilder MIB;
18595
18596   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18597   const int64_t SPOffset = 2 * PVT.getStoreSize();
18598
18599   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18600   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18601
18602   // Reload FP
18603   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18604   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18605     MIB.addOperand(MI->getOperand(i));
18606   MIB.setMemRefs(MMOBegin, MMOEnd);
18607   // Reload IP
18608   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18609   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18610     if (i == X86::AddrDisp)
18611       MIB.addDisp(MI->getOperand(i), LabelOffset);
18612     else
18613       MIB.addOperand(MI->getOperand(i));
18614   }
18615   MIB.setMemRefs(MMOBegin, MMOEnd);
18616   // Reload SP
18617   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18618   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18619     if (i == X86::AddrDisp)
18620       MIB.addDisp(MI->getOperand(i), SPOffset);
18621     else
18622       MIB.addOperand(MI->getOperand(i));
18623   }
18624   MIB.setMemRefs(MMOBegin, MMOEnd);
18625   // Jump
18626   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18627
18628   MI->eraseFromParent();
18629   return MBB;
18630 }
18631
18632 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18633 // accumulator loops. Writing back to the accumulator allows the coalescer
18634 // to remove extra copies in the loop.   
18635 MachineBasicBlock *
18636 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18637                                  MachineBasicBlock *MBB) const {
18638   MachineOperand &AddendOp = MI->getOperand(3);
18639
18640   // Bail out early if the addend isn't a register - we can't switch these.
18641   if (!AddendOp.isReg())
18642     return MBB;
18643
18644   MachineFunction &MF = *MBB->getParent();
18645   MachineRegisterInfo &MRI = MF.getRegInfo();
18646
18647   // Check whether the addend is defined by a PHI:
18648   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18649   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18650   if (!AddendDef.isPHI())
18651     return MBB;
18652
18653   // Look for the following pattern:
18654   // loop:
18655   //   %addend = phi [%entry, 0], [%loop, %result]
18656   //   ...
18657   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18658
18659   // Replace with:
18660   //   loop:
18661   //   %addend = phi [%entry, 0], [%loop, %result]
18662   //   ...
18663   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18664
18665   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18666     assert(AddendDef.getOperand(i).isReg());
18667     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18668     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18669     if (&PHISrcInst == MI) {
18670       // Found a matching instruction.
18671       unsigned NewFMAOpc = 0;
18672       switch (MI->getOpcode()) {
18673         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18674         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18675         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18676         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18677         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18678         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18679         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18680         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18681         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18682         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18683         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18684         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18685         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18686         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18687         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18688         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18689         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18690         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18691         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18692         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18693         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18694         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18695         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18696         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18697         default: llvm_unreachable("Unrecognized FMA variant.");
18698       }
18699
18700       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18701       MachineInstrBuilder MIB =
18702         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18703         .addOperand(MI->getOperand(0))
18704         .addOperand(MI->getOperand(3))
18705         .addOperand(MI->getOperand(2))
18706         .addOperand(MI->getOperand(1));
18707       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18708       MI->eraseFromParent();
18709     }
18710   }
18711
18712   return MBB;
18713 }
18714
18715 MachineBasicBlock *
18716 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18717                                                MachineBasicBlock *BB) const {
18718   switch (MI->getOpcode()) {
18719   default: llvm_unreachable("Unexpected instr type to insert");
18720   case X86::TAILJMPd64:
18721   case X86::TAILJMPr64:
18722   case X86::TAILJMPm64:
18723     llvm_unreachable("TAILJMP64 would not be touched here.");
18724   case X86::TCRETURNdi64:
18725   case X86::TCRETURNri64:
18726   case X86::TCRETURNmi64:
18727     return BB;
18728   case X86::WIN_ALLOCA:
18729     return EmitLoweredWinAlloca(MI, BB);
18730   case X86::SEG_ALLOCA_32:
18731     return EmitLoweredSegAlloca(MI, BB, false);
18732   case X86::SEG_ALLOCA_64:
18733     return EmitLoweredSegAlloca(MI, BB, true);
18734   case X86::TLSCall_32:
18735   case X86::TLSCall_64:
18736     return EmitLoweredTLSCall(MI, BB);
18737   case X86::CMOV_GR8:
18738   case X86::CMOV_FR32:
18739   case X86::CMOV_FR64:
18740   case X86::CMOV_V4F32:
18741   case X86::CMOV_V2F64:
18742   case X86::CMOV_V2I64:
18743   case X86::CMOV_V8F32:
18744   case X86::CMOV_V4F64:
18745   case X86::CMOV_V4I64:
18746   case X86::CMOV_V16F32:
18747   case X86::CMOV_V8F64:
18748   case X86::CMOV_V8I64:
18749   case X86::CMOV_GR16:
18750   case X86::CMOV_GR32:
18751   case X86::CMOV_RFP32:
18752   case X86::CMOV_RFP64:
18753   case X86::CMOV_RFP80:
18754     return EmitLoweredSelect(MI, BB);
18755
18756   case X86::FP32_TO_INT16_IN_MEM:
18757   case X86::FP32_TO_INT32_IN_MEM:
18758   case X86::FP32_TO_INT64_IN_MEM:
18759   case X86::FP64_TO_INT16_IN_MEM:
18760   case X86::FP64_TO_INT32_IN_MEM:
18761   case X86::FP64_TO_INT64_IN_MEM:
18762   case X86::FP80_TO_INT16_IN_MEM:
18763   case X86::FP80_TO_INT32_IN_MEM:
18764   case X86::FP80_TO_INT64_IN_MEM: {
18765     MachineFunction *F = BB->getParent();
18766     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18767     DebugLoc DL = MI->getDebugLoc();
18768
18769     // Change the floating point control register to use "round towards zero"
18770     // mode when truncating to an integer value.
18771     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18772     addFrameReference(BuildMI(*BB, MI, DL,
18773                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18774
18775     // Load the old value of the high byte of the control word...
18776     unsigned OldCW =
18777       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18778     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18779                       CWFrameIdx);
18780
18781     // Set the high part to be round to zero...
18782     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18783       .addImm(0xC7F);
18784
18785     // Reload the modified control word now...
18786     addFrameReference(BuildMI(*BB, MI, DL,
18787                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18788
18789     // Restore the memory image of control word to original value
18790     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18791       .addReg(OldCW);
18792
18793     // Get the X86 opcode to use.
18794     unsigned Opc;
18795     switch (MI->getOpcode()) {
18796     default: llvm_unreachable("illegal opcode!");
18797     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18798     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18799     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18800     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18801     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18802     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18803     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18804     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18805     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18806     }
18807
18808     X86AddressMode AM;
18809     MachineOperand &Op = MI->getOperand(0);
18810     if (Op.isReg()) {
18811       AM.BaseType = X86AddressMode::RegBase;
18812       AM.Base.Reg = Op.getReg();
18813     } else {
18814       AM.BaseType = X86AddressMode::FrameIndexBase;
18815       AM.Base.FrameIndex = Op.getIndex();
18816     }
18817     Op = MI->getOperand(1);
18818     if (Op.isImm())
18819       AM.Scale = Op.getImm();
18820     Op = MI->getOperand(2);
18821     if (Op.isImm())
18822       AM.IndexReg = Op.getImm();
18823     Op = MI->getOperand(3);
18824     if (Op.isGlobal()) {
18825       AM.GV = Op.getGlobal();
18826     } else {
18827       AM.Disp = Op.getImm();
18828     }
18829     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18830                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18831
18832     // Reload the original control word now.
18833     addFrameReference(BuildMI(*BB, MI, DL,
18834                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18835
18836     MI->eraseFromParent();   // The pseudo instruction is gone now.
18837     return BB;
18838   }
18839     // String/text processing lowering.
18840   case X86::PCMPISTRM128REG:
18841   case X86::VPCMPISTRM128REG:
18842   case X86::PCMPISTRM128MEM:
18843   case X86::VPCMPISTRM128MEM:
18844   case X86::PCMPESTRM128REG:
18845   case X86::VPCMPESTRM128REG:
18846   case X86::PCMPESTRM128MEM:
18847   case X86::VPCMPESTRM128MEM:
18848     assert(Subtarget->hasSSE42() &&
18849            "Target must have SSE4.2 or AVX features enabled");
18850     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18851
18852   // String/text processing lowering.
18853   case X86::PCMPISTRIREG:
18854   case X86::VPCMPISTRIREG:
18855   case X86::PCMPISTRIMEM:
18856   case X86::VPCMPISTRIMEM:
18857   case X86::PCMPESTRIREG:
18858   case X86::VPCMPESTRIREG:
18859   case X86::PCMPESTRIMEM:
18860   case X86::VPCMPESTRIMEM:
18861     assert(Subtarget->hasSSE42() &&
18862            "Target must have SSE4.2 or AVX features enabled");
18863     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18864
18865   // Thread synchronization.
18866   case X86::MONITOR:
18867     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18868                        Subtarget);
18869
18870   // xbegin
18871   case X86::XBEGIN:
18872     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18873
18874   case X86::VASTART_SAVE_XMM_REGS:
18875     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18876
18877   case X86::VAARG_64:
18878     return EmitVAARG64WithCustomInserter(MI, BB);
18879
18880   case X86::EH_SjLj_SetJmp32:
18881   case X86::EH_SjLj_SetJmp64:
18882     return emitEHSjLjSetJmp(MI, BB);
18883
18884   case X86::EH_SjLj_LongJmp32:
18885   case X86::EH_SjLj_LongJmp64:
18886     return emitEHSjLjLongJmp(MI, BB);
18887
18888   case TargetOpcode::STACKMAP:
18889   case TargetOpcode::PATCHPOINT:
18890     return emitPatchPoint(MI, BB);
18891
18892   case X86::VFMADDPDr213r:
18893   case X86::VFMADDPSr213r:
18894   case X86::VFMADDSDr213r:
18895   case X86::VFMADDSSr213r:
18896   case X86::VFMSUBPDr213r:
18897   case X86::VFMSUBPSr213r:
18898   case X86::VFMSUBSDr213r:
18899   case X86::VFMSUBSSr213r:
18900   case X86::VFNMADDPDr213r:
18901   case X86::VFNMADDPSr213r:
18902   case X86::VFNMADDSDr213r:
18903   case X86::VFNMADDSSr213r:
18904   case X86::VFNMSUBPDr213r:
18905   case X86::VFNMSUBPSr213r:
18906   case X86::VFNMSUBSDr213r:
18907   case X86::VFNMSUBSSr213r:
18908   case X86::VFMADDPDr213rY:
18909   case X86::VFMADDPSr213rY:
18910   case X86::VFMSUBPDr213rY:
18911   case X86::VFMSUBPSr213rY:
18912   case X86::VFNMADDPDr213rY:
18913   case X86::VFNMADDPSr213rY:
18914   case X86::VFNMSUBPDr213rY:
18915   case X86::VFNMSUBPSr213rY:
18916     return emitFMA3Instr(MI, BB);
18917   }
18918 }
18919
18920 //===----------------------------------------------------------------------===//
18921 //                           X86 Optimization Hooks
18922 //===----------------------------------------------------------------------===//
18923
18924 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18925                                                       APInt &KnownZero,
18926                                                       APInt &KnownOne,
18927                                                       const SelectionDAG &DAG,
18928                                                       unsigned Depth) const {
18929   unsigned BitWidth = KnownZero.getBitWidth();
18930   unsigned Opc = Op.getOpcode();
18931   assert((Opc >= ISD::BUILTIN_OP_END ||
18932           Opc == ISD::INTRINSIC_WO_CHAIN ||
18933           Opc == ISD::INTRINSIC_W_CHAIN ||
18934           Opc == ISD::INTRINSIC_VOID) &&
18935          "Should use MaskedValueIsZero if you don't know whether Op"
18936          " is a target node!");
18937
18938   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18939   switch (Opc) {
18940   default: break;
18941   case X86ISD::ADD:
18942   case X86ISD::SUB:
18943   case X86ISD::ADC:
18944   case X86ISD::SBB:
18945   case X86ISD::SMUL:
18946   case X86ISD::UMUL:
18947   case X86ISD::INC:
18948   case X86ISD::DEC:
18949   case X86ISD::OR:
18950   case X86ISD::XOR:
18951   case X86ISD::AND:
18952     // These nodes' second result is a boolean.
18953     if (Op.getResNo() == 0)
18954       break;
18955     // Fallthrough
18956   case X86ISD::SETCC:
18957     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18958     break;
18959   case ISD::INTRINSIC_WO_CHAIN: {
18960     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18961     unsigned NumLoBits = 0;
18962     switch (IntId) {
18963     default: break;
18964     case Intrinsic::x86_sse_movmsk_ps:
18965     case Intrinsic::x86_avx_movmsk_ps_256:
18966     case Intrinsic::x86_sse2_movmsk_pd:
18967     case Intrinsic::x86_avx_movmsk_pd_256:
18968     case Intrinsic::x86_mmx_pmovmskb:
18969     case Intrinsic::x86_sse2_pmovmskb_128:
18970     case Intrinsic::x86_avx2_pmovmskb: {
18971       // High bits of movmskp{s|d}, pmovmskb are known zero.
18972       switch (IntId) {
18973         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18974         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18975         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18976         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18977         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18978         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18979         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18980         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18981       }
18982       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18983       break;
18984     }
18985     }
18986     break;
18987   }
18988   }
18989 }
18990
18991 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18992   SDValue Op,
18993   const SelectionDAG &,
18994   unsigned Depth) const {
18995   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18996   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18997     return Op.getValueType().getScalarType().getSizeInBits();
18998
18999   // Fallback case.
19000   return 1;
19001 }
19002
19003 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19004 /// node is a GlobalAddress + offset.
19005 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19006                                        const GlobalValue* &GA,
19007                                        int64_t &Offset) const {
19008   if (N->getOpcode() == X86ISD::Wrapper) {
19009     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19010       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19011       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19012       return true;
19013     }
19014   }
19015   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19016 }
19017
19018 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19019 /// same as extracting the high 128-bit part of 256-bit vector and then
19020 /// inserting the result into the low part of a new 256-bit vector
19021 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19022   EVT VT = SVOp->getValueType(0);
19023   unsigned NumElems = VT.getVectorNumElements();
19024
19025   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19026   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19027     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19028         SVOp->getMaskElt(j) >= 0)
19029       return false;
19030
19031   return true;
19032 }
19033
19034 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19035 /// same as extracting the low 128-bit part of 256-bit vector and then
19036 /// inserting the result into the high part of a new 256-bit vector
19037 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19038   EVT VT = SVOp->getValueType(0);
19039   unsigned NumElems = VT.getVectorNumElements();
19040
19041   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19042   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19043     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19044         SVOp->getMaskElt(j) >= 0)
19045       return false;
19046
19047   return true;
19048 }
19049
19050 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19051 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19052                                         TargetLowering::DAGCombinerInfo &DCI,
19053                                         const X86Subtarget* Subtarget) {
19054   SDLoc dl(N);
19055   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19056   SDValue V1 = SVOp->getOperand(0);
19057   SDValue V2 = SVOp->getOperand(1);
19058   EVT VT = SVOp->getValueType(0);
19059   unsigned NumElems = VT.getVectorNumElements();
19060
19061   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19062       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19063     //
19064     //                   0,0,0,...
19065     //                      |
19066     //    V      UNDEF    BUILD_VECTOR    UNDEF
19067     //     \      /           \           /
19068     //  CONCAT_VECTOR         CONCAT_VECTOR
19069     //         \                  /
19070     //          \                /
19071     //          RESULT: V + zero extended
19072     //
19073     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19074         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19075         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19076       return SDValue();
19077
19078     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19079       return SDValue();
19080
19081     // To match the shuffle mask, the first half of the mask should
19082     // be exactly the first vector, and all the rest a splat with the
19083     // first element of the second one.
19084     for (unsigned i = 0; i != NumElems/2; ++i)
19085       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19086           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19087         return SDValue();
19088
19089     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19090     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19091       if (Ld->hasNUsesOfValue(1, 0)) {
19092         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19093         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19094         SDValue ResNode =
19095           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19096                                   Ld->getMemoryVT(),
19097                                   Ld->getPointerInfo(),
19098                                   Ld->getAlignment(),
19099                                   false/*isVolatile*/, true/*ReadMem*/,
19100                                   false/*WriteMem*/);
19101
19102         // Make sure the newly-created LOAD is in the same position as Ld in
19103         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19104         // and update uses of Ld's output chain to use the TokenFactor.
19105         if (Ld->hasAnyUseOfValue(1)) {
19106           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19107                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19108           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19109           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19110                                  SDValue(ResNode.getNode(), 1));
19111         }
19112
19113         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19114       }
19115     }
19116
19117     // Emit a zeroed vector and insert the desired subvector on its
19118     // first half.
19119     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19120     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19121     return DCI.CombineTo(N, InsV);
19122   }
19123
19124   //===--------------------------------------------------------------------===//
19125   // Combine some shuffles into subvector extracts and inserts:
19126   //
19127
19128   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19129   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19130     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19131     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19132     return DCI.CombineTo(N, InsV);
19133   }
19134
19135   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19136   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19137     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19138     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19139     return DCI.CombineTo(N, InsV);
19140   }
19141
19142   return SDValue();
19143 }
19144
19145 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19146 /// possible.
19147 ///
19148 /// This is the leaf of the recursive combinine below. When we have found some
19149 /// chain of single-use x86 shuffle instructions and accumulated the combined
19150 /// shuffle mask represented by them, this will try to pattern match that mask
19151 /// into either a single instruction if there is a special purpose instruction
19152 /// for this operation, or into a PSHUFB instruction which is a fully general
19153 /// instruction but should only be used to replace chains over a certain depth.
19154 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19155                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19156                                    TargetLowering::DAGCombinerInfo &DCI,
19157                                    const X86Subtarget *Subtarget) {
19158   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19159
19160   // Find the operand that enters the chain. Note that multiple uses are OK
19161   // here, we're not going to remove the operand we find.
19162   SDValue Input = Op.getOperand(0);
19163   while (Input.getOpcode() == ISD::BITCAST)
19164     Input = Input.getOperand(0);
19165
19166   MVT VT = Input.getSimpleValueType();
19167   MVT RootVT = Root.getSimpleValueType();
19168   SDLoc DL(Root);
19169
19170   // Just remove no-op shuffle masks.
19171   if (Mask.size() == 1) {
19172     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19173                   /*AddTo*/ true);
19174     return true;
19175   }
19176
19177   // Use the float domain if the operand type is a floating point type.
19178   bool FloatDomain = VT.isFloatingPoint();
19179
19180   // If we don't have access to VEX encodings, the generic PSHUF instructions
19181   // are preferable to some of the specialized forms despite requiring one more
19182   // byte to encode because they can implicitly copy.
19183   //
19184   // IF we *do* have VEX encodings, than we can use shorter, more specific
19185   // shuffle instructions freely as they can copy due to the extra register
19186   // operand.
19187   if (Subtarget->hasAVX()) {
19188     // We have both floating point and integer variants of shuffles that dup
19189     // either the low or high half of the vector.
19190     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19191       bool Lo = Mask.equals(0, 0);
19192       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19193                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19194       if (Depth == 1 && Root->getOpcode() == Shuffle)
19195         return false; // Nothing to do!
19196       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19197       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19198       DCI.AddToWorklist(Op.getNode());
19199       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19200       DCI.AddToWorklist(Op.getNode());
19201       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19202                     /*AddTo*/ true);
19203       return true;
19204     }
19205
19206     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19207
19208     // For the integer domain we have specialized instructions for duplicating
19209     // any element size from the low or high half.
19210     if (!FloatDomain &&
19211         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19212          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19213          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19214          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19215          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19216                      15))) {
19217       bool Lo = Mask[0] == 0;
19218       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19219       if (Depth == 1 && Root->getOpcode() == Shuffle)
19220         return false; // Nothing to do!
19221       MVT ShuffleVT;
19222       switch (Mask.size()) {
19223       case 4: ShuffleVT = MVT::v4i32; break;
19224       case 8: ShuffleVT = MVT::v8i16; break;
19225       case 16: ShuffleVT = MVT::v16i8; break;
19226       };
19227       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19228       DCI.AddToWorklist(Op.getNode());
19229       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19230       DCI.AddToWorklist(Op.getNode());
19231       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19232                     /*AddTo*/ true);
19233       return true;
19234     }
19235   }
19236
19237   // Don't try to re-form single instruction chains under any circumstances now
19238   // that we've done encoding canonicalization for them.
19239   if (Depth < 2)
19240     return false;
19241
19242   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19243   // can replace them with a single PSHUFB instruction profitably. Intel's
19244   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19245   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19246   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19247     SmallVector<SDValue, 16> PSHUFBMask;
19248     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19249     int Ratio = 16 / Mask.size();
19250     for (unsigned i = 0; i < 16; ++i) {
19251       int M = Mask[i / Ratio] != SM_SentinelZero
19252                   ? Ratio * Mask[i / Ratio] + i % Ratio
19253                   : 255;
19254       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19255     }
19256     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19257     DCI.AddToWorklist(Op.getNode());
19258     SDValue PSHUFBMaskOp =
19259         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19260     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19261     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19262     DCI.AddToWorklist(Op.getNode());
19263     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19264                   /*AddTo*/ true);
19265     return true;
19266   }
19267
19268   // Failed to find any combines.
19269   return false;
19270 }
19271
19272 /// \brief Fully generic combining of x86 shuffle instructions.
19273 ///
19274 /// This should be the last combine run over the x86 shuffle instructions. Once
19275 /// they have been fully optimized, this will recursively consider all chains
19276 /// of single-use shuffle instructions, build a generic model of the cumulative
19277 /// shuffle operation, and check for simpler instructions which implement this
19278 /// operation. We use this primarily for two purposes:
19279 ///
19280 /// 1) Collapse generic shuffles to specialized single instructions when
19281 ///    equivalent. In most cases, this is just an encoding size win, but
19282 ///    sometimes we will collapse multiple generic shuffles into a single
19283 ///    special-purpose shuffle.
19284 /// 2) Look for sequences of shuffle instructions with 3 or more total
19285 ///    instructions, and replace them with the slightly more expensive SSSE3
19286 ///    PSHUFB instruction if available. We do this as the last combining step
19287 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19288 ///    a suitable short sequence of other instructions. The PHUFB will either
19289 ///    use a register or have to read from memory and so is slightly (but only
19290 ///    slightly) more expensive than the other shuffle instructions.
19291 ///
19292 /// Because this is inherently a quadratic operation (for each shuffle in
19293 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19294 /// This should never be an issue in practice as the shuffle lowering doesn't
19295 /// produce sequences of more than 8 instructions.
19296 ///
19297 /// FIXME: We will currently miss some cases where the redundant shuffling
19298 /// would simplify under the threshold for PSHUFB formation because of
19299 /// combine-ordering. To fix this, we should do the redundant instruction
19300 /// combining in this recursive walk.
19301 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19302                                           ArrayRef<int> RootMask,
19303                                           int Depth, bool HasPSHUFB,
19304                                           SelectionDAG &DAG,
19305                                           TargetLowering::DAGCombinerInfo &DCI,
19306                                           const X86Subtarget *Subtarget) {
19307   // Bound the depth of our recursive combine because this is ultimately
19308   // quadratic in nature.
19309   if (Depth > 8)
19310     return false;
19311
19312   // Directly rip through bitcasts to find the underlying operand.
19313   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19314     Op = Op.getOperand(0);
19315
19316   MVT VT = Op.getSimpleValueType();
19317   if (!VT.isVector())
19318     return false; // Bail if we hit a non-vector.
19319   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19320   // version should be added.
19321   if (VT.getSizeInBits() != 128)
19322     return false;
19323
19324   assert(Root.getSimpleValueType().isVector() &&
19325          "Shuffles operate on vector types!");
19326   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19327          "Can only combine shuffles of the same vector register size.");
19328
19329   if (!isTargetShuffle(Op.getOpcode()))
19330     return false;
19331   SmallVector<int, 16> OpMask;
19332   bool IsUnary;
19333   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19334   // We only can combine unary shuffles which we can decode the mask for.
19335   if (!HaveMask || !IsUnary)
19336     return false;
19337
19338   assert(VT.getVectorNumElements() == OpMask.size() &&
19339          "Different mask size from vector size!");
19340   assert(((RootMask.size() > OpMask.size() &&
19341            RootMask.size() % OpMask.size() == 0) ||
19342           (OpMask.size() > RootMask.size() &&
19343            OpMask.size() % RootMask.size() == 0) ||
19344           OpMask.size() == RootMask.size()) &&
19345          "The smaller number of elements must divide the larger.");
19346   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19347   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19348   assert(((RootRatio == 1 && OpRatio == 1) ||
19349           (RootRatio == 1) != (OpRatio == 1)) &&
19350          "Must not have a ratio for both incoming and op masks!");
19351
19352   SmallVector<int, 16> Mask;
19353   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19354
19355   // Merge this shuffle operation's mask into our accumulated mask. Note that
19356   // this shuffle's mask will be the first applied to the input, followed by the
19357   // root mask to get us all the way to the root value arrangement. The reason
19358   // for this order is that we are recursing up the operation chain.
19359   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19360     int RootIdx = i / RootRatio;
19361     if (RootMask[RootIdx] == SM_SentinelZero) {
19362       // This is a zero-ed lane, we're done.
19363       Mask.push_back(SM_SentinelZero);
19364       continue;
19365     }
19366
19367     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19368     int OpIdx = RootMaskedIdx / OpRatio;
19369     if (OpMask[OpIdx] == SM_SentinelZero) {
19370       // The incoming lanes are zero, it doesn't matter which ones we are using.
19371       Mask.push_back(SM_SentinelZero);
19372       continue;
19373     }
19374
19375     // Ok, we have non-zero lanes, map them through.
19376     Mask.push_back(OpMask[OpIdx] * OpRatio +
19377                    RootMaskedIdx % OpRatio);
19378   }
19379
19380   // See if we can recurse into the operand to combine more things.
19381   switch (Op.getOpcode()) {
19382     case X86ISD::PSHUFB:
19383       HasPSHUFB = true;
19384     case X86ISD::PSHUFD:
19385     case X86ISD::PSHUFHW:
19386     case X86ISD::PSHUFLW:
19387       if (Op.getOperand(0).hasOneUse() &&
19388           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19389                                         HasPSHUFB, DAG, DCI, Subtarget))
19390         return true;
19391       break;
19392
19393     case X86ISD::UNPCKL:
19394     case X86ISD::UNPCKH:
19395       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19396       // We can't check for single use, we have to check that this shuffle is the only user.
19397       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19398           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19399                                         HasPSHUFB, DAG, DCI, Subtarget))
19400           return true;
19401       break;
19402   }
19403
19404   // Minor canonicalization of the accumulated shuffle mask to make it easier
19405   // to match below. All this does is detect masks with squential pairs of
19406   // elements, and shrink them to the half-width mask. It does this in a loop
19407   // so it will reduce the size of the mask to the minimal width mask which
19408   // performs an equivalent shuffle.
19409   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19410     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19411       Mask[i] = Mask[2 * i] / 2;
19412     Mask.resize(Mask.size() / 2);
19413   }
19414
19415   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19416                                 Subtarget);
19417 }
19418
19419 /// \brief Get the PSHUF-style mask from PSHUF node.
19420 ///
19421 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19422 /// PSHUF-style masks that can be reused with such instructions.
19423 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19424   SmallVector<int, 4> Mask;
19425   bool IsUnary;
19426   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19427   (void)HaveMask;
19428   assert(HaveMask);
19429
19430   switch (N.getOpcode()) {
19431   case X86ISD::PSHUFD:
19432     return Mask;
19433   case X86ISD::PSHUFLW:
19434     Mask.resize(4);
19435     return Mask;
19436   case X86ISD::PSHUFHW:
19437     Mask.erase(Mask.begin(), Mask.begin() + 4);
19438     for (int &M : Mask)
19439       M -= 4;
19440     return Mask;
19441   default:
19442     llvm_unreachable("No valid shuffle instruction found!");
19443   }
19444 }
19445
19446 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19447 ///
19448 /// We walk up the chain and look for a combinable shuffle, skipping over
19449 /// shuffles that we could hoist this shuffle's transformation past without
19450 /// altering anything.
19451 static SDValue
19452 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19453                              SelectionDAG &DAG,
19454                              TargetLowering::DAGCombinerInfo &DCI) {
19455   assert(N.getOpcode() == X86ISD::PSHUFD &&
19456          "Called with something other than an x86 128-bit half shuffle!");
19457   SDLoc DL(N);
19458
19459   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19460   // of the shuffles in the chain so that we can form a fresh chain to replace
19461   // this one.
19462   SmallVector<SDValue, 8> Chain;
19463   SDValue V = N.getOperand(0);
19464   for (; V.hasOneUse(); V = V.getOperand(0)) {
19465     switch (V.getOpcode()) {
19466     default:
19467       return SDValue(); // Nothing combined!
19468
19469     case ISD::BITCAST:
19470       // Skip bitcasts as we always know the type for the target specific
19471       // instructions.
19472       continue;
19473
19474     case X86ISD::PSHUFD:
19475       // Found another dword shuffle.
19476       break;
19477
19478     case X86ISD::PSHUFLW:
19479       // Check that the low words (being shuffled) are the identity in the
19480       // dword shuffle, and the high words are self-contained.
19481       if (Mask[0] != 0 || Mask[1] != 1 ||
19482           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19483         return SDValue();
19484
19485       Chain.push_back(V);
19486       continue;
19487
19488     case X86ISD::PSHUFHW:
19489       // Check that the high words (being shuffled) are the identity in the
19490       // dword shuffle, and the low words are self-contained.
19491       if (Mask[2] != 2 || Mask[3] != 3 ||
19492           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19493         return SDValue();
19494
19495       Chain.push_back(V);
19496       continue;
19497
19498     case X86ISD::UNPCKL:
19499     case X86ISD::UNPCKH:
19500       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19501       // shuffle into a preceding word shuffle.
19502       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19503         return SDValue();
19504
19505       // Search for a half-shuffle which we can combine with.
19506       unsigned CombineOp =
19507           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19508       if (V.getOperand(0) != V.getOperand(1) ||
19509           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19510         return SDValue();
19511       Chain.push_back(V);
19512       V = V.getOperand(0);
19513       do {
19514         switch (V.getOpcode()) {
19515         default:
19516           return SDValue(); // Nothing to combine.
19517
19518         case X86ISD::PSHUFLW:
19519         case X86ISD::PSHUFHW:
19520           if (V.getOpcode() == CombineOp)
19521             break;
19522
19523           Chain.push_back(V);
19524
19525           // Fallthrough!
19526         case ISD::BITCAST:
19527           V = V.getOperand(0);
19528           continue;
19529         }
19530         break;
19531       } while (V.hasOneUse());
19532       break;
19533     }
19534     // Break out of the loop if we break out of the switch.
19535     break;
19536   }
19537
19538   if (!V.hasOneUse())
19539     // We fell out of the loop without finding a viable combining instruction.
19540     return SDValue();
19541
19542   // Merge this node's mask and our incoming mask.
19543   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19544   for (int &M : Mask)
19545     M = VMask[M];
19546   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19547                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19548
19549   // Rebuild the chain around this new shuffle.
19550   while (!Chain.empty()) {
19551     SDValue W = Chain.pop_back_val();
19552
19553     if (V.getValueType() != W.getOperand(0).getValueType())
19554       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19555
19556     switch (W.getOpcode()) {
19557     default:
19558       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19559
19560     case X86ISD::UNPCKL:
19561     case X86ISD::UNPCKH:
19562       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19563       break;
19564
19565     case X86ISD::PSHUFD:
19566     case X86ISD::PSHUFLW:
19567     case X86ISD::PSHUFHW:
19568       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19569       break;
19570     }
19571   }
19572   if (V.getValueType() != N.getValueType())
19573     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19574
19575   // Return the new chain to replace N.
19576   return V;
19577 }
19578
19579 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19580 ///
19581 /// We walk up the chain, skipping shuffles of the other half and looking
19582 /// through shuffles which switch halves trying to find a shuffle of the same
19583 /// pair of dwords.
19584 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19585                                         SelectionDAG &DAG,
19586                                         TargetLowering::DAGCombinerInfo &DCI) {
19587   assert(
19588       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19589       "Called with something other than an x86 128-bit half shuffle!");
19590   SDLoc DL(N);
19591   unsigned CombineOpcode = N.getOpcode();
19592
19593   // Walk up a single-use chain looking for a combinable shuffle.
19594   SDValue V = N.getOperand(0);
19595   for (; V.hasOneUse(); V = V.getOperand(0)) {
19596     switch (V.getOpcode()) {
19597     default:
19598       return false; // Nothing combined!
19599
19600     case ISD::BITCAST:
19601       // Skip bitcasts as we always know the type for the target specific
19602       // instructions.
19603       continue;
19604
19605     case X86ISD::PSHUFLW:
19606     case X86ISD::PSHUFHW:
19607       if (V.getOpcode() == CombineOpcode)
19608         break;
19609
19610       // Other-half shuffles are no-ops.
19611       continue;
19612     }
19613     // Break out of the loop if we break out of the switch.
19614     break;
19615   }
19616
19617   if (!V.hasOneUse())
19618     // We fell out of the loop without finding a viable combining instruction.
19619     return false;
19620
19621   // Combine away the bottom node as its shuffle will be accumulated into
19622   // a preceding shuffle.
19623   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19624
19625   // Record the old value.
19626   SDValue Old = V;
19627
19628   // Merge this node's mask and our incoming mask (adjusted to account for all
19629   // the pshufd instructions encountered).
19630   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19631   for (int &M : Mask)
19632     M = VMask[M];
19633   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19634                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19635
19636   // Check that the shuffles didn't cancel each other out. If not, we need to
19637   // combine to the new one.
19638   if (Old != V)
19639     // Replace the combinable shuffle with the combined one, updating all users
19640     // so that we re-evaluate the chain here.
19641     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19642
19643   return true;
19644 }
19645
19646 /// \brief Try to combine x86 target specific shuffles.
19647 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19648                                            TargetLowering::DAGCombinerInfo &DCI,
19649                                            const X86Subtarget *Subtarget) {
19650   SDLoc DL(N);
19651   MVT VT = N.getSimpleValueType();
19652   SmallVector<int, 4> Mask;
19653
19654   switch (N.getOpcode()) {
19655   case X86ISD::PSHUFD:
19656   case X86ISD::PSHUFLW:
19657   case X86ISD::PSHUFHW:
19658     Mask = getPSHUFShuffleMask(N);
19659     assert(Mask.size() == 4);
19660     break;
19661   default:
19662     return SDValue();
19663   }
19664
19665   // Nuke no-op shuffles that show up after combining.
19666   if (isNoopShuffleMask(Mask))
19667     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19668
19669   // Look for simplifications involving one or two shuffle instructions.
19670   SDValue V = N.getOperand(0);
19671   switch (N.getOpcode()) {
19672   default:
19673     break;
19674   case X86ISD::PSHUFLW:
19675   case X86ISD::PSHUFHW:
19676     assert(VT == MVT::v8i16);
19677     (void)VT;
19678
19679     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19680       return SDValue(); // We combined away this shuffle, so we're done.
19681
19682     // See if this reduces to a PSHUFD which is no more expensive and can
19683     // combine with more operations.
19684     if (canWidenShuffleElements(Mask)) {
19685       int DMask[] = {-1, -1, -1, -1};
19686       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19687       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19688       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19689       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19690       DCI.AddToWorklist(V.getNode());
19691       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19692                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19693       DCI.AddToWorklist(V.getNode());
19694       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19695     }
19696
19697     // Look for shuffle patterns which can be implemented as a single unpack.
19698     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19699     // only works when we have a PSHUFD followed by two half-shuffles.
19700     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19701         (V.getOpcode() == X86ISD::PSHUFLW ||
19702          V.getOpcode() == X86ISD::PSHUFHW) &&
19703         V.getOpcode() != N.getOpcode() &&
19704         V.hasOneUse()) {
19705       SDValue D = V.getOperand(0);
19706       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19707         D = D.getOperand(0);
19708       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19709         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19710         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19711         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19712         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19713         int WordMask[8];
19714         for (int i = 0; i < 4; ++i) {
19715           WordMask[i + NOffset] = Mask[i] + NOffset;
19716           WordMask[i + VOffset] = VMask[i] + VOffset;
19717         }
19718         // Map the word mask through the DWord mask.
19719         int MappedMask[8];
19720         for (int i = 0; i < 8; ++i)
19721           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19722         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19723         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19724         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19725                        std::begin(UnpackLoMask)) ||
19726             std::equal(std::begin(MappedMask), std::end(MappedMask),
19727                        std::begin(UnpackHiMask))) {
19728           // We can replace all three shuffles with an unpack.
19729           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19730           DCI.AddToWorklist(V.getNode());
19731           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19732                                                 : X86ISD::UNPCKH,
19733                              DL, MVT::v8i16, V, V);
19734         }
19735       }
19736     }
19737
19738     break;
19739
19740   case X86ISD::PSHUFD:
19741     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19742       return NewN;
19743
19744     break;
19745   }
19746
19747   return SDValue();
19748 }
19749
19750 /// PerformShuffleCombine - Performs several different shuffle combines.
19751 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19752                                      TargetLowering::DAGCombinerInfo &DCI,
19753                                      const X86Subtarget *Subtarget) {
19754   SDLoc dl(N);
19755   SDValue N0 = N->getOperand(0);
19756   SDValue N1 = N->getOperand(1);
19757   EVT VT = N->getValueType(0);
19758
19759   // Don't create instructions with illegal types after legalize types has run.
19760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19761   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19762     return SDValue();
19763
19764   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19765   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19766       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19767     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19768
19769   // During Type Legalization, when promoting illegal vector types,
19770   // the backend might introduce new shuffle dag nodes and bitcasts.
19771   //
19772   // This code performs the following transformation:
19773   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19774   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19775   //
19776   // We do this only if both the bitcast and the BINOP dag nodes have
19777   // one use. Also, perform this transformation only if the new binary
19778   // operation is legal. This is to avoid introducing dag nodes that
19779   // potentially need to be further expanded (or custom lowered) into a
19780   // less optimal sequence of dag nodes.
19781   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19782       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19783       N0.getOpcode() == ISD::BITCAST) {
19784     SDValue BC0 = N0.getOperand(0);
19785     EVT SVT = BC0.getValueType();
19786     unsigned Opcode = BC0.getOpcode();
19787     unsigned NumElts = VT.getVectorNumElements();
19788     
19789     if (BC0.hasOneUse() && SVT.isVector() &&
19790         SVT.getVectorNumElements() * 2 == NumElts &&
19791         TLI.isOperationLegal(Opcode, VT)) {
19792       bool CanFold = false;
19793       switch (Opcode) {
19794       default : break;
19795       case ISD::ADD :
19796       case ISD::FADD :
19797       case ISD::SUB :
19798       case ISD::FSUB :
19799       case ISD::MUL :
19800       case ISD::FMUL :
19801         CanFold = true;
19802       }
19803
19804       unsigned SVTNumElts = SVT.getVectorNumElements();
19805       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19806       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19807         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19808       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19809         CanFold = SVOp->getMaskElt(i) < 0;
19810
19811       if (CanFold) {
19812         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19813         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19814         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19815         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19816       }
19817     }
19818   }
19819
19820   // Only handle 128 wide vector from here on.
19821   if (!VT.is128BitVector())
19822     return SDValue();
19823
19824   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19825   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19826   // consecutive, non-overlapping, and in the right order.
19827   SmallVector<SDValue, 16> Elts;
19828   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19829     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19830
19831   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19832   if (LD.getNode())
19833     return LD;
19834
19835   if (isTargetShuffle(N->getOpcode())) {
19836     SDValue Shuffle =
19837         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19838     if (Shuffle.getNode())
19839       return Shuffle;
19840
19841     // Try recursively combining arbitrary sequences of x86 shuffle
19842     // instructions into higher-order shuffles. We do this after combining
19843     // specific PSHUF instruction sequences into their minimal form so that we
19844     // can evaluate how many specialized shuffle instructions are involved in
19845     // a particular chain.
19846     SmallVector<int, 1> NonceMask; // Just a placeholder.
19847     NonceMask.push_back(0);
19848     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19849                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19850                                       DCI, Subtarget))
19851       return SDValue(); // This routine will use CombineTo to replace N.
19852   }
19853
19854   return SDValue();
19855 }
19856
19857 /// PerformTruncateCombine - Converts truncate operation to
19858 /// a sequence of vector shuffle operations.
19859 /// It is possible when we truncate 256-bit vector to 128-bit vector
19860 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19861                                       TargetLowering::DAGCombinerInfo &DCI,
19862                                       const X86Subtarget *Subtarget)  {
19863   return SDValue();
19864 }
19865
19866 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19867 /// specific shuffle of a load can be folded into a single element load.
19868 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19869 /// shuffles have been customed lowered so we need to handle those here.
19870 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19871                                          TargetLowering::DAGCombinerInfo &DCI) {
19872   if (DCI.isBeforeLegalizeOps())
19873     return SDValue();
19874
19875   SDValue InVec = N->getOperand(0);
19876   SDValue EltNo = N->getOperand(1);
19877
19878   if (!isa<ConstantSDNode>(EltNo))
19879     return SDValue();
19880
19881   EVT VT = InVec.getValueType();
19882
19883   if (InVec.getOpcode() == ISD::BITCAST) {
19884     // Don't duplicate a load with other uses.
19885     if (!InVec.hasOneUse())
19886       return SDValue();
19887     EVT BCVT = InVec.getOperand(0).getValueType();
19888     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19889       return SDValue();
19890     InVec = InVec.getOperand(0);
19891   }
19892
19893   if (!isTargetShuffle(InVec.getOpcode()))
19894     return SDValue();
19895
19896   // Don't duplicate a load with other uses.
19897   if (!InVec.hasOneUse())
19898     return SDValue();
19899
19900   SmallVector<int, 16> ShuffleMask;
19901   bool UnaryShuffle;
19902   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19903                             UnaryShuffle))
19904     return SDValue();
19905
19906   // Select the input vector, guarding against out of range extract vector.
19907   unsigned NumElems = VT.getVectorNumElements();
19908   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19909   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19910   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19911                                          : InVec.getOperand(1);
19912
19913   // If inputs to shuffle are the same for both ops, then allow 2 uses
19914   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19915
19916   if (LdNode.getOpcode() == ISD::BITCAST) {
19917     // Don't duplicate a load with other uses.
19918     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19919       return SDValue();
19920
19921     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19922     LdNode = LdNode.getOperand(0);
19923   }
19924
19925   if (!ISD::isNormalLoad(LdNode.getNode()))
19926     return SDValue();
19927
19928   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19929
19930   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19931     return SDValue();
19932
19933   EVT EltVT = N->getValueType(0);
19934   // If there's a bitcast before the shuffle, check if the load type and
19935   // alignment is valid.
19936   unsigned Align = LN0->getAlignment();
19937   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19938   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
19939       EltVT.getTypeForEVT(*DAG.getContext()));
19940
19941   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
19942     return SDValue();
19943
19944   // All checks match so transform back to vector_shuffle so that DAG combiner
19945   // can finish the job
19946   SDLoc dl(N);
19947
19948   // Create shuffle node taking into account the case that its a unary shuffle
19949   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19950   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19951                                  InVec.getOperand(0), Shuffle,
19952                                  &ShuffleMask[0]);
19953   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19954   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19955                      EltNo);
19956 }
19957
19958 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19959 /// generation and convert it from being a bunch of shuffles and extracts
19960 /// to a simple store and scalar loads to extract the elements.
19961 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19962                                          TargetLowering::DAGCombinerInfo &DCI) {
19963   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19964   if (NewOp.getNode())
19965     return NewOp;
19966
19967   SDValue InputVector = N->getOperand(0);
19968
19969   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19970   // from mmx to v2i32 has a single usage.
19971   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19972       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19973       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19974     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19975                        N->getValueType(0),
19976                        InputVector.getNode()->getOperand(0));
19977
19978   // Only operate on vectors of 4 elements, where the alternative shuffling
19979   // gets to be more expensive.
19980   if (InputVector.getValueType() != MVT::v4i32)
19981     return SDValue();
19982
19983   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19984   // single use which is a sign-extend or zero-extend, and all elements are
19985   // used.
19986   SmallVector<SDNode *, 4> Uses;
19987   unsigned ExtractedElements = 0;
19988   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19989        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19990     if (UI.getUse().getResNo() != InputVector.getResNo())
19991       return SDValue();
19992
19993     SDNode *Extract = *UI;
19994     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19995       return SDValue();
19996
19997     if (Extract->getValueType(0) != MVT::i32)
19998       return SDValue();
19999     if (!Extract->hasOneUse())
20000       return SDValue();
20001     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20002         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20003       return SDValue();
20004     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20005       return SDValue();
20006
20007     // Record which element was extracted.
20008     ExtractedElements |=
20009       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20010
20011     Uses.push_back(Extract);
20012   }
20013
20014   // If not all the elements were used, this may not be worthwhile.
20015   if (ExtractedElements != 15)
20016     return SDValue();
20017
20018   // Ok, we've now decided to do the transformation.
20019   SDLoc dl(InputVector);
20020
20021   // Store the value to a temporary stack slot.
20022   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20023   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20024                             MachinePointerInfo(), false, false, 0);
20025
20026   // Replace each use (extract) with a load of the appropriate element.
20027   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20028        UE = Uses.end(); UI != UE; ++UI) {
20029     SDNode *Extract = *UI;
20030
20031     // cOMpute the element's address.
20032     SDValue Idx = Extract->getOperand(1);
20033     unsigned EltSize =
20034         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20035     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20036     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20037     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20038
20039     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20040                                      StackPtr, OffsetVal);
20041
20042     // Load the scalar.
20043     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20044                                      ScalarAddr, MachinePointerInfo(),
20045                                      false, false, false, 0);
20046
20047     // Replace the exact with the load.
20048     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20049   }
20050
20051   // The replacement was made in place; don't return anything.
20052   return SDValue();
20053 }
20054
20055 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20056 static std::pair<unsigned, bool>
20057 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20058                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20059   if (!VT.isVector())
20060     return std::make_pair(0, false);
20061
20062   bool NeedSplit = false;
20063   switch (VT.getSimpleVT().SimpleTy) {
20064   default: return std::make_pair(0, false);
20065   case MVT::v32i8:
20066   case MVT::v16i16:
20067   case MVT::v8i32:
20068     if (!Subtarget->hasAVX2())
20069       NeedSplit = true;
20070     if (!Subtarget->hasAVX())
20071       return std::make_pair(0, false);
20072     break;
20073   case MVT::v16i8:
20074   case MVT::v8i16:
20075   case MVT::v4i32:
20076     if (!Subtarget->hasSSE2())
20077       return std::make_pair(0, false);
20078   }
20079
20080   // SSE2 has only a small subset of the operations.
20081   bool hasUnsigned = Subtarget->hasSSE41() ||
20082                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20083   bool hasSigned = Subtarget->hasSSE41() ||
20084                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20085
20086   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20087
20088   unsigned Opc = 0;
20089   // Check for x CC y ? x : y.
20090   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20091       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20092     switch (CC) {
20093     default: break;
20094     case ISD::SETULT:
20095     case ISD::SETULE:
20096       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20097     case ISD::SETUGT:
20098     case ISD::SETUGE:
20099       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20100     case ISD::SETLT:
20101     case ISD::SETLE:
20102       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20103     case ISD::SETGT:
20104     case ISD::SETGE:
20105       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20106     }
20107   // Check for x CC y ? y : x -- a min/max with reversed arms.
20108   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20109              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20110     switch (CC) {
20111     default: break;
20112     case ISD::SETULT:
20113     case ISD::SETULE:
20114       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20115     case ISD::SETUGT:
20116     case ISD::SETUGE:
20117       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20118     case ISD::SETLT:
20119     case ISD::SETLE:
20120       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20121     case ISD::SETGT:
20122     case ISD::SETGE:
20123       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20124     }
20125   }
20126
20127   return std::make_pair(Opc, NeedSplit);
20128 }
20129
20130 static SDValue
20131 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20132                                       const X86Subtarget *Subtarget) {
20133   SDLoc dl(N);
20134   SDValue Cond = N->getOperand(0);
20135   SDValue LHS = N->getOperand(1);
20136   SDValue RHS = N->getOperand(2);
20137
20138   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20139     SDValue CondSrc = Cond->getOperand(0);
20140     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20141       Cond = CondSrc->getOperand(0);
20142   }
20143
20144   MVT VT = N->getSimpleValueType(0);
20145   MVT EltVT = VT.getVectorElementType();
20146   unsigned NumElems = VT.getVectorNumElements();
20147   // There is no blend with immediate in AVX-512.
20148   if (VT.is512BitVector())
20149     return SDValue();
20150
20151   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20152     return SDValue();
20153   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20154     return SDValue();
20155
20156   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20157     return SDValue();
20158
20159   // A vselect where all conditions and data are constants can be optimized into
20160   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20161   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20162       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20163     return SDValue();
20164
20165   unsigned MaskValue = 0;
20166   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20167     return SDValue();
20168
20169   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20170   for (unsigned i = 0; i < NumElems; ++i) {
20171     // Be sure we emit undef where we can.
20172     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20173       ShuffleMask[i] = -1;
20174     else
20175       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20176   }
20177
20178   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20179 }
20180
20181 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20182 /// nodes.
20183 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20184                                     TargetLowering::DAGCombinerInfo &DCI,
20185                                     const X86Subtarget *Subtarget) {
20186   SDLoc DL(N);
20187   SDValue Cond = N->getOperand(0);
20188   // Get the LHS/RHS of the select.
20189   SDValue LHS = N->getOperand(1);
20190   SDValue RHS = N->getOperand(2);
20191   EVT VT = LHS.getValueType();
20192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20193
20194   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20195   // instructions match the semantics of the common C idiom x<y?x:y but not
20196   // x<=y?x:y, because of how they handle negative zero (which can be
20197   // ignored in unsafe-math mode).
20198   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20199       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20200       (Subtarget->hasSSE2() ||
20201        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20202     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20203
20204     unsigned Opcode = 0;
20205     // Check for x CC y ? x : y.
20206     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20207         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20208       switch (CC) {
20209       default: break;
20210       case ISD::SETULT:
20211         // Converting this to a min would handle NaNs incorrectly, and swapping
20212         // the operands would cause it to handle comparisons between positive
20213         // and negative zero incorrectly.
20214         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20215           if (!DAG.getTarget().Options.UnsafeFPMath &&
20216               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20217             break;
20218           std::swap(LHS, RHS);
20219         }
20220         Opcode = X86ISD::FMIN;
20221         break;
20222       case ISD::SETOLE:
20223         // Converting this to a min would handle comparisons between positive
20224         // and negative zero incorrectly.
20225         if (!DAG.getTarget().Options.UnsafeFPMath &&
20226             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20227           break;
20228         Opcode = X86ISD::FMIN;
20229         break;
20230       case ISD::SETULE:
20231         // Converting this to a min would handle both negative zeros and NaNs
20232         // incorrectly, but we can swap the operands to fix both.
20233         std::swap(LHS, RHS);
20234       case ISD::SETOLT:
20235       case ISD::SETLT:
20236       case ISD::SETLE:
20237         Opcode = X86ISD::FMIN;
20238         break;
20239
20240       case ISD::SETOGE:
20241         // Converting this to a max would handle comparisons between positive
20242         // and negative zero incorrectly.
20243         if (!DAG.getTarget().Options.UnsafeFPMath &&
20244             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20245           break;
20246         Opcode = X86ISD::FMAX;
20247         break;
20248       case ISD::SETUGT:
20249         // Converting this to a max would handle NaNs incorrectly, and swapping
20250         // the operands would cause it to handle comparisons between positive
20251         // and negative zero incorrectly.
20252         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20253           if (!DAG.getTarget().Options.UnsafeFPMath &&
20254               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20255             break;
20256           std::swap(LHS, RHS);
20257         }
20258         Opcode = X86ISD::FMAX;
20259         break;
20260       case ISD::SETUGE:
20261         // Converting this to a max would handle both negative zeros and NaNs
20262         // incorrectly, but we can swap the operands to fix both.
20263         std::swap(LHS, RHS);
20264       case ISD::SETOGT:
20265       case ISD::SETGT:
20266       case ISD::SETGE:
20267         Opcode = X86ISD::FMAX;
20268         break;
20269       }
20270     // Check for x CC y ? y : x -- a min/max with reversed arms.
20271     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20272                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20273       switch (CC) {
20274       default: break;
20275       case ISD::SETOGE:
20276         // Converting this to a min would handle comparisons between positive
20277         // and negative zero incorrectly, and swapping the operands would
20278         // cause it to handle NaNs incorrectly.
20279         if (!DAG.getTarget().Options.UnsafeFPMath &&
20280             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20281           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20282             break;
20283           std::swap(LHS, RHS);
20284         }
20285         Opcode = X86ISD::FMIN;
20286         break;
20287       case ISD::SETUGT:
20288         // Converting this to a min would handle NaNs incorrectly.
20289         if (!DAG.getTarget().Options.UnsafeFPMath &&
20290             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20291           break;
20292         Opcode = X86ISD::FMIN;
20293         break;
20294       case ISD::SETUGE:
20295         // Converting this to a min would handle both negative zeros and NaNs
20296         // incorrectly, but we can swap the operands to fix both.
20297         std::swap(LHS, RHS);
20298       case ISD::SETOGT:
20299       case ISD::SETGT:
20300       case ISD::SETGE:
20301         Opcode = X86ISD::FMIN;
20302         break;
20303
20304       case ISD::SETULT:
20305         // Converting this to a max would handle NaNs incorrectly.
20306         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20307           break;
20308         Opcode = X86ISD::FMAX;
20309         break;
20310       case ISD::SETOLE:
20311         // Converting this to a max would handle comparisons between positive
20312         // and negative zero incorrectly, and swapping the operands would
20313         // cause it to handle NaNs incorrectly.
20314         if (!DAG.getTarget().Options.UnsafeFPMath &&
20315             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20316           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20317             break;
20318           std::swap(LHS, RHS);
20319         }
20320         Opcode = X86ISD::FMAX;
20321         break;
20322       case ISD::SETULE:
20323         // Converting this to a max would handle both negative zeros and NaNs
20324         // incorrectly, but we can swap the operands to fix both.
20325         std::swap(LHS, RHS);
20326       case ISD::SETOLT:
20327       case ISD::SETLT:
20328       case ISD::SETLE:
20329         Opcode = X86ISD::FMAX;
20330         break;
20331       }
20332     }
20333
20334     if (Opcode)
20335       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20336   }
20337
20338   EVT CondVT = Cond.getValueType();
20339   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20340       CondVT.getVectorElementType() == MVT::i1) {
20341     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20342     // lowering on KNL. In this case we convert it to
20343     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20344     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20345     // Since SKX these selects have a proper lowering.
20346     EVT OpVT = LHS.getValueType();
20347     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20348         (OpVT.getVectorElementType() == MVT::i8 ||
20349          OpVT.getVectorElementType() == MVT::i16) &&
20350         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20351       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20352       DCI.AddToWorklist(Cond.getNode());
20353       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20354     }
20355   }
20356   // If this is a select between two integer constants, try to do some
20357   // optimizations.
20358   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20359     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20360       // Don't do this for crazy integer types.
20361       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20362         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20363         // so that TrueC (the true value) is larger than FalseC.
20364         bool NeedsCondInvert = false;
20365
20366         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20367             // Efficiently invertible.
20368             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20369              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20370               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20371           NeedsCondInvert = true;
20372           std::swap(TrueC, FalseC);
20373         }
20374
20375         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20376         if (FalseC->getAPIntValue() == 0 &&
20377             TrueC->getAPIntValue().isPowerOf2()) {
20378           if (NeedsCondInvert) // Invert the condition if needed.
20379             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20380                                DAG.getConstant(1, Cond.getValueType()));
20381
20382           // Zero extend the condition if needed.
20383           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20384
20385           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20386           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20387                              DAG.getConstant(ShAmt, MVT::i8));
20388         }
20389
20390         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20391         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20392           if (NeedsCondInvert) // Invert the condition if needed.
20393             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20394                                DAG.getConstant(1, Cond.getValueType()));
20395
20396           // Zero extend the condition if needed.
20397           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20398                              FalseC->getValueType(0), Cond);
20399           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20400                              SDValue(FalseC, 0));
20401         }
20402
20403         // Optimize cases that will turn into an LEA instruction.  This requires
20404         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20405         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20406           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20407           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20408
20409           bool isFastMultiplier = false;
20410           if (Diff < 10) {
20411             switch ((unsigned char)Diff) {
20412               default: break;
20413               case 1:  // result = add base, cond
20414               case 2:  // result = lea base(    , cond*2)
20415               case 3:  // result = lea base(cond, cond*2)
20416               case 4:  // result = lea base(    , cond*4)
20417               case 5:  // result = lea base(cond, cond*4)
20418               case 8:  // result = lea base(    , cond*8)
20419               case 9:  // result = lea base(cond, cond*8)
20420                 isFastMultiplier = true;
20421                 break;
20422             }
20423           }
20424
20425           if (isFastMultiplier) {
20426             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20427             if (NeedsCondInvert) // Invert the condition if needed.
20428               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20429                                  DAG.getConstant(1, Cond.getValueType()));
20430
20431             // Zero extend the condition if needed.
20432             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20433                                Cond);
20434             // Scale the condition by the difference.
20435             if (Diff != 1)
20436               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20437                                  DAG.getConstant(Diff, Cond.getValueType()));
20438
20439             // Add the base if non-zero.
20440             if (FalseC->getAPIntValue() != 0)
20441               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20442                                  SDValue(FalseC, 0));
20443             return Cond;
20444           }
20445         }
20446       }
20447   }
20448
20449   // Canonicalize max and min:
20450   // (x > y) ? x : y -> (x >= y) ? x : y
20451   // (x < y) ? x : y -> (x <= y) ? x : y
20452   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20453   // the need for an extra compare
20454   // against zero. e.g.
20455   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20456   // subl   %esi, %edi
20457   // testl  %edi, %edi
20458   // movl   $0, %eax
20459   // cmovgl %edi, %eax
20460   // =>
20461   // xorl   %eax, %eax
20462   // subl   %esi, $edi
20463   // cmovsl %eax, %edi
20464   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20465       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20466       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20467     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20468     switch (CC) {
20469     default: break;
20470     case ISD::SETLT:
20471     case ISD::SETGT: {
20472       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20473       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20474                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20475       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20476     }
20477     }
20478   }
20479
20480   // Early exit check
20481   if (!TLI.isTypeLegal(VT))
20482     return SDValue();
20483
20484   // Match VSELECTs into subs with unsigned saturation.
20485   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20486       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20487       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20488        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20489     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20490
20491     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20492     // left side invert the predicate to simplify logic below.
20493     SDValue Other;
20494     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20495       Other = RHS;
20496       CC = ISD::getSetCCInverse(CC, true);
20497     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20498       Other = LHS;
20499     }
20500
20501     if (Other.getNode() && Other->getNumOperands() == 2 &&
20502         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20503       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20504       SDValue CondRHS = Cond->getOperand(1);
20505
20506       // Look for a general sub with unsigned saturation first.
20507       // x >= y ? x-y : 0 --> subus x, y
20508       // x >  y ? x-y : 0 --> subus x, y
20509       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20510           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20511         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20512
20513       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20514         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20515           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20516             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20517               // If the RHS is a constant we have to reverse the const
20518               // canonicalization.
20519               // x > C-1 ? x+-C : 0 --> subus x, C
20520               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20521                   CondRHSConst->getAPIntValue() ==
20522                       (-OpRHSConst->getAPIntValue() - 1))
20523                 return DAG.getNode(
20524                     X86ISD::SUBUS, DL, VT, OpLHS,
20525                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20526
20527           // Another special case: If C was a sign bit, the sub has been
20528           // canonicalized into a xor.
20529           // FIXME: Would it be better to use computeKnownBits to determine
20530           //        whether it's safe to decanonicalize the xor?
20531           // x s< 0 ? x^C : 0 --> subus x, C
20532           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20533               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20534               OpRHSConst->getAPIntValue().isSignBit())
20535             // Note that we have to rebuild the RHS constant here to ensure we
20536             // don't rely on particular values of undef lanes.
20537             return DAG.getNode(
20538                 X86ISD::SUBUS, DL, VT, OpLHS,
20539                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20540         }
20541     }
20542   }
20543
20544   // Try to match a min/max vector operation.
20545   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20546     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20547     unsigned Opc = ret.first;
20548     bool NeedSplit = ret.second;
20549
20550     if (Opc && NeedSplit) {
20551       unsigned NumElems = VT.getVectorNumElements();
20552       // Extract the LHS vectors
20553       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20554       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20555
20556       // Extract the RHS vectors
20557       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20558       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20559
20560       // Create min/max for each subvector
20561       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20562       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20563
20564       // Merge the result
20565       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20566     } else if (Opc)
20567       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20568   }
20569
20570   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20571   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20572       // Check if SETCC has already been promoted
20573       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20574       // Check that condition value type matches vselect operand type
20575       CondVT == VT) { 
20576
20577     assert(Cond.getValueType().isVector() &&
20578            "vector select expects a vector selector!");
20579
20580     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20581     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20582
20583     if (!TValIsAllOnes && !FValIsAllZeros) {
20584       // Try invert the condition if true value is not all 1s and false value
20585       // is not all 0s.
20586       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20587       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20588
20589       if (TValIsAllZeros || FValIsAllOnes) {
20590         SDValue CC = Cond.getOperand(2);
20591         ISD::CondCode NewCC =
20592           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20593                                Cond.getOperand(0).getValueType().isInteger());
20594         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20595         std::swap(LHS, RHS);
20596         TValIsAllOnes = FValIsAllOnes;
20597         FValIsAllZeros = TValIsAllZeros;
20598       }
20599     }
20600
20601     if (TValIsAllOnes || FValIsAllZeros) {
20602       SDValue Ret;
20603
20604       if (TValIsAllOnes && FValIsAllZeros)
20605         Ret = Cond;
20606       else if (TValIsAllOnes)
20607         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20608                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20609       else if (FValIsAllZeros)
20610         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20611                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20612
20613       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20614     }
20615   }
20616
20617   // Try to fold this VSELECT into a MOVSS/MOVSD
20618   if (N->getOpcode() == ISD::VSELECT &&
20619       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20620     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20621         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20622       bool CanFold = false;
20623       unsigned NumElems = Cond.getNumOperands();
20624       SDValue A = LHS;
20625       SDValue B = RHS;
20626       
20627       if (isZero(Cond.getOperand(0))) {
20628         CanFold = true;
20629
20630         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20631         // fold (vselect <0,-1> -> (movsd A, B)
20632         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20633           CanFold = isAllOnes(Cond.getOperand(i));
20634       } else if (isAllOnes(Cond.getOperand(0))) {
20635         CanFold = true;
20636         std::swap(A, B);
20637
20638         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20639         // fold (vselect <-1,0> -> (movsd B, A)
20640         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20641           CanFold = isZero(Cond.getOperand(i));
20642       }
20643
20644       if (CanFold) {
20645         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20646           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20647         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20648       }
20649
20650       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20651         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20652         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20653         //                             (v2i64 (bitcast B)))))
20654         //
20655         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20656         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20657         //                             (v2f64 (bitcast B)))))
20658         //
20659         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20660         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20661         //                             (v2i64 (bitcast A)))))
20662         //
20663         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20664         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20665         //                             (v2f64 (bitcast A)))))
20666
20667         CanFold = (isZero(Cond.getOperand(0)) &&
20668                    isZero(Cond.getOperand(1)) &&
20669                    isAllOnes(Cond.getOperand(2)) &&
20670                    isAllOnes(Cond.getOperand(3)));
20671
20672         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20673             isAllOnes(Cond.getOperand(1)) &&
20674             isZero(Cond.getOperand(2)) &&
20675             isZero(Cond.getOperand(3))) {
20676           CanFold = true;
20677           std::swap(LHS, RHS);
20678         }
20679
20680         if (CanFold) {
20681           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20682           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20683           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20684           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20685                                                 NewB, DAG);
20686           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20687         }
20688       }
20689     }
20690   }
20691
20692   // If we know that this node is legal then we know that it is going to be
20693   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20694   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20695   // to simplify previous instructions.
20696   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20697       !DCI.isBeforeLegalize() &&
20698       // We explicitly check against v8i16 and v16i16 because, although
20699       // they're marked as Custom, they might only be legal when Cond is a
20700       // build_vector of constants. This will be taken care in a later
20701       // condition.
20702       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20703        VT != MVT::v8i16)) {
20704     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20705
20706     // Don't optimize vector selects that map to mask-registers.
20707     if (BitWidth == 1)
20708       return SDValue();
20709
20710     // Check all uses of that condition operand to check whether it will be
20711     // consumed by non-BLEND instructions, which may depend on all bits are set
20712     // properly.
20713     for (SDNode::use_iterator I = Cond->use_begin(),
20714                               E = Cond->use_end(); I != E; ++I)
20715       if (I->getOpcode() != ISD::VSELECT)
20716         // TODO: Add other opcodes eventually lowered into BLEND.
20717         return SDValue();
20718
20719     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20720     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20721
20722     APInt KnownZero, KnownOne;
20723     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20724                                           DCI.isBeforeLegalizeOps());
20725     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20726         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20727       DCI.CommitTargetLoweringOpt(TLO);
20728   }
20729
20730   // We should generate an X86ISD::BLENDI from a vselect if its argument
20731   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20732   // constants. This specific pattern gets generated when we split a
20733   // selector for a 512 bit vector in a machine without AVX512 (but with
20734   // 256-bit vectors), during legalization:
20735   //
20736   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20737   //
20738   // Iff we find this pattern and the build_vectors are built from
20739   // constants, we translate the vselect into a shuffle_vector that we
20740   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20741   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20742     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20743     if (Shuffle.getNode())
20744       return Shuffle;
20745   }
20746
20747   return SDValue();
20748 }
20749
20750 // Check whether a boolean test is testing a boolean value generated by
20751 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20752 // code.
20753 //
20754 // Simplify the following patterns:
20755 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20756 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20757 // to (Op EFLAGS Cond)
20758 //
20759 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20760 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20761 // to (Op EFLAGS !Cond)
20762 //
20763 // where Op could be BRCOND or CMOV.
20764 //
20765 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20766   // Quit if not CMP and SUB with its value result used.
20767   if (Cmp.getOpcode() != X86ISD::CMP &&
20768       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20769       return SDValue();
20770
20771   // Quit if not used as a boolean value.
20772   if (CC != X86::COND_E && CC != X86::COND_NE)
20773     return SDValue();
20774
20775   // Check CMP operands. One of them should be 0 or 1 and the other should be
20776   // an SetCC or extended from it.
20777   SDValue Op1 = Cmp.getOperand(0);
20778   SDValue Op2 = Cmp.getOperand(1);
20779
20780   SDValue SetCC;
20781   const ConstantSDNode* C = nullptr;
20782   bool needOppositeCond = (CC == X86::COND_E);
20783   bool checkAgainstTrue = false; // Is it a comparison against 1?
20784
20785   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20786     SetCC = Op2;
20787   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20788     SetCC = Op1;
20789   else // Quit if all operands are not constants.
20790     return SDValue();
20791
20792   if (C->getZExtValue() == 1) {
20793     needOppositeCond = !needOppositeCond;
20794     checkAgainstTrue = true;
20795   } else if (C->getZExtValue() != 0)
20796     // Quit if the constant is neither 0 or 1.
20797     return SDValue();
20798
20799   bool truncatedToBoolWithAnd = false;
20800   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20801   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20802          SetCC.getOpcode() == ISD::TRUNCATE ||
20803          SetCC.getOpcode() == ISD::AND) {
20804     if (SetCC.getOpcode() == ISD::AND) {
20805       int OpIdx = -1;
20806       ConstantSDNode *CS;
20807       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20808           CS->getZExtValue() == 1)
20809         OpIdx = 1;
20810       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20811           CS->getZExtValue() == 1)
20812         OpIdx = 0;
20813       if (OpIdx == -1)
20814         break;
20815       SetCC = SetCC.getOperand(OpIdx);
20816       truncatedToBoolWithAnd = true;
20817     } else
20818       SetCC = SetCC.getOperand(0);
20819   }
20820
20821   switch (SetCC.getOpcode()) {
20822   case X86ISD::SETCC_CARRY:
20823     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20824     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20825     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20826     // truncated to i1 using 'and'.
20827     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20828       break;
20829     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20830            "Invalid use of SETCC_CARRY!");
20831     // FALL THROUGH
20832   case X86ISD::SETCC:
20833     // Set the condition code or opposite one if necessary.
20834     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20835     if (needOppositeCond)
20836       CC = X86::GetOppositeBranchCondition(CC);
20837     return SetCC.getOperand(1);
20838   case X86ISD::CMOV: {
20839     // Check whether false/true value has canonical one, i.e. 0 or 1.
20840     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20841     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20842     // Quit if true value is not a constant.
20843     if (!TVal)
20844       return SDValue();
20845     // Quit if false value is not a constant.
20846     if (!FVal) {
20847       SDValue Op = SetCC.getOperand(0);
20848       // Skip 'zext' or 'trunc' node.
20849       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20850           Op.getOpcode() == ISD::TRUNCATE)
20851         Op = Op.getOperand(0);
20852       // A special case for rdrand/rdseed, where 0 is set if false cond is
20853       // found.
20854       if ((Op.getOpcode() != X86ISD::RDRAND &&
20855            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20856         return SDValue();
20857     }
20858     // Quit if false value is not the constant 0 or 1.
20859     bool FValIsFalse = true;
20860     if (FVal && FVal->getZExtValue() != 0) {
20861       if (FVal->getZExtValue() != 1)
20862         return SDValue();
20863       // If FVal is 1, opposite cond is needed.
20864       needOppositeCond = !needOppositeCond;
20865       FValIsFalse = false;
20866     }
20867     // Quit if TVal is not the constant opposite of FVal.
20868     if (FValIsFalse && TVal->getZExtValue() != 1)
20869       return SDValue();
20870     if (!FValIsFalse && TVal->getZExtValue() != 0)
20871       return SDValue();
20872     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20873     if (needOppositeCond)
20874       CC = X86::GetOppositeBranchCondition(CC);
20875     return SetCC.getOperand(3);
20876   }
20877   }
20878
20879   return SDValue();
20880 }
20881
20882 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20883 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20884                                   TargetLowering::DAGCombinerInfo &DCI,
20885                                   const X86Subtarget *Subtarget) {
20886   SDLoc DL(N);
20887
20888   // If the flag operand isn't dead, don't touch this CMOV.
20889   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20890     return SDValue();
20891
20892   SDValue FalseOp = N->getOperand(0);
20893   SDValue TrueOp = N->getOperand(1);
20894   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20895   SDValue Cond = N->getOperand(3);
20896
20897   if (CC == X86::COND_E || CC == X86::COND_NE) {
20898     switch (Cond.getOpcode()) {
20899     default: break;
20900     case X86ISD::BSR:
20901     case X86ISD::BSF:
20902       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20903       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20904         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20905     }
20906   }
20907
20908   SDValue Flags;
20909
20910   Flags = checkBoolTestSetCCCombine(Cond, CC);
20911   if (Flags.getNode() &&
20912       // Extra check as FCMOV only supports a subset of X86 cond.
20913       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20914     SDValue Ops[] = { FalseOp, TrueOp,
20915                       DAG.getConstant(CC, MVT::i8), Flags };
20916     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20917   }
20918
20919   // If this is a select between two integer constants, try to do some
20920   // optimizations.  Note that the operands are ordered the opposite of SELECT
20921   // operands.
20922   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20923     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20924       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20925       // larger than FalseC (the false value).
20926       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20927         CC = X86::GetOppositeBranchCondition(CC);
20928         std::swap(TrueC, FalseC);
20929         std::swap(TrueOp, FalseOp);
20930       }
20931
20932       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20933       // This is efficient for any integer data type (including i8/i16) and
20934       // shift amount.
20935       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20936         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20937                            DAG.getConstant(CC, MVT::i8), Cond);
20938
20939         // Zero extend the condition if needed.
20940         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20941
20942         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20943         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20944                            DAG.getConstant(ShAmt, MVT::i8));
20945         if (N->getNumValues() == 2)  // Dead flag value?
20946           return DCI.CombineTo(N, Cond, SDValue());
20947         return Cond;
20948       }
20949
20950       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20951       // for any integer data type, including i8/i16.
20952       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20953         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20954                            DAG.getConstant(CC, MVT::i8), Cond);
20955
20956         // Zero extend the condition if needed.
20957         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20958                            FalseC->getValueType(0), Cond);
20959         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20960                            SDValue(FalseC, 0));
20961
20962         if (N->getNumValues() == 2)  // Dead flag value?
20963           return DCI.CombineTo(N, Cond, SDValue());
20964         return Cond;
20965       }
20966
20967       // Optimize cases that will turn into an LEA instruction.  This requires
20968       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20969       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20970         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20971         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20972
20973         bool isFastMultiplier = false;
20974         if (Diff < 10) {
20975           switch ((unsigned char)Diff) {
20976           default: break;
20977           case 1:  // result = add base, cond
20978           case 2:  // result = lea base(    , cond*2)
20979           case 3:  // result = lea base(cond, cond*2)
20980           case 4:  // result = lea base(    , cond*4)
20981           case 5:  // result = lea base(cond, cond*4)
20982           case 8:  // result = lea base(    , cond*8)
20983           case 9:  // result = lea base(cond, cond*8)
20984             isFastMultiplier = true;
20985             break;
20986           }
20987         }
20988
20989         if (isFastMultiplier) {
20990           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20991           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20992                              DAG.getConstant(CC, MVT::i8), Cond);
20993           // Zero extend the condition if needed.
20994           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20995                              Cond);
20996           // Scale the condition by the difference.
20997           if (Diff != 1)
20998             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20999                                DAG.getConstant(Diff, Cond.getValueType()));
21000
21001           // Add the base if non-zero.
21002           if (FalseC->getAPIntValue() != 0)
21003             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21004                                SDValue(FalseC, 0));
21005           if (N->getNumValues() == 2)  // Dead flag value?
21006             return DCI.CombineTo(N, Cond, SDValue());
21007           return Cond;
21008         }
21009       }
21010     }
21011   }
21012
21013   // Handle these cases:
21014   //   (select (x != c), e, c) -> select (x != c), e, x),
21015   //   (select (x == c), c, e) -> select (x == c), x, e)
21016   // where the c is an integer constant, and the "select" is the combination
21017   // of CMOV and CMP.
21018   //
21019   // The rationale for this change is that the conditional-move from a constant
21020   // needs two instructions, however, conditional-move from a register needs
21021   // only one instruction.
21022   //
21023   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21024   //  some instruction-combining opportunities. This opt needs to be
21025   //  postponed as late as possible.
21026   //
21027   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21028     // the DCI.xxxx conditions are provided to postpone the optimization as
21029     // late as possible.
21030
21031     ConstantSDNode *CmpAgainst = nullptr;
21032     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21033         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21034         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21035
21036       if (CC == X86::COND_NE &&
21037           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21038         CC = X86::GetOppositeBranchCondition(CC);
21039         std::swap(TrueOp, FalseOp);
21040       }
21041
21042       if (CC == X86::COND_E &&
21043           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21044         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21045                           DAG.getConstant(CC, MVT::i8), Cond };
21046         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21047       }
21048     }
21049   }
21050
21051   return SDValue();
21052 }
21053
21054 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21055                                                 const X86Subtarget *Subtarget) {
21056   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21057   switch (IntNo) {
21058   default: return SDValue();
21059   // SSE/AVX/AVX2 blend intrinsics.
21060   case Intrinsic::x86_avx2_pblendvb:
21061   case Intrinsic::x86_avx2_pblendw:
21062   case Intrinsic::x86_avx2_pblendd_128:
21063   case Intrinsic::x86_avx2_pblendd_256:
21064     // Don't try to simplify this intrinsic if we don't have AVX2.
21065     if (!Subtarget->hasAVX2())
21066       return SDValue();
21067     // FALL-THROUGH
21068   case Intrinsic::x86_avx_blend_pd_256:
21069   case Intrinsic::x86_avx_blend_ps_256:
21070   case Intrinsic::x86_avx_blendv_pd_256:
21071   case Intrinsic::x86_avx_blendv_ps_256:
21072     // Don't try to simplify this intrinsic if we don't have AVX.
21073     if (!Subtarget->hasAVX())
21074       return SDValue();
21075     // FALL-THROUGH
21076   case Intrinsic::x86_sse41_pblendw:
21077   case Intrinsic::x86_sse41_blendpd:
21078   case Intrinsic::x86_sse41_blendps:
21079   case Intrinsic::x86_sse41_blendvps:
21080   case Intrinsic::x86_sse41_blendvpd:
21081   case Intrinsic::x86_sse41_pblendvb: {
21082     SDValue Op0 = N->getOperand(1);
21083     SDValue Op1 = N->getOperand(2);
21084     SDValue Mask = N->getOperand(3);
21085
21086     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21087     if (!Subtarget->hasSSE41())
21088       return SDValue();
21089
21090     // fold (blend A, A, Mask) -> A
21091     if (Op0 == Op1)
21092       return Op0;
21093     // fold (blend A, B, allZeros) -> A
21094     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21095       return Op0;
21096     // fold (blend A, B, allOnes) -> B
21097     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21098       return Op1;
21099     
21100     // Simplify the case where the mask is a constant i32 value.
21101     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21102       if (C->isNullValue())
21103         return Op0;
21104       if (C->isAllOnesValue())
21105         return Op1;
21106     }
21107
21108     return SDValue();
21109   }
21110
21111   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21112   case Intrinsic::x86_sse2_psrai_w:
21113   case Intrinsic::x86_sse2_psrai_d:
21114   case Intrinsic::x86_avx2_psrai_w:
21115   case Intrinsic::x86_avx2_psrai_d:
21116   case Intrinsic::x86_sse2_psra_w:
21117   case Intrinsic::x86_sse2_psra_d:
21118   case Intrinsic::x86_avx2_psra_w:
21119   case Intrinsic::x86_avx2_psra_d: {
21120     SDValue Op0 = N->getOperand(1);
21121     SDValue Op1 = N->getOperand(2);
21122     EVT VT = Op0.getValueType();
21123     assert(VT.isVector() && "Expected a vector type!");
21124
21125     if (isa<BuildVectorSDNode>(Op1))
21126       Op1 = Op1.getOperand(0);
21127
21128     if (!isa<ConstantSDNode>(Op1))
21129       return SDValue();
21130
21131     EVT SVT = VT.getVectorElementType();
21132     unsigned SVTBits = SVT.getSizeInBits();
21133
21134     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21135     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21136     uint64_t ShAmt = C.getZExtValue();
21137
21138     // Don't try to convert this shift into a ISD::SRA if the shift
21139     // count is bigger than or equal to the element size.
21140     if (ShAmt >= SVTBits)
21141       return SDValue();
21142
21143     // Trivial case: if the shift count is zero, then fold this
21144     // into the first operand.
21145     if (ShAmt == 0)
21146       return Op0;
21147
21148     // Replace this packed shift intrinsic with a target independent
21149     // shift dag node.
21150     SDValue Splat = DAG.getConstant(C, VT);
21151     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21152   }
21153   }
21154 }
21155
21156 /// PerformMulCombine - Optimize a single multiply with constant into two
21157 /// in order to implement it with two cheaper instructions, e.g.
21158 /// LEA + SHL, LEA + LEA.
21159 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21160                                  TargetLowering::DAGCombinerInfo &DCI) {
21161   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21162     return SDValue();
21163
21164   EVT VT = N->getValueType(0);
21165   if (VT != MVT::i64)
21166     return SDValue();
21167
21168   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21169   if (!C)
21170     return SDValue();
21171   uint64_t MulAmt = C->getZExtValue();
21172   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21173     return SDValue();
21174
21175   uint64_t MulAmt1 = 0;
21176   uint64_t MulAmt2 = 0;
21177   if ((MulAmt % 9) == 0) {
21178     MulAmt1 = 9;
21179     MulAmt2 = MulAmt / 9;
21180   } else if ((MulAmt % 5) == 0) {
21181     MulAmt1 = 5;
21182     MulAmt2 = MulAmt / 5;
21183   } else if ((MulAmt % 3) == 0) {
21184     MulAmt1 = 3;
21185     MulAmt2 = MulAmt / 3;
21186   }
21187   if (MulAmt2 &&
21188       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21189     SDLoc DL(N);
21190
21191     if (isPowerOf2_64(MulAmt2) &&
21192         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21193       // If second multiplifer is pow2, issue it first. We want the multiply by
21194       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21195       // is an add.
21196       std::swap(MulAmt1, MulAmt2);
21197
21198     SDValue NewMul;
21199     if (isPowerOf2_64(MulAmt1))
21200       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21201                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21202     else
21203       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21204                            DAG.getConstant(MulAmt1, VT));
21205
21206     if (isPowerOf2_64(MulAmt2))
21207       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21208                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21209     else
21210       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21211                            DAG.getConstant(MulAmt2, VT));
21212
21213     // Do not add new nodes to DAG combiner worklist.
21214     DCI.CombineTo(N, NewMul, false);
21215   }
21216   return SDValue();
21217 }
21218
21219 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21220   SDValue N0 = N->getOperand(0);
21221   SDValue N1 = N->getOperand(1);
21222   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21223   EVT VT = N0.getValueType();
21224
21225   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21226   // since the result of setcc_c is all zero's or all ones.
21227   if (VT.isInteger() && !VT.isVector() &&
21228       N1C && N0.getOpcode() == ISD::AND &&
21229       N0.getOperand(1).getOpcode() == ISD::Constant) {
21230     SDValue N00 = N0.getOperand(0);
21231     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21232         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21233           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21234          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21235       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21236       APInt ShAmt = N1C->getAPIntValue();
21237       Mask = Mask.shl(ShAmt);
21238       if (Mask != 0)
21239         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21240                            N00, DAG.getConstant(Mask, VT));
21241     }
21242   }
21243
21244   // Hardware support for vector shifts is sparse which makes us scalarize the
21245   // vector operations in many cases. Also, on sandybridge ADD is faster than
21246   // shl.
21247   // (shl V, 1) -> add V,V
21248   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21249     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21250       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21251       // We shift all of the values by one. In many cases we do not have
21252       // hardware support for this operation. This is better expressed as an ADD
21253       // of two values.
21254       if (N1SplatC->getZExtValue() == 1)
21255         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21256     }
21257
21258   return SDValue();
21259 }
21260
21261 /// \brief Returns a vector of 0s if the node in input is a vector logical
21262 /// shift by a constant amount which is known to be bigger than or equal
21263 /// to the vector element size in bits.
21264 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21265                                       const X86Subtarget *Subtarget) {
21266   EVT VT = N->getValueType(0);
21267
21268   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21269       (!Subtarget->hasInt256() ||
21270        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21271     return SDValue();
21272
21273   SDValue Amt = N->getOperand(1);
21274   SDLoc DL(N);
21275   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21276     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21277       APInt ShiftAmt = AmtSplat->getAPIntValue();
21278       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21279
21280       // SSE2/AVX2 logical shifts always return a vector of 0s
21281       // if the shift amount is bigger than or equal to
21282       // the element size. The constant shift amount will be
21283       // encoded as a 8-bit immediate.
21284       if (ShiftAmt.trunc(8).uge(MaxAmount))
21285         return getZeroVector(VT, Subtarget, DAG, DL);
21286     }
21287
21288   return SDValue();
21289 }
21290
21291 /// PerformShiftCombine - Combine shifts.
21292 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21293                                    TargetLowering::DAGCombinerInfo &DCI,
21294                                    const X86Subtarget *Subtarget) {
21295   if (N->getOpcode() == ISD::SHL) {
21296     SDValue V = PerformSHLCombine(N, DAG);
21297     if (V.getNode()) return V;
21298   }
21299
21300   if (N->getOpcode() != ISD::SRA) {
21301     // Try to fold this logical shift into a zero vector.
21302     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21303     if (V.getNode()) return V;
21304   }
21305
21306   return SDValue();
21307 }
21308
21309 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21310 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21311 // and friends.  Likewise for OR -> CMPNEQSS.
21312 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21313                             TargetLowering::DAGCombinerInfo &DCI,
21314                             const X86Subtarget *Subtarget) {
21315   unsigned opcode;
21316
21317   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21318   // we're requiring SSE2 for both.
21319   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21320     SDValue N0 = N->getOperand(0);
21321     SDValue N1 = N->getOperand(1);
21322     SDValue CMP0 = N0->getOperand(1);
21323     SDValue CMP1 = N1->getOperand(1);
21324     SDLoc DL(N);
21325
21326     // The SETCCs should both refer to the same CMP.
21327     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21328       return SDValue();
21329
21330     SDValue CMP00 = CMP0->getOperand(0);
21331     SDValue CMP01 = CMP0->getOperand(1);
21332     EVT     VT    = CMP00.getValueType();
21333
21334     if (VT == MVT::f32 || VT == MVT::f64) {
21335       bool ExpectingFlags = false;
21336       // Check for any users that want flags:
21337       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21338            !ExpectingFlags && UI != UE; ++UI)
21339         switch (UI->getOpcode()) {
21340         default:
21341         case ISD::BR_CC:
21342         case ISD::BRCOND:
21343         case ISD::SELECT:
21344           ExpectingFlags = true;
21345           break;
21346         case ISD::CopyToReg:
21347         case ISD::SIGN_EXTEND:
21348         case ISD::ZERO_EXTEND:
21349         case ISD::ANY_EXTEND:
21350           break;
21351         }
21352
21353       if (!ExpectingFlags) {
21354         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21355         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21356
21357         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21358           X86::CondCode tmp = cc0;
21359           cc0 = cc1;
21360           cc1 = tmp;
21361         }
21362
21363         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21364             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21365           // FIXME: need symbolic constants for these magic numbers.
21366           // See X86ATTInstPrinter.cpp:printSSECC().
21367           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21368           if (Subtarget->hasAVX512()) {
21369             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21370                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21371             if (N->getValueType(0) != MVT::i1)
21372               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21373                                  FSetCC);
21374             return FSetCC;
21375           }
21376           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21377                                               CMP00.getValueType(), CMP00, CMP01,
21378                                               DAG.getConstant(x86cc, MVT::i8));
21379
21380           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21381           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21382
21383           if (is64BitFP && !Subtarget->is64Bit()) {
21384             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21385             // 64-bit integer, since that's not a legal type. Since
21386             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21387             // bits, but can do this little dance to extract the lowest 32 bits
21388             // and work with those going forward.
21389             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21390                                            OnesOrZeroesF);
21391             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21392                                            Vector64);
21393             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21394                                         Vector32, DAG.getIntPtrConstant(0));
21395             IntVT = MVT::i32;
21396           }
21397
21398           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21399           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21400                                       DAG.getConstant(1, IntVT));
21401           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21402           return OneBitOfTruth;
21403         }
21404       }
21405     }
21406   }
21407   return SDValue();
21408 }
21409
21410 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21411 /// so it can be folded inside ANDNP.
21412 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21413   EVT VT = N->getValueType(0);
21414
21415   // Match direct AllOnes for 128 and 256-bit vectors
21416   if (ISD::isBuildVectorAllOnes(N))
21417     return true;
21418
21419   // Look through a bit convert.
21420   if (N->getOpcode() == ISD::BITCAST)
21421     N = N->getOperand(0).getNode();
21422
21423   // Sometimes the operand may come from a insert_subvector building a 256-bit
21424   // allones vector
21425   if (VT.is256BitVector() &&
21426       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21427     SDValue V1 = N->getOperand(0);
21428     SDValue V2 = N->getOperand(1);
21429
21430     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21431         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21432         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21433         ISD::isBuildVectorAllOnes(V2.getNode()))
21434       return true;
21435   }
21436
21437   return false;
21438 }
21439
21440 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21441 // register. In most cases we actually compare or select YMM-sized registers
21442 // and mixing the two types creates horrible code. This method optimizes
21443 // some of the transition sequences.
21444 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21445                                  TargetLowering::DAGCombinerInfo &DCI,
21446                                  const X86Subtarget *Subtarget) {
21447   EVT VT = N->getValueType(0);
21448   if (!VT.is256BitVector())
21449     return SDValue();
21450
21451   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21452           N->getOpcode() == ISD::ZERO_EXTEND ||
21453           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21454
21455   SDValue Narrow = N->getOperand(0);
21456   EVT NarrowVT = Narrow->getValueType(0);
21457   if (!NarrowVT.is128BitVector())
21458     return SDValue();
21459
21460   if (Narrow->getOpcode() != ISD::XOR &&
21461       Narrow->getOpcode() != ISD::AND &&
21462       Narrow->getOpcode() != ISD::OR)
21463     return SDValue();
21464
21465   SDValue N0  = Narrow->getOperand(0);
21466   SDValue N1  = Narrow->getOperand(1);
21467   SDLoc DL(Narrow);
21468
21469   // The Left side has to be a trunc.
21470   if (N0.getOpcode() != ISD::TRUNCATE)
21471     return SDValue();
21472
21473   // The type of the truncated inputs.
21474   EVT WideVT = N0->getOperand(0)->getValueType(0);
21475   if (WideVT != VT)
21476     return SDValue();
21477
21478   // The right side has to be a 'trunc' or a constant vector.
21479   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21480   ConstantSDNode *RHSConstSplat = nullptr;
21481   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21482     RHSConstSplat = RHSBV->getConstantSplatNode();
21483   if (!RHSTrunc && !RHSConstSplat)
21484     return SDValue();
21485
21486   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21487
21488   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21489     return SDValue();
21490
21491   // Set N0 and N1 to hold the inputs to the new wide operation.
21492   N0 = N0->getOperand(0);
21493   if (RHSConstSplat) {
21494     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21495                      SDValue(RHSConstSplat, 0));
21496     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21497     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21498   } else if (RHSTrunc) {
21499     N1 = N1->getOperand(0);
21500   }
21501
21502   // Generate the wide operation.
21503   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21504   unsigned Opcode = N->getOpcode();
21505   switch (Opcode) {
21506   case ISD::ANY_EXTEND:
21507     return Op;
21508   case ISD::ZERO_EXTEND: {
21509     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21510     APInt Mask = APInt::getAllOnesValue(InBits);
21511     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21512     return DAG.getNode(ISD::AND, DL, VT,
21513                        Op, DAG.getConstant(Mask, VT));
21514   }
21515   case ISD::SIGN_EXTEND:
21516     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21517                        Op, DAG.getValueType(NarrowVT));
21518   default:
21519     llvm_unreachable("Unexpected opcode");
21520   }
21521 }
21522
21523 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21524                                  TargetLowering::DAGCombinerInfo &DCI,
21525                                  const X86Subtarget *Subtarget) {
21526   EVT VT = N->getValueType(0);
21527   if (DCI.isBeforeLegalizeOps())
21528     return SDValue();
21529
21530   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21531   if (R.getNode())
21532     return R;
21533
21534   // Create BEXTR instructions
21535   // BEXTR is ((X >> imm) & (2**size-1))
21536   if (VT == MVT::i32 || VT == MVT::i64) {
21537     SDValue N0 = N->getOperand(0);
21538     SDValue N1 = N->getOperand(1);
21539     SDLoc DL(N);
21540
21541     // Check for BEXTR.
21542     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21543         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21544       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21545       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21546       if (MaskNode && ShiftNode) {
21547         uint64_t Mask = MaskNode->getZExtValue();
21548         uint64_t Shift = ShiftNode->getZExtValue();
21549         if (isMask_64(Mask)) {
21550           uint64_t MaskSize = CountPopulation_64(Mask);
21551           if (Shift + MaskSize <= VT.getSizeInBits())
21552             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21553                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21554         }
21555       }
21556     } // BEXTR
21557
21558     return SDValue();
21559   }
21560
21561   // Want to form ANDNP nodes:
21562   // 1) In the hopes of then easily combining them with OR and AND nodes
21563   //    to form PBLEND/PSIGN.
21564   // 2) To match ANDN packed intrinsics
21565   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21566     return SDValue();
21567
21568   SDValue N0 = N->getOperand(0);
21569   SDValue N1 = N->getOperand(1);
21570   SDLoc DL(N);
21571
21572   // Check LHS for vnot
21573   if (N0.getOpcode() == ISD::XOR &&
21574       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21575       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21576     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21577
21578   // Check RHS for vnot
21579   if (N1.getOpcode() == ISD::XOR &&
21580       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21581       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21582     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21583
21584   return SDValue();
21585 }
21586
21587 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21588                                 TargetLowering::DAGCombinerInfo &DCI,
21589                                 const X86Subtarget *Subtarget) {
21590   if (DCI.isBeforeLegalizeOps())
21591     return SDValue();
21592
21593   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21594   if (R.getNode())
21595     return R;
21596
21597   SDValue N0 = N->getOperand(0);
21598   SDValue N1 = N->getOperand(1);
21599   EVT VT = N->getValueType(0);
21600
21601   // look for psign/blend
21602   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21603     if (!Subtarget->hasSSSE3() ||
21604         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21605       return SDValue();
21606
21607     // Canonicalize pandn to RHS
21608     if (N0.getOpcode() == X86ISD::ANDNP)
21609       std::swap(N0, N1);
21610     // or (and (m, y), (pandn m, x))
21611     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21612       SDValue Mask = N1.getOperand(0);
21613       SDValue X    = N1.getOperand(1);
21614       SDValue Y;
21615       if (N0.getOperand(0) == Mask)
21616         Y = N0.getOperand(1);
21617       if (N0.getOperand(1) == Mask)
21618         Y = N0.getOperand(0);
21619
21620       // Check to see if the mask appeared in both the AND and ANDNP and
21621       if (!Y.getNode())
21622         return SDValue();
21623
21624       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21625       // Look through mask bitcast.
21626       if (Mask.getOpcode() == ISD::BITCAST)
21627         Mask = Mask.getOperand(0);
21628       if (X.getOpcode() == ISD::BITCAST)
21629         X = X.getOperand(0);
21630       if (Y.getOpcode() == ISD::BITCAST)
21631         Y = Y.getOperand(0);
21632
21633       EVT MaskVT = Mask.getValueType();
21634
21635       // Validate that the Mask operand is a vector sra node.
21636       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21637       // there is no psrai.b
21638       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21639       unsigned SraAmt = ~0;
21640       if (Mask.getOpcode() == ISD::SRA) {
21641         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21642           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21643             SraAmt = AmtConst->getZExtValue();
21644       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21645         SDValue SraC = Mask.getOperand(1);
21646         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21647       }
21648       if ((SraAmt + 1) != EltBits)
21649         return SDValue();
21650
21651       SDLoc DL(N);
21652
21653       // Now we know we at least have a plendvb with the mask val.  See if
21654       // we can form a psignb/w/d.
21655       // psign = x.type == y.type == mask.type && y = sub(0, x);
21656       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21657           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21658           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21659         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21660                "Unsupported VT for PSIGN");
21661         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21662         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21663       }
21664       // PBLENDVB only available on SSE 4.1
21665       if (!Subtarget->hasSSE41())
21666         return SDValue();
21667
21668       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21669
21670       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21671       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21672       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21673       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21674       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21675     }
21676   }
21677
21678   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21679     return SDValue();
21680
21681   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21682   MachineFunction &MF = DAG.getMachineFunction();
21683   bool OptForSize = MF.getFunction()->getAttributes().
21684     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21685
21686   // SHLD/SHRD instructions have lower register pressure, but on some
21687   // platforms they have higher latency than the equivalent
21688   // series of shifts/or that would otherwise be generated.
21689   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21690   // have higher latencies and we are not optimizing for size.
21691   if (!OptForSize && Subtarget->isSHLDSlow())
21692     return SDValue();
21693
21694   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21695     std::swap(N0, N1);
21696   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21697     return SDValue();
21698   if (!N0.hasOneUse() || !N1.hasOneUse())
21699     return SDValue();
21700
21701   SDValue ShAmt0 = N0.getOperand(1);
21702   if (ShAmt0.getValueType() != MVT::i8)
21703     return SDValue();
21704   SDValue ShAmt1 = N1.getOperand(1);
21705   if (ShAmt1.getValueType() != MVT::i8)
21706     return SDValue();
21707   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21708     ShAmt0 = ShAmt0.getOperand(0);
21709   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21710     ShAmt1 = ShAmt1.getOperand(0);
21711
21712   SDLoc DL(N);
21713   unsigned Opc = X86ISD::SHLD;
21714   SDValue Op0 = N0.getOperand(0);
21715   SDValue Op1 = N1.getOperand(0);
21716   if (ShAmt0.getOpcode() == ISD::SUB) {
21717     Opc = X86ISD::SHRD;
21718     std::swap(Op0, Op1);
21719     std::swap(ShAmt0, ShAmt1);
21720   }
21721
21722   unsigned Bits = VT.getSizeInBits();
21723   if (ShAmt1.getOpcode() == ISD::SUB) {
21724     SDValue Sum = ShAmt1.getOperand(0);
21725     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21726       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21727       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21728         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21729       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21730         return DAG.getNode(Opc, DL, VT,
21731                            Op0, Op1,
21732                            DAG.getNode(ISD::TRUNCATE, DL,
21733                                        MVT::i8, ShAmt0));
21734     }
21735   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21736     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21737     if (ShAmt0C &&
21738         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21739       return DAG.getNode(Opc, DL, VT,
21740                          N0.getOperand(0), N1.getOperand(0),
21741                          DAG.getNode(ISD::TRUNCATE, DL,
21742                                        MVT::i8, ShAmt0));
21743   }
21744
21745   return SDValue();
21746 }
21747
21748 // Generate NEG and CMOV for integer abs.
21749 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21750   EVT VT = N->getValueType(0);
21751
21752   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21753   // 8-bit integer abs to NEG and CMOV.
21754   if (VT.isInteger() && VT.getSizeInBits() == 8)
21755     return SDValue();
21756
21757   SDValue N0 = N->getOperand(0);
21758   SDValue N1 = N->getOperand(1);
21759   SDLoc DL(N);
21760
21761   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21762   // and change it to SUB and CMOV.
21763   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21764       N0.getOpcode() == ISD::ADD &&
21765       N0.getOperand(1) == N1 &&
21766       N1.getOpcode() == ISD::SRA &&
21767       N1.getOperand(0) == N0.getOperand(0))
21768     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21769       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21770         // Generate SUB & CMOV.
21771         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21772                                   DAG.getConstant(0, VT), N0.getOperand(0));
21773
21774         SDValue Ops[] = { N0.getOperand(0), Neg,
21775                           DAG.getConstant(X86::COND_GE, MVT::i8),
21776                           SDValue(Neg.getNode(), 1) };
21777         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21778       }
21779   return SDValue();
21780 }
21781
21782 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21783 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21784                                  TargetLowering::DAGCombinerInfo &DCI,
21785                                  const X86Subtarget *Subtarget) {
21786   if (DCI.isBeforeLegalizeOps())
21787     return SDValue();
21788
21789   if (Subtarget->hasCMov()) {
21790     SDValue RV = performIntegerAbsCombine(N, DAG);
21791     if (RV.getNode())
21792       return RV;
21793   }
21794
21795   return SDValue();
21796 }
21797
21798 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21799 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21800                                   TargetLowering::DAGCombinerInfo &DCI,
21801                                   const X86Subtarget *Subtarget) {
21802   LoadSDNode *Ld = cast<LoadSDNode>(N);
21803   EVT RegVT = Ld->getValueType(0);
21804   EVT MemVT = Ld->getMemoryVT();
21805   SDLoc dl(Ld);
21806   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21807
21808   // On Sandybridge unaligned 256bit loads are inefficient.
21809   ISD::LoadExtType Ext = Ld->getExtensionType();
21810   unsigned Alignment = Ld->getAlignment();
21811   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21812   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21813       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21814     unsigned NumElems = RegVT.getVectorNumElements();
21815     if (NumElems < 2)
21816       return SDValue();
21817
21818     SDValue Ptr = Ld->getBasePtr();
21819     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21820
21821     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21822                                   NumElems/2);
21823     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21824                                 Ld->getPointerInfo(), Ld->isVolatile(),
21825                                 Ld->isNonTemporal(), Ld->isInvariant(),
21826                                 Alignment);
21827     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21828     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21829                                 Ld->getPointerInfo(), Ld->isVolatile(),
21830                                 Ld->isNonTemporal(), Ld->isInvariant(),
21831                                 std::min(16U, Alignment));
21832     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21833                              Load1.getValue(1),
21834                              Load2.getValue(1));
21835
21836     SDValue NewVec = DAG.getUNDEF(RegVT);
21837     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21838     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21839     return DCI.CombineTo(N, NewVec, TF, true);
21840   }
21841
21842   return SDValue();
21843 }
21844
21845 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21846 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21847                                    const X86Subtarget *Subtarget) {
21848   StoreSDNode *St = cast<StoreSDNode>(N);
21849   EVT VT = St->getValue().getValueType();
21850   EVT StVT = St->getMemoryVT();
21851   SDLoc dl(St);
21852   SDValue StoredVal = St->getOperand(1);
21853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21854
21855   // If we are saving a concatenation of two XMM registers, perform two stores.
21856   // On Sandy Bridge, 256-bit memory operations are executed by two
21857   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21858   // memory  operation.
21859   unsigned Alignment = St->getAlignment();
21860   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21861   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21862       StVT == VT && !IsAligned) {
21863     unsigned NumElems = VT.getVectorNumElements();
21864     if (NumElems < 2)
21865       return SDValue();
21866
21867     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21868     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21869
21870     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21871     SDValue Ptr0 = St->getBasePtr();
21872     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21873
21874     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21875                                 St->getPointerInfo(), St->isVolatile(),
21876                                 St->isNonTemporal(), Alignment);
21877     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21878                                 St->getPointerInfo(), St->isVolatile(),
21879                                 St->isNonTemporal(),
21880                                 std::min(16U, Alignment));
21881     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21882   }
21883
21884   // Optimize trunc store (of multiple scalars) to shuffle and store.
21885   // First, pack all of the elements in one place. Next, store to memory
21886   // in fewer chunks.
21887   if (St->isTruncatingStore() && VT.isVector()) {
21888     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21889     unsigned NumElems = VT.getVectorNumElements();
21890     assert(StVT != VT && "Cannot truncate to the same type");
21891     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21892     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21893
21894     // From, To sizes and ElemCount must be pow of two
21895     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21896     // We are going to use the original vector elt for storing.
21897     // Accumulated smaller vector elements must be a multiple of the store size.
21898     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21899
21900     unsigned SizeRatio  = FromSz / ToSz;
21901
21902     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21903
21904     // Create a type on which we perform the shuffle
21905     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21906             StVT.getScalarType(), NumElems*SizeRatio);
21907
21908     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21909
21910     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21911     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21912     for (unsigned i = 0; i != NumElems; ++i)
21913       ShuffleVec[i] = i * SizeRatio;
21914
21915     // Can't shuffle using an illegal type.
21916     if (!TLI.isTypeLegal(WideVecVT))
21917       return SDValue();
21918
21919     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21920                                          DAG.getUNDEF(WideVecVT),
21921                                          &ShuffleVec[0]);
21922     // At this point all of the data is stored at the bottom of the
21923     // register. We now need to save it to mem.
21924
21925     // Find the largest store unit
21926     MVT StoreType = MVT::i8;
21927     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21928          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21929       MVT Tp = (MVT::SimpleValueType)tp;
21930       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21931         StoreType = Tp;
21932     }
21933
21934     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21935     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21936         (64 <= NumElems * ToSz))
21937       StoreType = MVT::f64;
21938
21939     // Bitcast the original vector into a vector of store-size units
21940     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21941             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21942     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21943     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21944     SmallVector<SDValue, 8> Chains;
21945     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21946                                         TLI.getPointerTy());
21947     SDValue Ptr = St->getBasePtr();
21948
21949     // Perform one or more big stores into memory.
21950     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21951       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21952                                    StoreType, ShuffWide,
21953                                    DAG.getIntPtrConstant(i));
21954       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21955                                 St->getPointerInfo(), St->isVolatile(),
21956                                 St->isNonTemporal(), St->getAlignment());
21957       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21958       Chains.push_back(Ch);
21959     }
21960
21961     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21962   }
21963
21964   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21965   // the FP state in cases where an emms may be missing.
21966   // A preferable solution to the general problem is to figure out the right
21967   // places to insert EMMS.  This qualifies as a quick hack.
21968
21969   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21970   if (VT.getSizeInBits() != 64)
21971     return SDValue();
21972
21973   const Function *F = DAG.getMachineFunction().getFunction();
21974   bool NoImplicitFloatOps = F->getAttributes().
21975     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21976   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21977                      && Subtarget->hasSSE2();
21978   if ((VT.isVector() ||
21979        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21980       isa<LoadSDNode>(St->getValue()) &&
21981       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21982       St->getChain().hasOneUse() && !St->isVolatile()) {
21983     SDNode* LdVal = St->getValue().getNode();
21984     LoadSDNode *Ld = nullptr;
21985     int TokenFactorIndex = -1;
21986     SmallVector<SDValue, 8> Ops;
21987     SDNode* ChainVal = St->getChain().getNode();
21988     // Must be a store of a load.  We currently handle two cases:  the load
21989     // is a direct child, and it's under an intervening TokenFactor.  It is
21990     // possible to dig deeper under nested TokenFactors.
21991     if (ChainVal == LdVal)
21992       Ld = cast<LoadSDNode>(St->getChain());
21993     else if (St->getValue().hasOneUse() &&
21994              ChainVal->getOpcode() == ISD::TokenFactor) {
21995       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21996         if (ChainVal->getOperand(i).getNode() == LdVal) {
21997           TokenFactorIndex = i;
21998           Ld = cast<LoadSDNode>(St->getValue());
21999         } else
22000           Ops.push_back(ChainVal->getOperand(i));
22001       }
22002     }
22003
22004     if (!Ld || !ISD::isNormalLoad(Ld))
22005       return SDValue();
22006
22007     // If this is not the MMX case, i.e. we are just turning i64 load/store
22008     // into f64 load/store, avoid the transformation if there are multiple
22009     // uses of the loaded value.
22010     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22011       return SDValue();
22012
22013     SDLoc LdDL(Ld);
22014     SDLoc StDL(N);
22015     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22016     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22017     // pair instead.
22018     if (Subtarget->is64Bit() || F64IsLegal) {
22019       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22020       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22021                                   Ld->getPointerInfo(), Ld->isVolatile(),
22022                                   Ld->isNonTemporal(), Ld->isInvariant(),
22023                                   Ld->getAlignment());
22024       SDValue NewChain = NewLd.getValue(1);
22025       if (TokenFactorIndex != -1) {
22026         Ops.push_back(NewChain);
22027         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22028       }
22029       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22030                           St->getPointerInfo(),
22031                           St->isVolatile(), St->isNonTemporal(),
22032                           St->getAlignment());
22033     }
22034
22035     // Otherwise, lower to two pairs of 32-bit loads / stores.
22036     SDValue LoAddr = Ld->getBasePtr();
22037     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22038                                  DAG.getConstant(4, MVT::i32));
22039
22040     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22041                                Ld->getPointerInfo(),
22042                                Ld->isVolatile(), Ld->isNonTemporal(),
22043                                Ld->isInvariant(), Ld->getAlignment());
22044     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22045                                Ld->getPointerInfo().getWithOffset(4),
22046                                Ld->isVolatile(), Ld->isNonTemporal(),
22047                                Ld->isInvariant(),
22048                                MinAlign(Ld->getAlignment(), 4));
22049
22050     SDValue NewChain = LoLd.getValue(1);
22051     if (TokenFactorIndex != -1) {
22052       Ops.push_back(LoLd);
22053       Ops.push_back(HiLd);
22054       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22055     }
22056
22057     LoAddr = St->getBasePtr();
22058     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22059                          DAG.getConstant(4, MVT::i32));
22060
22061     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22062                                 St->getPointerInfo(),
22063                                 St->isVolatile(), St->isNonTemporal(),
22064                                 St->getAlignment());
22065     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22066                                 St->getPointerInfo().getWithOffset(4),
22067                                 St->isVolatile(),
22068                                 St->isNonTemporal(),
22069                                 MinAlign(St->getAlignment(), 4));
22070     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22071   }
22072   return SDValue();
22073 }
22074
22075 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22076 /// and return the operands for the horizontal operation in LHS and RHS.  A
22077 /// horizontal operation performs the binary operation on successive elements
22078 /// of its first operand, then on successive elements of its second operand,
22079 /// returning the resulting values in a vector.  For example, if
22080 ///   A = < float a0, float a1, float a2, float a3 >
22081 /// and
22082 ///   B = < float b0, float b1, float b2, float b3 >
22083 /// then the result of doing a horizontal operation on A and B is
22084 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22085 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22086 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22087 /// set to A, RHS to B, and the routine returns 'true'.
22088 /// Note that the binary operation should have the property that if one of the
22089 /// operands is UNDEF then the result is UNDEF.
22090 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22091   // Look for the following pattern: if
22092   //   A = < float a0, float a1, float a2, float a3 >
22093   //   B = < float b0, float b1, float b2, float b3 >
22094   // and
22095   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22096   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22097   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22098   // which is A horizontal-op B.
22099
22100   // At least one of the operands should be a vector shuffle.
22101   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22102       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22103     return false;
22104
22105   MVT VT = LHS.getSimpleValueType();
22106
22107   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22108          "Unsupported vector type for horizontal add/sub");
22109
22110   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22111   // operate independently on 128-bit lanes.
22112   unsigned NumElts = VT.getVectorNumElements();
22113   unsigned NumLanes = VT.getSizeInBits()/128;
22114   unsigned NumLaneElts = NumElts / NumLanes;
22115   assert((NumLaneElts % 2 == 0) &&
22116          "Vector type should have an even number of elements in each lane");
22117   unsigned HalfLaneElts = NumLaneElts/2;
22118
22119   // View LHS in the form
22120   //   LHS = VECTOR_SHUFFLE A, B, LMask
22121   // If LHS is not a shuffle then pretend it is the shuffle
22122   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22123   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22124   // type VT.
22125   SDValue A, B;
22126   SmallVector<int, 16> LMask(NumElts);
22127   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22128     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22129       A = LHS.getOperand(0);
22130     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22131       B = LHS.getOperand(1);
22132     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22133     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22134   } else {
22135     if (LHS.getOpcode() != ISD::UNDEF)
22136       A = LHS;
22137     for (unsigned i = 0; i != NumElts; ++i)
22138       LMask[i] = i;
22139   }
22140
22141   // Likewise, view RHS in the form
22142   //   RHS = VECTOR_SHUFFLE C, D, RMask
22143   SDValue C, D;
22144   SmallVector<int, 16> RMask(NumElts);
22145   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22146     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22147       C = RHS.getOperand(0);
22148     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22149       D = RHS.getOperand(1);
22150     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22151     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22152   } else {
22153     if (RHS.getOpcode() != ISD::UNDEF)
22154       C = RHS;
22155     for (unsigned i = 0; i != NumElts; ++i)
22156       RMask[i] = i;
22157   }
22158
22159   // Check that the shuffles are both shuffling the same vectors.
22160   if (!(A == C && B == D) && !(A == D && B == C))
22161     return false;
22162
22163   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22164   if (!A.getNode() && !B.getNode())
22165     return false;
22166
22167   // If A and B occur in reverse order in RHS, then "swap" them (which means
22168   // rewriting the mask).
22169   if (A != C)
22170     CommuteVectorShuffleMask(RMask, NumElts);
22171
22172   // At this point LHS and RHS are equivalent to
22173   //   LHS = VECTOR_SHUFFLE A, B, LMask
22174   //   RHS = VECTOR_SHUFFLE A, B, RMask
22175   // Check that the masks correspond to performing a horizontal operation.
22176   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22177     for (unsigned i = 0; i != NumLaneElts; ++i) {
22178       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22179
22180       // Ignore any UNDEF components.
22181       if (LIdx < 0 || RIdx < 0 ||
22182           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22183           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22184         continue;
22185
22186       // Check that successive elements are being operated on.  If not, this is
22187       // not a horizontal operation.
22188       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22189       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22190       if (!(LIdx == Index && RIdx == Index + 1) &&
22191           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22192         return false;
22193     }
22194   }
22195
22196   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22197   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22198   return true;
22199 }
22200
22201 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22202 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22203                                   const X86Subtarget *Subtarget) {
22204   EVT VT = N->getValueType(0);
22205   SDValue LHS = N->getOperand(0);
22206   SDValue RHS = N->getOperand(1);
22207
22208   // Try to synthesize horizontal adds from adds of shuffles.
22209   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22210        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22211       isHorizontalBinOp(LHS, RHS, true))
22212     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22213   return SDValue();
22214 }
22215
22216 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22217 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22218                                   const X86Subtarget *Subtarget) {
22219   EVT VT = N->getValueType(0);
22220   SDValue LHS = N->getOperand(0);
22221   SDValue RHS = N->getOperand(1);
22222
22223   // Try to synthesize horizontal subs from subs of shuffles.
22224   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22225        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22226       isHorizontalBinOp(LHS, RHS, false))
22227     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22228   return SDValue();
22229 }
22230
22231 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22232 /// X86ISD::FXOR nodes.
22233 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22234   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22235   // F[X]OR(0.0, x) -> x
22236   // F[X]OR(x, 0.0) -> x
22237   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22238     if (C->getValueAPF().isPosZero())
22239       return N->getOperand(1);
22240   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22241     if (C->getValueAPF().isPosZero())
22242       return N->getOperand(0);
22243   return SDValue();
22244 }
22245
22246 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22247 /// X86ISD::FMAX nodes.
22248 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22249   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22250
22251   // Only perform optimizations if UnsafeMath is used.
22252   if (!DAG.getTarget().Options.UnsafeFPMath)
22253     return SDValue();
22254
22255   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22256   // into FMINC and FMAXC, which are Commutative operations.
22257   unsigned NewOp = 0;
22258   switch (N->getOpcode()) {
22259     default: llvm_unreachable("unknown opcode");
22260     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22261     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22262   }
22263
22264   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22265                      N->getOperand(0), N->getOperand(1));
22266 }
22267
22268 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22269 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22270   // FAND(0.0, x) -> 0.0
22271   // FAND(x, 0.0) -> 0.0
22272   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22273     if (C->getValueAPF().isPosZero())
22274       return N->getOperand(0);
22275   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22276     if (C->getValueAPF().isPosZero())
22277       return N->getOperand(1);
22278   return SDValue();
22279 }
22280
22281 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22282 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22283   // FANDN(x, 0.0) -> 0.0
22284   // FANDN(0.0, x) -> x
22285   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22286     if (C->getValueAPF().isPosZero())
22287       return N->getOperand(1);
22288   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22289     if (C->getValueAPF().isPosZero())
22290       return N->getOperand(1);
22291   return SDValue();
22292 }
22293
22294 static SDValue PerformBTCombine(SDNode *N,
22295                                 SelectionDAG &DAG,
22296                                 TargetLowering::DAGCombinerInfo &DCI) {
22297   // BT ignores high bits in the bit index operand.
22298   SDValue Op1 = N->getOperand(1);
22299   if (Op1.hasOneUse()) {
22300     unsigned BitWidth = Op1.getValueSizeInBits();
22301     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22302     APInt KnownZero, KnownOne;
22303     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22304                                           !DCI.isBeforeLegalizeOps());
22305     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22306     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22307         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22308       DCI.CommitTargetLoweringOpt(TLO);
22309   }
22310   return SDValue();
22311 }
22312
22313 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22314   SDValue Op = N->getOperand(0);
22315   if (Op.getOpcode() == ISD::BITCAST)
22316     Op = Op.getOperand(0);
22317   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22318   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22319       VT.getVectorElementType().getSizeInBits() ==
22320       OpVT.getVectorElementType().getSizeInBits()) {
22321     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22322   }
22323   return SDValue();
22324 }
22325
22326 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22327                                                const X86Subtarget *Subtarget) {
22328   EVT VT = N->getValueType(0);
22329   if (!VT.isVector())
22330     return SDValue();
22331
22332   SDValue N0 = N->getOperand(0);
22333   SDValue N1 = N->getOperand(1);
22334   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22335   SDLoc dl(N);
22336
22337   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22338   // both SSE and AVX2 since there is no sign-extended shift right
22339   // operation on a vector with 64-bit elements.
22340   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22341   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22342   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22343       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22344     SDValue N00 = N0.getOperand(0);
22345
22346     // EXTLOAD has a better solution on AVX2,
22347     // it may be replaced with X86ISD::VSEXT node.
22348     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22349       if (!ISD::isNormalLoad(N00.getNode()))
22350         return SDValue();
22351
22352     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22353         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22354                                   N00, N1);
22355       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22356     }
22357   }
22358   return SDValue();
22359 }
22360
22361 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22362                                   TargetLowering::DAGCombinerInfo &DCI,
22363                                   const X86Subtarget *Subtarget) {
22364   if (!DCI.isBeforeLegalizeOps())
22365     return SDValue();
22366
22367   if (!Subtarget->hasFp256())
22368     return SDValue();
22369
22370   EVT VT = N->getValueType(0);
22371   if (VT.isVector() && VT.getSizeInBits() == 256) {
22372     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22373     if (R.getNode())
22374       return R;
22375   }
22376
22377   return SDValue();
22378 }
22379
22380 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22381                                  const X86Subtarget* Subtarget) {
22382   SDLoc dl(N);
22383   EVT VT = N->getValueType(0);
22384
22385   // Let legalize expand this if it isn't a legal type yet.
22386   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22387     return SDValue();
22388
22389   EVT ScalarVT = VT.getScalarType();
22390   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22391       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22392     return SDValue();
22393
22394   SDValue A = N->getOperand(0);
22395   SDValue B = N->getOperand(1);
22396   SDValue C = N->getOperand(2);
22397
22398   bool NegA = (A.getOpcode() == ISD::FNEG);
22399   bool NegB = (B.getOpcode() == ISD::FNEG);
22400   bool NegC = (C.getOpcode() == ISD::FNEG);
22401
22402   // Negative multiplication when NegA xor NegB
22403   bool NegMul = (NegA != NegB);
22404   if (NegA)
22405     A = A.getOperand(0);
22406   if (NegB)
22407     B = B.getOperand(0);
22408   if (NegC)
22409     C = C.getOperand(0);
22410
22411   unsigned Opcode;
22412   if (!NegMul)
22413     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22414   else
22415     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22416
22417   return DAG.getNode(Opcode, dl, VT, A, B, C);
22418 }
22419
22420 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22421                                   TargetLowering::DAGCombinerInfo &DCI,
22422                                   const X86Subtarget *Subtarget) {
22423   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22424   //           (and (i32 x86isd::setcc_carry), 1)
22425   // This eliminates the zext. This transformation is necessary because
22426   // ISD::SETCC is always legalized to i8.
22427   SDLoc dl(N);
22428   SDValue N0 = N->getOperand(0);
22429   EVT VT = N->getValueType(0);
22430
22431   if (N0.getOpcode() == ISD::AND &&
22432       N0.hasOneUse() &&
22433       N0.getOperand(0).hasOneUse()) {
22434     SDValue N00 = N0.getOperand(0);
22435     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22436       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22437       if (!C || C->getZExtValue() != 1)
22438         return SDValue();
22439       return DAG.getNode(ISD::AND, dl, VT,
22440                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22441                                      N00.getOperand(0), N00.getOperand(1)),
22442                          DAG.getConstant(1, VT));
22443     }
22444   }
22445
22446   if (N0.getOpcode() == ISD::TRUNCATE &&
22447       N0.hasOneUse() &&
22448       N0.getOperand(0).hasOneUse()) {
22449     SDValue N00 = N0.getOperand(0);
22450     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22451       return DAG.getNode(ISD::AND, dl, VT,
22452                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22453                                      N00.getOperand(0), N00.getOperand(1)),
22454                          DAG.getConstant(1, VT));
22455     }
22456   }
22457   if (VT.is256BitVector()) {
22458     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22459     if (R.getNode())
22460       return R;
22461   }
22462
22463   return SDValue();
22464 }
22465
22466 // Optimize x == -y --> x+y == 0
22467 //          x != -y --> x+y != 0
22468 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22469                                       const X86Subtarget* Subtarget) {
22470   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22471   SDValue LHS = N->getOperand(0);
22472   SDValue RHS = N->getOperand(1);
22473   EVT VT = N->getValueType(0);
22474   SDLoc DL(N);
22475
22476   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22477     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22478       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22479         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22480                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22481         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22482                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22483       }
22484   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22485     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22486       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22487         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22488                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22489         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22490                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22491       }
22492
22493   if (VT.getScalarType() == MVT::i1) {
22494     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22495       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22496     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22497     if (!IsSEXT0 && !IsVZero0)
22498       return SDValue();
22499     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22500       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22501     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22502
22503     if (!IsSEXT1 && !IsVZero1)
22504       return SDValue();
22505
22506     if (IsSEXT0 && IsVZero1) {
22507       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22508       if (CC == ISD::SETEQ)
22509         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22510       return LHS.getOperand(0);
22511     }
22512     if (IsSEXT1 && IsVZero0) {
22513       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22514       if (CC == ISD::SETEQ)
22515         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22516       return RHS.getOperand(0);
22517     }
22518   }
22519
22520   return SDValue();
22521 }
22522
22523 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22524                                       const X86Subtarget *Subtarget) {
22525   SDLoc dl(N);
22526   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22527   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22528          "X86insertps is only defined for v4x32");
22529
22530   SDValue Ld = N->getOperand(1);
22531   if (MayFoldLoad(Ld)) {
22532     // Extract the countS bits from the immediate so we can get the proper
22533     // address when narrowing the vector load to a specific element.
22534     // When the second source op is a memory address, interps doesn't use
22535     // countS and just gets an f32 from that address.
22536     unsigned DestIndex =
22537         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22538     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22539   } else
22540     return SDValue();
22541
22542   // Create this as a scalar to vector to match the instruction pattern.
22543   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22544   // countS bits are ignored when loading from memory on insertps, which
22545   // means we don't need to explicitly set them to 0.
22546   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22547                      LoadScalarToVector, N->getOperand(2));
22548 }
22549
22550 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22551 // as "sbb reg,reg", since it can be extended without zext and produces
22552 // an all-ones bit which is more useful than 0/1 in some cases.
22553 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22554                                MVT VT) {
22555   if (VT == MVT::i8)
22556     return DAG.getNode(ISD::AND, DL, VT,
22557                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22558                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22559                        DAG.getConstant(1, VT));
22560   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22561   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22562                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22563                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22564 }
22565
22566 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22567 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22568                                    TargetLowering::DAGCombinerInfo &DCI,
22569                                    const X86Subtarget *Subtarget) {
22570   SDLoc DL(N);
22571   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22572   SDValue EFLAGS = N->getOperand(1);
22573
22574   if (CC == X86::COND_A) {
22575     // Try to convert COND_A into COND_B in an attempt to facilitate
22576     // materializing "setb reg".
22577     //
22578     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22579     // cannot take an immediate as its first operand.
22580     //
22581     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22582         EFLAGS.getValueType().isInteger() &&
22583         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22584       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22585                                    EFLAGS.getNode()->getVTList(),
22586                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22587       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22588       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22589     }
22590   }
22591
22592   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22593   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22594   // cases.
22595   if (CC == X86::COND_B)
22596     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22597
22598   SDValue Flags;
22599
22600   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22601   if (Flags.getNode()) {
22602     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22603     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22604   }
22605
22606   return SDValue();
22607 }
22608
22609 // Optimize branch condition evaluation.
22610 //
22611 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22612                                     TargetLowering::DAGCombinerInfo &DCI,
22613                                     const X86Subtarget *Subtarget) {
22614   SDLoc DL(N);
22615   SDValue Chain = N->getOperand(0);
22616   SDValue Dest = N->getOperand(1);
22617   SDValue EFLAGS = N->getOperand(3);
22618   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22619
22620   SDValue Flags;
22621
22622   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22623   if (Flags.getNode()) {
22624     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22625     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22626                        Flags);
22627   }
22628
22629   return SDValue();
22630 }
22631
22632 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22633                                                          SelectionDAG &DAG) {
22634   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22635   // optimize away operation when it's from a constant.
22636   //
22637   // The general transformation is:
22638   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22639   //       AND(VECTOR_CMP(x,y), constant2)
22640   //    constant2 = UNARYOP(constant)
22641
22642   // Early exit if this isn't a vector operation, the operand of the
22643   // unary operation isn't a bitwise AND, or if the sizes of the operations
22644   // aren't the same.
22645   EVT VT = N->getValueType(0);
22646   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22647       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22648       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22649     return SDValue();
22650
22651   // Now check that the other operand of the AND is a constant. We could
22652   // make the transformation for non-constant splats as well, but it's unclear
22653   // that would be a benefit as it would not eliminate any operations, just
22654   // perform one more step in scalar code before moving to the vector unit.
22655   if (BuildVectorSDNode *BV =
22656           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22657     // Bail out if the vector isn't a constant.
22658     if (!BV->isConstant())
22659       return SDValue();
22660
22661     // Everything checks out. Build up the new and improved node.
22662     SDLoc DL(N);
22663     EVT IntVT = BV->getValueType(0);
22664     // Create a new constant of the appropriate type for the transformed
22665     // DAG.
22666     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22667     // The AND node needs bitcasts to/from an integer vector type around it.
22668     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22669     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22670                                  N->getOperand(0)->getOperand(0), MaskConst);
22671     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22672     return Res;
22673   }
22674
22675   return SDValue();
22676 }
22677
22678 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22679                                         const X86TargetLowering *XTLI) {
22680   // First try to optimize away the conversion entirely when it's
22681   // conditionally from a constant. Vectors only.
22682   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22683   if (Res != SDValue())
22684     return Res;
22685
22686   // Now move on to more general possibilities.
22687   SDValue Op0 = N->getOperand(0);
22688   EVT InVT = Op0->getValueType(0);
22689
22690   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22691   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22692     SDLoc dl(N);
22693     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22694     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22695     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22696   }
22697
22698   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22699   // a 32-bit target where SSE doesn't support i64->FP operations.
22700   if (Op0.getOpcode() == ISD::LOAD) {
22701     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22702     EVT VT = Ld->getValueType(0);
22703     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22704         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22705         !XTLI->getSubtarget()->is64Bit() &&
22706         VT == MVT::i64) {
22707       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22708                                           Ld->getChain(), Op0, DAG);
22709       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22710       return FILDChain;
22711     }
22712   }
22713   return SDValue();
22714 }
22715
22716 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22717 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22718                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22719   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22720   // the result is either zero or one (depending on the input carry bit).
22721   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22722   if (X86::isZeroNode(N->getOperand(0)) &&
22723       X86::isZeroNode(N->getOperand(1)) &&
22724       // We don't have a good way to replace an EFLAGS use, so only do this when
22725       // dead right now.
22726       SDValue(N, 1).use_empty()) {
22727     SDLoc DL(N);
22728     EVT VT = N->getValueType(0);
22729     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22730     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22731                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22732                                            DAG.getConstant(X86::COND_B,MVT::i8),
22733                                            N->getOperand(2)),
22734                                DAG.getConstant(1, VT));
22735     return DCI.CombineTo(N, Res1, CarryOut);
22736   }
22737
22738   return SDValue();
22739 }
22740
22741 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22742 //      (add Y, (setne X, 0)) -> sbb -1, Y
22743 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22744 //      (sub (setne X, 0), Y) -> adc -1, Y
22745 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22746   SDLoc DL(N);
22747
22748   // Look through ZExts.
22749   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22750   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22751     return SDValue();
22752
22753   SDValue SetCC = Ext.getOperand(0);
22754   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22755     return SDValue();
22756
22757   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22758   if (CC != X86::COND_E && CC != X86::COND_NE)
22759     return SDValue();
22760
22761   SDValue Cmp = SetCC.getOperand(1);
22762   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22763       !X86::isZeroNode(Cmp.getOperand(1)) ||
22764       !Cmp.getOperand(0).getValueType().isInteger())
22765     return SDValue();
22766
22767   SDValue CmpOp0 = Cmp.getOperand(0);
22768   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22769                                DAG.getConstant(1, CmpOp0.getValueType()));
22770
22771   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22772   if (CC == X86::COND_NE)
22773     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22774                        DL, OtherVal.getValueType(), OtherVal,
22775                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22776   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22777                      DL, OtherVal.getValueType(), OtherVal,
22778                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22779 }
22780
22781 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22782 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22783                                  const X86Subtarget *Subtarget) {
22784   EVT VT = N->getValueType(0);
22785   SDValue Op0 = N->getOperand(0);
22786   SDValue Op1 = N->getOperand(1);
22787
22788   // Try to synthesize horizontal adds from adds of shuffles.
22789   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22790        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22791       isHorizontalBinOp(Op0, Op1, true))
22792     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22793
22794   return OptimizeConditionalInDecrement(N, DAG);
22795 }
22796
22797 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22798                                  const X86Subtarget *Subtarget) {
22799   SDValue Op0 = N->getOperand(0);
22800   SDValue Op1 = N->getOperand(1);
22801
22802   // X86 can't encode an immediate LHS of a sub. See if we can push the
22803   // negation into a preceding instruction.
22804   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22805     // If the RHS of the sub is a XOR with one use and a constant, invert the
22806     // immediate. Then add one to the LHS of the sub so we can turn
22807     // X-Y -> X+~Y+1, saving one register.
22808     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22809         isa<ConstantSDNode>(Op1.getOperand(1))) {
22810       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22811       EVT VT = Op0.getValueType();
22812       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22813                                    Op1.getOperand(0),
22814                                    DAG.getConstant(~XorC, VT));
22815       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22816                          DAG.getConstant(C->getAPIntValue()+1, VT));
22817     }
22818   }
22819
22820   // Try to synthesize horizontal adds from adds of shuffles.
22821   EVT VT = N->getValueType(0);
22822   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22823        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22824       isHorizontalBinOp(Op0, Op1, true))
22825     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22826
22827   return OptimizeConditionalInDecrement(N, DAG);
22828 }
22829
22830 /// performVZEXTCombine - Performs build vector combines
22831 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22832                                         TargetLowering::DAGCombinerInfo &DCI,
22833                                         const X86Subtarget *Subtarget) {
22834   // (vzext (bitcast (vzext (x)) -> (vzext x)
22835   SDValue In = N->getOperand(0);
22836   while (In.getOpcode() == ISD::BITCAST)
22837     In = In.getOperand(0);
22838
22839   if (In.getOpcode() != X86ISD::VZEXT)
22840     return SDValue();
22841
22842   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22843                      In.getOperand(0));
22844 }
22845
22846 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22847                                              DAGCombinerInfo &DCI) const {
22848   SelectionDAG &DAG = DCI.DAG;
22849   switch (N->getOpcode()) {
22850   default: break;
22851   case ISD::EXTRACT_VECTOR_ELT:
22852     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22853   case ISD::VSELECT:
22854   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22855   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22856   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22857   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22858   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22859   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22860   case ISD::SHL:
22861   case ISD::SRA:
22862   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22863   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22864   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22865   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22866   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22867   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22868   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22869   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22870   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22871   case X86ISD::FXOR:
22872   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22873   case X86ISD::FMIN:
22874   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22875   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22876   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22877   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22878   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22879   case ISD::ANY_EXTEND:
22880   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22881   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22882   case ISD::SIGN_EXTEND_INREG:
22883     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22884   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22885   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22886   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22887   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22888   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22889   case X86ISD::SHUFP:       // Handle all target specific shuffles
22890   case X86ISD::PALIGNR:
22891   case X86ISD::UNPCKH:
22892   case X86ISD::UNPCKL:
22893   case X86ISD::MOVHLPS:
22894   case X86ISD::MOVLHPS:
22895   case X86ISD::PSHUFB:
22896   case X86ISD::PSHUFD:
22897   case X86ISD::PSHUFHW:
22898   case X86ISD::PSHUFLW:
22899   case X86ISD::MOVSS:
22900   case X86ISD::MOVSD:
22901   case X86ISD::VPERMILP:
22902   case X86ISD::VPERM2X128:
22903   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22904   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22905   case ISD::INTRINSIC_WO_CHAIN:
22906     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22907   case X86ISD::INSERTPS:
22908     return PerformINSERTPSCombine(N, DAG, Subtarget);
22909   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22910   }
22911
22912   return SDValue();
22913 }
22914
22915 /// isTypeDesirableForOp - Return true if the target has native support for
22916 /// the specified value type and it is 'desirable' to use the type for the
22917 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22918 /// instruction encodings are longer and some i16 instructions are slow.
22919 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22920   if (!isTypeLegal(VT))
22921     return false;
22922   if (VT != MVT::i16)
22923     return true;
22924
22925   switch (Opc) {
22926   default:
22927     return true;
22928   case ISD::LOAD:
22929   case ISD::SIGN_EXTEND:
22930   case ISD::ZERO_EXTEND:
22931   case ISD::ANY_EXTEND:
22932   case ISD::SHL:
22933   case ISD::SRL:
22934   case ISD::SUB:
22935   case ISD::ADD:
22936   case ISD::MUL:
22937   case ISD::AND:
22938   case ISD::OR:
22939   case ISD::XOR:
22940     return false;
22941   }
22942 }
22943
22944 /// IsDesirableToPromoteOp - This method query the target whether it is
22945 /// beneficial for dag combiner to promote the specified node. If true, it
22946 /// should return the desired promotion type by reference.
22947 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22948   EVT VT = Op.getValueType();
22949   if (VT != MVT::i16)
22950     return false;
22951
22952   bool Promote = false;
22953   bool Commute = false;
22954   switch (Op.getOpcode()) {
22955   default: break;
22956   case ISD::LOAD: {
22957     LoadSDNode *LD = cast<LoadSDNode>(Op);
22958     // If the non-extending load has a single use and it's not live out, then it
22959     // might be folded.
22960     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22961                                                      Op.hasOneUse()*/) {
22962       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22963              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22964         // The only case where we'd want to promote LOAD (rather then it being
22965         // promoted as an operand is when it's only use is liveout.
22966         if (UI->getOpcode() != ISD::CopyToReg)
22967           return false;
22968       }
22969     }
22970     Promote = true;
22971     break;
22972   }
22973   case ISD::SIGN_EXTEND:
22974   case ISD::ZERO_EXTEND:
22975   case ISD::ANY_EXTEND:
22976     Promote = true;
22977     break;
22978   case ISD::SHL:
22979   case ISD::SRL: {
22980     SDValue N0 = Op.getOperand(0);
22981     // Look out for (store (shl (load), x)).
22982     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22983       return false;
22984     Promote = true;
22985     break;
22986   }
22987   case ISD::ADD:
22988   case ISD::MUL:
22989   case ISD::AND:
22990   case ISD::OR:
22991   case ISD::XOR:
22992     Commute = true;
22993     // fallthrough
22994   case ISD::SUB: {
22995     SDValue N0 = Op.getOperand(0);
22996     SDValue N1 = Op.getOperand(1);
22997     if (!Commute && MayFoldLoad(N1))
22998       return false;
22999     // Avoid disabling potential load folding opportunities.
23000     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23001       return false;
23002     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23003       return false;
23004     Promote = true;
23005   }
23006   }
23007
23008   PVT = MVT::i32;
23009   return Promote;
23010 }
23011
23012 //===----------------------------------------------------------------------===//
23013 //                           X86 Inline Assembly Support
23014 //===----------------------------------------------------------------------===//
23015
23016 namespace {
23017   // Helper to match a string separated by whitespace.
23018   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23019     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23020
23021     for (unsigned i = 0, e = args.size(); i != e; ++i) {
23022       StringRef piece(*args[i]);
23023       if (!s.startswith(piece)) // Check if the piece matches.
23024         return false;
23025
23026       s = s.substr(piece.size());
23027       StringRef::size_type pos = s.find_first_not_of(" \t");
23028       if (pos == 0) // We matched a prefix.
23029         return false;
23030
23031       s = s.substr(pos);
23032     }
23033
23034     return s.empty();
23035   }
23036   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23037 }
23038
23039 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23040
23041   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23042     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23043         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23044         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23045
23046       if (AsmPieces.size() == 3)
23047         return true;
23048       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23049         return true;
23050     }
23051   }
23052   return false;
23053 }
23054
23055 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23056   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23057
23058   std::string AsmStr = IA->getAsmString();
23059
23060   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23061   if (!Ty || Ty->getBitWidth() % 16 != 0)
23062     return false;
23063
23064   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23065   SmallVector<StringRef, 4> AsmPieces;
23066   SplitString(AsmStr, AsmPieces, ";\n");
23067
23068   switch (AsmPieces.size()) {
23069   default: return false;
23070   case 1:
23071     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23072     // we will turn this bswap into something that will be lowered to logical
23073     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23074     // lower so don't worry about this.
23075     // bswap $0
23076     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23077         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23078         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23079         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23080         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23081         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23082       // No need to check constraints, nothing other than the equivalent of
23083       // "=r,0" would be valid here.
23084       return IntrinsicLowering::LowerToByteSwap(CI);
23085     }
23086
23087     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23088     if (CI->getType()->isIntegerTy(16) &&
23089         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23090         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23091          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23092       AsmPieces.clear();
23093       const std::string &ConstraintsStr = IA->getConstraintString();
23094       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23095       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23096       if (clobbersFlagRegisters(AsmPieces))
23097         return IntrinsicLowering::LowerToByteSwap(CI);
23098     }
23099     break;
23100   case 3:
23101     if (CI->getType()->isIntegerTy(32) &&
23102         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23103         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23104         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23105         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23106       AsmPieces.clear();
23107       const std::string &ConstraintsStr = IA->getConstraintString();
23108       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23109       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23110       if (clobbersFlagRegisters(AsmPieces))
23111         return IntrinsicLowering::LowerToByteSwap(CI);
23112     }
23113
23114     if (CI->getType()->isIntegerTy(64)) {
23115       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23116       if (Constraints.size() >= 2 &&
23117           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23118           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23119         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23120         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23121             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23122             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23123           return IntrinsicLowering::LowerToByteSwap(CI);
23124       }
23125     }
23126     break;
23127   }
23128   return false;
23129 }
23130
23131 /// getConstraintType - Given a constraint letter, return the type of
23132 /// constraint it is for this target.
23133 X86TargetLowering::ConstraintType
23134 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23135   if (Constraint.size() == 1) {
23136     switch (Constraint[0]) {
23137     case 'R':
23138     case 'q':
23139     case 'Q':
23140     case 'f':
23141     case 't':
23142     case 'u':
23143     case 'y':
23144     case 'x':
23145     case 'Y':
23146     case 'l':
23147       return C_RegisterClass;
23148     case 'a':
23149     case 'b':
23150     case 'c':
23151     case 'd':
23152     case 'S':
23153     case 'D':
23154     case 'A':
23155       return C_Register;
23156     case 'I':
23157     case 'J':
23158     case 'K':
23159     case 'L':
23160     case 'M':
23161     case 'N':
23162     case 'G':
23163     case 'C':
23164     case 'e':
23165     case 'Z':
23166       return C_Other;
23167     default:
23168       break;
23169     }
23170   }
23171   return TargetLowering::getConstraintType(Constraint);
23172 }
23173
23174 /// Examine constraint type and operand type and determine a weight value.
23175 /// This object must already have been set up with the operand type
23176 /// and the current alternative constraint selected.
23177 TargetLowering::ConstraintWeight
23178   X86TargetLowering::getSingleConstraintMatchWeight(
23179     AsmOperandInfo &info, const char *constraint) const {
23180   ConstraintWeight weight = CW_Invalid;
23181   Value *CallOperandVal = info.CallOperandVal;
23182     // If we don't have a value, we can't do a match,
23183     // but allow it at the lowest weight.
23184   if (!CallOperandVal)
23185     return CW_Default;
23186   Type *type = CallOperandVal->getType();
23187   // Look at the constraint type.
23188   switch (*constraint) {
23189   default:
23190     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23191   case 'R':
23192   case 'q':
23193   case 'Q':
23194   case 'a':
23195   case 'b':
23196   case 'c':
23197   case 'd':
23198   case 'S':
23199   case 'D':
23200   case 'A':
23201     if (CallOperandVal->getType()->isIntegerTy())
23202       weight = CW_SpecificReg;
23203     break;
23204   case 'f':
23205   case 't':
23206   case 'u':
23207     if (type->isFloatingPointTy())
23208       weight = CW_SpecificReg;
23209     break;
23210   case 'y':
23211     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23212       weight = CW_SpecificReg;
23213     break;
23214   case 'x':
23215   case 'Y':
23216     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23217         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23218       weight = CW_Register;
23219     break;
23220   case 'I':
23221     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23222       if (C->getZExtValue() <= 31)
23223         weight = CW_Constant;
23224     }
23225     break;
23226   case 'J':
23227     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23228       if (C->getZExtValue() <= 63)
23229         weight = CW_Constant;
23230     }
23231     break;
23232   case 'K':
23233     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23234       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23235         weight = CW_Constant;
23236     }
23237     break;
23238   case 'L':
23239     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23240       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23241         weight = CW_Constant;
23242     }
23243     break;
23244   case 'M':
23245     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23246       if (C->getZExtValue() <= 3)
23247         weight = CW_Constant;
23248     }
23249     break;
23250   case 'N':
23251     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23252       if (C->getZExtValue() <= 0xff)
23253         weight = CW_Constant;
23254     }
23255     break;
23256   case 'G':
23257   case 'C':
23258     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23259       weight = CW_Constant;
23260     }
23261     break;
23262   case 'e':
23263     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23264       if ((C->getSExtValue() >= -0x80000000LL) &&
23265           (C->getSExtValue() <= 0x7fffffffLL))
23266         weight = CW_Constant;
23267     }
23268     break;
23269   case 'Z':
23270     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23271       if (C->getZExtValue() <= 0xffffffff)
23272         weight = CW_Constant;
23273     }
23274     break;
23275   }
23276   return weight;
23277 }
23278
23279 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23280 /// with another that has more specific requirements based on the type of the
23281 /// corresponding operand.
23282 const char *X86TargetLowering::
23283 LowerXConstraint(EVT ConstraintVT) const {
23284   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23285   // 'f' like normal targets.
23286   if (ConstraintVT.isFloatingPoint()) {
23287     if (Subtarget->hasSSE2())
23288       return "Y";
23289     if (Subtarget->hasSSE1())
23290       return "x";
23291   }
23292
23293   return TargetLowering::LowerXConstraint(ConstraintVT);
23294 }
23295
23296 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23297 /// vector.  If it is invalid, don't add anything to Ops.
23298 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23299                                                      std::string &Constraint,
23300                                                      std::vector<SDValue>&Ops,
23301                                                      SelectionDAG &DAG) const {
23302   SDValue Result;
23303
23304   // Only support length 1 constraints for now.
23305   if (Constraint.length() > 1) return;
23306
23307   char ConstraintLetter = Constraint[0];
23308   switch (ConstraintLetter) {
23309   default: break;
23310   case 'I':
23311     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23312       if (C->getZExtValue() <= 31) {
23313         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23314         break;
23315       }
23316     }
23317     return;
23318   case 'J':
23319     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23320       if (C->getZExtValue() <= 63) {
23321         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23322         break;
23323       }
23324     }
23325     return;
23326   case 'K':
23327     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23328       if (isInt<8>(C->getSExtValue())) {
23329         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23330         break;
23331       }
23332     }
23333     return;
23334   case 'N':
23335     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23336       if (C->getZExtValue() <= 255) {
23337         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23338         break;
23339       }
23340     }
23341     return;
23342   case 'e': {
23343     // 32-bit signed value
23344     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23345       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23346                                            C->getSExtValue())) {
23347         // Widen to 64 bits here to get it sign extended.
23348         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23349         break;
23350       }
23351     // FIXME gcc accepts some relocatable values here too, but only in certain
23352     // memory models; it's complicated.
23353     }
23354     return;
23355   }
23356   case 'Z': {
23357     // 32-bit unsigned value
23358     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23359       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23360                                            C->getZExtValue())) {
23361         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23362         break;
23363       }
23364     }
23365     // FIXME gcc accepts some relocatable values here too, but only in certain
23366     // memory models; it's complicated.
23367     return;
23368   }
23369   case 'i': {
23370     // Literal immediates are always ok.
23371     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23372       // Widen to 64 bits here to get it sign extended.
23373       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23374       break;
23375     }
23376
23377     // In any sort of PIC mode addresses need to be computed at runtime by
23378     // adding in a register or some sort of table lookup.  These can't
23379     // be used as immediates.
23380     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23381       return;
23382
23383     // If we are in non-pic codegen mode, we allow the address of a global (with
23384     // an optional displacement) to be used with 'i'.
23385     GlobalAddressSDNode *GA = nullptr;
23386     int64_t Offset = 0;
23387
23388     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23389     while (1) {
23390       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23391         Offset += GA->getOffset();
23392         break;
23393       } else if (Op.getOpcode() == ISD::ADD) {
23394         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23395           Offset += C->getZExtValue();
23396           Op = Op.getOperand(0);
23397           continue;
23398         }
23399       } else if (Op.getOpcode() == ISD::SUB) {
23400         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23401           Offset += -C->getZExtValue();
23402           Op = Op.getOperand(0);
23403           continue;
23404         }
23405       }
23406
23407       // Otherwise, this isn't something we can handle, reject it.
23408       return;
23409     }
23410
23411     const GlobalValue *GV = GA->getGlobal();
23412     // If we require an extra load to get this address, as in PIC mode, we
23413     // can't accept it.
23414     if (isGlobalStubReference(
23415             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23416       return;
23417
23418     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23419                                         GA->getValueType(0), Offset);
23420     break;
23421   }
23422   }
23423
23424   if (Result.getNode()) {
23425     Ops.push_back(Result);
23426     return;
23427   }
23428   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23429 }
23430
23431 std::pair<unsigned, const TargetRegisterClass*>
23432 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23433                                                 MVT VT) const {
23434   // First, see if this is a constraint that directly corresponds to an LLVM
23435   // register class.
23436   if (Constraint.size() == 1) {
23437     // GCC Constraint Letters
23438     switch (Constraint[0]) {
23439     default: break;
23440       // TODO: Slight differences here in allocation order and leaving
23441       // RIP in the class. Do they matter any more here than they do
23442       // in the normal allocation?
23443     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23444       if (Subtarget->is64Bit()) {
23445         if (VT == MVT::i32 || VT == MVT::f32)
23446           return std::make_pair(0U, &X86::GR32RegClass);
23447         if (VT == MVT::i16)
23448           return std::make_pair(0U, &X86::GR16RegClass);
23449         if (VT == MVT::i8 || VT == MVT::i1)
23450           return std::make_pair(0U, &X86::GR8RegClass);
23451         if (VT == MVT::i64 || VT == MVT::f64)
23452           return std::make_pair(0U, &X86::GR64RegClass);
23453         break;
23454       }
23455       // 32-bit fallthrough
23456     case 'Q':   // Q_REGS
23457       if (VT == MVT::i32 || VT == MVT::f32)
23458         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23459       if (VT == MVT::i16)
23460         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23461       if (VT == MVT::i8 || VT == MVT::i1)
23462         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23463       if (VT == MVT::i64)
23464         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23465       break;
23466     case 'r':   // GENERAL_REGS
23467     case 'l':   // INDEX_REGS
23468       if (VT == MVT::i8 || VT == MVT::i1)
23469         return std::make_pair(0U, &X86::GR8RegClass);
23470       if (VT == MVT::i16)
23471         return std::make_pair(0U, &X86::GR16RegClass);
23472       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23473         return std::make_pair(0U, &X86::GR32RegClass);
23474       return std::make_pair(0U, &X86::GR64RegClass);
23475     case 'R':   // LEGACY_REGS
23476       if (VT == MVT::i8 || VT == MVT::i1)
23477         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23478       if (VT == MVT::i16)
23479         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23480       if (VT == MVT::i32 || !Subtarget->is64Bit())
23481         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23482       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23483     case 'f':  // FP Stack registers.
23484       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23485       // value to the correct fpstack register class.
23486       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23487         return std::make_pair(0U, &X86::RFP32RegClass);
23488       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23489         return std::make_pair(0U, &X86::RFP64RegClass);
23490       return std::make_pair(0U, &X86::RFP80RegClass);
23491     case 'y':   // MMX_REGS if MMX allowed.
23492       if (!Subtarget->hasMMX()) break;
23493       return std::make_pair(0U, &X86::VR64RegClass);
23494     case 'Y':   // SSE_REGS if SSE2 allowed
23495       if (!Subtarget->hasSSE2()) break;
23496       // FALL THROUGH.
23497     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23498       if (!Subtarget->hasSSE1()) break;
23499
23500       switch (VT.SimpleTy) {
23501       default: break;
23502       // Scalar SSE types.
23503       case MVT::f32:
23504       case MVT::i32:
23505         return std::make_pair(0U, &X86::FR32RegClass);
23506       case MVT::f64:
23507       case MVT::i64:
23508         return std::make_pair(0U, &X86::FR64RegClass);
23509       // Vector types.
23510       case MVT::v16i8:
23511       case MVT::v8i16:
23512       case MVT::v4i32:
23513       case MVT::v2i64:
23514       case MVT::v4f32:
23515       case MVT::v2f64:
23516         return std::make_pair(0U, &X86::VR128RegClass);
23517       // AVX types.
23518       case MVT::v32i8:
23519       case MVT::v16i16:
23520       case MVT::v8i32:
23521       case MVT::v4i64:
23522       case MVT::v8f32:
23523       case MVT::v4f64:
23524         return std::make_pair(0U, &X86::VR256RegClass);
23525       case MVT::v8f64:
23526       case MVT::v16f32:
23527       case MVT::v16i32:
23528       case MVT::v8i64:
23529         return std::make_pair(0U, &X86::VR512RegClass);
23530       }
23531       break;
23532     }
23533   }
23534
23535   // Use the default implementation in TargetLowering to convert the register
23536   // constraint into a member of a register class.
23537   std::pair<unsigned, const TargetRegisterClass*> Res;
23538   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23539
23540   // Not found as a standard register?
23541   if (!Res.second) {
23542     // Map st(0) -> st(7) -> ST0
23543     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23544         tolower(Constraint[1]) == 's' &&
23545         tolower(Constraint[2]) == 't' &&
23546         Constraint[3] == '(' &&
23547         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23548         Constraint[5] == ')' &&
23549         Constraint[6] == '}') {
23550
23551       Res.first = X86::FP0+Constraint[4]-'0';
23552       Res.second = &X86::RFP80RegClass;
23553       return Res;
23554     }
23555
23556     // GCC allows "st(0)" to be called just plain "st".
23557     if (StringRef("{st}").equals_lower(Constraint)) {
23558       Res.first = X86::FP0;
23559       Res.second = &X86::RFP80RegClass;
23560       return Res;
23561     }
23562
23563     // flags -> EFLAGS
23564     if (StringRef("{flags}").equals_lower(Constraint)) {
23565       Res.first = X86::EFLAGS;
23566       Res.second = &X86::CCRRegClass;
23567       return Res;
23568     }
23569
23570     // 'A' means EAX + EDX.
23571     if (Constraint == "A") {
23572       Res.first = X86::EAX;
23573       Res.second = &X86::GR32_ADRegClass;
23574       return Res;
23575     }
23576     return Res;
23577   }
23578
23579   // Otherwise, check to see if this is a register class of the wrong value
23580   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23581   // turn into {ax},{dx}.
23582   if (Res.second->hasType(VT))
23583     return Res;   // Correct type already, nothing to do.
23584
23585   // All of the single-register GCC register classes map their values onto
23586   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23587   // really want an 8-bit or 32-bit register, map to the appropriate register
23588   // class and return the appropriate register.
23589   if (Res.second == &X86::GR16RegClass) {
23590     if (VT == MVT::i8 || VT == MVT::i1) {
23591       unsigned DestReg = 0;
23592       switch (Res.first) {
23593       default: break;
23594       case X86::AX: DestReg = X86::AL; break;
23595       case X86::DX: DestReg = X86::DL; break;
23596       case X86::CX: DestReg = X86::CL; break;
23597       case X86::BX: DestReg = X86::BL; break;
23598       }
23599       if (DestReg) {
23600         Res.first = DestReg;
23601         Res.second = &X86::GR8RegClass;
23602       }
23603     } else if (VT == MVT::i32 || VT == MVT::f32) {
23604       unsigned DestReg = 0;
23605       switch (Res.first) {
23606       default: break;
23607       case X86::AX: DestReg = X86::EAX; break;
23608       case X86::DX: DestReg = X86::EDX; break;
23609       case X86::CX: DestReg = X86::ECX; break;
23610       case X86::BX: DestReg = X86::EBX; break;
23611       case X86::SI: DestReg = X86::ESI; break;
23612       case X86::DI: DestReg = X86::EDI; break;
23613       case X86::BP: DestReg = X86::EBP; break;
23614       case X86::SP: DestReg = X86::ESP; break;
23615       }
23616       if (DestReg) {
23617         Res.first = DestReg;
23618         Res.second = &X86::GR32RegClass;
23619       }
23620     } else if (VT == MVT::i64 || VT == MVT::f64) {
23621       unsigned DestReg = 0;
23622       switch (Res.first) {
23623       default: break;
23624       case X86::AX: DestReg = X86::RAX; break;
23625       case X86::DX: DestReg = X86::RDX; break;
23626       case X86::CX: DestReg = X86::RCX; break;
23627       case X86::BX: DestReg = X86::RBX; break;
23628       case X86::SI: DestReg = X86::RSI; break;
23629       case X86::DI: DestReg = X86::RDI; break;
23630       case X86::BP: DestReg = X86::RBP; break;
23631       case X86::SP: DestReg = X86::RSP; break;
23632       }
23633       if (DestReg) {
23634         Res.first = DestReg;
23635         Res.second = &X86::GR64RegClass;
23636       }
23637     }
23638   } else if (Res.second == &X86::FR32RegClass ||
23639              Res.second == &X86::FR64RegClass ||
23640              Res.second == &X86::VR128RegClass ||
23641              Res.second == &X86::VR256RegClass ||
23642              Res.second == &X86::FR32XRegClass ||
23643              Res.second == &X86::FR64XRegClass ||
23644              Res.second == &X86::VR128XRegClass ||
23645              Res.second == &X86::VR256XRegClass ||
23646              Res.second == &X86::VR512RegClass) {
23647     // Handle references to XMM physical registers that got mapped into the
23648     // wrong class.  This can happen with constraints like {xmm0} where the
23649     // target independent register mapper will just pick the first match it can
23650     // find, ignoring the required type.
23651
23652     if (VT == MVT::f32 || VT == MVT::i32)
23653       Res.second = &X86::FR32RegClass;
23654     else if (VT == MVT::f64 || VT == MVT::i64)
23655       Res.second = &X86::FR64RegClass;
23656     else if (X86::VR128RegClass.hasType(VT))
23657       Res.second = &X86::VR128RegClass;
23658     else if (X86::VR256RegClass.hasType(VT))
23659       Res.second = &X86::VR256RegClass;
23660     else if (X86::VR512RegClass.hasType(VT))
23661       Res.second = &X86::VR512RegClass;
23662   }
23663
23664   return Res;
23665 }
23666
23667 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23668                                             Type *Ty) const {
23669   // Scaling factors are not free at all.
23670   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23671   // will take 2 allocations in the out of order engine instead of 1
23672   // for plain addressing mode, i.e. inst (reg1).
23673   // E.g.,
23674   // vaddps (%rsi,%drx), %ymm0, %ymm1
23675   // Requires two allocations (one for the load, one for the computation)
23676   // whereas:
23677   // vaddps (%rsi), %ymm0, %ymm1
23678   // Requires just 1 allocation, i.e., freeing allocations for other operations
23679   // and having less micro operations to execute.
23680   //
23681   // For some X86 architectures, this is even worse because for instance for
23682   // stores, the complex addressing mode forces the instruction to use the
23683   // "load" ports instead of the dedicated "store" port.
23684   // E.g., on Haswell:
23685   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23686   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23687   if (isLegalAddressingMode(AM, Ty))
23688     // Scale represents reg2 * scale, thus account for 1
23689     // as soon as we use a second register.
23690     return AM.Scale != 0;
23691   return -1;
23692 }
23693
23694 bool X86TargetLowering::isTargetFTOL() const {
23695   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23696 }